filename
stringlengths
3
9
code
stringlengths
4
2.03M
458505.c
/* C Y C L I C . C * BRL-CAD * * Copyright (c) 2008-2021 United States Government as represented by * the U.S. Army Research Laboratory. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 file; see the file named COPYING for more * information. */ /** @addtogroup db_search * @brief * Functionality for locating cyclic paths * * Cyclic paths (combs whose trees include a reference to the root object * within the tree) represent a problem for .g processing logic. (Infinite * looping bugs and empty tops lists in particular.) The routines in * this file are designed to identify and list comb objects whose trees * contain self referenceing paths - with that information, callers can * take steps to either handle or resolve the problems. */ #include "common.h" #include <string.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #include <limits.h> /* for INT_MAX */ #include "rt/defines.h" #include "rt/db_internal.h" #include "rt/db_io.h" #include "rt/directory.h" #include "rt/nongeom.h" #include "rt/search.h" /* Search client data container */ struct cyclic_client_data_t { struct db_i *dbip; struct bu_ptbl *cyclic; int cnt; int full_search; }; /** * A generic traversal function maintaining awareness of the full path * to a given object. */ static void db_fullpath_cyclic_subtree(struct db_full_path *path, int curr_bool, union tree *tp, void (*traverse_func) (struct db_full_path *path, void *), void *client_data) { struct directory *dp; struct cyclic_client_data_t *ccd = (struct cyclic_client_data_t *)client_data; int bool_val = curr_bool; if (!tp) return; RT_CK_FULL_PATH(path); RT_CHECK_DBI(ccd->dbip); RT_CK_TREE(tp); switch (tp->tr_op) { case OP_UNION: case OP_INTERSECT: case OP_SUBTRACT: case OP_XOR: if (tp->tr_op == OP_UNION) bool_val = 2; if (tp->tr_op == OP_INTERSECT) bool_val = 3; if (tp->tr_op == OP_SUBTRACT) bool_val = 4; db_fullpath_cyclic_subtree(path, bool_val, tp->tr_b.tb_right, traverse_func, client_data); /* fall through */ case OP_NOT: case OP_GUARD: case OP_XNOP: db_fullpath_cyclic_subtree(path, OP_UNION, tp->tr_b.tb_left, traverse_func, client_data); break; case OP_DB_LEAF: if ((dp=db_lookup(ccd->dbip, tp->tr_l.tl_name, LOOKUP_QUIET)) == RT_DIR_NULL) { return; } else { /* Create the new path. If doing so creates a cyclic path, * abort walk and (if path is minimally cyclic) report it - * else, keep going. */ struct db_full_path *newpath; db_add_node_to_full_path(path, dp); if (!db_full_path_cyclic(path, NULL, 0)) { /* Keep going */ traverse_func(path, client_data); } else { if (ccd->full_search) { if (dp == path->fp_names[0]) { // If dp matches the root dp, the cyclic path is a // "minimal" cyclic path. Otherwise, it is a "buried" // cyclic path - i.e., a reference by a higher level // comb to a comb with a cyclic path problem. A buried // cycle haults the tree walk, but it's not the minimal // "here's the problem to fix" path we want to report // in this case. (Because we are doing a full database // search, we have to walk all comb trees anyway to be // sure of finding all problems, so we will eventually // find the minimal verison of the problem.) ccd->cnt++; if (ccd->cyclic) { BU_ALLOC(newpath, struct db_full_path); db_full_path_init(newpath); db_dup_full_path(newpath, path); /* Insert the path in the bu_ptbl collecting paths */ bu_ptbl_ins(ccd->cyclic, (long *)newpath); } // Debugging char *path_string = db_path_to_string(path); bu_log("Found minimal cyclic path %s\n", path_string); bu_free(path_string, "free path str"); } } else { // We're not doing a full database search and don't // have any guarantees we will find minimal paths at // some point during the search; report everything we // find within this tree. ccd->cnt++; if (ccd->cyclic) { BU_ALLOC(newpath, struct db_full_path); db_full_path_init(newpath); db_dup_full_path(newpath, path); /* Insert the path in the bu_ptbl collecting paths */ bu_ptbl_ins(ccd->cyclic, (long *)newpath); } } } DB_FULL_PATH_POP(path); break; } default: bu_log("db_functree_subtree: unrecognized operator %d\n", tp->tr_op); bu_bomb("db_functree_subtree: unrecognized operator\n"); } } /** * This walker builds a list of db_full_path entries corresponding to * the contents of the tree under *path. It does so while assigning * the boolean operation associated with each path entry to the * db_full_path structure. This list is then used for further * processing and filtering by the search routines. */ static void db_fullpath_cyclic(struct db_full_path *path, void *client_data) { struct directory *dp; struct cyclic_client_data_t *ccd= (struct cyclic_client_data_t *)client_data; RT_CK_FULL_PATH(path); RT_CK_DBI(ccd->dbip); dp = DB_FULL_PATH_CUR_DIR(path); if (!dp) return; if (dp->d_flags & RT_DIR_COMB) { struct rt_db_internal in; struct rt_comb_internal *comb; if (rt_db_get_internal(&in, dp, ccd->dbip, NULL, &rt_uniresource) < 0) return; comb = (struct rt_comb_internal *)in.idb_ptr; db_fullpath_cyclic_subtree(path, OP_UNION, comb->tree, db_fullpath_cyclic, client_data); rt_db_free_internal(&in); } } int db_cyclic_paths(struct bu_ptbl *cyclic_paths, struct db_i *dbip, struct directory *sdp) { if (!dbip) return 0; /* First, check if cyclic is initialized - don't trust the caller to do it, * but it's fine if they did */ if (cyclic_paths && cyclic_paths != BU_PTBL_NULL) { if (!BU_PTBL_IS_INITIALIZED(cyclic_paths)) { BU_PTBL_INIT(cyclic_paths); } } struct cyclic_client_data_t ccd; ccd.dbip = dbip; ccd.cyclic = cyclic_paths; ccd.cnt = 0; if (sdp) { if (!(sdp->d_flags & RT_DIR_COMB)) return 0; ccd.full_search = 0; struct db_full_path *start_path = NULL; BU_ALLOC(start_path, struct db_full_path); db_full_path_init(start_path); db_add_node_to_full_path(start_path, sdp); db_fullpath_cyclic(start_path, (void **)&ccd); db_free_full_path(start_path); bu_free(start_path, "start_path"); } else { struct directory *dp; ccd.full_search = 1; for (int i = 0; i < RT_DBNHASH; i++) { for (dp = dbip->dbi_Head[i]; dp != RT_DIR_NULL; dp = dp->d_forw) { if (!(dp->d_flags & RT_DIR_COMB)) continue; struct db_full_path *start_path = NULL; BU_ALLOC(start_path, struct db_full_path); db_full_path_init(start_path); db_add_node_to_full_path(start_path, dp); db_fullpath_cyclic(start_path, (void **)&ccd); db_free_full_path(start_path); bu_free(start_path, "start_path"); } } } return ccd.cnt; } /* * Local Variables: * tab-width: 8 * mode: C * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
370548.c
/* * POSIX library for Lua 5.1, 5.2 & 5.3. * (c) Gary V. Vaughan <[email protected]>, 2013-2015 * (c) Reuben Thomas <[email protected]> 2010-2013 * (c) Natanael Copa <[email protected]> 2008-2010 * Clean up and bug fixes by Leo Razoumov <[email protected]> 2006-10-11 * Luiz Henrique de Figueiredo <[email protected]> 07 Apr 2006 23:17:49 * Based on original by Claudio Terra for Lua 3.x. * With contributions by Roberto Ierusalimschy. * With documentation from Steve Donovan 2012 */ /*** General Library. Functions for separating a pathname into file and directory components. @module posix.libgen */ #include <config.h> #include <libgen.h> #include "_helpers.c" /*** File part of path. @function basename @string path file to act on @treturn string filename part of *path* @see basename(3) */ static int Pbasename(lua_State *L) { char *b; size_t len; void *ud; lua_Alloc lalloc; const char *path = luaL_checklstring(L, 1, &len); size_t path_len; checknargs(L, 1); path_len = strlen(path) + 1; lalloc = lua_getallocf(L, &ud); if ((b = lalloc(ud, NULL, 0, path_len)) == NULL) return pusherror(L, "lalloc"); lua_pushstring(L, basename(strcpy(b,path))); lalloc(ud, b, path_len, 0); return 1; } /*** Directory name of path. @function dirname @string path file to act on @treturn string directory part of *path* @see dirname(3) */ static int Pdirname(lua_State *L) { char *b; size_t len; void *ud; lua_Alloc lalloc; const char *path = luaL_checklstring(L, 1, &len); size_t path_len; checknargs(L, 1); path_len = strlen(path) + 1; lalloc = lua_getallocf(L, &ud); if ((b = lalloc(ud, NULL, 0, path_len)) == NULL) return pusherror(L, "lalloc"); lua_pushstring(L, dirname(strcpy(b,path))); lalloc(ud, b, path_len, 0); return 1; } static const luaL_Reg posix_libgen_fns[] = { LPOSIX_FUNC( Pbasename ), LPOSIX_FUNC( Pdirname ), {NULL, NULL} }; LUALIB_API int luaopen_posix_libgen(lua_State *L) { luaL_register(L, "posix.libgen", posix_libgen_fns); lua_pushliteral(L, "posix.libgen for " LUA_VERSION " / " PACKAGE_STRING); lua_setfield(L, -2, "version"); return 1; }
551570.c
/* * Copyright (C) 2005-2013 Junjiro R. Okajima * * This program, aufs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* * module global variables and operations */ #include <linux/module.h> #include <linux/seq_file.h> #include "aufs.h" void *au_kzrealloc(void *p, unsigned int nused, unsigned int new_sz, gfp_t gfp) { if (new_sz <= nused) return p; p = krealloc(p, new_sz, gfp); if (p) memset(p + nused, 0, new_sz - nused); return p; } /* ---------------------------------------------------------------------- */ /* * aufs caches */ struct kmem_cache *au_cachep[AuCache_Last]; static int __init au_cache_init(void) { au_cachep[AuCache_DINFO] = AuCacheCtor(au_dinfo, au_di_init_once); if (au_cachep[AuCache_DINFO]) /* SLAB_DESTROY_BY_RCU */ au_cachep[AuCache_ICNTNR] = AuCacheCtor(au_icntnr, au_icntnr_init_once); if (au_cachep[AuCache_ICNTNR]) au_cachep[AuCache_FINFO] = AuCacheCtor(au_finfo, au_fi_init_once); if (au_cachep[AuCache_FINFO]) au_cachep[AuCache_VDIR] = AuCache(au_vdir); if (au_cachep[AuCache_VDIR]) au_cachep[AuCache_DEHSTR] = AuCache(au_vdir_dehstr); if (au_cachep[AuCache_DEHSTR]) return 0; return -ENOMEM; } static void au_cache_fin(void) { int i; /* excluding AuCache_HNOTIFY */ BUILD_BUG_ON(AuCache_HNOTIFY + 1 != AuCache_Last); for (i = 0; i < AuCache_HNOTIFY; i++) if (au_cachep[i]) { kmem_cache_destroy(au_cachep[i]); au_cachep[i] = NULL; } } /* ---------------------------------------------------------------------- */ int au_dir_roflags; #ifdef CONFIG_AUFS_SBILIST struct au_splhead au_sbilist; #endif struct lock_class_key au_lc_key[AuLcKey_Last]; /* * functions for module interface. */ MODULE_LICENSE("GPL"); /* MODULE_LICENSE("GPL v2"); */ MODULE_AUTHOR("Junjiro R. Okajima <[email protected]>"); MODULE_DESCRIPTION(AUFS_NAME " -- Advanced multi layered unification filesystem"); MODULE_VERSION(AUFS_VERSION); /* this module parameter has no meaning when SYSFS is disabled */ int sysaufs_brs = 1; MODULE_PARM_DESC(brs, "use <sysfs>/fs/aufs/si_*/brN"); module_param_named(brs, sysaufs_brs, int, S_IRUGO); /* ---------------------------------------------------------------------- */ static char au_esc_chars[0x20 + 3]; /* 0x01-0x20, backslash, del, and NULL */ int au_seq_path(struct seq_file *seq, struct path *path) { return seq_path(seq, path, au_esc_chars); } /* ---------------------------------------------------------------------- */ static int __init aufs_init(void) { int err, i; char *p; p = au_esc_chars; for (i = 1; i <= ' '; i++) *p++ = i; *p++ = '\\'; *p++ = '\x7f'; *p = 0; au_dir_roflags = au_file_roflags(O_DIRECTORY | O_LARGEFILE); au_sbilist_init(); sysaufs_brs_init(); au_debug_init(); au_dy_init(); err = sysaufs_init(); if (unlikely(err)) goto out; err = au_procfs_init(); if (unlikely(err)) goto out_sysaufs; err = au_wkq_init(); if (unlikely(err)) goto out_procfs; err = au_loopback_init(); if (unlikely(err)) goto out_wkq; err = au_hnotify_init(); if (unlikely(err)) goto out_loopback; err = au_sysrq_init(); if (unlikely(err)) goto out_hin; err = au_cache_init(); if (unlikely(err)) goto out_sysrq; err = register_filesystem(&aufs_fs_type); if (unlikely(err)) goto out_cache; /* since we define pr_fmt, call printk directly */ printk(KERN_INFO AUFS_NAME " " AUFS_VERSION "\n"); goto out; /* success */ out_cache: au_cache_fin(); out_sysrq: au_sysrq_fin(); out_hin: au_hnotify_fin(); out_loopback: au_loopback_fin(); out_wkq: au_wkq_fin(); out_procfs: au_procfs_fin(); out_sysaufs: sysaufs_fin(); au_dy_fin(); out: return err; } static void __exit aufs_exit(void) { unregister_filesystem(&aufs_fs_type); au_cache_fin(); au_sysrq_fin(); au_hnotify_fin(); au_loopback_fin(); au_wkq_fin(); au_procfs_fin(); sysaufs_fin(); au_dy_fin(); } module_init(aufs_init); module_exit(aufs_exit);
26500.c
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * This file contains the function WebRtcSpl_AutoCorrelation(). * The description header can be found in signal_processing_library.h * */ #include "signal_processing_library.h" int WebRtcSpl_AutoCorrelation(G_CONST WebRtc_Word16* in_vector, int in_vector_length, int order, WebRtc_Word32* result, int* scale) { WebRtc_Word32 sum; int i, j; WebRtc_Word16 smax; // Sample max G_CONST WebRtc_Word16* xptr1; G_CONST WebRtc_Word16* xptr2; WebRtc_Word32* resultptr; int scaling = 0; #ifdef _ARM_OPT_ #pragma message("NOTE: _ARM_OPT_ optimizations are used") WebRtc_Word16 loops4; #endif if (order < 0) order = in_vector_length; // Find the max. sample smax = WebRtcSpl_MaxAbsValueW16(in_vector, in_vector_length); // In order to avoid overflow when computing the sum we should scale the samples so that // (in_vector_length * smax * smax) will not overflow. if (smax == 0) { scaling = 0; } else { int nbits = WebRtcSpl_GetSizeInBits(in_vector_length); // # of bits in the sum loop int t = WebRtcSpl_NormW32(WEBRTC_SPL_MUL(smax, smax)); // # of bits to normalize smax if (t > nbits) { scaling = 0; } else { scaling = nbits - t; } } resultptr = result; // Perform the actual correlation calculation for (i = 0; i < order + 1; i++) { int loops = (in_vector_length - i); sum = 0; xptr1 = in_vector; xptr2 = &in_vector[i]; #ifndef _ARM_OPT_ for (j = loops; j > 0; j--) { sum += WEBRTC_SPL_MUL_16_16_RSFT(*xptr1++, *xptr2++, scaling); } #else loops4 = (loops >> 2) << 2; if (scaling == 0) { for (j = 0; j < loops4; j = j + 4) { sum += WEBRTC_SPL_MUL_16_16(*xptr1, *xptr2); xptr1++; xptr2++; sum += WEBRTC_SPL_MUL_16_16(*xptr1, *xptr2); xptr1++; xptr2++; sum += WEBRTC_SPL_MUL_16_16(*xptr1, *xptr2); xptr1++; xptr2++; sum += WEBRTC_SPL_MUL_16_16(*xptr1, *xptr2); xptr1++; xptr2++; } for (j = loops4; j < loops; j++) { sum += WEBRTC_SPL_MUL_16_16(*xptr1, *xptr2); xptr1++; xptr2++; } } else { for (j = 0; j < loops4; j = j + 4) { sum += WEBRTC_SPL_MUL_16_16_RSFT(*xptr1, *xptr2, scaling); xptr1++; xptr2++; sum += WEBRTC_SPL_MUL_16_16_RSFT(*xptr1, *xptr2, scaling); xptr1++; xptr2++; sum += WEBRTC_SPL_MUL_16_16_RSFT(*xptr1, *xptr2, scaling); xptr1++; xptr2++; sum += WEBRTC_SPL_MUL_16_16_RSFT(*xptr1, *xptr2, scaling); xptr1++; xptr2++; } for (j = loops4; j < loops; j++) { sum += WEBRTC_SPL_MUL_16_16_RSFT(*xptr1, *xptr2, scaling); xptr1++; xptr2++; } } #endif *resultptr++ = sum; } *scale = scaling; return order + 1; }
576236.c
/******************************************************************************* * * DO NOT EDIT THIS FILE! * This file is auto-generated by fltg from Logical Table mapping files. * * Tool: $SDK/INTERNAL/fltg/bin/fltg * * Edits to this file will be lost when it is regenerated. * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ /* Logical Table Adaptor for component bcmltx */ /* Handler: bcm56880_a0_lta_bcmltx_fp_destination_cos_q_map_mc_q_fv_handler */ #include <bcmltd/chip/bcmltd_id.h> #include <bcmdrd/chip/bcm56880_a0_enum.h> #include <bcmltx/bcmtm/bcmltx_mc_q_validate.h> static const uint32_t bcm56880_a0_lta_bcmltx_fp_destination_cos_q_map_mc_q_validate_src[1] = { FP_DESTINATION_COS_Q_MAPt_MC_COSf, }; static const bcmltd_generic_arg_t bcm56880_a0_lta_bcmltx_fp_destination_cos_q_map_mc_q_comp_data = { .sid = FP_DESTINATION_COS_Q_MAPt, .values = 0, .value = NULL, .user_data = NULL }; const bcmltd_field_val_arg_t bcm56880_a0_lta_bcmltx_fp_destination_cos_q_map_mc_q_fv_handler_arg = { .values = 0, .value = NULL, .fields = 1, .field = bcm56880_a0_lta_bcmltx_fp_destination_cos_q_map_mc_q_validate_src, .comp_data = &bcm56880_a0_lta_bcmltx_fp_destination_cos_q_map_mc_q_comp_data }; const bcmltd_field_val_handler_t bcm56880_a0_lta_bcmltx_fp_destination_cos_q_map_mc_q_fv_handler = { .validate = bcmltx_mc_q_validate, .arg = &bcm56880_a0_lta_bcmltx_fp_destination_cos_q_map_mc_q_fv_handler_arg };
736064.c
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * Copyright 2016-2020 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include "fsl_sdmmc_host.h" #include "fsl_sdmmc_common.h" /******************************************************************************* * Definitions ******************************************************************************/ #define SDMMCHOST_TRANSFER_COMPLETE_TIMEOUT (~0U) /******************************************************************************* * Prototypes ******************************************************************************/ /*! * @brief SDMMCHOST detect card insert status by host controller. * @param base host base address. * @param userData user can register a application card insert callback through userData. */ static void SDMMCHOST_DetectCardInsertByHost(SDIF_Type *base, void *userData); /*! * @brief SDMMCHOST detect card remove status by host controller. * @param base host base address. * @param userData user can register a application card insert callback through userData. */ static void SDMMCHOST_DetectCardRemoveByHost(SDIF_Type *base, void *userData); /*! * @brief SDMMCHOST transfer complete callback. * @param base host base address. * @param handle host handle. * @param status interrupt status. * @param userData user data. */ static void SDMMCHOST_TransferCompleteCallback(SDIF_Type *base, void *handle, status_t status, void *userData); /*! * @brief SDMMCHOST error recovery. * @param base host base address. */ static void SDMMCHOST_ErrorRecovery(SDIF_Type *base); /******************************************************************************* * Variables ******************************************************************************/ /******************************************************************************* * Code ******************************************************************************/ static void SDMMCHOST_DetectCardInsertByHost(SDIF_Type *base, void *userData) { sd_detect_card_t *cd = NULL; (void)SDMMC_OSAEventSet(&(((sdmmchost_t *)userData)->hostEvent), SDMMC_OSA_EVENT_CARD_INSERTED); (void)SDMMC_OSAEventClear(&(((sdmmchost_t *)userData)->hostEvent), SDMMC_OSA_EVENT_CARD_REMOVED); if (userData != NULL) { cd = (sd_detect_card_t *)(((sdmmchost_t *)userData)->cd); if (cd != NULL) { if (cd->callback != NULL) { cd->callback(true, cd->userData); } } } } static void SDMMCHOST_DetectCardRemoveByHost(SDIF_Type *base, void *userData) { sd_detect_card_t *cd = NULL; (void)SDMMC_OSAEventSet(&(((sdmmchost_t *)userData)->hostEvent), SDMMC_OSA_EVENT_CARD_REMOVED); (void)SDMMC_OSAEventClear(&(((sdmmchost_t *)userData)->hostEvent), SDMMC_OSA_EVENT_CARD_INSERTED); if (userData != NULL) { cd = (sd_detect_card_t *)(((sdmmchost_t *)userData)->cd); if (cd != NULL) { if (cd->callback != NULL) { cd->callback(false, cd->userData); } } } } static void SDMMCHOST_CardInterrupt(SDIF_Type *base, void *userData) { sdio_card_int_t *cardInt = NULL; /* application callback */ if (userData != NULL) { cardInt = ((sdmmchost_t *)userData)->cardInt; if ((cardInt != NULL) && (cardInt->cardInterrupt != NULL)) { cardInt->cardInterrupt(cardInt->userData); } } } status_t SDMMCHOST_CardIntInit(sdmmchost_t *host, void *sdioInt) { host->cardInt = sdioInt; host->handle.callback.SDIOInterrupt = SDMMCHOST_CardInterrupt; SDMMCHOST_EnableCardInt(host, true); return kStatus_Success; } status_t SDMMCHOST_CardDetectInit(sdmmchost_t *host, void *cd) { SDIF_Type *base = host->hostController.base; sd_detect_card_t *sdCD = (sd_detect_card_t *)cd; if (cd == NULL) { return kStatus_Fail; } host->cd = cd; /* enable card detect interrupt */ SDIF_EnableInterrupt(base, kSDIF_CardDetect); if (SDMMCHOST_CardDetectStatus(host) == (uint32_t)kSD_Inserted) { (void)SDMMC_OSAEventSet(&(host->hostEvent), SDMMC_OSA_EVENT_CARD_INSERTED); /* notify application about the card insertion status */ if (sdCD->callback != NULL) { sdCD->callback(true, sdCD->userData); } } else { (void)SDMMC_OSAEventSet(&(host->hostEvent), SDMMC_OSA_EVENT_CARD_REMOVED); } return kStatus_Success; } uint32_t SDMMCHOST_CardDetectStatus(sdmmchost_t *host) { SDIF_Type *base = host->hostController.base; sd_detect_card_t *sdCD = (sd_detect_card_t *)host->cd; #if defined(FSL_FEATURE_SDIF_ONE_INSTANCE_SUPPORT_TWO_CARD) && FSL_FEATURE_SDIF_ONE_INSTANCE_SUPPORT_TWO_CARD if (((host->hostPort == 0U) && SDIF_DetectCardInsert(base, sdCD->type == kSD_DetectCardByHostDATA3 ? true : false)) || ((host->hostPort == 1U) && SDIF_DetectCard1Insert(base, sdCD->type == kSD_DetectCardByHostDATA3 ? true : false))) #else if ((host->hostPort == 0U) && (SDIF_DetectCardInsert(base, sdCD->type == kSD_DetectCardByHostDATA3 ? true : false) == 1U)) #endif { return kSD_Inserted; } return kSD_Removed; } status_t SDMMCHOST_PollingCardDetectStatus(sdmmchost_t *host, uint32_t waitCardStatus, uint32_t timeout) { assert(host != NULL); assert(host->cd != NULL); sd_detect_card_t *cd = host->cd; uint32_t event = 0U; (void)SDMMC_OSAEventGet(&(host->hostEvent), SDMMC_OSA_EVENT_CARD_INSERTED | SDMMC_OSA_EVENT_CARD_REMOVED, &event); if ((((event & SDMMC_OSA_EVENT_CARD_INSERTED) == SDMMC_OSA_EVENT_CARD_INSERTED) && (waitCardStatus == (uint32_t)kSD_Inserted)) || (((event & SDMMC_OSA_EVENT_CARD_REMOVED) == SDMMC_OSA_EVENT_CARD_REMOVED) && (waitCardStatus == (uint32_t)kSD_Removed))) { return kStatus_Success; } /* Wait card inserted. */ do { if (SDMMC_OSAEventWait(&(host->hostEvent), SDMMC_OSA_EVENT_CARD_INSERTED | SDMMC_OSA_EVENT_CARD_REMOVED, timeout, &event) != kStatus_Success) { return kStatus_Fail; } else { if ((waitCardStatus == (uint32_t)kSD_Inserted) && ((event & SDMMC_OSA_EVENT_CARD_INSERTED) == SDMMC_OSA_EVENT_CARD_INSERTED)) { SDMMC_OSADelay(cd->cdDebounce_ms); if (SDMMCHOST_CardDetectStatus(host) == (uint32_t)kSD_Inserted) { break; } } if (((event & SDMMC_OSA_EVENT_CARD_REMOVED) == SDMMC_OSA_EVENT_CARD_REMOVED) && (waitCardStatus == (uint32_t)kSD_Removed)) { break; } } } while (true); return kStatus_Success; } status_t SDMMCHOST_WaitCardDetectStatus(SDMMCHOST_TYPE *hostBase, const sdmmchost_detect_card_t *cd, bool waitCardStatus) { assert(cd != NULL); while (SDIF_DetectCardInsert(hostBase, false) != (uint32_t)waitCardStatus) { } return kStatus_Success; } static void SDMMCHOST_TransferCompleteCallback(SDIF_Type *base, void *handle, status_t status, void *userData) { uint32_t eventStatus = 0U; if (status == kStatus_SDIF_DataTransferFail) { eventStatus = SDMMC_OSA_EVENT_TRANSFER_DATA_FAIL; } else if (status == kStatus_SDIF_DataTransferSuccess) { eventStatus = SDMMC_OSA_EVENT_TRANSFER_DATA_SUCCESS; } else if (status == kStatus_SDIF_SendCmdFail) { eventStatus = SDMMC_OSA_EVENT_TRANSFER_CMD_FAIL; } else { eventStatus = SDMMC_OSA_EVENT_TRANSFER_CMD_SUCCESS; } (void)SDMMC_OSAEventSet(&(((sdmmchost_t *)userData)->hostEvent), eventStatus); } status_t SDMMCHOST_TransferFunction(sdmmchost_t *host, sdmmchost_transfer_t *content) { status_t error = kStatus_Success; uint32_t event = 0U; sdif_dma_config_t dmaConfig; /* clear redundant transfer event flag */ (void)SDMMC_OSAEventClear(&(host->hostEvent), SDMMC_OSA_EVENT_TRANSFER_CMD_SUCCESS | SDMMC_OSA_EVENT_TRANSFER_CMD_FAIL | SDMMC_OSA_EVENT_TRANSFER_DATA_SUCCESS | SDMMC_OSA_EVENT_TRANSFER_DATA_FAIL); /* user DMA mode transfer data */ if (content->data != NULL) { (void)memset(&dmaConfig, 0, sizeof(dmaConfig)); dmaConfig.enableFixBurstLen = false; dmaConfig.mode = kSDIF_DualDMAMode; dmaConfig.dmaDesBufferStartAddr = host->dmaDesBuffer; dmaConfig.dmaDesBufferLen = host->dmaDesBufferWordsNum; dmaConfig.dmaDesSkipLen = 0U; } do { error = SDIF_TransferNonBlocking(host->hostController.base, &host->handle, &dmaConfig, content); } while (error == kStatus_SDIF_SyncCmdTimeout); if (error == kStatus_Success) { /* wait command event */ if ((kStatus_Fail == SDMMC_OSAEventWait(&(host->hostEvent), SDMMC_OSA_EVENT_TRANSFER_CMD_SUCCESS | SDMMC_OSA_EVENT_TRANSFER_CMD_FAIL | SDMMC_OSA_EVENT_TRANSFER_DATA_SUCCESS | SDMMC_OSA_EVENT_TRANSFER_DATA_FAIL, SDMMCHOST_TRANSFER_COMPLETE_TIMEOUT, &event)) || ((event & SDMMC_OSA_EVENT_TRANSFER_CMD_FAIL) != 0U)) { error = kStatus_Fail; } else { if (content->data != NULL) { if ((event & SDMMC_OSA_EVENT_TRANSFER_DATA_SUCCESS) == 0U) { if (((event & SDMMC_OSA_EVENT_TRANSFER_DATA_FAIL) != 0U) || (kStatus_Fail == SDMMC_OSAEventWait( &(host->hostEvent), SDMMC_OSA_EVENT_TRANSFER_DATA_SUCCESS | SDMMC_OSA_EVENT_TRANSFER_DATA_FAIL, SDMMCHOST_TRANSFER_COMPLETE_TIMEOUT, &event) || ((event & SDMMC_OSA_EVENT_TRANSFER_DATA_FAIL) != 0U))) { error = kStatus_Fail; } } } } } /* * error = kStatus_SDIF_DescriptorBufferLenError means that the DMA descriptor buffer not len enough for current * transfer, application should assign a bigger descriptor memory space. */ else { error = kStatus_Fail; /* host error recovery */ SDMMCHOST_ErrorRecovery(host->hostController.base); } return error; } static void SDMMCHOST_ErrorRecovery(SDIF_Type *base) { (void)SDIF_Reset(base, kSDIF_ResetAll, SDMMCHOST_RESET_TIMEOUT_VALUE); /* the host controller clock will be disabled by the reset operation, so re-send the clock sync command to enable the output clock */ sdif_command_t clockSync = { .flags = kSDIF_WaitPreTransferComplete | kSDIF_CmdUpdateClockRegisterOnly, .index = 0U, .argument = 0U}; (void)SDIF_SendCommand(base, &clockSync, 0U); } void SDMMCHOST_SetCardPower(sdmmchost_t *host, bool enable) { if (host->hostPort == 0U) { SDIF_EnableCardPower(host->hostController.base, enable); } #if defined(FSL_FEATURE_SDIF_ONE_INSTANCE_SUPPORT_TWO_CARD) && FSL_FEATURE_SDIF_ONE_INSTANCE_SUPPORT_TWO_CARD else { SDIF_EnableCard1Power(host->hostController.base, enable); } #endif if (enable) { /* perform SDIF host controller reset only when DATA BUSY is assert */ if ((SDIF_GetControllerStatus(host->hostController.base) & SDIF_STATUS_DATA_BUSY_MASK) != 0U) { (void)SDIF_Reset(host->hostController.base, kSDIF_ResetAll, SDMMCHOST_RESET_TIMEOUT_VALUE); } } } void SDMMCHOST_PowerOffCard(SDMMCHOST_TYPE *base, const sdmmchost_pwr_card_t *pwr) { if (pwr != NULL) { pwr->powerOff(); SDMMC_OSADelay(pwr->powerOffDelay_ms); } else { /* disable the card power */ SDIF_EnableCardPower(base, false); /* Delay several milliseconds to make card stable. */ SDMMC_OSADelay(500U); } } void SDMMCHOST_PowerOnCard(SDMMCHOST_TYPE *base, const sdmmchost_pwr_card_t *pwr) { /* use user define the power on function */ if (pwr != NULL) { pwr->powerOn(); SDMMC_OSADelay(pwr->powerOnDelay_ms); } else { /* Enable the card power */ SDIF_EnableCardPower(base, true); /* Delay several milliseconds to make card stable. */ SDMMC_OSADelay(500U); } /* perform SDIF host controller reset only when DATA BUSY is assert */ if ((SDIF_GetControllerStatus(base) & SDIF_STATUS_DATA_BUSY_MASK) != 0U) { (void)SDIF_Reset(base, kSDIF_ResetAll, SDMMCHOST_RESET_TIMEOUT_VALUE); } } status_t SDMMCHOST_Init(sdmmchost_t *host) { assert(host != NULL); sdif_transfer_callback_t sdifCallback = {0}; sdif_host_t *sdifHost = &(host->hostController); /* sdmmc osa init */ SDMMC_OSAInit(); /* Initialize SDIF. */ sdifHost->config.endianMode = (uint32_t)kSDMMCHOST_EndianModeLittle; sdifHost->config.responseTimeout = 0xFFU; sdifHost->config.cardDetDebounce_Clock = 0xFFFFFFU; sdifHost->config.dataTimeout = 0xFFFFFFU; SDIF_Init(sdifHost->base, &(sdifHost->config)); /* Create handle for SDIF driver */ sdifCallback.TransferComplete = SDMMCHOST_TransferCompleteCallback; sdifCallback.cardInserted = SDMMCHOST_DetectCardInsertByHost; sdifCallback.cardRemoved = SDMMCHOST_DetectCardRemoveByHost; SDIF_TransferCreateHandle(sdifHost->base, &host->handle, &sdifCallback, host); /* Create transfer event. */ if (kStatus_Success != SDMMC_OSAEventCreate(&(host->hostEvent))) { return kStatus_Fail; } return kStatus_Success; } void SDMMCHOST_Reset(sdmmchost_t *host) { /* make sure host controller release all the bus line. */ (void)SDIF_Reset(host->hostController.base, kSDIF_ResetAll, SDMMCHOST_RESET_TIMEOUT_VALUE); } void SDMMCHOST_SetCardBusWidth(sdmmchost_t *host, uint32_t dataBusWidth) { if (host->hostPort == 0U) { SDIF_SetCardBusWidth(host->hostController.base, dataBusWidth == (uint32_t)kSDMMC_BusWdith1Bit ? kSDIF_Bus1BitWidth : dataBusWidth == (uint32_t)kSDMMC_BusWdith4Bit ? kSDIF_Bus4BitWidth : kSDIF_Bus8BitWidth); } #if defined(FSL_FEATURE_SDIF_ONE_INSTANCE_SUPPORT_TWO_CARD) && FSL_FEATURE_SDIF_ONE_INSTANCE_SUPPORT_TWO_CARD else { SDIF_SetCard1BusWidth(host->hostController.base, dataBusWidth == (uint32_t)kSDMMC_BusWdith1Bit ? kSDIF_Bus1BitWidth : dataBusWidth == (uint32_t)kSDMMC_BusWdith4Bit ? kSDIF_Bus4BitWidth : kSDIF_Bus8BitWidth); } #endif } void SDMMCHOST_Deinit(sdmmchost_t *host) { sdif_host_t *sdifHost = &host->hostController; SDIF_Deinit(sdifHost->base); (void)SDMMC_OSAEventDestroy(&(host->hostEvent)); } status_t SDMMCHOST_StartBoot(sdmmchost_t *host, sdmmchost_boot_config_t *hostConfig, sdmmchost_cmd_t *cmd, uint8_t *buffer) { /* not support */ return kStatus_Success; } status_t SDMMCHOST_ReadBootData(sdmmchost_t *host, sdmmchost_boot_config_t *hostConfig, uint8_t *buffer) { /* not support */ return kStatus_Success; }
799826.c
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define CONFIG_FFT_FLOAT 1 #define CONFIG_FFT_FIXED_32 0 #include "fft.c"
802080.c
/* * fs/cifs/smb2pdu.c * * Copyright (C) International Business Machines Corp., 2009, 2013 * Etersoft, 2012 * Author(s): Steve French ([email protected]) * Pavel Shilovsky ([email protected]) 2012 * * Contains the routines for constructing the SMB2 PDUs themselves * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */ /* Note that there are handle based routines which must be */ /* treated slightly differently for reconnection purposes since we never */ /* want to reuse a stale file handle and only the caller knows the file info */ #include <linux/fs.h> #include <linux/kernel.h> #include <linux/vfs.h> #include <linux/task_io_accounting_ops.h> #include <linux/uaccess.h> #include <linux/uuid.h> #include <linux/pagemap.h> #include <linux/xattr.h> #include "smb2pdu.h" #include "cifsglob.h" #include "cifsacl.h" #include "cifsproto.h" #include "smb2proto.h" #include "cifs_unicode.h" #include "cifs_debug.h" #include "ntlmssp.h" #include "smb2status.h" #include "smb2glob.h" #include "cifspdu.h" #include "cifs_spnego.h" /* * The following table defines the expected "StructureSize" of SMB2 requests * in order by SMB2 command. This is similar to "wct" in SMB/CIFS requests. * * Note that commands are defined in smb2pdu.h in le16 but the array below is * indexed by command in host byte order. */ static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = { /* SMB2_NEGOTIATE */ 36, /* SMB2_SESSION_SETUP */ 25, /* SMB2_LOGOFF */ 4, /* SMB2_TREE_CONNECT */ 9, /* SMB2_TREE_DISCONNECT */ 4, /* SMB2_CREATE */ 57, /* SMB2_CLOSE */ 24, /* SMB2_FLUSH */ 24, /* SMB2_READ */ 49, /* SMB2_WRITE */ 49, /* SMB2_LOCK */ 48, /* SMB2_IOCTL */ 57, /* SMB2_CANCEL */ 4, /* SMB2_ECHO */ 4, /* SMB2_QUERY_DIRECTORY */ 33, /* SMB2_CHANGE_NOTIFY */ 32, /* SMB2_QUERY_INFO */ 41, /* SMB2_SET_INFO */ 33, /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */ }; static int encryption_required(const struct cifs_tcon *tcon) { if (!tcon) return 0; if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) || (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA)) return 1; if (tcon->seal && (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)) return 1; return 0; } static void smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd, const struct cifs_tcon *tcon) { shdr->ProtocolId = SMB2_PROTO_NUMBER; shdr->StructureSize = cpu_to_le16(64); shdr->Command = smb2_cmd; if (tcon && tcon->ses && tcon->ses->server) { struct TCP_Server_Info *server = tcon->ses->server; spin_lock(&server->req_lock); /* Request up to 2 credits but don't go over the limit. */ if (server->credits >= server->max_credits) shdr->CreditRequest = cpu_to_le16(0); else shdr->CreditRequest = cpu_to_le16( min_t(int, server->max_credits - server->credits, 2)); spin_unlock(&server->req_lock); } else { shdr->CreditRequest = cpu_to_le16(2); } shdr->ProcessId = cpu_to_le32((__u16)current->tgid); if (!tcon) goto out; /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */ /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */ if ((tcon->ses) && (tcon->ses->server) && (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU)) shdr->CreditCharge = cpu_to_le16(1); /* else CreditCharge MBZ */ shdr->TreeId = tcon->tid; /* Uid is not converted */ if (tcon->ses) shdr->SessionId = tcon->ses->Suid; /* * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have * to pass the path on the Open SMB prefixed by \\server\share. * Not sure when we would need to do the augmented path (if ever) and * setting this flag breaks the SMB2 open operation since it is * illegal to send an empty path name (without \\server\share prefix) * when the DFS flag is set in the SMB open header. We could * consider setting the flag on all operations other than open * but it is safer to net set it for now. */ /* if (tcon->share_flags & SHI1005_FLAGS_DFS) shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */ if (tcon->ses && tcon->ses->server && tcon->ses->server->sign && !encryption_required(tcon)) shdr->Flags |= SMB2_FLAGS_SIGNED; out: return; } static int smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon) { int rc = 0; struct nls_table *nls_codepage; struct cifs_ses *ses; struct TCP_Server_Info *server; /* * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so * check for tcp and smb session status done differently * for those three - in the calling routine. */ if (tcon == NULL) return rc; if (smb2_command == SMB2_TREE_CONNECT) return rc; if (tcon->tidStatus == CifsExiting) { /* * only tree disconnect, open, and write, * (and ulogoff which does not have tcon) * are allowed as we start force umount. */ if ((smb2_command != SMB2_WRITE) && (smb2_command != SMB2_CREATE) && (smb2_command != SMB2_TREE_DISCONNECT)) { cifs_dbg(FYI, "can not send cmd %d while umounting\n", smb2_command); return -ENODEV; } } if ((!tcon->ses) || (tcon->ses->status == CifsExiting) || (!tcon->ses->server)) return -EIO; ses = tcon->ses; server = ses->server; /* * Give demultiplex thread up to 10 seconds to reconnect, should be * greater than cifs socket timeout which is 7 seconds */ while (server->tcpStatus == CifsNeedReconnect) { /* * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE * here since they are implicitly done when session drops. */ switch (smb2_command) { /* * BB Should we keep oplock break and add flush to exceptions? */ case SMB2_TREE_DISCONNECT: case SMB2_CANCEL: case SMB2_CLOSE: case SMB2_OPLOCK_BREAK: return -EAGAIN; } wait_event_interruptible_timeout(server->response_q, (server->tcpStatus != CifsNeedReconnect), 10 * HZ); /* are we still trying to reconnect? */ if (server->tcpStatus != CifsNeedReconnect) break; /* * on "soft" mounts we wait once. Hard mounts keep * retrying until process is killed or server comes * back on-line */ if (!tcon->retry) { cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n"); return -EHOSTDOWN; } } if (!tcon->ses->need_reconnect && !tcon->need_reconnect) return rc; nls_codepage = load_nls_default(); /* * need to prevent multiple threads trying to simultaneously reconnect * the same SMB session */ mutex_lock(&tcon->ses->session_mutex); /* * Recheck after acquire mutex. If another thread is negotiating * and the server never sends an answer the socket will be closed * and tcpStatus set to reconnect. */ if (server->tcpStatus == CifsNeedReconnect) { rc = -EHOSTDOWN; mutex_unlock(&tcon->ses->session_mutex); goto out; } rc = cifs_negotiate_protocol(0, tcon->ses); if (!rc && tcon->ses->need_reconnect) rc = cifs_setup_session(0, tcon->ses, nls_codepage); if (rc || !tcon->need_reconnect) { mutex_unlock(&tcon->ses->session_mutex); goto out; } cifs_mark_open_files_invalid(tcon); if (tcon->use_persistent) tcon->need_reopen_files = true; rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage); mutex_unlock(&tcon->ses->session_mutex); cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc); if (rc) goto out; if (smb2_command != SMB2_INTERNAL_CMD) queue_delayed_work(cifsiod_wq, &server->reconnect, 0); atomic_inc(&tconInfoReconnectCount); out: /* * Check if handle based operation so we know whether we can continue * or not without returning to caller to reset file handle. */ /* * BB Is flush done by server on drop of tcp session? Should we special * case it and skip above? */ switch (smb2_command) { case SMB2_FLUSH: case SMB2_READ: case SMB2_WRITE: case SMB2_LOCK: case SMB2_IOCTL: case SMB2_QUERY_DIRECTORY: case SMB2_CHANGE_NOTIFY: case SMB2_QUERY_INFO: case SMB2_SET_INFO: rc = -EAGAIN; } unload_nls(nls_codepage); return rc; } static void fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf, unsigned int *total_len) { struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf; /* lookup word count ie StructureSize from table */ __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)]; /* * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of * largest operations (Create) */ memset(buf, 0, 256); smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon); spdu->StructureSize2 = cpu_to_le16(parmsize); *total_len = parmsize + sizeof(struct smb2_sync_hdr); } /* init request without RFC1001 length at the beginning */ static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon, void **request_buf, unsigned int *total_len) { int rc; struct smb2_sync_hdr *shdr; rc = smb2_reconnect(smb2_command, tcon); if (rc) return rc; /* BB eventually switch this to SMB2 specific small buf size */ *request_buf = cifs_small_buf_get(); if (*request_buf == NULL) { /* BB should we add a retry in here if not a writepage? */ return -ENOMEM; } shdr = (struct smb2_sync_hdr *)(*request_buf); fill_small_buf(smb2_command, tcon, shdr, total_len); if (tcon != NULL) { #ifdef CONFIG_CIFS_STATS2 uint16_t com_code = le16_to_cpu(smb2_command); cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]); #endif cifs_stats_inc(&tcon->num_smbs_sent); } return rc; } /* * Allocate and return pointer to an SMB request hdr, and set basic * SMB information in the SMB header. If the return code is zero, this * function must have filled in request_buf pointer. The returned buffer * has RFC1001 length at the beginning. */ static int small_smb2_init(__le16 smb2_command, struct cifs_tcon *tcon, void **request_buf) { int rc; unsigned int total_len; struct smb2_pdu *pdu; rc = smb2_reconnect(smb2_command, tcon); if (rc) return rc; /* BB eventually switch this to SMB2 specific small buf size */ *request_buf = cifs_small_buf_get(); if (*request_buf == NULL) { /* BB should we add a retry in here if not a writepage? */ return -ENOMEM; } pdu = (struct smb2_pdu *)(*request_buf); fill_small_buf(smb2_command, tcon, get_sync_hdr(pdu), &total_len); /* Note this is only network field converted to big endian */ pdu->hdr.smb2_buf_length = cpu_to_be32(total_len); if (tcon != NULL) { #ifdef CONFIG_CIFS_STATS2 uint16_t com_code = le16_to_cpu(smb2_command); cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]); #endif cifs_stats_inc(&tcon->num_smbs_sent); } return rc; } #ifdef CONFIG_CIFS_SMB311 /* offset is sizeof smb2_negotiate_req - 4 but rounded up to 8 bytes */ #define OFFSET_OF_NEG_CONTEXT 0x68 /* sizeof(struct smb2_negotiate_req) - 4 */ #define SMB2_PREAUTH_INTEGRITY_CAPABILITIES cpu_to_le16(1) #define SMB2_ENCRYPTION_CAPABILITIES cpu_to_le16(2) static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt) { pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES; pneg_ctxt->DataLength = cpu_to_le16(38); pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1); pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE); get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE); pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512; } static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt) { pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES; pneg_ctxt->DataLength = cpu_to_le16(6); pneg_ctxt->CipherCount = cpu_to_le16(2); pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM; pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM; } static void assemble_neg_contexts(struct smb2_negotiate_req *req) { /* +4 is to account for the RFC1001 len field */ char *pneg_ctxt = (char *)req + OFFSET_OF_NEG_CONTEXT + 4; build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt); /* Add 2 to size to round to 8 byte boundary */ pneg_ctxt += 2 + sizeof(struct smb2_preauth_neg_context); build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt); req->NegotiateContextOffset = cpu_to_le32(OFFSET_OF_NEG_CONTEXT); req->NegotiateContextCount = cpu_to_le16(2); inc_rfc1001_len(req, 4 + sizeof(struct smb2_preauth_neg_context) + sizeof(struct smb2_encryption_neg_context)); /* calculate hash */ } #else static void assemble_neg_contexts(struct smb2_negotiate_req *req) { return; } #endif /* SMB311 */ /* * * SMB2 Worker functions follow: * * The general structure of the worker functions is: * 1) Call smb2_init (assembles SMB2 header) * 2) Initialize SMB2 command specific fields in fixed length area of SMB * 3) Call smb_sendrcv2 (sends request on socket and waits for response) * 4) Decode SMB2 command specific fields in the fixed length area * 5) Decode variable length data area (if any for this SMB2 command type) * 6) Call free smb buffer * 7) return * */ int SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses) { struct smb2_negotiate_req *req; struct smb2_negotiate_rsp *rsp; struct kvec iov[1]; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct TCP_Server_Info *server = ses->server; int blob_offset, blob_length; char *security_blob; int flags = CIFS_NEG_OP; cifs_dbg(FYI, "Negotiate protocol\n"); if (!server) { WARN(1, "%s: server is NULL!\n", __func__); return -EIO; } rc = small_smb2_init(SMB2_NEGOTIATE, NULL, (void **) &req); if (rc) return rc; req->hdr.sync_hdr.SessionId = 0; if (strcmp(ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID); req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID); req->DialectCount = cpu_to_le16(2); inc_rfc1001_len(req, 4); } else if (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID); req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID); req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID); req->DialectCount = cpu_to_le16(3); inc_rfc1001_len(req, 6); } else { /* otherwise send specific dialect */ req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id); req->DialectCount = cpu_to_le16(1); inc_rfc1001_len(req, 2); } /* only one of SMB2 signing flags may be set in SMB2 request */ if (ses->sign) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED); else if (global_secflags & CIFSSEC_MAY_SIGN) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED); else req->SecurityMode = 0; req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities); /* ClientGUID must be zero for SMB2.02 dialect */ if (ses->server->vals->protocol_id == SMB20_PROT_ID) memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE); else { memcpy(req->ClientGUID, server->client_guid, SMB2_CLIENT_GUID_SIZE); if (ses->server->vals->protocol_id == SMB311_PROT_ID) assemble_neg_contexts(req); } iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base; /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ if (rc == -EOPNOTSUPP) { cifs_dbg(VFS, "Dialect not supported by server. Consider " "specifying vers=1.0 or vers=2.0 on mount for accessing" " older servers\n"); goto neg_exit; } else if (rc != 0) goto neg_exit; if (strcmp(ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) { cifs_dbg(VFS, "SMB2 dialect returned but not requested\n"); return -EIO; } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) { cifs_dbg(VFS, "SMB2.1 dialect returned but not requested\n"); return -EIO; } } else if (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) { cifs_dbg(VFS, "SMB2 dialect returned but not requested\n"); return -EIO; } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) { /* ops set to 3.0 by default for default so update */ ses->server->ops = &smb21_operations; } } else if (le16_to_cpu(rsp->DialectRevision) != ses->server->vals->protocol_id) { /* if requested single dialect ensure returned dialect matched */ cifs_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n", le16_to_cpu(rsp->DialectRevision)); return -EIO; } cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode); if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) cifs_dbg(FYI, "negotiated smb2.0 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) cifs_dbg(FYI, "negotiated smb2.1 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.0 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.02 dialect\n"); #ifdef CONFIG_CIFS_SMB311 else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n"); #endif /* SMB311 */ else { cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n", le16_to_cpu(rsp->DialectRevision)); rc = -EIO; goto neg_exit; } server->dialect = le16_to_cpu(rsp->DialectRevision); /* BB: add check that dialect was valid given dialect(s) we asked for */ /* SMB2 only has an extended negflavor */ server->negflavor = CIFS_NEGFLAVOR_EXTENDED; /* set it to the maximum buffer size value we can send with 1 credit */ server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize), SMB2_MAX_BUFFER_SIZE); server->max_read = le32_to_cpu(rsp->MaxReadSize); server->max_write = le32_to_cpu(rsp->MaxWriteSize); /* BB Do we need to validate the SecurityMode? */ server->sec_mode = le16_to_cpu(rsp->SecurityMode); server->capabilities = le32_to_cpu(rsp->Capabilities); /* Internal types */ server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES; security_blob = smb2_get_data_area_len(&blob_offset, &blob_length, &rsp->hdr); /* * See MS-SMB2 section 2.2.4: if no blob, client picks default which * for us will be * ses->sectype = RawNTLMSSP; * but for time being this is our only auth choice so doesn't matter. * We just found a server which sets blob length to zero expecting raw. */ if (blob_length == 0) { cifs_dbg(FYI, "missing security blob on negprot\n"); server->sec_ntlmssp = true; } rc = cifs_enable_signing(server, ses->sign); if (rc) goto neg_exit; if (blob_length) { rc = decode_negTokenInit(security_blob, blob_length, server); if (rc == 1) rc = 0; else if (rc == 0) rc = -EIO; } neg_exit: free_rsp_buf(resp_buftype, rsp); return rc; } int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon) { int rc = 0; struct validate_negotiate_info_req vneg_inbuf; struct validate_negotiate_info_rsp *pneg_rsp = NULL; u32 rsplen; u32 inbuflen; /* max of 4 dialects */ cifs_dbg(FYI, "validate negotiate\n"); /* * validation ioctl must be signed, so no point sending this if we * can not sign it (ie are not known user). Even if signing is not * required (enabled but not negotiated), in those cases we selectively * sign just this, the first and only signed request on a connection. * Having validation of negotiate info helps reduce attack vectors. */ if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) return 0; /* validation requires signing */ if (tcon->ses->user_name == NULL) { cifs_dbg(FYI, "Can't validate negotiate: null user mount\n"); return 0; /* validation requires signing */ } if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL) cifs_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n"); vneg_inbuf.Capabilities = cpu_to_le32(tcon->ses->server->vals->req_capabilities); memcpy(vneg_inbuf.Guid, tcon->ses->server->client_guid, SMB2_CLIENT_GUID_SIZE); if (tcon->ses->sign) vneg_inbuf.SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED); else if (global_secflags & CIFSSEC_MAY_SIGN) vneg_inbuf.SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED); else vneg_inbuf.SecurityMode = 0; if (strcmp(tcon->ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { vneg_inbuf.Dialects[0] = cpu_to_le16(SMB30_PROT_ID); vneg_inbuf.Dialects[1] = cpu_to_le16(SMB302_PROT_ID); vneg_inbuf.DialectCount = cpu_to_le16(2); /* structure is big enough for 3 dialects, sending only 2 */ inbuflen = sizeof(struct validate_negotiate_info_req) - 2; } else if (strcmp(tcon->ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { vneg_inbuf.Dialects[0] = cpu_to_le16(SMB21_PROT_ID); vneg_inbuf.Dialects[1] = cpu_to_le16(SMB30_PROT_ID); vneg_inbuf.Dialects[2] = cpu_to_le16(SMB302_PROT_ID); vneg_inbuf.DialectCount = cpu_to_le16(3); /* structure is big enough for 3 dialects */ inbuflen = sizeof(struct validate_negotiate_info_req); } else { /* otherwise specific dialect was requested */ vneg_inbuf.Dialects[0] = cpu_to_le16(tcon->ses->server->vals->protocol_id); vneg_inbuf.DialectCount = cpu_to_le16(1); /* structure is big enough for 3 dialects, sending only 1 */ inbuflen = sizeof(struct validate_negotiate_info_req) - 4; } rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID, FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */, false /* use_ipc */, (char *)&vneg_inbuf, sizeof(struct validate_negotiate_info_req), (char **)&pneg_rsp, &rsplen); if (rc != 0) { cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc); return -EIO; } if (rsplen != sizeof(struct validate_negotiate_info_rsp)) { cifs_dbg(VFS, "invalid protocol negotiate response size: %d\n", rsplen); /* relax check since Mac returns max bufsize allowed on ioctl */ if ((rsplen > CIFSMaxBufSize) || (rsplen < sizeof(struct validate_negotiate_info_rsp))) goto err_rsp_free; } /* check validate negotiate info response matches what we got earlier */ if (pneg_rsp->Dialect != cpu_to_le16(tcon->ses->server->vals->protocol_id)) goto vneg_out; if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode)) goto vneg_out; /* do not validate server guid because not saved at negprot time yet */ if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND | SMB2_LARGE_FILES) != tcon->ses->server->capabilities) goto vneg_out; /* validate negotiate successful */ cifs_dbg(FYI, "validate negotiate info successful\n"); kfree(pneg_rsp); return 0; vneg_out: cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n"); err_rsp_free: kfree(pneg_rsp); return -EIO; } enum securityEnum smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested) { switch (requested) { case Kerberos: case RawNTLMSSP: return requested; case NTLMv2: return RawNTLMSSP; case Unspecified: if (server->sec_ntlmssp && (global_secflags & CIFSSEC_MAY_NTLMSSP)) return RawNTLMSSP; if ((server->sec_kerberos || server->sec_mskerberos) && (global_secflags & CIFSSEC_MAY_KRB5)) return Kerberos; /* Fallthrough */ default: return Unspecified; } } struct SMB2_sess_data { unsigned int xid; struct cifs_ses *ses; struct nls_table *nls_cp; void (*func)(struct SMB2_sess_data *); int result; u64 previous_session; /* we will send the SMB in three pieces: * a fixed length beginning part, an optional * SPNEGO blob (which can be zero length), and a * last part which will include the strings * and rest of bcc area. This allows us to avoid * a large buffer 17K allocation */ int buf0_type; struct kvec iov[2]; }; static int SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_req *req; struct TCP_Server_Info *server = ses->server; rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req); if (rc) return rc; /* First session, not a reauthenticate */ req->hdr.sync_hdr.SessionId = 0; /* if reconnect, we need to send previous sess id, otherwise it is 0 */ req->PreviousSessionId = sess_data->previous_session; req->Flags = 0; /* MBZ */ /* to enable echos and oplocks */ req->hdr.sync_hdr.CreditRequest = cpu_to_le16(3); /* only one of SMB2 signing flags may be set in SMB2 request */ if (server->sign) req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED; else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */ req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED; else req->SecurityMode = 0; req->Capabilities = 0; req->Channel = 0; /* MBZ */ sess_data->iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for pad */ sess_data->iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* * This variable will be used to clear the buffer * allocated above in case of any error in the calling function. */ sess_data->buf0_type = CIFS_SMALL_BUFFER; return 0; } static void SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data) { free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base); sess_data->buf0_type = CIFS_NO_BUFFER; } static int SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data) { int rc; struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base; struct kvec rsp_iov = { NULL, 0 }; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->SecurityBufferOffset = cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */ - 4 /* rfc1001 len */); req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len); inc_rfc1001_len(req, sess_data->iov[1].iov_len - 1 /* pad */); /* BB add code to build os and lm fields */ rc = SendReceive2(sess_data->xid, sess_data->ses, sess_data->iov, 2, &sess_data->buf0_type, CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov); cifs_small_buf_release(sess_data->iov[0].iov_base); memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec)); return rc; } static int SMB2_sess_establish_session(struct SMB2_sess_data *sess_data) { int rc = 0; struct cifs_ses *ses = sess_data->ses; mutex_lock(&ses->server->srv_mutex); if (ses->server->ops->generate_signingkey) { rc = ses->server->ops->generate_signingkey(ses); if (rc) { cifs_dbg(FYI, "SMB3 session key generation failed\n"); mutex_unlock(&ses->server->srv_mutex); return rc; } } if (!ses->server->session_estab) { ses->server->sequence_number = 0x2; ses->server->session_estab = true; } mutex_unlock(&ses->server->srv_mutex); cifs_dbg(FYI, "SMB2/3 session established successfully\n"); spin_lock(&GlobalMid_Lock); ses->status = CifsGood; ses->need_reconnect = false; spin_unlock(&GlobalMid_Lock); return rc; } #ifdef CONFIG_CIFS_UPCALL static void SMB2_auth_kerberos(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct cifs_spnego_msg *msg; struct key *spnego_key = NULL; struct smb2_sess_setup_rsp *rsp = NULL; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out; spnego_key = cifs_get_spnego_key(ses); if (IS_ERR(spnego_key)) { rc = PTR_ERR(spnego_key); spnego_key = NULL; goto out; } msg = spnego_key->payload.data[0]; /* * check version field to make sure that cifs.upcall is * sending us a response in an expected form */ if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) { cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d", CIFS_SPNEGO_UPCALL_VERSION, msg->version); rc = -EKEYREJECTED; goto out_put_spnego_key; } ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len, GFP_KERNEL); if (!ses->auth_key.response) { cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory", msg->sesskey_len); rc = -ENOMEM; goto out_put_spnego_key; } ses->auth_key.len = msg->sesskey_len; sess_data->iov[1].iov_base = msg->data + msg->sesskey_len; sess_data->iov[1].iov_len = msg->secblob_len; rc = SMB2_sess_sendreceive(sess_data); if (rc) goto out_put_spnego_key; rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; ses->Suid = rsp->hdr.sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); rc = SMB2_sess_establish_session(sess_data); out_put_spnego_key: key_invalidate(spnego_key); key_put(spnego_key); out: sess_data->result = rc; sess_data->func = NULL; SMB2_sess_free_buffer(sess_data); } #else static void SMB2_auth_kerberos(struct SMB2_sess_data *sess_data) { cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n"); sess_data->result = -EOPNOTSUPP; sess_data->func = NULL; } #endif static void SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data); static void SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_rsp *rsp = NULL; char *ntlmssp_blob = NULL; bool use_spnego = false; /* else use raw ntlmssp */ u16 blob_length = 0; /* * If memory allocation is successful, caller of this function * frees it. */ ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL); if (!ses->ntlmssp) { rc = -ENOMEM; goto out_err; } ses->ntlmssp->sesskey_per_smbsess = true; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out_err; ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE), GFP_KERNEL); if (ntlmssp_blob == NULL) { rc = -ENOMEM; goto out; } build_ntlmssp_negotiate_blob(ntlmssp_blob, ses); if (use_spnego) { /* BB eventually need to add this */ cifs_dbg(VFS, "spnego not supported for SMB2 yet\n"); rc = -EOPNOTSUPP; goto out; } else { blob_length = sizeof(struct _NEGOTIATE_MESSAGE); /* with raw NTLMSSP we don't encapsulate in SPNEGO */ } sess_data->iov[1].iov_base = ntlmssp_blob; sess_data->iov[1].iov_len = blob_length; rc = SMB2_sess_sendreceive(sess_data); rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; /* If true, rc here is expected and not an error */ if (sess_data->buf0_type != CIFS_NO_BUFFER && rsp->hdr.sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED) rc = 0; if (rc) goto out; if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 != le16_to_cpu(rsp->SecurityBufferOffset)) { cifs_dbg(VFS, "Invalid security buffer offset %d\n", le16_to_cpu(rsp->SecurityBufferOffset)); rc = -EIO; goto out; } rc = decode_ntlmssp_challenge(rsp->Buffer, le16_to_cpu(rsp->SecurityBufferLength), ses); if (rc) goto out; cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n"); ses->Suid = rsp->hdr.sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); out: kfree(ntlmssp_blob); SMB2_sess_free_buffer(sess_data); if (!rc) { sess_data->result = 0; sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate; return; } out_err: kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->result = rc; sess_data->func = NULL; } static void SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_req *req; struct smb2_sess_setup_rsp *rsp = NULL; unsigned char *ntlmssp_blob = NULL; bool use_spnego = false; /* else use raw ntlmssp */ u16 blob_length = 0; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out; req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base; req->hdr.sync_hdr.SessionId = ses->Suid; rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses, sess_data->nls_cp); if (rc) { cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc); goto out; } if (use_spnego) { /* BB eventually need to add this */ cifs_dbg(VFS, "spnego not supported for SMB2 yet\n"); rc = -EOPNOTSUPP; goto out; } sess_data->iov[1].iov_base = ntlmssp_blob; sess_data->iov[1].iov_len = blob_length; rc = SMB2_sess_sendreceive(sess_data); if (rc) goto out; rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; ses->Suid = rsp->hdr.sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); rc = SMB2_sess_establish_session(sess_data); out: kfree(ntlmssp_blob); SMB2_sess_free_buffer(sess_data); kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->result = rc; sess_data->func = NULL; } static int SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data) { int type; type = smb2_select_sectype(ses->server, ses->sectype); cifs_dbg(FYI, "sess setup type %d\n", type); if (type == Unspecified) { cifs_dbg(VFS, "Unable to select appropriate authentication method!"); return -EINVAL; } switch (type) { case Kerberos: sess_data->func = SMB2_auth_kerberos; break; case RawNTLMSSP: sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate; break; default: cifs_dbg(VFS, "secType %d not supported!\n", type); return -EOPNOTSUPP; } return 0; } int SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses, const struct nls_table *nls_cp) { int rc = 0; struct TCP_Server_Info *server = ses->server; struct SMB2_sess_data *sess_data; cifs_dbg(FYI, "Session Setup\n"); if (!server) { WARN(1, "%s: server is NULL!\n", __func__); return -EIO; } sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL); if (!sess_data) return -ENOMEM; rc = SMB2_select_sec(ses, sess_data); if (rc) goto out; sess_data->xid = xid; sess_data->ses = ses; sess_data->buf0_type = CIFS_NO_BUFFER; sess_data->nls_cp = (struct nls_table *) nls_cp; while (sess_data->func) sess_data->func(sess_data); if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign)) cifs_dbg(VFS, "signing requested but authenticated as guest\n"); rc = sess_data->result; out: kfree(sess_data); return rc; } int SMB2_logoff(const unsigned int xid, struct cifs_ses *ses) { struct smb2_logoff_req *req; /* response is also trivial struct */ int rc = 0; struct TCP_Server_Info *server; int flags = 0; cifs_dbg(FYI, "disconnect session %p\n", ses); if (ses && (ses->server)) server = ses->server; else return -EIO; /* no need to send SMB logoff if uid already closed due to reconnect */ if (ses->need_reconnect) goto smb2_session_already_dead; rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req); if (rc) return rc; /* since no tcon, smb2_init can not do this, so do here */ req->hdr.sync_hdr.SessionId = ses->Suid; if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) flags |= CIFS_TRANSFORM_REQ; else if (server->sign) req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED; rc = SendReceiveNoRsp(xid, ses, (char *) req, flags); cifs_small_buf_release(req); /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ smb2_session_already_dead: return rc; } static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code) { cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]); } #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */) /* These are similar values to what Windows uses */ static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon) { tcon->max_chunks = 256; tcon->max_bytes_chunk = 1048576; tcon->max_bytes_copy = 16777216; } int SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree, struct cifs_tcon *tcon, const struct nls_table *cp) { struct smb2_tree_connect_req *req; struct smb2_tree_connect_rsp *rsp = NULL; struct kvec iov[2]; struct kvec rsp_iov = { NULL, 0 }; int rc = 0; int resp_buftype; int unc_path_len; __le16 *unc_path = NULL; int flags = 0; cifs_dbg(FYI, "TCON\n"); if (!(ses->server) || !tree) return -EIO; unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL); if (unc_path == NULL) return -ENOMEM; unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1; unc_path_len *= 2; if (unc_path_len < 2) { kfree(unc_path); return -EINVAL; } /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */ if (tcon) tcon->tid = 0; rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req); if (rc) { kfree(unc_path); return rc; } if (tcon == NULL) { if ((ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)) flags |= CIFS_TRANSFORM_REQ; /* since no tcon, smb2_init can not do this, so do here */ req->hdr.sync_hdr.SessionId = ses->Suid; if (ses->server->sign) req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED; } else if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for pad */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req) - 1 /* pad */ - 4 /* do not count rfc1001 len field */); req->PathLength = cpu_to_le16(unc_path_len - 2); iov[1].iov_base = unc_path; iov[1].iov_len = unc_path_len; inc_rfc1001_len(req, unc_path_len - 1 /* pad */); rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base; if (rc != 0) { if (tcon) { cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE); tcon->need_reconnect = true; } goto tcon_error_exit; } if (tcon == NULL) { ses->ipc_tid = rsp->hdr.sync_hdr.TreeId; goto tcon_exit; } switch (rsp->ShareType) { case SMB2_SHARE_TYPE_DISK: cifs_dbg(FYI, "connection to disk share\n"); break; case SMB2_SHARE_TYPE_PIPE: tcon->ipc = true; cifs_dbg(FYI, "connection to pipe share\n"); break; case SMB2_SHARE_TYPE_PRINT: tcon->ipc = true; cifs_dbg(FYI, "connection to printer\n"); break; default: cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType); rc = -EOPNOTSUPP; goto tcon_error_exit; } tcon->share_flags = le32_to_cpu(rsp->ShareFlags); tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */ tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess); tcon->tidStatus = CifsGood; tcon->need_reconnect = false; tcon->tid = rsp->hdr.sync_hdr.TreeId; strlcpy(tcon->treeName, tree, sizeof(tcon->treeName)); if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) && ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0)) cifs_dbg(VFS, "DFS capability contradicts DFS flag\n"); if (tcon->seal && !(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)) cifs_dbg(VFS, "Encryption is requested but not supported\n"); init_copy_chunk_defaults(tcon); if (tcon->ses->server->ops->validate_negotiate) rc = tcon->ses->server->ops->validate_negotiate(xid, tcon); tcon_exit: free_rsp_buf(resp_buftype, rsp); kfree(unc_path); return rc; tcon_error_exit: if (rsp && rsp->hdr.sync_hdr.Status == STATUS_BAD_NETWORK_NAME) { cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree); } goto tcon_exit; } int SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon) { struct smb2_tree_disconnect_req *req; /* response is trivial */ int rc = 0; struct cifs_ses *ses = tcon->ses; int flags = 0; cifs_dbg(FYI, "Tree Disconnect\n"); if (!ses || !(ses->server)) return -EIO; if ((tcon->need_reconnect) || (tcon->ses->need_reconnect)) return 0; rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; rc = SendReceiveNoRsp(xid, ses, (char *)req, flags); cifs_small_buf_release(req); if (rc) cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE); return rc; } static struct create_durable * create_durable_buf(void) { struct create_durable *buf; buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable, Data)); buf->ccontext.DataLength = cpu_to_le32(16); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable, Name)); buf->ccontext.NameLength = cpu_to_le16(4); /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = 'n'; buf->Name[3] = 'Q'; return buf; } static struct create_durable * create_reconnect_durable_buf(struct cifs_fid *fid) { struct create_durable *buf; buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable, Data)); buf->ccontext.DataLength = cpu_to_le32(16); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable, Name)); buf->ccontext.NameLength = cpu_to_le16(4); buf->Data.Fid.PersistentFileId = fid->persistent_fid; buf->Data.Fid.VolatileFileId = fid->volatile_fid; /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = 'n'; buf->Name[3] = 'C'; return buf; } static __u8 parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp, unsigned int *epoch) { char *data_offset; struct create_context *cc; unsigned int next; unsigned int remaining; char *name; data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset); remaining = le32_to_cpu(rsp->CreateContextsLength); cc = (struct create_context *)data_offset; while (remaining >= sizeof(struct create_context)) { name = le16_to_cpu(cc->NameOffset) + (char *)cc; if (le16_to_cpu(cc->NameLength) == 4 && strncmp(name, "RqLs", 4) == 0) return server->ops->parse_lease_buf(cc, epoch); next = le32_to_cpu(cc->Next); if (!next) break; remaining -= next; cc = (struct create_context *)((char *)cc + next); } return 0; } static int add_lease_context(struct TCP_Server_Info *server, struct kvec *iov, unsigned int *num_iovec, __u8 *oplock) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; iov[num].iov_base = server->ops->create_lease_buf(oplock+1, *oplock); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = server->vals->create_lease_size; req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE; if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32( sizeof(struct smb2_create_req) - 4 + iov[num - 1].iov_len); le32_add_cpu(&req->CreateContextsLength, server->vals->create_lease_size); inc_rfc1001_len(&req->hdr, server->vals->create_lease_size); *num_iovec = num + 1; return 0; } static struct create_durable_v2 * create_durable_v2_buf(struct cifs_fid *pfid) { struct create_durable_v2 *buf; buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable_v2, dcontext)); buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2)); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable_v2, Name)); buf->ccontext.NameLength = cpu_to_le16(4); buf->dcontext.Timeout = 0; /* Should this be configurable by workload */ buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT); generate_random_uuid(buf->dcontext.CreateGuid); memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16); /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = '2'; buf->Name[3] = 'Q'; return buf; } static struct create_durable_handle_reconnect_v2 * create_reconnect_durable_v2_buf(struct cifs_fid *fid) { struct create_durable_handle_reconnect_v2 *buf; buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2, dcontext)); buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_reconnect_context_v2)); buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2, Name)); buf->ccontext.NameLength = cpu_to_le16(4); buf->dcontext.Fid.PersistentFileId = fid->persistent_fid; buf->dcontext.Fid.VolatileFileId = fid->volatile_fid; buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT); memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16); /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = '2'; buf->Name[3] = 'C'; return buf; } static int add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; iov[num].iov_base = create_durable_v2_buf(oparms->fid); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable_v2); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) - 4 + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2)); inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_v2)); *num_iovec = num + 1; return 0; } static int add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; /* indicate that we don't need to relock the file */ oparms->reconnect = false; iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) - 4 + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_handle_reconnect_v2)); inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_handle_reconnect_v2)); *num_iovec = num + 1; return 0; } static int add_durable_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms, bool use_persistent) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; if (use_persistent) { if (oparms->reconnect) return add_durable_reconnect_v2_context(iov, num_iovec, oparms); else return add_durable_v2_context(iov, num_iovec, oparms); } if (oparms->reconnect) { iov[num].iov_base = create_reconnect_durable_buf(oparms->fid); /* indicate that we don't need to relock the file */ oparms->reconnect = false; } else iov[num].iov_base = create_durable_buf(); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) - 4 + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable)); inc_rfc1001_len(&req->hdr, sizeof(struct create_durable)); *num_iovec = num + 1; return 0; } static int alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len, const char *treename, const __le16 *path) { int treename_len, path_len; struct nls_table *cp; const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)}; /* * skip leading "\\" */ treename_len = strlen(treename); if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\')) return -EINVAL; treename += 2; treename_len -= 2; path_len = UniStrnlen((wchar_t *)path, PATH_MAX); /* * make room for one path separator between the treename and * path */ *out_len = treename_len + 1 + path_len; /* * final path needs to be null-terminated UTF16 with a * size aligned to 8 */ *out_size = roundup((*out_len+1)*2, 8); *out_path = kzalloc(*out_size, GFP_KERNEL); if (!*out_path) return -ENOMEM; cp = load_nls_default(); cifs_strtoUTF16(*out_path, treename, treename_len, cp); UniStrcat(*out_path, sep); UniStrcat(*out_path, path); unload_nls(cp); return 0; } int SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path, __u8 *oplock, struct smb2_file_all_info *buf, struct smb2_err_rsp **err_buf) { struct smb2_create_req *req; struct smb2_create_rsp *rsp; struct TCP_Server_Info *server; struct cifs_tcon *tcon = oparms->tcon; struct cifs_ses *ses = tcon->ses; struct kvec iov[4]; struct kvec rsp_iov = {NULL, 0}; int resp_buftype; int uni_path_len; __le16 *copy_path = NULL; int copy_size; int rc = 0; unsigned int n_iov = 2; __u32 file_attributes = 0; char *dhc_buf = NULL, *lc_buf = NULL; int flags = 0; cifs_dbg(FYI, "create/open\n"); if (ses && (ses->server)) server = ses->server; else return -EIO; rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; if (oparms->create_options & CREATE_OPTION_READONLY) file_attributes |= ATTR_READONLY; if (oparms->create_options & CREATE_OPTION_SPECIAL) file_attributes |= ATTR_SYSTEM; req->ImpersonationLevel = IL_IMPERSONATION; req->DesiredAccess = cpu_to_le32(oparms->desired_access); /* File attributes ignored on open (used in create though) */ req->FileAttributes = cpu_to_le32(file_attributes); req->ShareAccess = FILE_SHARE_ALL_LE; req->CreateDisposition = cpu_to_le32(oparms->disposition); req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK); iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; /* -1 since last byte is buf[0] which is sent below (path) */ iov[0].iov_len--; req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req) - 4); /* [MS-SMB2] 2.2.13 NameOffset: * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of * the SMB2 header, the file name includes a prefix that will * be processed during DFS name normalization as specified in * section 3.3.5.9. Otherwise, the file name is relative to * the share that is identified by the TreeId in the SMB2 * header. */ if (tcon->share_flags & SHI1005_FLAGS_DFS) { int name_len; req->hdr.sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS; rc = alloc_path_with_tree_prefix(&copy_path, &copy_size, &name_len, tcon->treeName, path); if (rc) return rc; req->NameLength = cpu_to_le16(name_len * 2); uni_path_len = copy_size; path = copy_path; } else { uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2; /* MUST set path len (NameLength) to 0 opening root of share */ req->NameLength = cpu_to_le16(uni_path_len - 2); if (uni_path_len % 8 != 0) { copy_size = roundup(uni_path_len, 8); copy_path = kzalloc(copy_size, GFP_KERNEL); if (!copy_path) return -ENOMEM; memcpy((char *)copy_path, (const char *)path, uni_path_len); uni_path_len = copy_size; path = copy_path; } } iov[1].iov_len = uni_path_len; iov[1].iov_base = path; /* -1 since last byte is buf[0] which was counted in smb2_buf_len */ inc_rfc1001_len(req, uni_path_len - 1); if (!server->oplocks) *oplock = SMB2_OPLOCK_LEVEL_NONE; if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) || *oplock == SMB2_OPLOCK_LEVEL_NONE) req->RequestedOplockLevel = *oplock; else { rc = add_lease_context(server, iov, &n_iov, oplock); if (rc) { cifs_small_buf_release(req); kfree(copy_path); return rc; } lc_buf = iov[n_iov-1].iov_base; } if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) { /* need to set Next field of lease context if we request it */ if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) { struct create_context *ccontext = (struct create_context *)iov[n_iov-1].iov_base; ccontext->Next = cpu_to_le32(server->vals->create_lease_size); } rc = add_durable_context(iov, &n_iov, oparms, tcon->use_persistent); if (rc) { cifs_small_buf_release(req); kfree(copy_path); kfree(lc_buf); return rc; } dhc_buf = iov[n_iov-1].iov_base; } rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_create_rsp *)rsp_iov.iov_base; if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_CREATE_HE); if (err_buf && rsp) *err_buf = kmemdup(rsp, get_rfc1002_length(rsp) + 4, GFP_KERNEL); goto creat_exit; } oparms->fid->persistent_fid = rsp->PersistentFileId; oparms->fid->volatile_fid = rsp->VolatileFileId; if (buf) { memcpy(buf, &rsp->CreationTime, 32); buf->AllocationSize = rsp->AllocationSize; buf->EndOfFile = rsp->EndofFile; buf->Attributes = rsp->FileAttributes; buf->NumberOfLinks = cpu_to_le32(1); buf->DeletePending = 0; } if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE) *oplock = parse_lease_state(server, rsp, &oparms->fid->epoch); else *oplock = rsp->OplockLevel; creat_exit: kfree(copy_path); kfree(lc_buf); kfree(dhc_buf); free_rsp_buf(resp_buftype, rsp); return rc; } /* * SMB2 IOCTL is used for both IOCTLs and FSCTLs */ int SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 opcode, bool is_fsctl, bool use_ipc, char *in_data, u32 indatalen, char **out_data, u32 *plen /* returned data len */) { struct smb2_ioctl_req *req; struct smb2_ioctl_rsp *rsp; struct smb2_sync_hdr *shdr; struct cifs_ses *ses; struct kvec iov[2]; struct kvec rsp_iov; int resp_buftype; int n_iov; int rc = 0; int flags = 0; cifs_dbg(FYI, "SMB2 IOCTL\n"); if (out_data != NULL) *out_data = NULL; /* zero out returned data len, in case of error */ if (plen) *plen = 0; if (tcon) ses = tcon->ses; else return -EIO; if (!ses || !(ses->server)) return -EIO; rc = small_smb2_init(SMB2_IOCTL, tcon, (void **) &req); if (rc) return rc; if (use_ipc) { if (ses->ipc_tid == 0) { cifs_small_buf_release(req); return -ENOTCONN; } cifs_dbg(FYI, "replacing tid 0x%x with IPC tid 0x%x\n", req->hdr.sync_hdr.TreeId, ses->ipc_tid); req->hdr.sync_hdr.TreeId = ses->ipc_tid; } if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->CtlCode = cpu_to_le32(opcode); req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; if (indatalen) { req->InputCount = cpu_to_le32(indatalen); /* do not set InputOffset if no input data */ req->InputOffset = cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer) - 4); iov[1].iov_base = in_data; iov[1].iov_len = indatalen; n_iov = 2; } else n_iov = 1; req->OutputOffset = 0; req->OutputCount = 0; /* MBZ */ /* * Could increase MaxOutputResponse, but that would require more * than one credit. Windows typically sets this smaller, but for some * ioctls it may be useful to allow server to send more. No point * limiting what the server can send as long as fits in one credit * Unfortunately - we can not handle more than CIFS_MAX_MSG_SIZE * (by default, note that it can be overridden to make max larger) * in responses (except for read responses which can be bigger. * We may want to bump this limit up */ req->MaxOutputResponse = cpu_to_le32(CIFSMaxBufSize); if (is_fsctl) req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL); else req->Flags = 0; iov[0].iov_base = (char *)req; /* * If no input data, the size of ioctl struct in * protocol spec still includes a 1 byte data buffer, * but if input data passed to ioctl, we do not * want to double count this, so we do not send * the dummy one byte of data in iovec[0] if sending * input data (in iovec[1]). We also must add 4 bytes * in first iovec to allow for rfc1002 length field. */ if (indatalen) { iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; inc_rfc1001_len(req, indatalen - 1); } else iov[0].iov_len = get_rfc1002_length(req) + 4; /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */ if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED; rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base; if ((rc != 0) && (rc != -EINVAL)) { cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE); goto ioctl_exit; } else if (rc == -EINVAL) { if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) && (opcode != FSCTL_SRV_COPYCHUNK)) { cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE); goto ioctl_exit; } } /* check if caller wants to look at return data or just return rc */ if ((plen == NULL) || (out_data == NULL)) goto ioctl_exit; *plen = le32_to_cpu(rsp->OutputCount); /* We check for obvious errors in the output buffer length and offset */ if (*plen == 0) goto ioctl_exit; /* server returned no data */ else if (*plen > 0xFF00) { cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen); *plen = 0; rc = -EIO; goto ioctl_exit; } if (get_rfc1002_length(rsp) < le32_to_cpu(rsp->OutputOffset) + *plen) { cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen, le32_to_cpu(rsp->OutputOffset)); *plen = 0; rc = -EIO; goto ioctl_exit; } *out_data = kmalloc(*plen, GFP_KERNEL); if (*out_data == NULL) { rc = -ENOMEM; goto ioctl_exit; } shdr = get_sync_hdr(rsp); memcpy(*out_data, (char *)shdr + le32_to_cpu(rsp->OutputOffset), *plen); ioctl_exit: free_rsp_buf(resp_buftype, rsp); return rc; } /* * Individual callers to ioctl worker function follow */ int SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { int rc; struct compress_ioctl fsctl_input; char *ret_data = NULL; fsctl_input.CompressionState = cpu_to_le16(COMPRESSION_FORMAT_DEFAULT); rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid, FSCTL_SET_COMPRESSION, true /* is_fsctl */, false /* use_ipc */, (char *)&fsctl_input /* data input */, 2 /* in data len */, &ret_data /* out data */, NULL); cifs_dbg(FYI, "set compression rc %d\n", rc); return rc; } int SMB2_close(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { struct smb2_close_req *req; struct smb2_close_rsp *rsp; struct cifs_ses *ses = tcon->ses; struct kvec iov[1]; struct kvec rsp_iov; int resp_buftype; int rc = 0; int flags = 0; cifs_dbg(FYI, "Close\n"); if (!ses || !(ses->server)) return -EIO; rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_close_rsp *)rsp_iov.iov_base; if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE); goto close_exit; } /* BB FIXME - decode close response, update inode for caching */ close_exit: free_rsp_buf(resp_buftype, rsp); return rc; } static int validate_buf(unsigned int offset, unsigned int buffer_length, struct smb2_hdr *hdr, unsigned int min_buf_size) { unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length); char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr; char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr; char *end_of_buf = begin_of_buf + buffer_length; if (buffer_length < min_buf_size) { cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n", buffer_length, min_buf_size); return -EINVAL; } /* check if beyond RFC1001 maximum length */ if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) { cifs_dbg(VFS, "buffer length %d or smb length %d too large\n", buffer_length, smb_len); return -EINVAL; } if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) { cifs_dbg(VFS, "illegal server response, bad offset to data\n"); return -EINVAL; } return 0; } /* * If SMB buffer fields are valid, copy into temporary buffer to hold result. * Caller must free buffer. */ static int validate_and_copy_buf(unsigned int offset, unsigned int buffer_length, struct smb2_hdr *hdr, unsigned int minbufsize, char *data) { char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr; int rc; if (!data) return -EINVAL; rc = validate_buf(offset, buffer_length, hdr, minbufsize); if (rc) return rc; memcpy(data, begin_of_buf, buffer_length); return 0; } static int query_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type, u32 additional_info, size_t output_len, size_t min_len, void **data, u32 *dlen) { struct smb2_query_info_req *req; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov[2]; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; int flags = 0; cifs_dbg(FYI, "Query Info\n"); if (!ses || !(ses->server)) return -EIO; rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->InfoType = info_type; req->FileInfoClass = info_class; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; req->AdditionalInformation = cpu_to_le32(additional_info); /* * We do not use the input buffer (do not send extra byte) */ req->InputBufferOffset = 0; inc_rfc1001_len(req, -1); req->OutputBufferLength = cpu_to_le32(output_len); iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qinf_exit; } if (dlen) { *dlen = le32_to_cpu(rsp->OutputBufferLength); if (!*data) { *data = kmalloc(*dlen, GFP_KERNEL); if (!*data) { cifs_dbg(VFS, "Error %d allocating memory for acl\n", rc); *dlen = 0; goto qinf_exit; } } } rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr, min_len, *data); qinf_exit: free_rsp_buf(resp_buftype, rsp); return rc; } int SMB2_query_eas(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int ea_buf_size, struct smb2_file_full_ea_info *data) { return query_info(xid, tcon, persistent_fid, volatile_fid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE, 0, ea_buf_size, sizeof(struct smb2_file_full_ea_info), (void **)&data, NULL); } int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data) { return query_info(xid, tcon, persistent_fid, volatile_fid, FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0, sizeof(struct smb2_file_all_info) + PATH_MAX * 2, sizeof(struct smb2_file_all_info), (void **)&data, NULL); } int SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, void **data, u32 *plen) { __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO; *plen = 0; return query_info(xid, tcon, persistent_fid, volatile_fid, 0, SMB2_O_INFO_SECURITY, additional_info, SMB2_MAX_BUFFER_SIZE, sizeof(struct smb2_file_all_info), data, plen); } int SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid) { return query_info(xid, tcon, persistent_fid, volatile_fid, FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0, sizeof(struct smb2_file_internal_info), sizeof(struct smb2_file_internal_info), (void **)&uniqueid, NULL); } /* * This is a no-op for now. We're not really interested in the reply, but * rather in the fact that the server sent one and that server->lstrp * gets updated. * * FIXME: maybe we should consider checking that the reply matches request? */ static void smb2_echo_callback(struct mid_q_entry *mid) { struct TCP_Server_Info *server = mid->callback_data; struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf; unsigned int credits_received = 1; if (mid->mid_state == MID_RESPONSE_RECEIVED) credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest); DeleteMidQEntry(mid); add_credits(server, credits_received, CIFS_ECHO_OP); } void smb2_reconnect_server(struct work_struct *work) { struct TCP_Server_Info *server = container_of(work, struct TCP_Server_Info, reconnect.work); struct cifs_ses *ses; struct cifs_tcon *tcon, *tcon2; struct list_head tmp_list; int tcon_exist = false; int rc; int resched = false; /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */ mutex_lock(&server->reconnect_mutex); INIT_LIST_HEAD(&tmp_list); cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n"); spin_lock(&cifs_tcp_ses_lock); list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) { list_for_each_entry(tcon, &ses->tcon_list, tcon_list) { if (tcon->need_reconnect || tcon->need_reopen_files) { tcon->tc_count++; list_add_tail(&tcon->rlist, &tmp_list); tcon_exist = true; } } } /* * Get the reference to server struct to be sure that the last call of * cifs_put_tcon() in the loop below won't release the server pointer. */ if (tcon_exist) server->srv_count++; spin_unlock(&cifs_tcp_ses_lock); list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) { rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon); if (!rc) cifs_reopen_persistent_handles(tcon); else resched = true; list_del_init(&tcon->rlist); cifs_put_tcon(tcon); } cifs_dbg(FYI, "Reconnecting tcons finished\n"); if (resched) queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ); mutex_unlock(&server->reconnect_mutex); /* now we can safely release srv struct */ if (tcon_exist) cifs_put_tcp_session(server, 1); } int SMB2_echo(struct TCP_Server_Info *server) { struct smb2_echo_req *req; int rc = 0; struct kvec iov[2]; struct smb_rqst rqst = { .rq_iov = iov, .rq_nvec = 2 }; cifs_dbg(FYI, "In echo request\n"); if (server->tcpStatus == CifsNeedNegotiate) { /* No need to send echo on newly established connections */ queue_delayed_work(cifsiod_wq, &server->reconnect, 0); return rc; } rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req); if (rc) return rc; req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1); /* 4 for rfc1002 length field */ iov[0].iov_len = 4; iov[0].iov_base = (char *)req; iov[1].iov_len = get_rfc1002_length(req); iov[1].iov_base = (char *)req + 4; rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL, server, CIFS_ECHO_OP); if (rc) cifs_dbg(FYI, "Echo request failed: %d\n", rc); cifs_small_buf_release(req); return rc; } int SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { struct smb2_flush_req *req; struct cifs_ses *ses = tcon->ses; struct kvec iov[1]; struct kvec rsp_iov; int resp_buftype; int rc = 0; int flags = 0; cifs_dbg(FYI, "Flush\n"); if (!ses || !(ses->server)) return -EIO; rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); if (rc != 0) cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE); free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } /* * To form a chain of read requests, any read requests after the first should * have the end_of_chain boolean set to true. */ static int smb2_new_read_req(void **buf, unsigned int *total_len, struct cifs_io_parms *io_parms, unsigned int remaining_bytes, int request_type) { int rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_sync_hdr *shdr; rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req, total_len); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; shdr = &req->sync_hdr; shdr->ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->ReadChannelInfoOffset = 0; /* reserved */ req->ReadChannelInfoLength = 0; /* reserved */ req->Channel = 0; /* reserved */ req->MinimumCount = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); if (request_type & CHAINED_REQUEST) { if (!(request_type & END_OF_CHAIN)) { /* next 8-byte aligned request */ *total_len = DIV_ROUND_UP(*total_len, 8) * 8; shdr->NextCommand = cpu_to_le32(*total_len); } else /* END_OF_CHAIN */ shdr->NextCommand = 0; if (request_type & RELATED_REQUEST) { shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS; /* * Related requests use info from previous read request * in chain. */ shdr->SessionId = 0xFFFFFFFF; shdr->TreeId = 0xFFFFFFFF; req->PersistentFileId = 0xFFFFFFFF; req->VolatileFileId = 0xFFFFFFFF; } } if (remaining_bytes > io_parms->length) req->RemainingBytes = cpu_to_le32(remaining_bytes); else req->RemainingBytes = 0; *buf = req; return rc; } static void smb2_readv_callback(struct mid_q_entry *mid) { struct cifs_readdata *rdata = mid->callback_data; struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)rdata->iov[1].iov_base; unsigned int credits_received = 1; struct smb_rqst rqst = { .rq_iov = rdata->iov, .rq_nvec = 2, .rq_pages = rdata->pages, .rq_npages = rdata->nr_pages, .rq_pagesz = rdata->pagesz, .rq_tailsz = rdata->tailsz }; cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n", __func__, mid->mid, mid->mid_state, rdata->result, rdata->bytes); switch (mid->mid_state) { case MID_RESPONSE_RECEIVED: credits_received = le16_to_cpu(shdr->CreditRequest); /* result already set, check signature */ if (server->sign && !mid->decrypted) { int rc; rc = smb2_verify_signature(&rqst, server); if (rc) cifs_dbg(VFS, "SMB signature verification returned error = %d\n", rc); } /* FIXME: should this be counted toward the initiating task? */ task_io_account_read(rdata->got_bytes); cifs_stats_bytes_read(tcon, rdata->got_bytes); break; case MID_REQUEST_SUBMITTED: case MID_RETRY_NEEDED: rdata->result = -EAGAIN; if (server->sign && rdata->got_bytes) /* reset bytes number since we can not check a sign */ rdata->got_bytes = 0; /* FIXME: should this be counted toward the initiating task? */ task_io_account_read(rdata->got_bytes); cifs_stats_bytes_read(tcon, rdata->got_bytes); break; default: if (rdata->result != -ENODATA) rdata->result = -EIO; } if (rdata->result) cifs_stats_fail_inc(tcon, SMB2_READ_HE); queue_work(cifsiod_wq, &rdata->work); DeleteMidQEntry(mid); add_credits(server, credits_received, 0); } /* smb2_async_readv - send an async read, and set up mid to handle result */ int smb2_async_readv(struct cifs_readdata *rdata) { int rc, flags = 0; char *buf; struct smb2_sync_hdr *shdr; struct cifs_io_parms io_parms; struct smb_rqst rqst = { .rq_iov = rdata->iov, .rq_nvec = 2 }; struct TCP_Server_Info *server; unsigned int total_len; __be32 req_len; cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n", __func__, rdata->offset, rdata->bytes); io_parms.tcon = tlink_tcon(rdata->cfile->tlink); io_parms.offset = rdata->offset; io_parms.length = rdata->bytes; io_parms.persistent_fid = rdata->cfile->fid.persistent_fid; io_parms.volatile_fid = rdata->cfile->fid.volatile_fid; io_parms.pid = rdata->pid; server = io_parms.tcon->ses->server; rc = smb2_new_read_req((void **) &buf, &total_len, &io_parms, 0, 0); if (rc) { if (rc == -EAGAIN && rdata->credits) { /* credits was reset by reconnect */ rdata->credits = 0; /* reduce in_flight value since we won't send the req */ spin_lock(&server->req_lock); server->in_flight--; spin_unlock(&server->req_lock); } return rc; } if (encryption_required(io_parms.tcon)) flags |= CIFS_TRANSFORM_REQ; req_len = cpu_to_be32(total_len); rdata->iov[0].iov_base = &req_len; rdata->iov[0].iov_len = sizeof(__be32); rdata->iov[1].iov_base = buf; rdata->iov[1].iov_len = total_len; shdr = (struct smb2_sync_hdr *)buf; if (rdata->credits) { shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes, SMB2_MAX_BUFFER_SIZE)); shdr->CreditRequest = shdr->CreditCharge; spin_lock(&server->req_lock); server->credits += rdata->credits - le16_to_cpu(shdr->CreditCharge); spin_unlock(&server->req_lock); wake_up(&server->request_q); flags |= CIFS_HAS_CREDITS; } kref_get(&rdata->refcount); rc = cifs_call_async(io_parms.tcon->ses->server, &rqst, cifs_readv_receive, smb2_readv_callback, smb3_handle_read_data, rdata, flags); if (rc) { kref_put(&rdata->refcount, cifs_readdata_release); cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE); } cifs_small_buf_release(buf); return rc; } int SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, char **buf, int *buf_type) { int resp_buftype, rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_read_rsp *rsp = NULL; struct smb2_sync_hdr *shdr; struct kvec iov[2]; struct kvec rsp_iov; unsigned int total_len; __be32 req_len; struct smb_rqst rqst = { .rq_iov = iov, .rq_nvec = 2 }; int flags = CIFS_LOG_ERROR; struct cifs_ses *ses = io_parms->tcon->ses; *nbytes = 0; rc = smb2_new_read_req((void **)&req, &total_len, io_parms, 0, 0); if (rc) return rc; if (encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req_len = cpu_to_be32(total_len); iov[0].iov_base = &req_len; iov[0].iov_len = sizeof(__be32); iov[1].iov_base = req; iov[1].iov_len = total_len; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_read_rsp *)rsp_iov.iov_base; if (rc) { if (rc != -ENODATA) { cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE); cifs_dbg(VFS, "Send error in read = %d\n", rc); } free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc == -ENODATA ? 0 : rc; } *nbytes = le32_to_cpu(rsp->DataLength); if ((*nbytes > CIFS_MAX_MSGSIZE) || (*nbytes > io_parms->length)) { cifs_dbg(FYI, "bad length %d for count %d\n", *nbytes, io_parms->length); rc = -EIO; *nbytes = 0; } shdr = get_sync_hdr(rsp); if (*buf) { memcpy(*buf, (char *)shdr + rsp->DataOffset, *nbytes); free_rsp_buf(resp_buftype, rsp_iov.iov_base); } else if (resp_buftype != CIFS_NO_BUFFER) { *buf = rsp_iov.iov_base; if (resp_buftype == CIFS_SMALL_BUFFER) *buf_type = CIFS_SMALL_BUFFER; else if (resp_buftype == CIFS_LARGE_BUFFER) *buf_type = CIFS_LARGE_BUFFER; } return rc; } /* * Check the mid_state and signature on received buffer (if any), and queue the * workqueue completion task. */ static void smb2_writev_callback(struct mid_q_entry *mid) { struct cifs_writedata *wdata = mid->callback_data; struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink); unsigned int written; struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf; unsigned int credits_received = 1; switch (mid->mid_state) { case MID_RESPONSE_RECEIVED: credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest); wdata->result = smb2_check_receive(mid, tcon->ses->server, 0); if (wdata->result != 0) break; written = le32_to_cpu(rsp->DataLength); /* * Mask off high 16 bits when bytes written as returned * by the server is greater than bytes requested by the * client. OS/2 servers are known to set incorrect * CountHigh values. */ if (written > wdata->bytes) written &= 0xFFFF; if (written < wdata->bytes) wdata->result = -ENOSPC; else wdata->bytes = written; break; case MID_REQUEST_SUBMITTED: case MID_RETRY_NEEDED: wdata->result = -EAGAIN; break; default: wdata->result = -EIO; break; } if (wdata->result) cifs_stats_fail_inc(tcon, SMB2_WRITE_HE); queue_work(cifsiod_wq, &wdata->work); DeleteMidQEntry(mid); add_credits(tcon->ses->server, credits_received, 0); } /* smb2_async_writev - send an async write, and set up mid to handle result */ int smb2_async_writev(struct cifs_writedata *wdata, void (*release)(struct kref *kref)) { int rc = -EACCES, flags = 0; struct smb2_write_req *req = NULL; struct smb2_sync_hdr *shdr; struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; struct kvec iov[2]; struct smb_rqst rqst = { }; rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req); if (rc) { if (rc == -EAGAIN && wdata->credits) { /* credits was reset by reconnect */ wdata->credits = 0; /* reduce in_flight value since we won't send the req */ spin_lock(&server->req_lock); server->in_flight--; spin_unlock(&server->req_lock); } goto async_writev_out; } if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; shdr = get_sync_hdr(req); shdr->ProcessId = cpu_to_le32(wdata->cfile->pid); req->PersistentFileId = wdata->cfile->fid.persistent_fid; req->VolatileFileId = wdata->cfile->fid.volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Offset = cpu_to_le64(wdata->offset); /* 4 for rfc1002 length field */ req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer) - 4); req->RemainingBytes = 0; /* 4 for rfc1002 length field and 1 for Buffer */ iov[0].iov_len = 4; iov[0].iov_base = req; iov[1].iov_len = get_rfc1002_length(req) - 1; iov[1].iov_base = (char *)req + 4; rqst.rq_iov = iov; rqst.rq_nvec = 2; rqst.rq_pages = wdata->pages; rqst.rq_npages = wdata->nr_pages; rqst.rq_pagesz = wdata->pagesz; rqst.rq_tailsz = wdata->tailsz; cifs_dbg(FYI, "async write at %llu %u bytes\n", wdata->offset, wdata->bytes); req->Length = cpu_to_le32(wdata->bytes); inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */); if (wdata->credits) { shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes, SMB2_MAX_BUFFER_SIZE)); shdr->CreditRequest = shdr->CreditCharge; spin_lock(&server->req_lock); server->credits += wdata->credits - le16_to_cpu(shdr->CreditCharge); spin_unlock(&server->req_lock); wake_up(&server->request_q); flags |= CIFS_HAS_CREDITS; } kref_get(&wdata->refcount); rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL, wdata, flags); if (rc) { kref_put(&wdata->refcount, release); cifs_stats_fail_inc(tcon, SMB2_WRITE_HE); } async_writev_out: cifs_small_buf_release(req); return rc; } /* * SMB2_write function gets iov pointer to kvec array with n_vec as a length. * The length field from io_parms must be at least 1 and indicates a number of * elements with data to write that begins with position 1 in iov array. All * data length is specified by count. */ int SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; *nbytes = 0; if (n_vec < 1) return rc; rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); /* 4 for rfc1002 length field */ req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer) - 4); req->RemainingBytes = 0; iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for Buffer */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* length of entire message including data to be written */ inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */); rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, "Send error in write = %d\n", rc); } else *nbytes = le32_to_cpu(rsp->DataLength); free_rsp_buf(resp_buftype, rsp); return rc; } static unsigned int num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size) { int len; unsigned int entrycount = 0; unsigned int next_offset = 0; FILE_DIRECTORY_INFO *entryptr; if (bufstart == NULL) return 0; entryptr = (FILE_DIRECTORY_INFO *)bufstart; while (1) { entryptr = (FILE_DIRECTORY_INFO *) ((char *)entryptr + next_offset); if ((char *)entryptr + size > end_of_buf) { cifs_dbg(VFS, "malformed search entry would overflow\n"); break; } len = le32_to_cpu(entryptr->FileNameLength); if ((char *)entryptr + len + size > end_of_buf) { cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n", end_of_buf); break; } *lastentry = (char *)entryptr; entrycount++; next_offset = le32_to_cpu(entryptr->NextEntryOffset); if (!next_offset) break; } return entrycount; } /* * Readdir/FindFirst */ int SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int index, struct cifs_search_info *srch_inf) { struct smb2_query_directory_req *req; struct smb2_query_directory_rsp *rsp = NULL; struct kvec iov[2]; struct kvec rsp_iov; int rc = 0; int len; int resp_buftype = CIFS_NO_BUFFER; unsigned char *bufptr; struct TCP_Server_Info *server; struct cifs_ses *ses = tcon->ses; __le16 asteriks = cpu_to_le16('*'); char *end_of_smb; unsigned int output_size = CIFSMaxBufSize; size_t info_buf_size; int flags = 0; if (ses && (ses->server)) server = ses->server; else return -EIO; rc = small_smb2_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; switch (srch_inf->info_level) { case SMB_FIND_FILE_DIRECTORY_INFO: req->FileInformationClass = FILE_DIRECTORY_INFORMATION; info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1; break; case SMB_FIND_FILE_ID_FULL_DIR_INFO: req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION; info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1; break; default: cifs_dbg(VFS, "info level %u isn't supported\n", srch_inf->info_level); rc = -EINVAL; goto qdir_exit; } req->FileIndex = cpu_to_le32(index); req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; len = 0x2; bufptr = req->Buffer; memcpy(bufptr, &asteriks, len); req->FileNameOffset = cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1 - 4); req->FileNameLength = cpu_to_le16(len); /* * BB could be 30 bytes or so longer if we used SMB2 specific * buffer lengths, but this is safe and close enough. */ output_size = min_t(unsigned int, output_size, server->maxBuf); output_size = min_t(unsigned int, output_size, 2 << 15); req->OutputBufferLength = cpu_to_le32(output_size); iov[0].iov_base = (char *)req; /* 4 for RFC1001 length and 1 for Buffer */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; iov[1].iov_base = (char *)(req->Buffer); iov[1].iov_len = len; inc_rfc1001_len(req, len - 1 /* Buffer */); rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base; if (rc) { if (rc == -ENODATA && rsp->hdr.sync_hdr.Status == STATUS_NO_MORE_FILES) { srch_inf->endOfSearch = true; rc = 0; } cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE); goto qdir_exit; } rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr, info_buf_size); if (rc) goto qdir_exit; srch_inf->unicode = true; if (srch_inf->ntwrk_buf_start) { if (srch_inf->smallBuf) cifs_small_buf_release(srch_inf->ntwrk_buf_start); else cifs_buf_release(srch_inf->ntwrk_buf_start); } srch_inf->ntwrk_buf_start = (char *)rsp; srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ + (char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset); /* 4 for rfc1002 length field */ end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr; srch_inf->entries_in_buffer = num_entries(srch_inf->srch_entries_start, end_of_smb, &srch_inf->last_entry, info_buf_size); srch_inf->index_of_last_entry += srch_inf->entries_in_buffer; cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n", srch_inf->entries_in_buffer, srch_inf->index_of_last_entry, srch_inf->srch_entries_start, srch_inf->last_entry); if (resp_buftype == CIFS_LARGE_BUFFER) srch_inf->smallBuf = false; else if (resp_buftype == CIFS_SMALL_BUFFER) srch_inf->smallBuf = true; else cifs_dbg(VFS, "illegal search buffer type\n"); return rc; qdir_exit: free_rsp_buf(resp_buftype, rsp); return rc; } static int send_set_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class, u8 info_type, u32 additional_info, unsigned int num, void **data, unsigned int *size) { struct smb2_set_info_req *req; struct smb2_set_info_rsp *rsp = NULL; struct kvec *iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; unsigned int i; struct cifs_ses *ses = tcon->ses; int flags = 0; if (!ses || !(ses->server)) return -EIO; if (!num) return -EINVAL; iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL); if (!iov) return -ENOMEM; rc = small_smb2_init(SMB2_SET_INFO, tcon, (void **) &req); if (rc) { kfree(iov); return rc; } if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid); req->InfoType = info_type; req->FileInfoClass = info_class; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; req->AdditionalInformation = cpu_to_le32(additional_info); /* 4 for RFC1001 length and 1 for Buffer */ req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req) - 1 - 4); req->BufferLength = cpu_to_le32(*size); inc_rfc1001_len(req, *size - 1 /* Buffer */); memcpy(req->Buffer, *data, *size); iov[0].iov_base = (char *)req; /* 4 for RFC1001 length */ iov[0].iov_len = get_rfc1002_length(req) + 4; for (i = 1; i < num; i++) { inc_rfc1001_len(req, size[i]); le32_add_cpu(&req->BufferLength, size[i]); iov[i].iov_base = (char *)data[i]; iov[i].iov_len = size[i]; } rc = SendReceive2(xid, ses, iov, num, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base; if (rc != 0) cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE); free_rsp_buf(resp_buftype, rsp); kfree(iov); return rc; } int SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, __le16 *target_file) { struct smb2_file_rename_info info; void **data; unsigned int size[2]; int rc; int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX)); data = kmalloc(sizeof(void *) * 2, GFP_KERNEL); if (!data) return -ENOMEM; info.ReplaceIfExists = 1; /* 1 = replace existing target with new */ /* 0 = fail if target already exists */ info.RootDirectory = 0; /* MBZ for network ops (why does spec say?) */ info.FileNameLength = cpu_to_le32(len); data[0] = &info; size[0] = sizeof(struct smb2_file_rename_info); data[1] = target_file; size[1] = len + 2 /* null */; rc = send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_RENAME_INFORMATION, SMB2_O_INFO_FILE, 0, 2, data, size); kfree(data); return rc; } int SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { __u8 delete_pending = 1; void *data; unsigned int size; data = &delete_pending; size = 1; /* sizeof __u8 */ return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_DISPOSITION_INFORMATION, SMB2_O_INFO_FILE, 0, 1, &data, &size); } int SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, __le16 *target_file) { struct smb2_file_link_info info; void **data; unsigned int size[2]; int rc; int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX)); data = kmalloc(sizeof(void *) * 2, GFP_KERNEL); if (!data) return -ENOMEM; info.ReplaceIfExists = 0; /* 1 = replace existing link with new */ /* 0 = fail if link already exists */ info.RootDirectory = 0; /* MBZ for network ops (why does spec say?) */ info.FileNameLength = cpu_to_le32(len); data[0] = &info; size[0] = sizeof(struct smb2_file_link_info); data[1] = target_file; size[1] = len + 2 /* null */; rc = send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_LINK_INFORMATION, SMB2_O_INFO_FILE, 0, 2, data, size); kfree(data); return rc; } int SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc) { struct smb2_file_eof_info info; void *data; unsigned int size; info.EndOfFile = *eof; data = &info; size = sizeof(struct smb2_file_eof_info); if (is_falloc) return send_set_info(xid, tcon, persistent_fid, volatile_fid, pid, FILE_ALLOCATION_INFORMATION, SMB2_O_INFO_FILE, 0, 1, &data, &size); else return send_set_info(xid, tcon, persistent_fid, volatile_fid, pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE, 0, 1, &data, &size); } int SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf) { unsigned int size; size = sizeof(FILE_BASIC_INFO); return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_BASIC_INFORMATION, SMB2_O_INFO_FILE, 0, 1, (void **)&buf, &size); } int SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct cifs_ntsd *pnntsd, int pacllen, int aclflag) { return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag, 1, (void **)&pnntsd, &pacllen); } int SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct smb2_file_full_ea_info *buf, int len) { return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE, 0, 1, (void **)&buf, &len); } int SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon, const u64 persistent_fid, const u64 volatile_fid, __u8 oplock_level) { int rc; struct smb2_oplock_break *req = NULL; int flags = CIFS_OBREAK_OP; cifs_dbg(FYI, "SMB2_oplock_break\n"); rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->VolatileFid = volatile_fid; req->PersistentFid = persistent_fid; req->OplockLevel = oplock_level; req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1); rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags); cifs_small_buf_release(req); if (rc) { cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE); cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc); } return rc; } static void copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf, struct kstatfs *kst) { kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) * le32_to_cpu(pfs_inf->SectorsPerAllocationUnit); kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits); kst->f_bfree = kst->f_bavail = le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits); return; } static int build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level, int outbuf_len, u64 persistent_fid, u64 volatile_fid) { int rc; struct smb2_query_info_req *req; cifs_dbg(FYI, "Query FSInfo level %d\n", level); if ((tcon->ses == NULL) || (tcon->ses->server == NULL)) return -EIO; rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req); if (rc) return rc; req->InfoType = SMB2_O_INFO_FILESYSTEM; req->FileInfoClass = level; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; /* 4 for rfc1002 length field and 1 for pad */ req->InputBufferOffset = cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4); req->OutputBufferLength = cpu_to_le32( outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4); iov->iov_base = (char *)req; /* 4 for rfc1002 length field */ iov->iov_len = get_rfc1002_length(req) + 4; return 0; } int SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata) { struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; struct smb2_fs_full_size_info *info = NULL; int flags = 0; rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION, sizeof(struct smb2_fs_full_size_info), persistent_fid, volatile_fid); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsinf_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ + le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr); rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr, sizeof(struct smb2_fs_full_size_info)); if (!rc) copy_fs_info_to_kstatfs(info, fsdata); qfsinf_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } int SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int level) { struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype, max_len, min_len; struct cifs_ses *ses = tcon->ses; unsigned int rsp_len, offset; int flags = 0; if (level == FS_DEVICE_INFORMATION) { max_len = sizeof(FILE_SYSTEM_DEVICE_INFO); min_len = sizeof(FILE_SYSTEM_DEVICE_INFO); } else if (level == FS_ATTRIBUTE_INFORMATION) { max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO); min_len = MIN_FS_ATTR_INFO_SIZE; } else if (level == FS_SECTOR_SIZE_INFORMATION) { max_len = sizeof(struct smb3_fs_ss_info); min_len = sizeof(struct smb3_fs_ss_info); } else { cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level); return -EINVAL; } rc = build_qfs_info_req(&iov, tcon, level, max_len, persistent_fid, volatile_fid); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsattr_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; rsp_len = le32_to_cpu(rsp->OutputBufferLength); offset = le16_to_cpu(rsp->OutputBufferOffset); rc = validate_buf(offset, rsp_len, &rsp->hdr, min_len); if (rc) goto qfsattr_exit; if (level == FS_ATTRIBUTE_INFORMATION) memcpy(&tcon->fsAttrInfo, 4 /* RFC1001 len */ + offset + (char *)&rsp->hdr, min_t(unsigned int, rsp_len, max_len)); else if (level == FS_DEVICE_INFORMATION) memcpy(&tcon->fsDevInfo, 4 /* RFC1001 len */ + offset + (char *)&rsp->hdr, sizeof(FILE_SYSTEM_DEVICE_INFO)); else if (level == FS_SECTOR_SIZE_INFORMATION) { struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *) (4 /* RFC1001 len */ + offset + (char *)&rsp->hdr); tcon->ss_flags = le32_to_cpu(ss_info->Flags); tcon->perf_sector_size = le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf); } qfsattr_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } int smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon, const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid, const __u32 num_lock, struct smb2_lock_element *buf) { int rc = 0; struct smb2_lock_req *req = NULL; struct kvec iov[2]; struct kvec rsp_iov; int resp_buf_type; unsigned int count; int flags = CIFS_NO_RESP; cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock); rc = small_smb2_init(SMB2_LOCK, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid); req->LockCount = cpu_to_le16(num_lock); req->PersistentFileId = persist_fid; req->VolatileFileId = volatile_fid; count = num_lock * sizeof(struct smb2_lock_element); inc_rfc1001_len(req, count - sizeof(struct smb2_lock_element)); iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and count for all locks */ iov[0].iov_len = get_rfc1002_length(req) + 4 - count; iov[1].iov_base = (char *)buf; iov[1].iov_len = count; cifs_stats_inc(&tcon->stats.cifs_stats.num_locks); rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, flags, &rsp_iov); cifs_small_buf_release(req); if (rc) { cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc); cifs_stats_fail_inc(tcon, SMB2_LOCK_HE); } return rc; } int SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon, const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid, const __u64 length, const __u64 offset, const __u32 lock_flags, const bool wait) { struct smb2_lock_element lock; lock.Offset = cpu_to_le64(offset); lock.Length = cpu_to_le64(length); lock.Flags = cpu_to_le32(lock_flags); if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK) lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY); return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock); } int SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon, __u8 *lease_key, const __le32 lease_state) { int rc; struct smb2_lease_ack *req = NULL; int flags = CIFS_OBREAK_OP; cifs_dbg(FYI, "SMB2_lease_break\n"); rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1); req->StructureSize = cpu_to_le16(36); inc_rfc1001_len(req, 12); memcpy(req->LeaseKey, lease_key, 16); req->LeaseState = lease_state; rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags); cifs_small_buf_release(req); if (rc) { cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE); cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc); } return rc; }
711722.c
// SPDX-License-Identifier: BSD-3-Clause /*============================================================================ This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic Package, Release 3a, by John R. Hauser. Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =============================================================================*/ #include <stdint.h> #include "platform.h" #ifndef softfloat_shiftRightM #define softfloat_shiftRightM softfloat_shiftRightM #include "primitives.h" void softfloat_shiftRightM( uint_fast8_t size_words, const uint32_t *aPtr, uint32_t count, uint32_t *zPtr ) { uint32_t wordCount; uint_fast8_t innerCount; uint32_t *destPtr; uint_fast8_t i; wordCount = count>>5; if ( wordCount < size_words ) { aPtr += indexMultiwordHiBut( size_words, wordCount ); innerCount = count & 31; if ( innerCount ) { softfloat_shortShiftRightM( size_words - wordCount, aPtr, innerCount, zPtr + indexMultiwordLoBut( size_words, wordCount ) ); if ( ! wordCount ) return; } else { aPtr += indexWordLo( size_words - wordCount ); destPtr = zPtr + indexWordLo( size_words ); for ( i = size_words - wordCount; i; --i ) { *destPtr = *aPtr; aPtr += wordIncr; destPtr += wordIncr; } } zPtr += indexMultiwordHi( size_words, wordCount ); } else { wordCount = size_words; } do { *zPtr++ = 0; --wordCount; } while ( wordCount ); } #endif
356186.c
/* * NASA Docket No. GSC-18,370-1, and identified as "Operating System Abstraction Layer" * * Copyright (c) 2019 United States Government as represented by * the Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * \file coveragetest-sockets.c * \ingroup shared * \author [email protected] * */ #include "os-shared-coveragetest.h" #include "os-shared-sockets.h" #include "os-shared-idmap.h" #include "os-shared-file.h" #include <OCS_stdio.h> void Test_OS_SocketAPI_Init(void) { /* * Test Case For: * int32 OS_SocketAPI_Init(void) */ int32 expected = OS_SUCCESS; int32 actual = OS_SocketAPI_Init(); UtAssert_True(actual == expected, "OS_SocketAPI_Init() (%ld) == OS_SUCCESS", (long)actual); } /***************************************************************************** * * Test case for OS_CreateSocketName() * This is a static helper function invoked via a wrapper * *****************************************************************************/ void Test_OS_CreateSocketName(void) { /* * Test Case For: * static void OS_CreateSocketName(OS_stream_internal_record_t *sock, * const OS_SockAddr_t *Addr, const char *parent_name) * * This focuses on coverage paths, as this function does not return a value */ OS_SockAddr_t testaddr; UT_SetForceFail(UT_KEY(OS_SocketAddrToString_Impl), OS_ERROR); OS_CreateSocketName(0, &testaddr, "ut"); /* * The function should have called snprintf() to create the name */ UtAssert_True(UT_GetStubCount(UT_KEY(OCS_snprintf)) == 2, "OS_CreateSocketName() invoked snprintf()"); UtAssert_True(OS_stream_table[0].stream_name[0] != 'x', "OS_CreateSocketName() set stream name"); } /***************************************************************************** * * Test case for OS_SocketOpen() * *****************************************************************************/ void Test_OS_SocketOpen(void) { /* * Test Case For: * int32 OS_SocketOpen(uint32 *sock_id, OS_SocketDomain_t Domain, OS_SocketType_t Type) */ int32 expected = OS_SUCCESS; uint32 objid = 0xFFFFFFFF; int32 actual = OS_SocketOpen(&objid, OS_SocketDomain_INET, OS_SocketType_STREAM); UtAssert_True(actual == expected, "OS_SocketOpen() (%ld) == OS_SUCCESS", (long)actual); UtAssert_True(objid != 0, "objid (%lu) != 0", (unsigned long)objid); expected = OS_INVALID_POINTER; actual = OS_SocketOpen(NULL, OS_SocketDomain_INVALID, OS_SocketType_INVALID); UtAssert_True(actual == expected, "OS_SocketOpen(NULL) (%ld) == OS_INVALID_POINTER", (long)actual); } /***************************************************************************** * * Test case for OS_SocketBind() * *****************************************************************************/ void Test_OS_SocketBind(void) { /* * Test Case For: * int32 OS_SocketBind(uint32 sock_id, const OS_SockAddr_t *Addr) */ int32 expected = OS_SUCCESS; int32 actual = ~OS_SUCCESS; OS_SockAddr_t Addr; OS_stream_table[1].socket_domain = OS_SocketDomain_INET; memset(&Addr,0,sizeof(Addr)); actual = OS_SocketBind(1, &Addr); UtAssert_True(actual == expected, "OS_SocketBind() (%ld) == OS_SUCCESS", (long)actual); expected = OS_INVALID_POINTER; actual = OS_SocketBind(1, NULL); UtAssert_True(actual == expected, "OS_SocketBind(NULL) (%ld) == OS_INVALID_POINTER", (long)actual); /* * Should fail if not a socket domain */ OS_stream_table[1].socket_domain = OS_SocketDomain_INVALID; expected = OS_ERR_INCORRECT_OBJ_TYPE; actual = OS_SocketBind(1, &Addr); UtAssert_True(actual == expected, "OS_SocketBind() non-socket (%ld) == OS_ERR_INCORRECT_OBJ_TYPE", (long)actual); /* * Should fail if already bound */ OS_stream_table[1].socket_domain = OS_SocketDomain_INET; OS_stream_table[1].stream_state = OS_STREAM_STATE_BOUND; expected = OS_ERR_INCORRECT_OBJ_STATE; actual = OS_SocketBind(1, &Addr); UtAssert_True(actual == expected, "OS_SocketBind() already bound (%ld) == OS_ERR_INCORRECT_OBJ_STATE", (long)actual); } /***************************************************************************** * * Test case for OS_SocketAccept() * *****************************************************************************/ void Test_OS_SocketAccept(void) { /* * Test Case For: * int32 OS_SocketAccept(uint32 sock_id, uint32 *connsock_id, OS_SockAddr_t *Addr, int32 timeout) */ int32 expected = OS_SUCCESS; int32 actual = ~OS_SUCCESS; uint32 local_id = 0; uint32 connsock_id; OS_SockAddr_t Addr; connsock_id = 0; OS_stream_table[local_id].socket_type = OS_SocketType_STREAM; OS_stream_table[local_id].stream_state = OS_STREAM_STATE_BOUND; UT_SetDataBuffer(UT_KEY(OS_ObjectIdGetById), &local_id, sizeof(local_id), false); memset(&Addr,0,sizeof(Addr)); actual = OS_SocketAccept(1, &connsock_id, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketAccept() (%ld) == OS_SUCCESS", (long)actual); expected = OS_INVALID_POINTER; actual = OS_SocketAccept(1, NULL, NULL, 0); UtAssert_True(actual == expected, "OS_SocketAccept(NULL) (%ld) == OS_INVALID_POINTER", (long)actual); /* * Should fail if not a stream socket */ OS_stream_table[1].socket_type = OS_SocketType_INVALID; expected = OS_ERR_INCORRECT_OBJ_TYPE; actual = OS_SocketAccept(1, &connsock_id, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketAccept() non-stream (%ld) == OS_ERR_INCORRECT_OBJ_TYPE", (long)actual); /* * Should fail if already connected */ OS_stream_table[1].socket_type = OS_SocketType_STREAM; OS_stream_table[1].stream_state = OS_STREAM_STATE_BOUND|OS_STREAM_STATE_CONNECTED; expected = OS_ERR_INCORRECT_OBJ_STATE; actual = OS_SocketAccept(1, &connsock_id, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketAccept() already bound (%ld) == OS_ERR_INCORRECT_OBJ_STATE", (long)actual); /* * Underlying implementation failure test */ OS_stream_table[1].stream_state = OS_STREAM_STATE_BOUND; expected = -1234; UT_SetForceFail(UT_KEY(OS_SocketAccept_Impl), -1234); actual = OS_SocketAccept(1, &connsock_id, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketAccept() underlying failure (%ld) == -1234", (long)actual); } /***************************************************************************** * * Test case for OS_SocketConnect() * *****************************************************************************/ void Test_OS_SocketConnect(void) { /* * Test Case For: * int32 OS_SocketConnect(uint32 sock_id, const OS_SockAddr_t *Addr, int32 Timeout) */ int32 expected = OS_SUCCESS; int32 actual = ~OS_SUCCESS; OS_SockAddr_t Addr; uint32 idbuf; memset(&Addr,0,sizeof(Addr)); idbuf = 1; UT_SetDataBuffer(UT_KEY(OS_ObjectIdGetById),&idbuf, sizeof(idbuf), false); OS_stream_table[idbuf].socket_domain = OS_SocketDomain_INET; OS_stream_table[idbuf].socket_type = OS_SocketType_STREAM; OS_stream_table[idbuf].stream_state = 0; actual = OS_SocketConnect(1, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketConnect() (%ld) == OS_SUCCESS", (long)actual); expected = OS_INVALID_POINTER; actual = OS_SocketConnect(1, NULL, 0); UtAssert_True(actual == expected, "OS_SocketConnect(NULL) (%ld) == OS_INVALID_POINTER", (long)actual); /* * Should fail if not a stream socket */ OS_stream_table[1].socket_domain = OS_SocketDomain_INVALID; OS_stream_table[1].socket_type = OS_SocketType_INVALID; expected = OS_ERR_INCORRECT_OBJ_TYPE; actual = OS_SocketConnect(1, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketConnect() non-stream (%ld) == OS_ERR_INCORRECT_OBJ_TYPE", (long)actual); /* * Should fail if already connected */ OS_stream_table[1].socket_domain = OS_SocketDomain_INET; OS_stream_table[1].socket_type = OS_SocketType_STREAM; OS_stream_table[1].stream_state = OS_STREAM_STATE_CONNECTED; expected = OS_ERR_INCORRECT_OBJ_STATE; actual = OS_SocketConnect(1, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketConnect() already connected (%ld) == OS_ERR_INCORRECT_OBJ_STATE", (long)actual); } /***************************************************************************** * * Test case for OS_SocketRecvFrom() * *****************************************************************************/ void Test_OS_SocketRecvFrom(void) { /* * Test Case For: * OS_SocketRecvFrom(uint32 sock_id, void *buffer, uint32 buflen, OS_SockAddr_t *RemoteAddr, int32 timeout) */ char Buf; int32 expected = OS_SUCCESS; int32 actual = ~OS_SUCCESS; OS_SockAddr_t Addr; uint32 idbuf; memset(&Addr,0,sizeof(Addr)); idbuf = 1; UT_SetDataBuffer(UT_KEY(OS_ObjectIdGetById),&idbuf, sizeof(idbuf), false); OS_stream_table[idbuf].socket_type = OS_SocketType_DATAGRAM; OS_stream_table[idbuf].stream_state = OS_STREAM_STATE_BOUND; actual = OS_SocketRecvFrom(1, &Buf, 1, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketRecvFrom() (%ld) == OS_SUCCESS", (long)actual); expected = OS_INVALID_POINTER; actual = OS_SocketRecvFrom(1, NULL, 0, NULL, 0); UtAssert_True(actual == expected, "OS_SocketRecvFrom(NULL) (%ld) == OS_INVALID_POINTER", (long)actual); /* * Should fail if not a datagram socket */ OS_stream_table[1].socket_type = OS_SocketType_INVALID; expected = OS_ERR_INCORRECT_OBJ_TYPE; actual = OS_SocketRecvFrom(1, &Buf, 1, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketRecvFrom() non-datagram (%ld) == OS_ERR_INCORRECT_OBJ_TYPE", (long)actual); /* * Should fail if not bound */ OS_stream_table[1].socket_type = OS_SocketType_DATAGRAM; OS_stream_table[1].stream_state = 0; expected = OS_ERR_INCORRECT_OBJ_STATE; actual = OS_SocketRecvFrom(1, &Buf, 1, &Addr, 0); UtAssert_True(actual == expected, "OS_SocketRecvFrom() non-bound (%ld) == OS_ERR_INCORRECT_OBJ_STATE", (long)actual); } /***************************************************************************** * * Test case for OS_SocketSendTo() * *****************************************************************************/ void Test_OS_SocketSendTo(void) { /* * Test Case For: * int32 OS_SocketSendTo(uint32 sock_id, const void *buffer, uint32 buflen, const OS_SockAddr_t *RemoteAddr) */ char Buf = 'A'; int32 expected = OS_SUCCESS; int32 actual = ~OS_SUCCESS; OS_SockAddr_t Addr; uint32 idbuf; memset(&Addr,0,sizeof(Addr)); idbuf = 1; UT_SetDataBuffer(UT_KEY(OS_ObjectIdGetById),&idbuf, sizeof(idbuf), false); OS_stream_table[idbuf].socket_type = OS_SocketType_DATAGRAM; OS_stream_table[idbuf].stream_state = OS_STREAM_STATE_BOUND; actual = OS_SocketSendTo(1, &Buf, 1, &Addr); UtAssert_True(actual == expected, "OS_SocketSendTo() (%ld) == OS_SUCCESS", (long)actual); expected = OS_INVALID_POINTER; actual = OS_SocketSendTo(1, NULL, 0, NULL); UtAssert_True(actual == expected, "OS_SocketSendTo(NULL) (%ld) == OS_INVALID_POINTER", (long)actual); /* * Should fail if not a datagram socket */ OS_stream_table[1].socket_type = OS_SocketType_INVALID; expected = OS_ERR_INCORRECT_OBJ_TYPE; actual = OS_SocketSendTo(1, &Buf, 1, &Addr); UtAssert_True(actual == expected, "OS_SocketSendTo() non-datagram (%ld) == OS_ERR_INCORRECT_OBJ_TYPE", (long)actual); } /***************************************************************************** * * Test case for OS_SocketGetIdByName() * *****************************************************************************/ void Test_OS_SocketGetIdByName (void) { /* * Test Case For: * int32 OS_SocketGetIdByName (uint32 *sock_id, const char *sock_name) */ int32 expected = OS_SUCCESS; int32 actual = ~OS_SUCCESS; uint32 objid = 0; UT_SetForceFail(UT_KEY(OS_ObjectIdFindByName), OS_SUCCESS); actual = OS_SocketGetIdByName(&objid, "UT"); UtAssert_True(actual == expected, "OS_SocketGetIdByName() (%ld) == OS_SUCCESS", (long)actual); UtAssert_True(objid != 0, "OS_SocketGetIdByName() objid (%lu) != 0", (unsigned long)objid); UT_ClearForceFail(UT_KEY(OS_ObjectIdFindByName)); expected = OS_ERR_NAME_NOT_FOUND; actual = OS_SocketGetIdByName(&objid, "NF"); UtAssert_True(actual == expected, "OS_SocketGetIdByName() (%ld) == %ld", (long)actual, (long)expected); expected = OS_INVALID_POINTER; actual = OS_SocketGetIdByName(NULL, NULL); UtAssert_True(actual == expected, "Test_OS_SocketGetIdByName(NULL) (%ld) == OS_INVALID_POINTER", (long)actual); } /***************************************************************************** * * Test case for OS_SocketGetInfo() * *****************************************************************************/ void Test_OS_SocketGetInfo (void) { /* * Test Case For: * int32 OS_SocketGetInfo (uint32 sock_id, OS_socket_prop_t *sock_prop) */ int32 expected = OS_SUCCESS; int32 actual = ~OS_SUCCESS; OS_socket_prop_t prop; uint32 local_index = 1; OS_common_record_t utrec; OS_common_record_t *rptr = &utrec; memset(&utrec, 0, sizeof(utrec)); utrec.creator = 111; utrec.name_entry = "ABC"; UT_SetDataBuffer(UT_KEY(OS_ObjectIdGetById), &local_index, sizeof(local_index), false); UT_SetDataBuffer(UT_KEY(OS_ObjectIdGetById), &rptr, sizeof(rptr), false); actual = OS_SocketGetInfo(1, &prop); UtAssert_True(actual == expected, "OS_SocketGetInfo() (%ld) == OS_SUCCESS", (long)actual); UtAssert_True(prop.creator == 111, "prop.creator (%lu) == 111", (unsigned long)prop.creator); UtAssert_True(strcmp(prop.name, "ABC") == 0, "prop.name (%s) == ABC", prop.name); expected = OS_INVALID_POINTER; actual = OS_SocketGetInfo(1, NULL); UtAssert_True(actual == expected, "OS_SocketGetInfo() (%ld) == OS_INVALID_POINTER", (long)actual); } void Test_OS_SocketAddr (void) { /* * Test Case For: * int32 OS_SocketAddrInit(OS_SockAddr_t *Addr, OS_SocketDomain_t Domain) * int32 OS_SocketAddrToString(char *buffer, uint32 buflen, const OS_SockAddr_t *Addr) * int32 OS_SocketAddrSetPort(OS_SockAddr_t *Addr, uint16 PortNum) * int32 OS_SocketAddrGetPort(uint16 *PortNum, const OS_SockAddr_t *Addr) */ OS_SockAddr_t Addr; char Buffer[32]; uint16 PortNum; int32 expected = OS_SUCCESS; int32 actual = ~OS_SUCCESS; /* First verify nominal case for each function */ actual = OS_SocketAddrInit(&Addr, OS_SocketDomain_INVALID); UtAssert_True(actual == expected, "OS_SocketAddrInit() (%ld) == OS_SUCCESS", (long)actual); actual = OS_SocketAddrToString(Buffer, sizeof(Buffer), &Addr); UtAssert_True(actual == expected, "OS_SocketAddrToString() (%ld) == OS_SUCCESS", (long)actual); actual = OS_SocketAddrFromString(&Addr, Buffer); UtAssert_True(actual == expected, "OS_SocketAddrFromString() (%ld) == OS_SUCCESS", (long)actual); actual = OS_SocketAddrSetPort(&Addr, 1234); UtAssert_True(actual == expected, "OS_SocketAddrSetPort() (%ld) == OS_SUCCESS", (long)actual); actual = OS_SocketAddrGetPort(&PortNum, &Addr); UtAssert_True(actual == expected, "OS_SocketAddrGetPort() (%ld) == OS_SUCCESS", (long)actual); /* Verify invalid pointer checking in each function */ expected = OS_INVALID_POINTER; actual = OS_SocketAddrInit(NULL, OS_SocketDomain_INVALID); UtAssert_True(actual == expected, "OS_SocketAddrInit() (%ld) == OS_INVALID_POINTER", (long)actual); actual = OS_SocketAddrToString(NULL, 0, NULL); UtAssert_True(actual == expected, "OS_SocketAddrToString() (%ld) == OS_INVALID_POINTER", (long)actual); actual = OS_SocketAddrFromString(NULL, NULL); UtAssert_True(actual == expected, "OS_SocketAddrFromString() (%ld) == OS_INVALID_POINTER", (long)actual); actual = OS_SocketAddrSetPort(NULL, 1234); UtAssert_True(actual == expected, "OS_SocketAddrSetPort() (%ld) == OS_INVALID_POINTER", (long)actual); actual = OS_SocketAddrGetPort(NULL, NULL); UtAssert_True(actual == expected, "OS_SocketAddrGetPort() (%ld) == OS_INVALID_POINTER", (long)actual); } /* Osapi_Test_Setup * * Purpose: * Called by the unit test tool to set up the app prior to each test */ void Osapi_Test_Setup(void) { UT_ResetState(0); memset(OS_stream_table, 0, sizeof(OS_stream_table)); memset(OS_global_stream_table, 0, sizeof(OS_common_record_t) * OS_MAX_NUM_OPEN_FILES); } /* * Osapi_Test_Teardown * * Purpose: * Called by the unit test tool to tear down the app after each test */ void Osapi_Test_Teardown(void) { } /* * Register the test cases to execute with the unit test tool */ void UtTest_Setup(void) { ADD_TEST(OS_SocketAPI_Init); ADD_TEST(OS_SocketAddr); ADD_TEST(OS_SocketOpen); ADD_TEST(OS_SocketBind); ADD_TEST(OS_SocketAccept); ADD_TEST(OS_SocketConnect); ADD_TEST(OS_SocketRecvFrom); ADD_TEST(OS_SocketSendTo); ADD_TEST(OS_SocketGetIdByName); ADD_TEST(OS_SocketGetInfo); ADD_TEST(OS_CreateSocketName); }
417801.c
#include <interrupt.h> #include <uart.h> #include <stdint.h> #include <string.h> #include <timer.h> #include <mmio.h> #include <stddef.h> uint32_t interrupt_depth; void interrupt_irq_handler() { uint32_t irq_pend_base_reg = mmio_load(ARMINT_IRQ_PEND_BASE_REG); uint32_t irq_pend1_reg = mmio_load(ARMINT_IRQ_PEND1_REG); uint32_t irq_pend2_reg = mmio_load(ARMINT_IRQ_PEND2_REG); uint32_t core0_int_src = mmio_load(CORE0_INTERRUPT_SOURCE); uint32_t aux_mu_iir_reg = mmio_load(AUX_MU_IIR_REG); /* uart_puts("IRQ Handler."); uart_print("GPU IRQ pend base: 0x"); uart_putshex((uint64_t)irq_pend_base_reg); uart_print("GPU IRQ pend 1: 0x"); uart_putshex((uint64_t)irq_pend1_reg); uart_print("GPU IRQ pend 2: 0x"); uart_putshex((uint64_t)irq_pend2_reg); uart_print("Core0 interrupt source: 0x"); uart_putshex((uint64_t)core0_int_src); uart_print("AUX_MU_IIR_REG: 0x"); uart_putshex((uint64_t)aux_mu_iir_reg); */ if(core0_int_src & 0b10){ //CNTPNSIRQ interrupt coretimer_el0_handler(); } if(aux_mu_iir_reg&0b100){ //uart_puts("uart read interrupt!!"); uart_interrupt_handler(); } //uart_puts("irq interrupt"); } void not_implemented_interrupt() { uart_puts("not_implemented_interrupt"); } void interrupt_fiq_handler() { uart_puts("FIQ Handler."); while(1); } void interrupt_enable() { //if(interrupt_depth==0){ //uart_puts("enable interrupt"); //uart_print("interrupt_depth: 0x"); //uart_putshex(interrupt_depth); asm("msr DAIFClr, 0xf"); //} //interrupt_depth++; } void interrupt_disable() { //interrupt_depth--; //if(interrupt_depth==0) asm("msr DAIFSet, 0xf"); } void interrupt_enable_restore(size_t flag) { asm( "msr DAIF, %0" ::"r"(flag) ); } size_t interrupt_disable_save() { size_t flags; asm( "mrs %0, DAIF\t\n" "msr DAIFSet, 0xf" :"=r"(flags) ); return flags; }
131492.c
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. * * 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 <service_app.h> #include <mv_common.h> #include "http-server-log-private.h" #include "http-server-common.h" #include "hs-route-root.h" #include "hs-route-api-connection.h" #include "hs-route-api-applist.h" #include "hs-route-api-sysinfo.h" #include "hs-route-api-storage.h" #include "hs-route-api-image-upload.h" #include "hs-route-api-face-detect.h" #include "app.h" #include "face-recognize.h" #include "usb-camera.h" #include "thingspark_api.h" #include "resource_relay.h" #include "resource_relay_internal.h" #define SERVER_NAME "http-server-app" #define SERVER_PORT 8080 static int route_modules_init(void *data) { int ret = 0; ret = hs_route_root_init(); retv_if(ret, -1); ret = hs_route_api_connection_init(); retv_if(ret, -1); ret = hs_route_api_applist_init(); retv_if(ret, -1); ret = hs_route_api_sysinfo_init(); retv_if(ret, -1); ret = hs_route_api_storage_init(); retv_if(ret, -1); ret = hs_route_api_image_upload_init(); retv_if(ret, -1); ret = hs_route_api_face_detect_init(data); retv_if(ret, -1); return 0; } static void server_destroy(void) { http_server_destroy(); _D("server is destroyed"); } static int server_init_n_start(void *data) { int ret = 0; ret = http_server_create(SERVER_NAME, SERVER_PORT); retv_if(ret, -1); ret = route_modules_init(data); retv_if(ret, -1); ret = http_server_start(); retv_if(ret, -1); _D("server is started"); return 0; } static void conn_type_changed_cb(connection_type_e type, void *data) { app_data *ad = data; _D("connection type is changed [%d] -> [%d]", ad->cur_conn_type, type); server_destroy(); if (type != CONNECTION_TYPE_DISCONNECTED) { int ret = 0; _D("restart server"); ret = server_init_n_start(data); if (ret) { _E("failed to start server"); service_app_exit(); } } ad->cur_conn_type = type; return; } Eina_Bool _tp_timer_cb(void *data) { app_data *ad = data; int ret = 0; ret = tp_initialize("czRXVbgv72ILyJUl", &ad->handle); retv_if(ret != 0, ECORE_CALLBACK_RENEW); ret = tp_set_field_value(ad->handle, 1, "0"); retv_if(ret != 0, ECORE_CALLBACK_RENEW); ret = tp_send_data(ad->handle); retv_if(ret != 0, ECORE_CALLBACK_RENEW); tp_finalize(ad->handle); return ECORE_CALLBACK_RENEW; } static void service_app_control(app_control_h app_control, void *data) { int ret = 0; app_data *ad = data; tp_handle_h handle = NULL; face_recognize(); ret = usb_camera_prepare(data); ret_if(ret < 0); ret = usb_camera_preview(data); ret_if(ret < 0); ad->tp_timer = ecore_timer_add(20.0f, _tp_timer_cb, ad); ret_if(!ad->tp_timer); } static bool service_app_create(void *data) { app_data *ad = data; int ret = 0; retv_if(!ad, false); if (ad->tp_timer) { ecore_timer_del(ad->tp_timer); ad->tp_timer = NULL; } ret = connection_create(&ad->conn_h); retv_if(ret, false); ret = connection_set_type_changed_cb(ad->conn_h, conn_type_changed_cb, ad); goto_if(ret, ERROR); connection_get_type(ad->conn_h, &ad->cur_conn_type); if (ad->cur_conn_type == CONNECTION_TYPE_DISCONNECTED) { _D("network is not connected, waiting to be connected to any type of network"); return true; } ret = server_init_n_start(data); goto_if(ret, ERROR); return true; ERROR: if (ad->conn_h) connection_destroy(ad->conn_h); server_destroy(); return false; } static void service_app_terminate(void *data) { app_data *ad = data; resource_close_relay(19); resource_close_relay(26); usb_camera_unprepare(data); server_destroy(); if (ad->conn_h) { connection_destroy(ad->conn_h); ad->conn_h = NULL; } ad->cur_conn_type = CONNECTION_TYPE_DISCONNECTED; return; } int main(int argc, char* argv[]) { app_data ad = {0, }; service_app_lifecycle_callback_s event_callback; ad.conn_h = NULL; ad.cur_conn_type = CONNECTION_TYPE_DISCONNECTED; event_callback.create = service_app_create; event_callback.terminate = service_app_terminate; event_callback.app_control = service_app_control; service_app_main(argc, argv, &event_callback, &ad); return 0; }
69804.c
/*============================================================================ Filename : touch.c Project : QTouch Modular Library Purpose : Provides Initialization, Processing and ISR handler of touch library, Simple API functions to get/set the key touch parameters from/to the touch library data structures This file is part of QTouch Modular Library Release 6.3 application. Important Note: Do not edit this file manually. Use QTouch Configurator within Atmel Start to apply any modifications to this file. Usage License: Refer license.h file for license information Support: Visit http://www.microchip.com/support/hottopics.aspx to create MySupport case. ------------------------------------------------------------------------------ Copyright (c) 2019 Microchip. All rights reserved. ------------------------------------------------------------------------------ ============================================================================*/ #ifndef TOUCH_C #define TOUCH_C /*---------------------------------------------------------------------------- * include files *----------------------------------------------------------------------------*/ #include "touch.h" #include "license.h" #include "port.h" /*---------------------------------------------------------------------------- * prototypes *----------------------------------------------------------------------------*/ /*! \brief configure the ptc port pins to Input */ static void touch_ptc_pin_config(void); /*! \brief configure keys, wheels and sliders. */ static touch_ret_t touch_sensors_config(void); /*! \brief Touch measure complete callback function example prototype. */ static void qtm_measure_complete_callback(void); /*! \brief Touch Error callback function prototype. */ static void qtm_error_callback(uint8_t error); /*---------------------------------------------------------------------------- * Global Variables *----------------------------------------------------------------------------*/ /* Flag to indicate time for touch measurement */ volatile uint8_t time_to_measure_touch_flag = 0; /* postporcess request flag */ volatile uint8_t touch_postprocess_request = 0; /* Measurement Done Touch Flag */ volatile uint8_t measurement_done_touch = 0; /* Error Handling */ uint8_t module_error_code = 0; /* Acquisition module internal data - Size to largest acquisition set */ uint16_t touch_acq_signals_raw[DEF_NUM_CHANNELS]; /* Acquisition set 1 - General settings */ qtm_acq_node_group_config_t ptc_qtlib_acq_gen1 = {DEF_NUM_CHANNELS, DEF_SENSOR_TYPE, DEF_PTC_CAL_AUTO_TUNE, DEF_SEL_FREQ_INIT}; /* Node status, signal, calibration values */ qtm_acq_node_data_t ptc_qtlib_node_stat1[DEF_NUM_CHANNELS]; /* Node configurations */ qtm_acq_t161x_node_config_t ptc_seq_node_cfg1[DEF_NUM_CHANNELS] = {NODE_0_PARAMS, NODE_1_PARAMS, NODE_2_PARAMS, NODE_3_PARAMS, NODE_4_PARAMS}; /* Container */ qtm_acquisition_control_t qtlib_acq_set1 = {&ptc_qtlib_acq_gen1, &ptc_seq_node_cfg1[0], &ptc_qtlib_node_stat1[0]}; /**********************************************************/ /*********** Frequency Hop Auto tune Module **********************/ /**********************************************************/ /* Buffer used with various noise filtering functions */ uint16_t noise_filter_buffer[DEF_NUM_SENSORS * NUM_FREQ_STEPS]; uint8_t freq_hop_delay_selection[NUM_FREQ_STEPS] = {DEF_MEDIAN_FILTER_FREQUENCIES}; uint8_t freq_hop_autotune_counters[NUM_FREQ_STEPS]; /* Configuration */ qtm_freq_hop_autotune_config_t qtm_freq_hop_autotune_config1 = {DEF_NUM_CHANNELS, NUM_FREQ_STEPS, &ptc_qtlib_acq_gen1.freq_option_select, &freq_hop_delay_selection[0], DEF_FREQ_AUTOTUNE_ENABLE, FREQ_AUTOTUNE_MAX_VARIANCE, FREQ_AUTOTUNE_COUNT_IN}; /* Data */ qtm_freq_hop_autotune_data_t qtm_freq_hop_autotune_data1 = {0, 0, &noise_filter_buffer[0], &ptc_qtlib_node_stat1[0], &freq_hop_autotune_counters[0]}; /* Container */ qtm_freq_hop_autotune_control_t qtm_freq_hop_autotune_control1 = {&qtm_freq_hop_autotune_data1, &qtm_freq_hop_autotune_config1}; /**********************************************************/ /*********************** Keys Module **********************/ /**********************************************************/ /* Keys set 1 - General settings */ qtm_touch_key_group_config_t qtlib_key_grp_config_set1 = {DEF_NUM_SENSORS, DEF_TOUCH_DET_INT, DEF_MAX_ON_DURATION, DEF_ANTI_TCH_DET_INT, DEF_ANTI_TCH_RECAL_THRSHLD, DEF_TCH_DRIFT_RATE, DEF_ANTI_TCH_DRIFT_RATE, DEF_DRIFT_HOLD_TIME, DEF_REBURST_MODE}; qtm_touch_key_group_data_t qtlib_key_grp_data_set1; /* Key data */ qtm_touch_key_data_t qtlib_key_data_set1[DEF_NUM_SENSORS]; /* Key Configurations */ qtm_touch_key_config_t qtlib_key_configs_set1[DEF_NUM_SENSORS] = {KEY_0_PARAMS, KEY_1_PARAMS, KEY_2_PARAMS, KEY_3_PARAMS, KEY_4_PARAMS}; /* Container */ qtm_touch_key_control_t qtlib_key_set1 = {&qtlib_key_grp_data_set1, &qtlib_key_grp_config_set1, &qtlib_key_data_set1[0], &qtlib_key_configs_set1[0]}; static void touch_ptc_pin_config(void) { PORTB_set_pin_pull_mode(0, PORT_PULL_OFF); PORTB_pin_set_isc(0, PORT_ISC_INPUT_DISABLE_gc); PORTA_set_pin_pull_mode(7, PORT_PULL_OFF); PORTA_pin_set_isc(7, PORT_ISC_INPUT_DISABLE_gc); PORTA_set_pin_pull_mode(6, PORT_PULL_OFF); PORTA_pin_set_isc(6, PORT_ISC_INPUT_DISABLE_gc); PORTA_set_pin_pull_mode(5, PORT_PULL_OFF); PORTA_pin_set_isc(5, PORT_ISC_INPUT_DISABLE_gc); PORTA_set_pin_pull_mode(4, PORT_PULL_OFF); PORTA_pin_set_isc(4, PORT_ISC_INPUT_DISABLE_gc); } /*============================================================================ static touch_ret_t touch_sensors_config(void) ------------------------------------------------------------------------------ Purpose: Initialization of touch key sensors Input : none Output : none Notes : ============================================================================*/ /* Touch sensors config - assign nodes to buttons / wheels / sliders / surfaces / water level / etc */ static touch_ret_t touch_sensors_config(void) { uint16_t sensor_nodes; touch_ret_t touch_ret = TOUCH_SUCCESS; /* Init acquisition module */ qtm_ptc_init_acquisition_module(&qtlib_acq_set1); /* Init pointers to DMA sequence memory */ qtm_ptc_qtlib_assign_signal_memory(&touch_acq_signals_raw[0]); /* Initialize sensor nodes */ for (sensor_nodes = 0u; sensor_nodes < DEF_NUM_CHANNELS; sensor_nodes++) { /* Enable each node for measurement and mark for calibration */ qtm_enable_sensor_node(&qtlib_acq_set1, sensor_nodes); qtm_calibrate_sensor_node(&qtlib_acq_set1, sensor_nodes); } /* Enable sensor keys and assign nodes */ for (sensor_nodes = 0u; sensor_nodes < DEF_NUM_CHANNELS; sensor_nodes++) { qtm_init_sensor_key(&qtlib_key_set1, sensor_nodes, &ptc_qtlib_node_stat1[sensor_nodes]); } return (touch_ret); } /*============================================================================ static void qtm_measure_complete_callback( void ) ------------------------------------------------------------------------------ Purpose: this function is called after the completion of measurement cycle. This function sets the post processing request flag to trigger the post processing. Input : none Output : none Notes : ============================================================================*/ static void qtm_measure_complete_callback(void) { touch_postprocess_request = 1u; } /*============================================================================ static void qtm_error_callback(uint8_t error) ------------------------------------------------------------------------------ Purpose: this function is used to report error in the modules. Input : error code Output : decoded module error code Notes : Derived Module_error_codes: Acquisition module error =1 post processing module1 error = 2 post processing module2 error = 3 ... and so on ============================================================================*/ static void qtm_error_callback(uint8_t error) { module_error_code = error + 1u; #if DEF_TOUCH_DATA_STREAMER_ENABLE == 1 datastreamer_output(); #endif } /*============================================================================ void Timer_set_period(const uint8_t val) ------------------------------------------------------------------------------ Purpose: This function sets the time interval on the RTC/Timer peripheral based on the user configuration. Input : Time interval Output : none Notes : ============================================================================*/ void Timer_set_period(const uint8_t val) { while (RTC.STATUS & RTC_PERBUSY_bm) /* wait for RTC synchronization */ ; RTC.PER = val; } /*============================================================================ void touch_init(void) ------------------------------------------------------------------------------ Purpose: Initialization of touch library. PTC, timer, and datastreamer modules are initialized in this function. Input : none Output : none Notes : ============================================================================*/ void touch_init(void) { /* Set match value for timer */ Timer_set_period(32); /* configure the PTC pins for Input*/ touch_ptc_pin_config(); /* Configure touch sensors with Application specific settings */ touch_sensors_config(); } /*============================================================================ void touch_process(void) ------------------------------------------------------------------------------ Purpose: Main processing function of touch library. This function initiates the acquisition, calls post processing after the acquistion complete and sets the flag for next measurement based on the sensor status. Input : none Output : none Notes : ============================================================================*/ void touch_process(void) { touch_ret_t touch_ret; /* check the time_to_measure_touch_flag flag for Touch Acquisition */ if (time_to_measure_touch_flag == 1u) { /* Do the acquisition */ touch_ret = qtm_ptc_start_measurement_seq(&qtlib_acq_set1, qtm_measure_complete_callback); /* if the Acquistion request was successful then clear the request flag */ if (TOUCH_SUCCESS == touch_ret) { /* Clear the Measure request flag */ time_to_measure_touch_flag = 0u; } } /* check the flag for node level post processing */ if (touch_postprocess_request == 1u) { /* Reset the flags for node_level_post_processing */ touch_postprocess_request = 0u; /* Run Acquisition module level post processing*/ touch_ret = qtm_acquisition_process(); /* Check the return value */ if (TOUCH_SUCCESS == touch_ret) { /* Returned with success: Start module level post processing */ //touch_ret = qtm_freq_hop_autotune(&qtm_freq_hop_autotune_control1); //if (TOUCH_SUCCESS != touch_ret) { //qtm_error_callback(1); //} touch_ret = qtm_key_sensors_process(&qtlib_key_set1); if (TOUCH_SUCCESS != touch_ret) { qtm_error_callback(2); } } else { /* Acq module Eror Detected: Issue an Acq module common error code 0x80 */ qtm_error_callback(0); } if ((0u != (qtlib_key_set1.qtm_touch_key_group_data->qtm_keys_status & 0x80u))) { time_to_measure_touch_flag = 1u; } else { measurement_done_touch = 1u; } } } uint8_t interrupt_cnt; /*============================================================================ void touch_timer_handler(void) ------------------------------------------------------------------------------ Purpose: This function updates the time elapsed to the touch key module to synchronize the internal time counts used by the module. Input : none Output : none Notes : ============================================================================*/ void touch_timer_handler(void) { interrupt_cnt++; if (interrupt_cnt >= DEF_TOUCH_MEASUREMENT_PERIOD_MS) { interrupt_cnt = 0; /* Count complete - Measure touch sensors */ time_to_measure_touch_flag = 1u; qtm_update_qtlib_timer(DEF_TOUCH_MEASUREMENT_PERIOD_MS); } } uint16_t get_sensor_node_signal(uint16_t sensor_node) { return (ptc_qtlib_node_stat1[sensor_node].node_acq_signals); } void update_sensor_node_signal(uint16_t sensor_node, uint16_t new_signal) { ptc_qtlib_node_stat1[sensor_node].node_acq_signals = new_signal; } uint16_t get_sensor_node_reference(uint16_t sensor_node) { return (qtlib_key_data_set1[sensor_node].channel_reference); } void update_sensor_node_reference(uint16_t sensor_node, uint16_t new_reference) { qtlib_key_data_set1[sensor_node].channel_reference = new_reference; } uint16_t get_sensor_cc_val(uint16_t sensor_node) { return (ptc_qtlib_node_stat1[sensor_node].node_comp_caps); } void update_sensor_cc_val(uint16_t sensor_node, uint16_t new_cc_value) { ptc_qtlib_node_stat1[sensor_node].node_comp_caps = new_cc_value; } uint8_t get_sensor_state(uint16_t sensor_node) { return (qtlib_key_set1.qtm_touch_key_data[sensor_node].sensor_state); } void update_sensor_state(uint16_t sensor_node, uint8_t new_state) { qtlib_key_set1.qtm_touch_key_data[sensor_node].sensor_state = new_state; } void calibrate_node(uint16_t sensor_node) { /* Calibrate Node */ qtm_calibrate_sensor_node(&qtlib_acq_set1, sensor_node); /* Initialize key */ qtm_init_sensor_key(&qtlib_key_set1, sensor_node, &ptc_qtlib_node_stat1[sensor_node]); } /*============================================================================ ISR(ADC0_RESRDY_vect) ------------------------------------------------------------------------------ Purpose: Interrupt handler for ADC / PTC EOC Interrupt Input : none Output : none Notes : none ============================================================================*/ ISR(ADC0_RESRDY_vect) { qtm_t161x_ptc_handler_eoc(); } #endif /* TOUCH_C */
236839.c
/* ibmtr.c: A shared-memory IBM Token Ring 16/4 driver for linux * * Written 1993 by Mark Swanson and Peter De Schrijver. * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * This device driver should work with Any IBM Token Ring Card that does * not use DMA. * * I used Donald Becker's ([email protected]) device driver work * as a base for most of my initial work. * * Changes by Peter De Schrijver * ([email protected]) : * * + changed name to ibmtr.c in anticipation of other tr boards. * + changed reset code and adapter open code. * + added SAP open code. * + a first attempt to write interrupt, transmit and receive routines. * * Changes by David W. Morris ([email protected]) : * 941003 dwm: - Restructure tok_probe for multiple adapters, devices. * + Add comments, misc reorg for clarity. * + Flatten interrupt handler levels. * * Changes by Farzad Farid ([email protected]) * and Pascal Andre ([email protected]) (March 9 1995) : * + multi ring support clean up. * + RFC1042 compliance enhanced. * * Changes by Pascal Andre ([email protected]) (September 7 1995) : * + bug correction in tr_tx * + removed redundant information display * + some code reworking * * Changes by Michel Lespinasse ([email protected]), * Yann Doussot ([email protected]) and Pascal Andre ([email protected]) * (February 18, 1996) : * + modified shared memory and mmio access port the driver to * alpha platform (structure access -> readb/writeb) * * Changes by Steve Kipisz ([email protected] or [email protected]) * (January 18 1996): * + swapped WWOR and WWCR in ibmtr.h * + moved some init code from tok_probe into trdev_init. The * PCMCIA code can call trdev_init to complete initializing * the driver. * + added -DPCMCIA to support PCMCIA * + detecting PCMCIA Card Removal in interrupt handler. If * ISRP is FF, then a PCMCIA card has been removed * 10/2000 Burt needed a new method to avoid crashing the OS * * Changes by Paul Norton ([email protected]) : * + restructured the READ.LOG logic to prevent the transmit SRB * from being rudely overwritten before the transmit cycle is * complete. (August 15 1996) * + completed multiple adapter support. (November 20 1996) * + implemented csum_partial_copy in tr_rx and increased receive * buffer size and count. Minor fixes. (March 15, 1997) * * Changes by Christopher Turcksin <[email protected]> * + Now compiles ok as a module again. * * Changes by Paul Norton ([email protected]) : * + moved the header manipulation code in tr_tx and tr_rx to * net/802/tr.c. (July 12 1997) * + add retry and timeout on open if cable disconnected. (May 5 1998) * + lifted 2000 byte mtu limit. now depends on shared-RAM size. * May 25 1998) * + can't allocate 2k recv buff at 8k shared-RAM. (20 October 1998) * * Changes by Joel Sloan ([email protected]) : * + disable verbose debug messages by default - to enable verbose * debugging, edit the IBMTR_DEBUG_MESSAGES define below * * Changes by Mike Phillips <[email protected]> : * + Added extra #ifdef's to work with new PCMCIA Token Ring Code. * The PCMCIA code now just sets up the card so it can be recognized * by ibmtr_probe. Also checks allocated memory vs. on-board memory * for correct figure to use. * * Changes by Tim Hockin ([email protected]) : * + added spinlocks for SMP sanity (10 March 1999) * * Changes by Jochen Friedrich to enable RFC1469 Option 2 multicasting * i.e. using functional address C0 00 00 04 00 00 to transmit and * receive multicast packets. * * Changes by Mike Sullivan (based on original sram patch by Dave Grothe * to support windowing into on adapter shared ram. * i.e. Use LANAID to setup a PnP configuration with 16K RAM. Paging * will shift this 16K window over the entire available shared RAM. * * Changes by Peter De Schrijver ([email protected]) : * + fixed a problem with PCMCIA card removal * * Change by Mike Sullivan et al.: * + added turbo card support. No need to use lanaid to configure * the adapter into isa compatibility mode. * * Changes by Burt Silverman to allow the computer to behave nicely when * a cable is pulled or not in place, or a PCMCIA card is removed hot. */ /* change the define of IBMTR_DEBUG_MESSAGES to a nonzero value in the event that chatty debug messages are desired - jjs 12/30/98 */ #define IBMTR_DEBUG_MESSAGES 0 #include <linux/module.h> #include <linux/sched.h> #ifdef PCMCIA /* required for ibmtr_cs.c to build */ #undef MODULE /* yes, really */ #undef ENABLE_PAGING #else #define ENABLE_PAGING 1 #endif /* changes the output format of driver initialization */ #define TR_VERBOSE 0 /* some 95 OS send many non UI frame; this allow removing the warning */ #define TR_FILTERNONUI 1 #include <linux/ioport.h> #include <linux/netdevice.h> #include <linux/ip.h> #include <linux/trdevice.h> #include <linux/ibmtr.h> #include <net/checksum.h> #include <asm/io.h> #define DPRINTK(format, args...) printk("%s: " format, dev->name , ## args) #define DPRINTD(format, args...) DummyCall("%s: " format, dev->name , ## args) /* version and credits */ #ifndef PCMCIA static char version[] __devinitdata = "\nibmtr.c: v1.3.57 8/ 7/94 Peter De Schrijver and Mark Swanson\n" " v2.1.125 10/20/98 Paul Norton <[email protected]>\n" " v2.2.0 12/30/98 Joel Sloan <[email protected]>\n" " v2.2.1 02/08/00 Mike Sullivan <[email protected]>\n" " v2.2.2 07/27/00 Burt Silverman <[email protected]>\n" " v2.4.0 03/01/01 Mike Sullivan <[email protected]>\n"; #endif /* this allows displaying full adapter information */ static char *channel_def[] __devinitdata = { "ISA", "MCA", "ISA P&P" }; static char pcchannelid[] __devinitdata = { 0x05, 0x00, 0x04, 0x09, 0x04, 0x03, 0x04, 0x0f, 0x03, 0x06, 0x03, 0x01, 0x03, 0x01, 0x03, 0x00, 0x03, 0x09, 0x03, 0x09, 0x03, 0x00, 0x02, 0x00 }; static char mcchannelid[] __devinitdata = { 0x04, 0x0d, 0x04, 0x01, 0x05, 0x02, 0x05, 0x03, 0x03, 0x06, 0x03, 0x03, 0x05, 0x08, 0x03, 0x04, 0x03, 0x05, 0x03, 0x01, 0x03, 0x08, 0x02, 0x00 }; static char __devinit *adapter_def(char type) { switch (type) { case 0xF: return "PC Adapter | PC Adapter II | Adapter/A"; case 0xE: return "16/4 Adapter | 16/4 Adapter/A (long)"; case 0xD: return "16/4 Adapter/A (short) | 16/4 ISA-16 Adapter"; case 0xC: return "Auto 16/4 Adapter"; default: return "adapter (unknown type)"; }; }; #define TRC_INIT 0x01 /* Trace initialization & PROBEs */ #define TRC_INITV 0x02 /* verbose init trace points */ static unsigned char ibmtr_debug_trace = 0; static int ibmtr_probe1(struct net_device *dev, int ioaddr); static unsigned char get_sram_size(struct tok_info *adapt_info); static int trdev_init(struct net_device *dev); static int tok_open(struct net_device *dev); static int tok_init_card(struct net_device *dev); static void tok_open_adapter(unsigned long dev_addr); static void open_sap(unsigned char type, struct net_device *dev); static void tok_set_multicast_list(struct net_device *dev); static netdev_tx_t tok_send_packet(struct sk_buff *skb, struct net_device *dev); static int tok_close(struct net_device *dev); static irqreturn_t tok_interrupt(int irq, void *dev_id); static void initial_tok_int(struct net_device *dev); static void tr_tx(struct net_device *dev); static void tr_rx(struct net_device *dev); static void ibmtr_reset_timer(struct timer_list*tmr,struct net_device *dev); static void tok_rerun(unsigned long dev_addr); static void ibmtr_readlog(struct net_device *dev); static int ibmtr_change_mtu(struct net_device *dev, int mtu); static void find_turbo_adapters(int *iolist); static int ibmtr_portlist[IBMTR_MAX_ADAPTERS+1] __devinitdata = { 0xa20, 0xa24, 0, 0, 0 }; static int __devinitdata turbo_io[IBMTR_MAX_ADAPTERS] = {0}; static int __devinitdata turbo_irq[IBMTR_MAX_ADAPTERS] = {0}; static int __devinitdata turbo_searched = 0; #ifndef PCMCIA static __u32 ibmtr_mem_base __devinitdata = 0xd0000; #endif static void __devinit PrtChanID(char *pcid, short stride) { short i, j; for (i = 0, j = 0; i < 24; i++, j += stride) printk("%1x", ((int) pcid[j]) & 0x0f); printk("\n"); } static void __devinit HWPrtChanID(void __iomem *pcid, short stride) { short i, j; for (i = 0, j = 0; i < 24; i++, j += stride) printk("%1x", ((int) readb(pcid + j)) & 0x0f); printk("\n"); } /* We have to ioremap every checked address, because isa_readb is * going away. */ static void __devinit find_turbo_adapters(int *iolist) { int ram_addr; int index=0; void __iomem *chanid; int found_turbo=0; unsigned char *tchanid, ctemp; int i, j; unsigned long jif; void __iomem *ram_mapped ; if (turbo_searched == 1) return; turbo_searched=1; for (ram_addr=0xC0000; ram_addr < 0xE0000; ram_addr+=0x2000) { __u32 intf_tbl=0; found_turbo=1; ram_mapped = ioremap((u32)ram_addr,0x1fff) ; if (ram_mapped==NULL) continue ; chanid=(CHANNEL_ID + ram_mapped); tchanid=pcchannelid; ctemp=readb(chanid) & 0x0f; if (ctemp != *tchanid) continue; for (i=2,j=1; i<=46; i=i+2,j++) { if ((readb(chanid+i) & 0x0f) != tchanid[j]){ found_turbo=0; break; } } if (!found_turbo) continue; writeb(0x90, ram_mapped+0x1E01); for(i=2; i<0x0f; i++) { writeb(0x00, ram_mapped+0x1E01+i); } writeb(0x00, ram_mapped+0x1E01); for(jif=jiffies+TR_BUSY_INTERVAL; time_before_eq(jiffies,jif);); intf_tbl=ntohs(readw(ram_mapped+ACA_OFFSET+ACA_RW+WRBR_EVEN)); if (intf_tbl) { #if IBMTR_DEBUG_MESSAGES printk("ibmtr::find_turbo_adapters, Turbo found at " "ram_addr %x\n",ram_addr); printk("ibmtr::find_turbo_adapters, interface_table "); for(i=0; i<6; i++) { printk("%x:",readb(ram_addr+intf_tbl+i)); } printk("\n"); #endif turbo_io[index]=ntohs(readw(ram_mapped+intf_tbl+4)); turbo_irq[index]=readb(ram_mapped+intf_tbl+3); outb(0, turbo_io[index] + ADAPTRESET); for(jif=jiffies+TR_RST_TIME;time_before_eq(jiffies,jif);); outb(0, turbo_io[index] + ADAPTRESETREL); index++; continue; } #if IBMTR_DEBUG_MESSAGES printk("ibmtr::find_turbo_adapters, ibmtr card found at" " %x but not a Turbo model\n",ram_addr); #endif iounmap(ram_mapped) ; } /* for */ for(i=0; i<IBMTR_MAX_ADAPTERS; i++) { if(!turbo_io[i]) break; for (j=0; j<IBMTR_MAX_ADAPTERS; j++) { if ( iolist[j] && iolist[j] != turbo_io[i]) continue; iolist[j]=turbo_io[i]; break; } } } static void ibmtr_cleanup_card(struct net_device *dev) { if (dev->base_addr) { outb(0,dev->base_addr+ADAPTRESET); schedule_timeout_uninterruptible(TR_RST_TIME); /* wait 50ms */ outb(0,dev->base_addr+ADAPTRESETREL); } #ifndef PCMCIA free_irq(dev->irq, dev); release_region(dev->base_addr, IBMTR_IO_EXTENT); { struct tok_info *ti = netdev_priv(dev); iounmap(ti->mmio); iounmap(ti->sram_virt); } #endif } /**************************************************************************** * ibmtr_probe(): Routine specified in the network device structure * to probe for an IBM Token Ring Adapter. Routine outline: * I. Interrogate hardware to determine if an adapter exists * and what the speeds and feeds are * II. Setup data structures to control execution based upon * adapter characteristics. * * We expect ibmtr_probe to be called once for each device entry * which references it. ****************************************************************************/ static int __devinit ibmtr_probe(struct net_device *dev) { int i; int base_addr = dev->base_addr; if (base_addr && base_addr <= 0x1ff) /* Don't probe at all. */ return -ENXIO; if (base_addr > 0x1ff) { /* Check a single specified location. */ if (!ibmtr_probe1(dev, base_addr)) return 0; return -ENODEV; } find_turbo_adapters(ibmtr_portlist); for (i = 0; ibmtr_portlist[i]; i++) { int ioaddr = ibmtr_portlist[i]; if (!ibmtr_probe1(dev, ioaddr)) return 0; } return -ENODEV; } int __devinit ibmtr_probe_card(struct net_device *dev) { int err = ibmtr_probe(dev); if (!err) { err = register_netdev(dev); if (err) ibmtr_cleanup_card(dev); } return err; } /*****************************************************************************/ static int __devinit ibmtr_probe1(struct net_device *dev, int PIOaddr) { unsigned char segment, intr=0, irq=0, i, j, cardpresent=NOTOK, temp=0; void __iomem * t_mmio = NULL; struct tok_info *ti = netdev_priv(dev); void __iomem *cd_chanid; unsigned char *tchanid, ctemp; #ifndef PCMCIA unsigned char t_irq=0; unsigned long timeout; static int version_printed; #endif /* Query the adapter PIO base port which will return * indication of where MMIO was placed. We also have a * coded interrupt number. */ segment = inb(PIOaddr); if (segment < 0x40 || segment > 0xe0) { /* Out of range values so we'll assume non-existent IO device * but this is not necessarily a problem, esp if a turbo * adapter is being used. */ #if IBMTR_DEBUG_MESSAGES DPRINTK("ibmtr_probe1(): unhappy that inb(0x%X) == 0x%X, " "Hardware Problem?\n",PIOaddr,segment); #endif return -ENODEV; } /* * Compute the linear base address of the MMIO area * as LINUX doesn't care about segments */ t_mmio = ioremap(((__u32) (segment & 0xfc) << 11) + 0x80000,2048); if (!t_mmio) { DPRINTK("Cannot remap mmiobase memory area") ; return -ENODEV ; } intr = segment & 0x03; /* low bits is coded interrupt # */ if (ibmtr_debug_trace & TRC_INIT) DPRINTK("PIOaddr: %4hx seg/intr: %2x mmio base: %p intr: %d\n" , PIOaddr, (int) segment, t_mmio, (int) intr); /* * Now we will compare expected 'channelid' strings with * what we is there to learn of ISA/MCA or not TR card */ #ifdef PCMCIA iounmap(t_mmio); t_mmio = ti->mmio; /*BMS to get virtual address */ irq = ti->irq; /*BMS to display the irq! */ #endif cd_chanid = (CHANNEL_ID + t_mmio); /* for efficiency */ tchanid = pcchannelid; cardpresent = TR_ISA; /* try ISA */ /* Suboptimize knowing first byte different */ ctemp = readb(cd_chanid) & 0x0f; if (ctemp != *tchanid) { /* NOT ISA card, try MCA */ tchanid = mcchannelid; cardpresent = TR_MCA; if (ctemp != *tchanid) /* Neither ISA nor MCA */ cardpresent = NOTOK; } if (cardpresent != NOTOK) { /* Know presumed type, try rest of ID */ for (i = 2, j = 1; i <= 46; i = i + 2, j++) { if( (readb(cd_chanid+i)&0x0f) == tchanid[j]) continue; /* match failed, not TR card */ cardpresent = NOTOK; break; } } /* * If we have an ISA board check for the ISA P&P version, * as it has different IRQ settings */ if (cardpresent == TR_ISA && (readb(AIPFID + t_mmio) == 0x0e)) cardpresent = TR_ISAPNP; if (cardpresent == NOTOK) { /* "channel_id" did not match, report */ if (!(ibmtr_debug_trace & TRC_INIT)) { #ifndef PCMCIA iounmap(t_mmio); #endif return -ENODEV; } DPRINTK( "Channel ID string not found for PIOaddr: %4hx\n", PIOaddr); DPRINTK("Expected for ISA: "); PrtChanID(pcchannelid, 1); DPRINTK(" found: "); /* BMS Note that this can be misleading, when hardware is flaky, because you are reading it a second time here. So with my flaky hardware, I'll see my- self in this block, with the HW ID matching the ISA ID exactly! */ HWPrtChanID(cd_chanid, 2); DPRINTK("Expected for MCA: "); PrtChanID(mcchannelid, 1); } /* Now, setup some of the pl0 buffers for this driver.. */ /* If called from PCMCIA, it is already set up, so no need to waste the memory, just use the existing structure */ #ifndef PCMCIA ti->mmio = t_mmio; for (i = 0; i < IBMTR_MAX_ADAPTERS; i++) { if (turbo_io[i] != PIOaddr) continue; #if IBMTR_DEBUG_MESSAGES printk("ibmtr::tr_probe1, setting PIOaddr %x to Turbo\n", PIOaddr); #endif ti->turbo = 1; t_irq = turbo_irq[i]; } #endif /* !PCMCIA */ ti->readlog_pending = 0; init_waitqueue_head(&ti->wait_for_reset); /* if PCMCIA, the card can be recognized as either TR_ISA or TR_ISAPNP * depending which card is inserted. */ #ifndef PCMCIA switch (cardpresent) { case TR_ISA: if (intr == 0) irq = 9; /* irq2 really is irq9 */ if (intr == 1) irq = 3; if (intr == 2) irq = 6; if (intr == 3) irq = 7; ti->adapter_int_enable = PIOaddr + ADAPTINTREL; break; case TR_MCA: if (intr == 0) irq = 9; if (intr == 1) irq = 3; if (intr == 2) irq = 10; if (intr == 3) irq = 11; ti->global_int_enable = 0; ti->adapter_int_enable = 0; ti->sram_phys=(__u32)(inb(PIOaddr+ADAPTRESETREL) & 0xfe) << 12; break; case TR_ISAPNP: if (!t_irq) { if (intr == 0) irq = 9; if (intr == 1) irq = 3; if (intr == 2) irq = 10; if (intr == 3) irq = 11; } else irq=t_irq; timeout = jiffies + TR_SPIN_INTERVAL; while (!readb(ti->mmio + ACA_OFFSET + ACA_RW + RRR_EVEN)){ if (!time_after(jiffies, timeout)) continue; DPRINTK( "Hardware timeout during initialization.\n"); iounmap(t_mmio); return -ENODEV; } ti->sram_phys = ((__u32)readb(ti->mmio+ACA_OFFSET+ACA_RW+RRR_EVEN)<<12); ti->adapter_int_enable = PIOaddr + ADAPTINTREL; break; } /*end switch (cardpresent) */ #endif /*not PCMCIA */ if (ibmtr_debug_trace & TRC_INIT) { /* just report int */ DPRINTK("irq=%d", irq); printk(", sram_phys=0x%x", ti->sram_phys); if(ibmtr_debug_trace&TRC_INITV){ /* full chat in verbose only */ DPRINTK(", ti->mmio=%p", ti->mmio); printk(", segment=%02X", segment); } printk(".\n"); } /* Get hw address of token ring card */ j = 0; for (i = 0; i < 0x18; i = i + 2) { /* technical reference states to do this */ temp = readb(ti->mmio + AIP + i) & 0x0f; ti->hw_address[j] = temp; if (j & 1) dev->dev_addr[(j / 2)] = ti->hw_address[j]+ (ti->hw_address[j - 1] << 4); ++j; } /* get Adapter type: 'F' = Adapter/A, 'E' = 16/4 Adapter II,... */ ti->adapter_type = readb(ti->mmio + AIPADAPTYPE); /* get Data Rate: F=4Mb, E=16Mb, D=4Mb & 16Mb ?? */ ti->data_rate = readb(ti->mmio + AIPDATARATE); /* Get Early Token Release support?: F=no, E=4Mb, D=16Mb, C=4&16Mb */ ti->token_release = readb(ti->mmio + AIPEARLYTOKEN); /* How much shared RAM is on adapter ? */ if (ti->turbo) { ti->avail_shared_ram=127; } else { ti->avail_shared_ram = get_sram_size(ti);/*in 512 byte units */ } /* We need to set or do a bunch of work here based on previous results*/ /* Support paging? What sizes?: F=no, E=16k, D=32k, C=16 & 32k */ ti->shared_ram_paging = readb(ti->mmio + AIPSHRAMPAGE); /* Available DHB 4Mb size: F=2048, E=4096, D=4464 */ switch (readb(ti->mmio + AIP4MBDHB)) { case 0xe: ti->dhb_size4mb = 4096; break; case 0xd: ti->dhb_size4mb = 4464; break; default: ti->dhb_size4mb = 2048; break; } /* Available DHB 16Mb size: F=2048, E=4096, D=8192, C=16384, B=17960 */ switch (readb(ti->mmio + AIP16MBDHB)) { case 0xe: ti->dhb_size16mb = 4096; break; case 0xd: ti->dhb_size16mb = 8192; break; case 0xc: ti->dhb_size16mb = 16384; break; case 0xb: ti->dhb_size16mb = 17960; break; default: ti->dhb_size16mb = 2048; break; } /* We must figure out how much shared memory space this adapter * will occupy so that if there are two adapters we can fit both * in. Given a choice, we will limit this adapter to 32K. The * maximum space will will use for two adapters is 64K so if the * adapter we are working on demands 64K (it also doesn't support * paging), then only one adapter can be supported. */ /* * determine how much of total RAM is mapped into PC space */ ti->mapped_ram_size= /*sixteen to onehundredtwentyeight 512byte blocks*/ 1<< ((readb(ti->mmio+ACA_OFFSET+ACA_RW+RRR_ODD) >> 2 & 0x03) + 4); ti->page_mask = 0; if (ti->turbo) ti->page_mask=0xf0; else if (ti->shared_ram_paging == 0xf); /* No paging in adapter */ else { #ifdef ENABLE_PAGING unsigned char pg_size = 0; /* BMS: page size: PCMCIA, use configuration register; ISAPNP, use LANAIDC config tool from www.ibm.com */ switch (ti->shared_ram_paging) { case 0xf: break; case 0xe: ti->page_mask = (ti->mapped_ram_size == 32) ? 0xc0 : 0; pg_size = 32; /* 16KB page size */ break; case 0xd: ti->page_mask = (ti->mapped_ram_size == 64) ? 0x80 : 0; pg_size = 64; /* 32KB page size */ break; case 0xc: switch (ti->mapped_ram_size) { case 32: ti->page_mask = 0xc0; pg_size = 32; break; case 64: ti->page_mask = 0x80; pg_size = 64; break; } break; default: DPRINTK("Unknown shared ram paging info %01X\n", ti->shared_ram_paging); iounmap(t_mmio); return -ENODEV; break; } /*end switch shared_ram_paging */ if (ibmtr_debug_trace & TRC_INIT) DPRINTK("Shared RAM paging code: %02X, " "mapped RAM size: %dK, shared RAM size: %dK, " "page mask: %02X\n:", ti->shared_ram_paging, ti->mapped_ram_size / 2, ti->avail_shared_ram / 2, ti->page_mask); #endif /*ENABLE_PAGING */ } #ifndef PCMCIA /* finish figuring the shared RAM address */ if (cardpresent == TR_ISA) { static __u32 ram_bndry_mask[] = { 0xffffe000, 0xffffc000, 0xffff8000, 0xffff0000 }; __u32 new_base, rrr_32, chk_base, rbm; rrr_32=readb(ti->mmio+ACA_OFFSET+ACA_RW+RRR_ODD) >> 2 & 0x03; rbm = ram_bndry_mask[rrr_32]; new_base = (ibmtr_mem_base + (~rbm)) & rbm;/* up to boundary */ chk_base = new_base + (ti->mapped_ram_size << 9); if (chk_base > (ibmtr_mem_base + IBMTR_SHARED_RAM_SIZE)) { DPRINTK("Shared RAM for this adapter (%05x) exceeds " "driver limit (%05x), adapter not started.\n", chk_base, ibmtr_mem_base + IBMTR_SHARED_RAM_SIZE); iounmap(t_mmio); return -ENODEV; } else { /* seems cool, record what we have figured out */ ti->sram_base = new_base >> 12; ibmtr_mem_base = chk_base; } } else ti->sram_base = ti->sram_phys >> 12; /* The PCMCIA has already got the interrupt line and the io port, so no chance of anybody else getting it - MLP */ if (request_irq(dev->irq = irq, tok_interrupt, 0, "ibmtr", dev) != 0) { DPRINTK("Could not grab irq %d. Halting Token Ring driver.\n", irq); iounmap(t_mmio); return -ENODEV; } /*?? Now, allocate some of the PIO PORTs for this driver.. */ /* record PIOaddr range as busy */ if (!request_region(PIOaddr, IBMTR_IO_EXTENT, "ibmtr")) { DPRINTK("Could not grab PIO range. Halting driver.\n"); free_irq(dev->irq, dev); iounmap(t_mmio); return -EBUSY; } if (!version_printed++) { printk(version); } #endif /* !PCMCIA */ DPRINTK("%s %s found\n", channel_def[cardpresent - 1], adapter_def(ti->adapter_type)); DPRINTK("using irq %d, PIOaddr %hx, %dK shared RAM.\n", irq, PIOaddr, ti->mapped_ram_size / 2); DPRINTK("Hardware address : %pM\n", dev->dev_addr); if (ti->page_mask) DPRINTK("Shared RAM paging enabled. " "Page size: %uK Shared Ram size %dK\n", ((ti->page_mask^0xff)+1) >>2, ti->avail_shared_ram / 2); else DPRINTK("Shared RAM paging disabled. ti->page_mask %x\n", ti->page_mask); /* Calculate the maximum DHB we can use */ /* two cases where avail_shared_ram doesn't equal mapped_ram_size: 1. avail_shared_ram is 127 but mapped_ram_size is 128 (typical) 2. user has configured adapter for less than avail_shared_ram but is not using paging (she should use paging, I believe) */ if (!ti->page_mask) { ti->avail_shared_ram= min(ti->mapped_ram_size,ti->avail_shared_ram); } switch (ti->avail_shared_ram) { case 16: /* 8KB shared RAM */ ti->dhb_size4mb = min(ti->dhb_size4mb, (unsigned short)2048); ti->rbuf_len4 = 1032; ti->rbuf_cnt4=2; ti->dhb_size16mb = min(ti->dhb_size16mb, (unsigned short)2048); ti->rbuf_len16 = 1032; ti->rbuf_cnt16=2; break; case 32: /* 16KB shared RAM */ ti->dhb_size4mb = min(ti->dhb_size4mb, (unsigned short)4464); ti->rbuf_len4 = 1032; ti->rbuf_cnt4=4; ti->dhb_size16mb = min(ti->dhb_size16mb, (unsigned short)4096); ti->rbuf_len16 = 1032; /*1024 usable */ ti->rbuf_cnt16=4; break; case 64: /* 32KB shared RAM */ ti->dhb_size4mb = min(ti->dhb_size4mb, (unsigned short)4464); ti->rbuf_len4 = 1032; ti->rbuf_cnt4=6; ti->dhb_size16mb = min(ti->dhb_size16mb, (unsigned short)10240); ti->rbuf_len16 = 1032; ti->rbuf_cnt16=6; break; case 127: /* 63.5KB shared RAM */ ti->dhb_size4mb = min(ti->dhb_size4mb, (unsigned short)4464); ti->rbuf_len4 = 1032; ti->rbuf_cnt4=6; ti->dhb_size16mb = min(ti->dhb_size16mb, (unsigned short)16384); ti->rbuf_len16 = 1032; ti->rbuf_cnt16=16; break; case 128: /* 64KB shared RAM */ ti->dhb_size4mb = min(ti->dhb_size4mb, (unsigned short)4464); ti->rbuf_len4 = 1032; ti->rbuf_cnt4=6; ti->dhb_size16mb = min(ti->dhb_size16mb, (unsigned short)17960); ti->rbuf_len16 = 1032; ti->rbuf_cnt16=16; break; default: ti->dhb_size4mb = 2048; ti->rbuf_len4 = 1032; ti->rbuf_cnt4=2; ti->dhb_size16mb = 2048; ti->rbuf_len16 = 1032; ti->rbuf_cnt16=2; break; } /* this formula is not smart enough for the paging case ti->rbuf_cnt<x> = (ti->avail_shared_ram * BLOCKSZ - ADAPT_PRIVATE - ARBLENGTH - SSBLENGTH - DLC_MAX_SAP * SAPLENGTH - DLC_MAX_STA * STALENGTH - ti->dhb_size<x>mb * NUM_DHB - SRBLENGTH - ASBLENGTH) / ti->rbuf_len<x>; */ ti->maxmtu16 = (ti->rbuf_len16 - 8) * ti->rbuf_cnt16 - TR_HLEN; ti->maxmtu4 = (ti->rbuf_len4 - 8) * ti->rbuf_cnt4 - TR_HLEN; /*BMS assuming 18 bytes of Routing Information (usually works) */ DPRINTK("Maximum Receive Internet Protocol MTU 16Mbps: %d, 4Mbps: %d\n", ti->maxmtu16, ti->maxmtu4); dev->base_addr = PIOaddr; /* set the value for device */ dev->mem_start = ti->sram_base << 12; dev->mem_end = dev->mem_start + (ti->mapped_ram_size << 9) - 1; trdev_init(dev); return 0; /* Return 0 to indicate we have found a Token Ring card. */ } /*ibmtr_probe1() */ /*****************************************************************************/ /* query the adapter for the size of shared RAM */ /* the function returns the RAM size in units of 512 bytes */ static unsigned char __devinit get_sram_size(struct tok_info *adapt_info) { unsigned char avail_sram_code; static unsigned char size_code[] = { 0, 16, 32, 64, 127, 128 }; /* Adapter gives 'F' -- use RRR bits 3,2 'E' -- 8kb 'D' -- 16kb 'C' -- 32kb 'A' -- 64KB 'B' - 64KB less 512 bytes at top (WARNING ... must zero top bytes in INIT */ avail_sram_code = 0xf - readb(adapt_info->mmio + AIPAVAILSHRAM); if (avail_sram_code) return size_code[avail_sram_code]; else /* for code 'F', must compute size from RRR(3,2) bits */ return 1 << ((readb(adapt_info->mmio+ACA_OFFSET+ACA_RW+RRR_ODD)>>2&3)+4); } /*****************************************************************************/ static const struct net_device_ops trdev_netdev_ops = { .ndo_open = tok_open, .ndo_stop = tok_close, .ndo_start_xmit = tok_send_packet, .ndo_set_multicast_list = tok_set_multicast_list, .ndo_change_mtu = ibmtr_change_mtu, }; static int __devinit trdev_init(struct net_device *dev) { struct tok_info *ti = netdev_priv(dev); SET_PAGE(ti->srb_page); ti->open_failure = NO ; dev->netdev_ops = &trdev_netdev_ops; return 0; } /*****************************************************************************/ static int tok_init_card(struct net_device *dev) { struct tok_info *ti; short PIOaddr; unsigned long i; PIOaddr = dev->base_addr; ti = netdev_priv(dev); /* Special processing for first interrupt after reset */ ti->do_tok_int = FIRST_INT; /* Reset adapter */ writeb(~INT_ENABLE, ti->mmio + ACA_OFFSET + ACA_RESET + ISRP_EVEN); outb(0, PIOaddr + ADAPTRESET); schedule_timeout_uninterruptible(TR_RST_TIME); /* wait 50ms */ outb(0, PIOaddr + ADAPTRESETREL); #ifdef ENABLE_PAGING if (ti->page_mask) writeb(SRPR_ENABLE_PAGING,ti->mmio+ACA_OFFSET+ACA_RW+SRPR_EVEN); #endif writeb(INT_ENABLE, ti->mmio + ACA_OFFSET + ACA_SET + ISRP_EVEN); i = sleep_on_timeout(&ti->wait_for_reset, 4 * HZ); return i? 0 : -EAGAIN; } /*****************************************************************************/ static int tok_open(struct net_device *dev) { struct tok_info *ti = netdev_priv(dev); int i; /*the case we were left in a failure state during a previous open */ if (ti->open_failure == YES) { DPRINTK("Last time you were disconnected, how about now?\n"); printk("You can't insert with an ICS connector half-cocked.\n"); } ti->open_status = CLOSED; /* CLOSED or OPEN */ ti->sap_status = CLOSED; /* CLOSED or OPEN */ ti->open_failure = NO; /* NO or YES */ ti->open_mode = MANUAL; /* MANUAL or AUTOMATIC */ ti->sram_phys &= ~1; /* to reverse what we do in tok_close */ /* init the spinlock */ spin_lock_init(&ti->lock); init_timer(&ti->tr_timer); i = tok_init_card(dev); if (i) return i; while (1){ tok_open_adapter((unsigned long) dev); i= interruptible_sleep_on_timeout(&ti->wait_for_reset, 25 * HZ); /* sig catch: estimate opening adapter takes more than .5 sec*/ if (i>(245*HZ)/10) break; /* fancier than if (i==25*HZ) */ if (i==0) break; if (ti->open_status == OPEN && ti->sap_status==OPEN) { netif_start_queue(dev); DPRINTK("Adapter is up and running\n"); return 0; } i=schedule_timeout_interruptible(TR_RETRY_INTERVAL); /* wait 30 seconds */ if(i!=0) break; /*prob. a signal, like the i>24*HZ case above */ } outb(0, dev->base_addr + ADAPTRESET);/* kill pending interrupts*/ DPRINTK("TERMINATED via signal\n"); /*BMS useful */ return -EAGAIN; } /*****************************************************************************/ #define COMMAND_OFST 0 #define OPEN_OPTIONS_OFST 8 #define NUM_RCV_BUF_OFST 24 #define RCV_BUF_LEN_OFST 26 #define DHB_LENGTH_OFST 28 #define NUM_DHB_OFST 30 #define DLC_MAX_SAP_OFST 32 #define DLC_MAX_STA_OFST 33 static void tok_open_adapter(unsigned long dev_addr) { struct net_device *dev = (struct net_device *) dev_addr; struct tok_info *ti; int i; ti = netdev_priv(dev); SET_PAGE(ti->init_srb_page); writeb(~SRB_RESP_INT, ti->mmio + ACA_OFFSET + ACA_RESET + ISRP_ODD); for (i = 0; i < sizeof(struct dir_open_adapter); i++) writeb(0, ti->init_srb + i); writeb(DIR_OPEN_ADAPTER, ti->init_srb + COMMAND_OFST); writew(htons(OPEN_PASS_BCON_MAC), ti->init_srb + OPEN_OPTIONS_OFST); if (ti->ring_speed == 16) { writew(htons(ti->dhb_size16mb), ti->init_srb + DHB_LENGTH_OFST); writew(htons(ti->rbuf_cnt16), ti->init_srb + NUM_RCV_BUF_OFST); writew(htons(ti->rbuf_len16), ti->init_srb + RCV_BUF_LEN_OFST); } else { writew(htons(ti->dhb_size4mb), ti->init_srb + DHB_LENGTH_OFST); writew(htons(ti->rbuf_cnt4), ti->init_srb + NUM_RCV_BUF_OFST); writew(htons(ti->rbuf_len4), ti->init_srb + RCV_BUF_LEN_OFST); } writeb(NUM_DHB, /* always 2 */ ti->init_srb + NUM_DHB_OFST); writeb(DLC_MAX_SAP, ti->init_srb + DLC_MAX_SAP_OFST); writeb(DLC_MAX_STA, ti->init_srb + DLC_MAX_STA_OFST); ti->srb = ti->init_srb; /* We use this one in the interrupt handler */ ti->srb_page = ti->init_srb_page; DPRINTK("Opening adapter: Xmit bfrs: %d X %d, Rcv bfrs: %d X %d\n", readb(ti->init_srb + NUM_DHB_OFST), ntohs(readw(ti->init_srb + DHB_LENGTH_OFST)), ntohs(readw(ti->init_srb + NUM_RCV_BUF_OFST)), ntohs(readw(ti->init_srb + RCV_BUF_LEN_OFST))); writeb(INT_ENABLE, ti->mmio + ACA_OFFSET + ACA_SET + ISRP_EVEN); writeb(CMD_IN_SRB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); } /*****************************************************************************/ static void open_sap(unsigned char type, struct net_device *dev) { int i; struct tok_info *ti = netdev_priv(dev); SET_PAGE(ti->srb_page); for (i = 0; i < sizeof(struct dlc_open_sap); i++) writeb(0, ti->srb + i); #define MAX_I_FIELD_OFST 14 #define SAP_VALUE_OFST 16 #define SAP_OPTIONS_OFST 17 #define STATION_COUNT_OFST 18 writeb(DLC_OPEN_SAP, ti->srb + COMMAND_OFST); writew(htons(MAX_I_FIELD), ti->srb + MAX_I_FIELD_OFST); writeb(SAP_OPEN_IND_SAP | SAP_OPEN_PRIORITY, ti->srb+ SAP_OPTIONS_OFST); writeb(SAP_OPEN_STATION_CNT, ti->srb + STATION_COUNT_OFST); writeb(type, ti->srb + SAP_VALUE_OFST); writeb(CMD_IN_SRB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); } /*****************************************************************************/ static void tok_set_multicast_list(struct net_device *dev) { struct tok_info *ti = netdev_priv(dev); struct netdev_hw_addr *ha; unsigned char address[4]; int i; /*BMS the next line is CRUCIAL or you may be sad when you */ /*BMS ifconfig tr down or hot unplug a PCMCIA card ??hownowbrowncow*/ if (/*BMSHELPdev->start == 0 ||*/ ti->open_status != OPEN) return; address[0] = address[1] = address[2] = address[3] = 0; netdev_for_each_mc_addr(ha, dev) { address[0] |= ha->addr[2]; address[1] |= ha->addr[3]; address[2] |= ha->addr[4]; address[3] |= ha->addr[5]; } SET_PAGE(ti->srb_page); for (i = 0; i < sizeof(struct srb_set_funct_addr); i++) writeb(0, ti->srb + i); #define FUNCT_ADDRESS_OFST 6 writeb(DIR_SET_FUNC_ADDR, ti->srb + COMMAND_OFST); for (i = 0; i < 4; i++) writeb(address[i], ti->srb + FUNCT_ADDRESS_OFST + i); writeb(CMD_IN_SRB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); #if TR_VERBOSE DPRINTK("Setting functional address: "); for (i=0;i<4;i++) printk("%02X ", address[i]); printk("\n"); #endif } /*****************************************************************************/ #define STATION_ID_OFST 4 static netdev_tx_t tok_send_packet(struct sk_buff *skb, struct net_device *dev) { struct tok_info *ti; unsigned long flags; ti = netdev_priv(dev); netif_stop_queue(dev); /* lock against other CPUs */ spin_lock_irqsave(&(ti->lock), flags); /* Save skb; we'll need it when the adapter asks for the data */ ti->current_skb = skb; SET_PAGE(ti->srb_page); writeb(XMIT_UI_FRAME, ti->srb + COMMAND_OFST); writew(ti->exsap_station_id, ti->srb + STATION_ID_OFST); writeb(CMD_IN_SRB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); spin_unlock_irqrestore(&(ti->lock), flags); return NETDEV_TX_OK; } /*****************************************************************************/ static int tok_close(struct net_device *dev) { struct tok_info *ti = netdev_priv(dev); /* Important for PCMCIA hot unplug, otherwise, we'll pull the card, */ /* unloading the module from memory, and then if a timer pops, ouch */ del_timer_sync(&ti->tr_timer); outb(0, dev->base_addr + ADAPTRESET); ti->sram_phys |= 1; ti->open_status = CLOSED; netif_stop_queue(dev); DPRINTK("Adapter is closed.\n"); return 0; } /*****************************************************************************/ #define RETCODE_OFST 2 #define OPEN_ERROR_CODE_OFST 6 #define ASB_ADDRESS_OFST 8 #define SRB_ADDRESS_OFST 10 #define ARB_ADDRESS_OFST 12 #define SSB_ADDRESS_OFST 14 static char *printphase[]= {"Lobe media test","Physical insertion", "Address verification","Roll call poll","Request Parameters"}; static char *printerror[]={"Function failure","Signal loss","Reserved", "Frequency error","Timeout","Ring failure","Ring beaconing", "Duplicate node address", "Parameter request-retry count exceeded","Remove received", "IMPL force received","Duplicate modifier", "No monitor detected","Monitor contention failed for RPL"}; static void __iomem *map_address(struct tok_info *ti, unsigned index, __u8 *page) { if (ti->page_mask) { *page = (index >> 8) & ti->page_mask; index &= ~(ti->page_mask << 8); } return ti->sram_virt + index; } static void dir_open_adapter (struct net_device *dev) { struct tok_info *ti = netdev_priv(dev); unsigned char ret_code; __u16 err; ti->srb = map_address(ti, ntohs(readw(ti->init_srb + SRB_ADDRESS_OFST)), &ti->srb_page); ti->ssb = map_address(ti, ntohs(readw(ti->init_srb + SSB_ADDRESS_OFST)), &ti->ssb_page); ti->arb = map_address(ti, ntohs(readw(ti->init_srb + ARB_ADDRESS_OFST)), &ti->arb_page); ti->asb = map_address(ti, ntohs(readw(ti->init_srb + ASB_ADDRESS_OFST)), &ti->asb_page); ti->current_skb = NULL; ret_code = readb(ti->init_srb + RETCODE_OFST); err = ntohs(readw(ti->init_srb + OPEN_ERROR_CODE_OFST)); if (!ret_code) { ti->open_status = OPEN; /* TR adapter is now available */ if (ti->open_mode == AUTOMATIC) { DPRINTK("Adapter reopened.\n"); } writeb(~SRB_RESP_INT, ti->mmio+ACA_OFFSET+ACA_RESET+ISRP_ODD); open_sap(EXTENDED_SAP, dev); return; } ti->open_failure = YES; if (ret_code == 7){ if (err == 0x24) { if (!ti->auto_speedsave) { DPRINTK("Open failed: Adapter speed must match " "ring speed if Automatic Ring Speed Save is " "disabled.\n"); ti->open_action = FAIL; }else DPRINTK("Retrying open to adjust to " "ring speed, "); } else if (err == 0x2d) { DPRINTK("Physical Insertion: No Monitor Detected, "); printk("retrying after %ds delay...\n", TR_RETRY_INTERVAL/HZ); } else if (err == 0x11) { DPRINTK("Lobe Media Function Failure (0x11), "); printk(" retrying after %ds delay...\n", TR_RETRY_INTERVAL/HZ); } else { char **prphase = printphase; char **prerror = printerror; int pnr = err / 16 - 1; int enr = err % 16 - 1; DPRINTK("TR Adapter misc open failure, error code = "); if (pnr < 0 || pnr >= ARRAY_SIZE(printphase) || enr < 0 || enr >= ARRAY_SIZE(printerror)) printk("0x%x, invalid Phase/Error.", err); else printk("0x%x, Phase: %s, Error: %s\n", err, prphase[pnr], prerror[enr]); printk(" retrying after %ds delay...\n", TR_RETRY_INTERVAL/HZ); } } else DPRINTK("open failed: ret_code = %02X..., ", ret_code); if (ti->open_action != FAIL) { if (ti->open_mode==AUTOMATIC){ ti->open_action = REOPEN; ibmtr_reset_timer(&(ti->tr_timer), dev); return; } wake_up(&ti->wait_for_reset); return; } DPRINTK("FAILURE, CAPUT\n"); } /******************************************************************************/ static irqreturn_t tok_interrupt(int irq, void *dev_id) { unsigned char status; /* unsigned char status_even ; */ struct tok_info *ti; struct net_device *dev; #ifdef ENABLE_PAGING unsigned char save_srpr; #endif dev = dev_id; #if TR_VERBOSE DPRINTK("Int from tok_driver, dev : %p irq%d\n", dev,irq); #endif ti = netdev_priv(dev); if (ti->sram_phys & 1) return IRQ_NONE; /* PCMCIA card extraction flag */ spin_lock(&(ti->lock)); #ifdef ENABLE_PAGING save_srpr = readb(ti->mmio + ACA_OFFSET + ACA_RW + SRPR_EVEN); #endif /* Disable interrupts till processing is finished */ writeb((~INT_ENABLE), ti->mmio + ACA_OFFSET + ACA_RESET + ISRP_EVEN); /* Reset interrupt for ISA boards */ if (ti->adapter_int_enable) outb(0, ti->adapter_int_enable); else /* used for PCMCIA cards */ outb(0, ti->global_int_enable); if (ti->do_tok_int == FIRST_INT){ initial_tok_int(dev); #ifdef ENABLE_PAGING writeb(save_srpr, ti->mmio + ACA_OFFSET + ACA_RW + SRPR_EVEN); #endif spin_unlock(&(ti->lock)); return IRQ_HANDLED; } /* Begin interrupt handler HERE inline to avoid the extra levels of logic and call depth for the original solution. */ status = readb(ti->mmio + ACA_OFFSET + ACA_RW + ISRP_ODD); /*BMSstatus_even = readb (ti->mmio + ACA_OFFSET + ACA_RW + ISRP_EVEN) */ /*BMSdebugprintk("tok_interrupt: ISRP_ODD = 0x%x ISRP_EVEN = 0x%x\n", */ /*BMS status,status_even); */ if (status & ADAP_CHK_INT) { int i; void __iomem *check_reason; __u8 check_reason_page = 0; check_reason = map_address(ti, ntohs(readw(ti->mmio+ ACA_OFFSET+ACA_RW + WWCR_EVEN)), &check_reason_page); SET_PAGE(check_reason_page); DPRINTK("Adapter check interrupt\n"); DPRINTK("8 reason bytes follow: "); for (i = 0; i < 8; i++, check_reason++) printk("%02X ", (int) readb(check_reason)); printk("\n"); writeb(~ADAP_CHK_INT, ti->mmio+ ACA_OFFSET+ACA_RESET+ ISRP_ODD); status = readb(ti->mmio + ACA_OFFSET + ACA_RW + ISRA_EVEN); DPRINTK("ISRA_EVEN == 0x02%x\n",status); ti->open_status = CLOSED; ti->sap_status = CLOSED; ti->open_mode = AUTOMATIC; netif_carrier_off(dev); netif_stop_queue(dev); ti->open_action = RESTART; outb(0, dev->base_addr + ADAPTRESET); ibmtr_reset_timer(&(ti->tr_timer), dev);/*BMS try to reopen*/ spin_unlock(&(ti->lock)); return IRQ_HANDLED; } if (readb(ti->mmio + ACA_OFFSET + ACA_RW + ISRP_EVEN) & (TCR_INT | ERR_INT | ACCESS_INT)) { DPRINTK("adapter error: ISRP_EVEN : %02x\n", (int)readb(ti->mmio+ ACA_OFFSET + ACA_RW + ISRP_EVEN)); writeb(~(TCR_INT | ERR_INT | ACCESS_INT), ti->mmio + ACA_OFFSET + ACA_RESET + ISRP_EVEN); status= readb(ti->mmio+ ACA_OFFSET + ACA_RW + ISRA_EVEN);/*BMS*/ DPRINTK("ISRA_EVEN == 0x02%x\n",status);/*BMS*/ writeb(INT_ENABLE, ti->mmio + ACA_OFFSET + ACA_SET + ISRP_EVEN); #ifdef ENABLE_PAGING writeb(save_srpr, ti->mmio + ACA_OFFSET + ACA_RW + SRPR_EVEN); #endif spin_unlock(&(ti->lock)); return IRQ_HANDLED; } if (status & SRB_RESP_INT) { /* SRB response */ SET_PAGE(ti->srb_page); #if TR_VERBOSE DPRINTK("SRB resp: cmd=%02X rsp=%02X\n", readb(ti->srb), readb(ti->srb + RETCODE_OFST)); #endif switch (readb(ti->srb)) { /* SRB command check */ case XMIT_DIR_FRAME:{ unsigned char xmit_ret_code; xmit_ret_code = readb(ti->srb + RETCODE_OFST); if (xmit_ret_code == 0xff) break; DPRINTK("error on xmit_dir_frame request: %02X\n", xmit_ret_code); if (ti->current_skb) { dev_kfree_skb_irq(ti->current_skb); ti->current_skb = NULL; } /*dev->tbusy = 0;*/ netif_wake_queue(dev); if (ti->readlog_pending) ibmtr_readlog(dev); break; } case XMIT_UI_FRAME:{ unsigned char xmit_ret_code; xmit_ret_code = readb(ti->srb + RETCODE_OFST); if (xmit_ret_code == 0xff) break; DPRINTK("error on xmit_ui_frame request: %02X\n", xmit_ret_code); if (ti->current_skb) { dev_kfree_skb_irq(ti->current_skb); ti->current_skb = NULL; } netif_wake_queue(dev); if (ti->readlog_pending) ibmtr_readlog(dev); break; } case DIR_OPEN_ADAPTER: dir_open_adapter(dev); break; case DLC_OPEN_SAP: if (readb(ti->srb + RETCODE_OFST)) { DPRINTK("open_sap failed: ret_code = %02X, " "retrying\n", (int) readb(ti->srb + RETCODE_OFST)); ti->open_action = REOPEN; ibmtr_reset_timer(&(ti->tr_timer), dev); break; } ti->exsap_station_id = readw(ti->srb + STATION_ID_OFST); ti->sap_status = OPEN;/* TR adapter is now available */ if (ti->open_mode==MANUAL){ wake_up(&ti->wait_for_reset); break; } netif_wake_queue(dev); netif_carrier_on(dev); break; case DIR_INTERRUPT: case DIR_MOD_OPEN_PARAMS: case DIR_SET_GRP_ADDR: case DIR_SET_FUNC_ADDR: case DLC_CLOSE_SAP: if (readb(ti->srb + RETCODE_OFST)) DPRINTK("error on %02X: %02X\n", (int) readb(ti->srb + COMMAND_OFST), (int) readb(ti->srb + RETCODE_OFST)); break; case DIR_READ_LOG: if (readb(ti->srb + RETCODE_OFST)){ DPRINTK("error on dir_read_log: %02X\n", (int) readb(ti->srb + RETCODE_OFST)); netif_wake_queue(dev); break; } #if IBMTR_DEBUG_MESSAGES #define LINE_ERRORS_OFST 0 #define INTERNAL_ERRORS_OFST 1 #define BURST_ERRORS_OFST 2 #define AC_ERRORS_OFST 3 #define ABORT_DELIMITERS_OFST 4 #define LOST_FRAMES_OFST 6 #define RECV_CONGEST_COUNT_OFST 7 #define FRAME_COPIED_ERRORS_OFST 8 #define FREQUENCY_ERRORS_OFST 9 #define TOKEN_ERRORS_OFST 10 DPRINTK("Line errors %02X, Internal errors %02X, " "Burst errors %02X\n" "A/C errors %02X, " "Abort delimiters %02X, Lost frames %02X\n" "Receive congestion count %02X, " "Frame copied errors %02X\nFrequency errors %02X, " "Token errors %02X\n", (int) readb(ti->srb + LINE_ERRORS_OFST), (int) readb(ti->srb + INTERNAL_ERRORS_OFST), (int) readb(ti->srb + BURST_ERRORS_OFST), (int) readb(ti->srb + AC_ERRORS_OFST), (int) readb(ti->srb + ABORT_DELIMITERS_OFST), (int) readb(ti->srb + LOST_FRAMES_OFST), (int) readb(ti->srb + RECV_CONGEST_COUNT_OFST), (int) readb(ti->srb + FRAME_COPIED_ERRORS_OFST), (int) readb(ti->srb + FREQUENCY_ERRORS_OFST), (int) readb(ti->srb + TOKEN_ERRORS_OFST)); #endif netif_wake_queue(dev); break; default: DPRINTK("Unknown command %02X encountered\n", (int) readb(ti->srb)); } /* end switch SRB command check */ writeb(~SRB_RESP_INT, ti->mmio+ ACA_OFFSET+ACA_RESET+ ISRP_ODD); } /* if SRB response */ if (status & ASB_FREE_INT) { /* ASB response */ SET_PAGE(ti->asb_page); #if TR_VERBOSE DPRINTK("ASB resp: cmd=%02X\n", readb(ti->asb)); #endif switch (readb(ti->asb)) { /* ASB command check */ case REC_DATA: case XMIT_UI_FRAME: case XMIT_DIR_FRAME: break; default: DPRINTK("unknown command in asb %02X\n", (int) readb(ti->asb)); } /* switch ASB command check */ if (readb(ti->asb + 2) != 0xff) /* checks ret_code */ DPRINTK("ASB error %02X in cmd %02X\n", (int) readb(ti->asb + 2), (int) readb(ti->asb)); writeb(~ASB_FREE_INT, ti->mmio+ ACA_OFFSET+ACA_RESET+ ISRP_ODD); } /* if ASB response */ #define STATUS_OFST 6 #define NETW_STATUS_OFST 6 if (status & ARB_CMD_INT) { /* ARB response */ SET_PAGE(ti->arb_page); #if TR_VERBOSE DPRINTK("ARB resp: cmd=%02X\n", readb(ti->arb)); #endif switch (readb(ti->arb)) { /* ARB command check */ case DLC_STATUS: DPRINTK("DLC_STATUS new status: %02X on station %02X\n", ntohs(readw(ti->arb + STATUS_OFST)), ntohs(readw(ti->arb+ STATION_ID_OFST))); break; case REC_DATA: tr_rx(dev); break; case RING_STAT_CHANGE:{ unsigned short ring_status; ring_status= ntohs(readw(ti->arb + NETW_STATUS_OFST)); if (ibmtr_debug_trace & TRC_INIT) DPRINTK("Ring Status Change...(0x%x)\n", ring_status); if(ring_status& (REMOVE_RECV|AUTO_REMOVAL|LOBE_FAULT)){ netif_stop_queue(dev); netif_carrier_off(dev); DPRINTK("Remove received, or Auto-removal error" ", or Lobe fault\n"); DPRINTK("We'll try to reopen the closed adapter" " after a %d second delay.\n", TR_RETRY_INTERVAL/HZ); /*I was confused: I saw the TR reopening but */ /*forgot:with an RJ45 in an RJ45/ICS adapter */ /*but adapter not in the ring, the TR will */ /* open, and then soon close and come here. */ ti->open_mode = AUTOMATIC; ti->open_status = CLOSED; /*12/2000 BMS*/ ti->open_action = REOPEN; ibmtr_reset_timer(&(ti->tr_timer), dev); } else if (ring_status & LOG_OVERFLOW) { if(netif_queue_stopped(dev)) ti->readlog_pending = 1; else ibmtr_readlog(dev); } break; } case XMIT_DATA_REQ: tr_tx(dev); break; default: DPRINTK("Unknown command %02X in arb\n", (int) readb(ti->arb)); break; } /* switch ARB command check */ writeb(~ARB_CMD_INT, ti->mmio+ ACA_OFFSET+ACA_RESET + ISRP_ODD); writeb(ARB_FREE, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); } /* if ARB response */ if (status & SSB_RESP_INT) { /* SSB response */ unsigned char retcode; SET_PAGE(ti->ssb_page); #if TR_VERBOSE DPRINTK("SSB resp: cmd=%02X rsp=%02X\n", readb(ti->ssb), readb(ti->ssb + 2)); #endif switch (readb(ti->ssb)) { /* SSB command check */ case XMIT_DIR_FRAME: case XMIT_UI_FRAME: retcode = readb(ti->ssb + 2); if (retcode && (retcode != 0x22))/* checks ret_code */ DPRINTK("xmit ret_code: %02X xmit error code: " "%02X\n", (int)retcode, (int)readb(ti->ssb + 6)); else dev->stats.tx_packets++; break; case XMIT_XID_CMD: DPRINTK("xmit xid ret_code: %02X\n", (int) readb(ti->ssb + 2)); default: DPRINTK("Unknown command %02X in ssb\n", (int) readb(ti->ssb)); } /* SSB command check */ writeb(~SSB_RESP_INT, ti->mmio+ ACA_OFFSET+ACA_RESET+ ISRP_ODD); writeb(SSB_FREE, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); } /* if SSB response */ #ifdef ENABLE_PAGING writeb(save_srpr, ti->mmio + ACA_OFFSET + ACA_RW + SRPR_EVEN); #endif writeb(INT_ENABLE, ti->mmio + ACA_OFFSET + ACA_SET + ISRP_EVEN); spin_unlock(&(ti->lock)); return IRQ_HANDLED; } /*tok_interrupt */ /*****************************************************************************/ #define INIT_STATUS_OFST 1 #define INIT_STATUS_2_OFST 2 #define ENCODED_ADDRESS_OFST 8 static void initial_tok_int(struct net_device *dev) { __u32 encoded_addr, hw_encoded_addr; struct tok_info *ti; unsigned char init_status; /*BMS 12/2000*/ ti = netdev_priv(dev); ti->do_tok_int = NOT_FIRST; /* we assign the shared-ram address for ISA devices */ writeb(ti->sram_base, ti->mmio + ACA_OFFSET + ACA_RW + RRR_EVEN); #ifndef PCMCIA ti->sram_virt = ioremap(((__u32)ti->sram_base << 12), ti->avail_shared_ram); #endif ti->init_srb = map_address(ti, ntohs(readw(ti->mmio + ACA_OFFSET + WRBR_EVEN)), &ti->init_srb_page); if (ti->page_mask && ti->avail_shared_ram == 127) { void __iomem *last_512; __u8 last_512_page=0; int i; last_512 = map_address(ti, 0xfe00, &last_512_page); /* initialize high section of ram (if necessary) */ SET_PAGE(last_512_page); for (i = 0; i < 512; i++) writeb(0, last_512 + i); } SET_PAGE(ti->init_srb_page); #if TR_VERBOSE { int i; DPRINTK("ti->init_srb_page=0x%x\n", ti->init_srb_page); DPRINTK("init_srb(%p):", ti->init_srb ); for (i = 0; i < 20; i++) printk("%02X ", (int) readb(ti->init_srb + i)); printk("\n"); } #endif hw_encoded_addr = readw(ti->init_srb + ENCODED_ADDRESS_OFST); encoded_addr = ntohs(hw_encoded_addr); init_status= /*BMS 12/2000 check for shallow mode possibility (Turbo)*/ readb(ti->init_srb+offsetof(struct srb_init_response,init_status)); /*printk("Initial interrupt: init_status= 0x%02x\n",init_status);*/ ti->ring_speed = init_status & 0x01 ? 16 : 4; DPRINTK("Initial interrupt : %d Mbps, shared RAM base %08x.\n", ti->ring_speed, (unsigned int)dev->mem_start); ti->auto_speedsave = (readb(ti->init_srb+INIT_STATUS_2_OFST) & 4) != 0; if (ti->open_mode == MANUAL) wake_up(&ti->wait_for_reset); else tok_open_adapter((unsigned long)dev); } /*initial_tok_int() */ /*****************************************************************************/ #define CMD_CORRELATE_OFST 1 #define DHB_ADDRESS_OFST 6 #define FRAME_LENGTH_OFST 6 #define HEADER_LENGTH_OFST 8 #define RSAP_VALUE_OFST 9 static void tr_tx(struct net_device *dev) { struct tok_info *ti = netdev_priv(dev); struct trh_hdr *trhdr = (struct trh_hdr *) ti->current_skb->data; unsigned int hdr_len; __u32 dhb=0,dhb_base; void __iomem *dhbuf = NULL; unsigned char xmit_command; int i,dhb_len=0x4000,src_len,src_offset; struct trllc *llc; struct srb_xmit xsrb; __u8 dhb_page = 0; __u8 llc_ssap; SET_PAGE(ti->asb_page); if (readb(ti->asb+RETCODE_OFST) != 0xFF) DPRINTK("ASB not free !!!\n"); /* in providing the transmit interrupts, is telling us it is ready for data and providing a shared memory address for us to stuff with data. Here we compute the effective address where we will place data. */ SET_PAGE(ti->arb_page); dhb=dhb_base=ntohs(readw(ti->arb + DHB_ADDRESS_OFST)); if (ti->page_mask) { dhb_page = (dhb_base >> 8) & ti->page_mask; dhb=dhb_base & ~(ti->page_mask << 8); } dhbuf = ti->sram_virt + dhb; /* Figure out the size of the 802.5 header */ if (!(trhdr->saddr[0] & 0x80)) /* RIF present? */ hdr_len = sizeof(struct trh_hdr) - TR_MAXRIFLEN; else hdr_len = ((ntohs(trhdr->rcf) & TR_RCF_LEN_MASK) >> 8) + sizeof(struct trh_hdr) - TR_MAXRIFLEN; llc = (struct trllc *) (ti->current_skb->data + hdr_len); llc_ssap = llc->ssap; SET_PAGE(ti->srb_page); memcpy_fromio(&xsrb, ti->srb, sizeof(xsrb)); SET_PAGE(ti->asb_page); xmit_command = xsrb.command; writeb(xmit_command, ti->asb + COMMAND_OFST); writew(xsrb.station_id, ti->asb + STATION_ID_OFST); writeb(llc_ssap, ti->asb + RSAP_VALUE_OFST); writeb(xsrb.cmd_corr, ti->asb + CMD_CORRELATE_OFST); writeb(0, ti->asb + RETCODE_OFST); if ((xmit_command == XMIT_XID_CMD) || (xmit_command == XMIT_TEST_CMD)) { writew(htons(0x11), ti->asb + FRAME_LENGTH_OFST); writeb(0x0e, ti->asb + HEADER_LENGTH_OFST); SET_PAGE(dhb_page); writeb(AC, dhbuf); writeb(LLC_FRAME, dhbuf + 1); for (i = 0; i < TR_ALEN; i++) writeb((int) 0x0FF, dhbuf + i + 2); for (i = 0; i < TR_ALEN; i++) writeb(0, dhbuf + i + TR_ALEN + 2); writeb(RESP_IN_ASB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); return; } /* * the token ring packet is copied from sk_buff to the adapter * buffer identified in the command data received with the interrupt. */ writeb(hdr_len, ti->asb + HEADER_LENGTH_OFST); writew(htons(ti->current_skb->len), ti->asb + FRAME_LENGTH_OFST); src_len=ti->current_skb->len; src_offset=0; dhb=dhb_base; while(1) { if (ti->page_mask) { dhb_page=(dhb >> 8) & ti->page_mask; dhb=dhb & ~(ti->page_mask << 8); dhb_len=0x4000-dhb; /* remaining size of this page */ } dhbuf = ti->sram_virt + dhb; SET_PAGE(dhb_page); if (src_len > dhb_len) { memcpy_toio(dhbuf,&ti->current_skb->data[src_offset], dhb_len); src_len -= dhb_len; src_offset += dhb_len; dhb_base+=dhb_len; dhb=dhb_base; continue; } memcpy_toio(dhbuf, &ti->current_skb->data[src_offset], src_len); break; } writeb(RESP_IN_ASB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); dev->stats.tx_bytes += ti->current_skb->len; dev_kfree_skb_irq(ti->current_skb); ti->current_skb = NULL; netif_wake_queue(dev); if (ti->readlog_pending) ibmtr_readlog(dev); } /*tr_tx */ /*****************************************************************************/ #define RECEIVE_BUFFER_OFST 6 #define LAN_HDR_LENGTH_OFST 8 #define DLC_HDR_LENGTH_OFST 9 #define DSAP_OFST 0 #define SSAP_OFST 1 #define LLC_OFST 2 #define PROTID_OFST 3 #define ETHERTYPE_OFST 6 static void tr_rx(struct net_device *dev) { struct tok_info *ti = netdev_priv(dev); __u32 rbuffer; void __iomem *rbuf, *rbufdata, *llc; __u8 rbuffer_page = 0; unsigned char *data; unsigned int rbuffer_len, lan_hdr_len, hdr_len, ip_len, length; unsigned char dlc_hdr_len; struct sk_buff *skb; unsigned int skb_size = 0; int IPv4_p = 0; unsigned int chksum = 0; struct iphdr *iph; struct arb_rec_req rarb; SET_PAGE(ti->arb_page); memcpy_fromio(&rarb, ti->arb, sizeof(rarb)); rbuffer = ntohs(rarb.rec_buf_addr) ; rbuf = map_address(ti, rbuffer, &rbuffer_page); SET_PAGE(ti->asb_page); if (readb(ti->asb + RETCODE_OFST) !=0xFF) DPRINTK("ASB not free !!!\n"); writeb(REC_DATA, ti->asb + COMMAND_OFST); writew(rarb.station_id, ti->asb + STATION_ID_OFST); writew(rarb.rec_buf_addr, ti->asb + RECEIVE_BUFFER_OFST); lan_hdr_len = rarb.lan_hdr_len; if (lan_hdr_len > sizeof(struct trh_hdr)) { DPRINTK("Linux cannot handle greater than 18 bytes RIF\n"); return; } /*BMS I added this above just to be very safe */ dlc_hdr_len = readb(ti->arb + DLC_HDR_LENGTH_OFST); hdr_len = lan_hdr_len + sizeof(struct trllc) + sizeof(struct iphdr); SET_PAGE(rbuffer_page); llc = rbuf + offsetof(struct rec_buf, data) + lan_hdr_len; #if TR_VERBOSE DPRINTK("offsetof data: %02X lan_hdr_len: %02X\n", (__u32) offsetof(struct rec_buf, data), (unsigned int) lan_hdr_len); DPRINTK("llc: %08X rec_buf_addr: %04X dev->mem_start: %lX\n", llc, ntohs(rarb.rec_buf_addr), dev->mem_start); DPRINTK("dsap: %02X, ssap: %02X, llc: %02X, protid: %02X%02X%02X, " "ethertype: %04X\n", (int) readb(llc + DSAP_OFST), (int) readb(llc + SSAP_OFST), (int) readb(llc + LLC_OFST), (int) readb(llc + PROTID_OFST), (int) readb(llc+PROTID_OFST+1),(int)readb(llc+PROTID_OFST + 2), (int) ntohs(readw(llc + ETHERTYPE_OFST))); #endif if (readb(llc + offsetof(struct trllc, llc)) != UI_CMD) { SET_PAGE(ti->asb_page); writeb(DATA_LOST, ti->asb + RETCODE_OFST); dev->stats.rx_dropped++; writeb(RESP_IN_ASB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); return; } length = ntohs(rarb.frame_len); if (readb(llc + DSAP_OFST) == EXTENDED_SAP && readb(llc + SSAP_OFST) == EXTENDED_SAP && length >= hdr_len) IPv4_p = 1; #if TR_VERBOSE #define SADDR_OFST 8 #define DADDR_OFST 2 if (!IPv4_p) { void __iomem *trhhdr = rbuf + offsetof(struct rec_buf, data); u8 saddr[6]; u8 daddr[6]; int i; for (i = 0 ; i < 6 ; i++) saddr[i] = readb(trhhdr + SADDR_OFST + i); for (i = 0 ; i < 6 ; i++) daddr[i] = readb(trhhdr + DADDR_OFST + i); DPRINTK("Probably non-IP frame received.\n"); DPRINTK("ssap: %02X dsap: %02X " "saddr: %pM daddr: %pM\n", readb(llc + SSAP_OFST), readb(llc + DSAP_OFST), saddr, daddr); } #endif /*BMS handle the case she comes in with few hops but leaves with many */ skb_size=length-lan_hdr_len+sizeof(struct trh_hdr)+sizeof(struct trllc); if (!(skb = dev_alloc_skb(skb_size))) { DPRINTK("out of memory. frame dropped.\n"); dev->stats.rx_dropped++; SET_PAGE(ti->asb_page); writeb(DATA_LOST, ti->asb + offsetof(struct asb_rec, ret_code)); writeb(RESP_IN_ASB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); return; } /*BMS again, if she comes in with few but leaves with many */ skb_reserve(skb, sizeof(struct trh_hdr) - lan_hdr_len); skb_put(skb, length); data = skb->data; rbuffer_len = ntohs(readw(rbuf + offsetof(struct rec_buf, buf_len))); rbufdata = rbuf + offsetof(struct rec_buf, data); if (IPv4_p) { /* Copy the headers without checksumming */ memcpy_fromio(data, rbufdata, hdr_len); /* Watch for padded packets and bogons */ iph= (struct iphdr *)(data+ lan_hdr_len + sizeof(struct trllc)); ip_len = ntohs(iph->tot_len) - sizeof(struct iphdr); length -= hdr_len; if ((ip_len <= length) && (ip_len > 7)) length = ip_len; data += hdr_len; rbuffer_len -= hdr_len; rbufdata += hdr_len; } /* Copy the payload... */ #define BUFFER_POINTER_OFST 2 #define BUFFER_LENGTH_OFST 6 for (;;) { if (ibmtr_debug_trace&TRC_INITV && length < rbuffer_len) DPRINTK("CURIOUS, length=%d < rbuffer_len=%d\n", length,rbuffer_len); if (IPv4_p) chksum=csum_partial_copy_nocheck((void*)rbufdata, data,length<rbuffer_len?length:rbuffer_len,chksum); else memcpy_fromio(data, rbufdata, rbuffer_len); rbuffer = ntohs(readw(rbuf+BUFFER_POINTER_OFST)) ; if (!rbuffer) break; rbuffer -= 2; length -= rbuffer_len; data += rbuffer_len; rbuf = map_address(ti, rbuffer, &rbuffer_page); SET_PAGE(rbuffer_page); rbuffer_len = ntohs(readw(rbuf + BUFFER_LENGTH_OFST)); rbufdata = rbuf + offsetof(struct rec_buf, data); } SET_PAGE(ti->asb_page); writeb(0, ti->asb + offsetof(struct asb_rec, ret_code)); writeb(RESP_IN_ASB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); dev->stats.rx_bytes += skb->len; dev->stats.rx_packets++; skb->protocol = tr_type_trans(skb, dev); if (IPv4_p) { skb->csum = chksum; skb->ip_summed = CHECKSUM_COMPLETE; } netif_rx(skb); } /*tr_rx */ /*****************************************************************************/ static void ibmtr_reset_timer(struct timer_list *tmr, struct net_device *dev) { tmr->expires = jiffies + TR_RETRY_INTERVAL; tmr->data = (unsigned long) dev; tmr->function = tok_rerun; init_timer(tmr); add_timer(tmr); } /*****************************************************************************/ static void tok_rerun(unsigned long dev_addr) { struct net_device *dev = (struct net_device *)dev_addr; struct tok_info *ti = netdev_priv(dev); if ( ti->open_action == RESTART){ ti->do_tok_int = FIRST_INT; outb(0, dev->base_addr + ADAPTRESETREL); #ifdef ENABLE_PAGING if (ti->page_mask) writeb(SRPR_ENABLE_PAGING, ti->mmio + ACA_OFFSET + ACA_RW + SRPR_EVEN); #endif writeb(INT_ENABLE, ti->mmio + ACA_OFFSET + ACA_SET + ISRP_EVEN); } else tok_open_adapter(dev_addr); } /*****************************************************************************/ static void ibmtr_readlog(struct net_device *dev) { struct tok_info *ti; ti = netdev_priv(dev); ti->readlog_pending = 0; SET_PAGE(ti->srb_page); writeb(DIR_READ_LOG, ti->srb); writeb(INT_ENABLE, ti->mmio + ACA_OFFSET + ACA_SET + ISRP_EVEN); writeb(CMD_IN_SRB, ti->mmio + ACA_OFFSET + ACA_SET + ISRA_ODD); netif_stop_queue(dev); } /*****************************************************************************/ static int ibmtr_change_mtu(struct net_device *dev, int mtu) { struct tok_info *ti = netdev_priv(dev); if (ti->ring_speed == 16 && mtu > ti->maxmtu16) return -EINVAL; if (ti->ring_speed == 4 && mtu > ti->maxmtu4) return -EINVAL; dev->mtu = mtu; return 0; } /*****************************************************************************/ #ifdef MODULE /* 3COM 3C619C supports 8 interrupts, 32 I/O ports */ static struct net_device *dev_ibmtr[IBMTR_MAX_ADAPTERS]; static int io[IBMTR_MAX_ADAPTERS] = { 0xa20, 0xa24 }; static int irq[IBMTR_MAX_ADAPTERS]; static int mem[IBMTR_MAX_ADAPTERS]; MODULE_LICENSE("GPL"); module_param_array(io, int, NULL, 0); module_param_array(irq, int, NULL, 0); module_param_array(mem, int, NULL, 0); static int __init ibmtr_init(void) { int i; int count=0; find_turbo_adapters(io); for (i = 0; i < IBMTR_MAX_ADAPTERS && io[i]; i++) { struct net_device *dev; irq[i] = 0; mem[i] = 0; dev = alloc_trdev(sizeof(struct tok_info)); if (dev == NULL) { if (i == 0) return -ENOMEM; break; } dev->base_addr = io[i]; dev->irq = irq[i]; dev->mem_start = mem[i]; if (ibmtr_probe_card(dev)) { free_netdev(dev); continue; } dev_ibmtr[i] = dev; count++; } if (count) return 0; printk("ibmtr: register_netdev() returned non-zero.\n"); return -EIO; } module_init(ibmtr_init); static void __exit ibmtr_cleanup(void) { int i; for (i = 0; i < IBMTR_MAX_ADAPTERS; i++){ if (!dev_ibmtr[i]) continue; unregister_netdev(dev_ibmtr[i]); ibmtr_cleanup_card(dev_ibmtr[i]); free_netdev(dev_ibmtr[i]); } } module_exit(ibmtr_cleanup); #endif
803308.c
#include <stdio.h> #include <ctype.h> int main(){ char vDat[20], tekst[256]; int linija, lnDat = 1; FILE *IN_DAT, *TEMP_DAT; printf("Vnesi ime na datoteka za obrabotka: "); scanf("%s", &vDat); if((IN_DAT = fopen(vDat, "r+")) == NULL){ fprintf(stderr, "Ne mozham da ja otvaram datotekata \"%s\"\n", vDat); return -1; } else printf("Datotekata \"%s\" e uspeshno otvorena...\n", vDat); TEMP_DAT = fopen("Temp.txt", "w+"); printf("Vnesi linija za otstranuvanje: "); scanf("%d", &linija); while((fgets(tekst, 256, IN_DAT)) != NULL){ if(lnDat != linija) fputs(tekst, TEMP_DAT); lnDat++; } fclose(IN_DAT); rewind(TEMP_DAT); IN_DAT = fopen(vDat, "w"); while((fgets(tekst, 256, TEMP_DAT)) != NULL){ fputs(tekst, IN_DAT); } fclose(IN_DAT); fclose(TEMP_DAT); remove("Temp.txt"); return 0; }
596770.c
/* affyAllExonGSColumn - Calculate median expressions of UCSC genes using exons from Affy All Exon data. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "options.h" #include "jksql.h" #include "expData.h" #include "microarray.h" void usage() /* Explain usage and exit. */ { errAbort( "affyAllExonGSColumn - Calculate median expressions of UCSC genes using exons from Affy All Exon data\n" "usage:\n" " affyAllExonGSColumn expData.txt mapping.txt newExpData.txt\n" ); } static struct optionSpec options[] = { {NULL, 0}, }; struct hash *makeExpHash(struct expData *exps) /* hash up the expression data. */ { struct hash *expHash = newHash(22); struct expData *exp; for (exp = exps; exp != NULL; exp = exp->next) hashAdd(expHash, exp->name, exp); return expHash; } struct expData *combinedExpData(struct slRef *refList, char *name) /* Median all the exons for each gene at each tissue. */ { struct expData *comb; int i; int numExons = 0; double *array; if (!refList || !refList->val) errAbort("Trying to combine nothing? Check the data or better yet this code."); numExons = slCount(refList); AllocArray(array, numExons); AllocVar(comb); comb->name = cloneString(name); comb->expCount = ((struct expData *)refList->val)->expCount; AllocArray(comb->expScores, comb->expCount); for (i = 0; i < comb->expCount; i++) /* There's still the same number of experiments. */ { struct slRef *cur; int j; for (cur = refList, j = 0; (cur != NULL) && (j < numExons); cur = cur->next, j++) /* Go through each exon for the experiment. */ { struct expData *exp = cur->val; array[j] = (double)exp->expScores[i]; } comb->expScores[i] = (float)maDoubleMedianHandleNA(numExons, array); } freez(&array); return comb; } void outputCombinedExpData(FILE *output, struct slRef *refList, char *name) /* Combine and output expData */ { struct expData *exp = combinedExpData(refList, name); expDataTabOut(exp, output); expDataFree(&exp); } void affyAllExonGSColumn(char *expDataFile, char *mappingFile, char *outputFile) /* affyAllExonGSColumn - Calculate median expressions of UCSC genes using exons from Affy All Exon data. */ { struct expData *exps = expDataLoadAll(expDataFile); struct hash *expHash = makeExpHash(exps); struct lineFile *lf = lineFileOpen(mappingFile, TRUE); struct slRef *refList = NULL; FILE *output = mustOpen(outputFile, "w"); char *words[2]; char *prevName = NULL; while (lineFileRowTab(lf, words)) { struct expData *exp = hashFindVal(expHash, words[1]); if (!exp) errAbort("Can't find %s\n", words[1]); if (!(prevName && (sameString(prevName, words[0])))) { /* output slRef list */ if (prevName) outputCombinedExpData(output, refList, prevName); freeMem(prevName); prevName = cloneString(words[0]); slFreeList(&refList); refList = NULL; } refAdd(&refList, exp); } /* output slRef list */ outputCombinedExpData(output, refList, prevName); freeMem(prevName); slFreeList(&refList); expDataFreeList(&exps); hashFree(&expHash); lineFileClose(&lf); carefulClose(&output); } int main(int argc, char *argv[]) /* Process command line. */ { optionInit(&argc, argv, options); if (argc != 4) usage(); affyAllExonGSColumn(argv[1], argv[2], argv[3]); return 0; }
27688.c
// Copyright (c) 2016-2018 Ulord Foundation Ltd. #include "c_rc4.h" #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/rc4.h> #include "common.h" /* * 功能:单向函数 RC4 * 输入:1. input :输入消息 * 2. output:输出结果 */ void crypto_rc4(uint8_t *input, uint32_t inputLen, uint8_t *output) { /** * $hash[0:31] = sha256($input) * $hash2[0:15] = md5($hash[0:31]) * $key = RC4_set_key($hash2[0:15]) * $output[0:31] = RC4($key, $hash[0:31]) **/ uint8_t sha256Digest[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256_ctx; SHA256_Init(&sha256_ctx); SHA256_Update(&sha256_ctx, input, inputLen); SHA256_Final(sha256Digest, &sha256_ctx); uint8_t md5Digest[MD5_DIGEST_LENGTH]; MD5_CTX md5_ctx; MD5_Init(&md5_ctx); MD5_Update(&md5_ctx, sha256Digest, SHA256_DIGEST_LENGTH); MD5_Final(md5Digest, &md5_ctx); RC4_KEY akey; RC4_set_key(&akey, MD5_DIGEST_LENGTH, md5Digest); uint8_t result[SHA256_DIGEST_LENGTH]; RC4(&akey, SHA256_DIGEST_LENGTH, sha256Digest, result); memcpy(output, result, OUTPUT_LEN*sizeof(uint8_t)); }
108110.c
#include <stdio.h> #include <string.h> #include "smsh.h" enum states { NEUTRAL, WANT_THEN, THEN_BLOCK }; enum results { SUCCESS, FAIL }; static int if_state = NEUTRAL; static int if_result = SUCCESS; static int last_stat = 0; int syn_err(char *); int ok_to_execute() { int rv = 1; if ( if_state == WANT_THEN ) { syn_err("then expected"); rv = 0; } else if ( if_state == THEN_BLOCK && if_result == SUCCESS ) { rv = 1; } else if ( if_state == THEN_BLOCK && if_result == FAIL ) { rv = 0; } return rv; } int is_control_command(char *s) { return ( strcmp(s, "if") == 0 || strcmp(s, "then") == 0 || strcmp(s, "fi") == 0 ); } int do_control_command(char **args) { char *cmd = args[0]; int rv = -1; if ( strcmp(cmd, "if") == 0 ) { if ( if_state != NEUTRAL ) { rv = syn_err("if unexpected"); } else { last_stat = process(args + 1); if_result = ( last_stat == 0 ? SUCCESS : FAIL ); if_state = WANT_THEN; rv = 0; } } else if ( strcmp(cmd, "then") == 0 ) { if ( if_state != WANT_THEN ) { rv = syn_err("then unexpected"); } else { if_state = THEN_BLOCK; rv = 0; } } else if ( strcmp(cmd, "fi") == 0 ) { if ( if_state != THEN_BLOCK ) { rv = syn_err("fi unexpected"); } else { if_state = NEUTRAL; rv = 0; } } else { fatal("internal error processing:", cmd, 2); } return rv; } int syn_err(char *msg) { if_state = NEUTRAL; fprintf(stderr, "syntax error: %s\n", msg); return -1; }
348342.c
/* Pillow grid surface. Matches p4est_connectivity_new_pillow (). */ #include <fclaw2d_map.h> #ifdef __cplusplus extern "C" { #if 0 } #endif #endif static int fclaw2d_map_query_torus (fclaw2d_map_context_t * cont, int query_identifier) { switch (query_identifier) { case FCLAW2D_MAP_QUERY_IS_USED: return 1; /* no break necessary after return statement */ case FCLAW2D_MAP_QUERY_IS_SCALEDSHIFT: return 0; case FCLAW2D_MAP_QUERY_IS_AFFINE: return 0; case FCLAW2D_MAP_QUERY_IS_NONLINEAR: return 1; case FCLAW2D_MAP_QUERY_IS_CART: return 0; case FCLAW2D_MAP_QUERY_IS_GRAPH: return 0; case FCLAW2D_MAP_QUERY_IS_PLANAR: return 0; case FCLAW2D_MAP_QUERY_IS_ALIGNED: return 0; case FCLAW2D_MAP_QUERY_IS_FLAT: return 0; case FCLAW2D_MAP_QUERY_IS_DISK: return 0; case FCLAW2D_MAP_QUERY_IS_SPHERE: return 0; case FCLAW2D_MAP_QUERY_IS_PILLOWDISK: return 0; case FCLAW2D_MAP_QUERY_IS_SQUAREDDISK: return 0; case FCLAW2D_MAP_QUERY_IS_PILLOWSPHERE: return 0; case FCLAW2D_MAP_QUERY_IS_CUBEDSPHERE: return 0; case FCLAW2D_MAP_QUERY_IS_BRICK: return 0; default: printf("\n"); printf("fclaw2d_map_query_torus (fclaw2d_map.c) : Query id not "\ "identified; Maybe the query is not up to date?\nSee " \ "fclaw2d_map_torus.c.\n"); printf("Requested query id : %d\n",query_identifier); SC_ABORT_NOT_REACHED (); } return 0; } static void fclaw2d_map_c2m_torus (fclaw2d_map_context_t * cont, int blockno, double xc, double yc, double *xp, double *yp, double *zp) { /* Data is not already in brick domain */ double xc1,yc1,zc1; FCLAW2D_MAP_BRICK2C(&cont,&blockno,&xc,&yc,&xc1,&yc1,&zc1); double alpha = cont->user_double[0]; double beta = cont->user_double[1]; MAPC2M_TORUS(&blockno,&xc1,&yc1,xp,yp,zp,&alpha,&beta); } fclaw2d_map_context_t * fclaw2d_map_new_torus (fclaw2d_map_context_t* brick, const double scale[], const double shift[], const double rotate[], const double alpha, const double beta) { int i; fclaw2d_map_context_t *cont; cont = FCLAW_ALLOC_ZERO (fclaw2d_map_context_t, 1); cont->query = fclaw2d_map_query_torus; cont->mapc2m = fclaw2d_map_c2m_torus; cont->user_double[0] = alpha; cont->user_double[1] = beta; /* Are we really using these? */ set_scale(cont,scale); set_shift(cont,shift); set_rotate(cont,rotate); cont->brick = brick; return cont; } #ifdef __cplusplus #if 0 { #endif } #endif
447449.c
/* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * Copyright 2005 Nokia. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "../ssl_local.h" #include "statem_local.h" #include "internal/constant_time.h" #include "internal/cryptlib.h" #include <openssl/buffer.h> #include <openssl/rand.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/x509.h> #include <openssl/dh.h> #include <openssl/bn.h> #include <openssl/md5.h> #include <openssl/trace.h> #define TICKET_NONCE_SIZE 8 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt); /* * ossl_statem_server13_read_transition() encapsulates the logic for the allowed * handshake state transitions when a TLSv1.3 server is reading messages from * the client. The message type that the client has sent is provided in |mt|. * The current state is in |s->statem.hand_state|. * * Return values are 1 for success (transition allowed) and 0 on error * (transition not allowed) */ static int ossl_statem_server13_read_transition(SSL *s, int mt) { OSSL_STATEM *st = &s->statem; /* * Note: There is no case for TLS_ST_BEFORE because at that stage we have * not negotiated TLSv1.3 yet, so that case is handled by * ossl_statem_server_read_transition() */ switch (st->hand_state) { default: break; case TLS_ST_EARLY_DATA: if (s->hello_retry_request == SSL_HRR_PENDING) { if (mt == SSL3_MT_CLIENT_HELLO) { st->hand_state = TLS_ST_SR_CLNT_HELLO; return 1; } break; } else if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) { if (mt == SSL3_MT_END_OF_EARLY_DATA) { st->hand_state = TLS_ST_SR_END_OF_EARLY_DATA; return 1; } break; } /* Fall through */ case TLS_ST_SR_END_OF_EARLY_DATA: case TLS_ST_SW_FINISHED: if (s->s3.tmp.cert_request) { if (mt == SSL3_MT_CERTIFICATE) { st->hand_state = TLS_ST_SR_CERT; return 1; } } else { if (mt == SSL3_MT_FINISHED) { st->hand_state = TLS_ST_SR_FINISHED; return 1; } } break; case TLS_ST_SR_CERT: if (s->session->peer == NULL) { if (mt == SSL3_MT_FINISHED) { st->hand_state = TLS_ST_SR_FINISHED; return 1; } } else { if (mt == SSL3_MT_CERTIFICATE_VERIFY) { st->hand_state = TLS_ST_SR_CERT_VRFY; return 1; } } break; case TLS_ST_SR_CERT_VRFY: if (mt == SSL3_MT_FINISHED) { st->hand_state = TLS_ST_SR_FINISHED; return 1; } break; case TLS_ST_OK: /* * Its never ok to start processing handshake messages in the middle of * early data (i.e. before we've received the end of early data alert) */ if (s->early_data_state == SSL_EARLY_DATA_READING) break; if (mt == SSL3_MT_CERTIFICATE && s->post_handshake_auth == SSL_PHA_REQUESTED) { st->hand_state = TLS_ST_SR_CERT; return 1; } if (mt == SSL3_MT_KEY_UPDATE) { st->hand_state = TLS_ST_SR_KEY_UPDATE; return 1; } break; } /* No valid transition found */ return 0; } /* * ossl_statem_server_read_transition() encapsulates the logic for the allowed * handshake state transitions when the server is reading messages from the * client. The message type that the client has sent is provided in |mt|. The * current state is in |s->statem.hand_state|. * * Return values are 1 for success (transition allowed) and 0 on error * (transition not allowed) */ int ossl_statem_server_read_transition(SSL *s, int mt) { OSSL_STATEM *st = &s->statem; if (SSL_IS_TLS13(s)) { if (!ossl_statem_server13_read_transition(s, mt)) goto err; return 1; } switch (st->hand_state) { default: break; case TLS_ST_BEFORE: case TLS_ST_OK: case DTLS_ST_SW_HELLO_VERIFY_REQUEST: if (mt == SSL3_MT_CLIENT_HELLO) { st->hand_state = TLS_ST_SR_CLNT_HELLO; return 1; } break; case TLS_ST_SW_SRVR_DONE: /* * If we get a CKE message after a ServerDone then either * 1) We didn't request a Certificate * OR * 2) If we did request one then * a) We allow no Certificate to be returned * AND * b) We are running SSL3 (in TLS1.0+ the client must return a 0 * list if we requested a certificate) */ if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) { if (s->s3.tmp.cert_request) { if (s->version == SSL3_VERSION) { if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) { /* * This isn't an unexpected message as such - we're just * not going to accept it because we require a client * cert. */ SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); return 0; } st->hand_state = TLS_ST_SR_KEY_EXCH; return 1; } } else { st->hand_state = TLS_ST_SR_KEY_EXCH; return 1; } } else if (s->s3.tmp.cert_request) { if (mt == SSL3_MT_CERTIFICATE) { st->hand_state = TLS_ST_SR_CERT; return 1; } } break; case TLS_ST_SR_CERT: if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) { st->hand_state = TLS_ST_SR_KEY_EXCH; return 1; } break; case TLS_ST_SR_KEY_EXCH: /* * We should only process a CertificateVerify message if we have * received a Certificate from the client. If so then |s->session->peer| * will be non NULL. In some instances a CertificateVerify message is * not required even if the peer has sent a Certificate (e.g. such as in * the case of static DH). In that case |st->no_cert_verify| should be * set. */ if (s->session->peer == NULL || st->no_cert_verify) { if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) { /* * For the ECDH ciphersuites when the client sends its ECDH * pub key in a certificate, the CertificateVerify message is * not sent. Also for GOST ciphersuites when the client uses * its key from the certificate for key exchange. */ st->hand_state = TLS_ST_SR_CHANGE; return 1; } } else { if (mt == SSL3_MT_CERTIFICATE_VERIFY) { st->hand_state = TLS_ST_SR_CERT_VRFY; return 1; } } break; case TLS_ST_SR_CERT_VRFY: if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) { st->hand_state = TLS_ST_SR_CHANGE; return 1; } break; case TLS_ST_SR_CHANGE: #ifndef OPENSSL_NO_NEXTPROTONEG if (s->s3.npn_seen) { if (mt == SSL3_MT_NEXT_PROTO) { st->hand_state = TLS_ST_SR_NEXT_PROTO; return 1; } } else { #endif if (mt == SSL3_MT_FINISHED) { st->hand_state = TLS_ST_SR_FINISHED; return 1; } #ifndef OPENSSL_NO_NEXTPROTONEG } #endif break; #ifndef OPENSSL_NO_NEXTPROTONEG case TLS_ST_SR_NEXT_PROTO: if (mt == SSL3_MT_FINISHED) { st->hand_state = TLS_ST_SR_FINISHED; return 1; } break; #endif case TLS_ST_SW_FINISHED: if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) { st->hand_state = TLS_ST_SR_CHANGE; return 1; } break; } err: /* No valid transition found */ if (SSL_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) { BIO *rbio; /* * CCS messages don't have a message sequence number so this is probably * because of an out-of-order CCS. We'll just drop it. */ s->init_num = 0; s->rwstate = SSL_READING; rbio = SSL_get_rbio(s); BIO_clear_retry_flags(rbio); BIO_set_retry_read(rbio); return 0; } SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION, SSL_R_UNEXPECTED_MESSAGE); return 0; } /* * Should we send a ServerKeyExchange message? * * Valid return values are: * 1: Yes * 0: No */ static int send_server_key_exchange(SSL *s) { unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey; /* * only send a ServerKeyExchange if DH or fortezza but we have a * sign only certificate PSK: may send PSK identity hints For * ECC ciphersuites, we send a serverKeyExchange message only if * the cipher suite is either ECDH-anon or ECDHE. In other cases, * the server certificate contains the server's public key for * key exchange. */ if (alg_k & (SSL_kDHE | SSL_kECDHE) /* * PSK: send ServerKeyExchange if PSK identity hint if * provided */ #ifndef OPENSSL_NO_PSK /* Only send SKE if we have identity hint for plain PSK */ || ((alg_k & (SSL_kPSK | SSL_kRSAPSK)) && s->cert->psk_identity_hint) /* For other PSK always send SKE */ || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK))) #endif #ifndef OPENSSL_NO_SRP /* SRP: send ServerKeyExchange */ || (alg_k & SSL_kSRP) #endif ) { return 1; } return 0; } /* * Should we send a CertificateRequest message? * * Valid return values are: * 1: Yes * 0: No */ int send_certificate_request(SSL *s) { if ( /* don't request cert unless asked for it: */ s->verify_mode & SSL_VERIFY_PEER /* * don't request if post-handshake-only unless doing * post-handshake in TLSv1.3: */ && (!SSL_IS_TLS13(s) || !(s->verify_mode & SSL_VERIFY_POST_HANDSHAKE) || s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) /* * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert * a second time: */ && (s->certreqs_sent < 1 || !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) /* * never request cert in anonymous ciphersuites (see * section "Certificate request" in SSL 3 drafts and in * RFC 2246): */ && (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL) /* * ... except when the application insists on * verification (against the specs, but statem_clnt.c accepts * this for SSL 3) */ || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) /* don't request certificate for SRP auth */ && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aSRP) /* * With normal PSK Certificates and Certificate Requests * are omitted */ && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aPSK)) { return 1; } return 0; } /* * ossl_statem_server13_write_transition() works out what handshake state to * move to next when a TLSv1.3 server is writing messages to be sent to the * client. */ static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s) { OSSL_STATEM *st = &s->statem; /* * No case for TLS_ST_BEFORE, because at that stage we have not negotiated * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition() */ switch (st->hand_state) { default: /* Shouldn't happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_OSSL_STATEM_SERVER13_WRITE_TRANSITION, ERR_R_INTERNAL_ERROR); return WRITE_TRAN_ERROR; case TLS_ST_OK: if (s->key_update != SSL_KEY_UPDATE_NONE) { st->hand_state = TLS_ST_SW_KEY_UPDATE; return WRITE_TRAN_CONTINUE; } if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) { st->hand_state = TLS_ST_SW_CERT_REQ; return WRITE_TRAN_CONTINUE; } /* Try to read from the client instead */ return WRITE_TRAN_FINISHED; case TLS_ST_SR_CLNT_HELLO: st->hand_state = TLS_ST_SW_SRVR_HELLO; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_SRVR_HELLO: if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0 && s->hello_retry_request != SSL_HRR_COMPLETE) st->hand_state = TLS_ST_SW_CHANGE; else if (s->hello_retry_request == SSL_HRR_PENDING) st->hand_state = TLS_ST_EARLY_DATA; else st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_CHANGE: if (s->hello_retry_request == SSL_HRR_PENDING) st->hand_state = TLS_ST_EARLY_DATA; else st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_ENCRYPTED_EXTENSIONS: if (s->hit) st->hand_state = TLS_ST_SW_FINISHED; else if (send_certificate_request(s)) st->hand_state = TLS_ST_SW_CERT_REQ; else st->hand_state = TLS_ST_SW_CERT; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_CERT_REQ: if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) { s->post_handshake_auth = SSL_PHA_REQUESTED; st->hand_state = TLS_ST_OK; } else { st->hand_state = TLS_ST_SW_CERT; } return WRITE_TRAN_CONTINUE; case TLS_ST_SW_CERT: st->hand_state = TLS_ST_SW_CERT_VRFY; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_CERT_VRFY: st->hand_state = TLS_ST_SW_FINISHED; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_FINISHED: st->hand_state = TLS_ST_EARLY_DATA; return WRITE_TRAN_CONTINUE; case TLS_ST_EARLY_DATA: return WRITE_TRAN_FINISHED; case TLS_ST_SR_FINISHED: /* * Technically we have finished the handshake at this point, but we're * going to remain "in_init" for now and write out any session tickets * immediately. */ if (s->post_handshake_auth == SSL_PHA_REQUESTED) { s->post_handshake_auth = SSL_PHA_EXT_RECEIVED; } else if (!s->ext.ticket_expected) { /* * If we're not going to renew the ticket then we just finish the * handshake at this point. */ st->hand_state = TLS_ST_OK; return WRITE_TRAN_CONTINUE; } if (s->num_tickets > s->sent_tickets) st->hand_state = TLS_ST_SW_SESSION_TICKET; else st->hand_state = TLS_ST_OK; return WRITE_TRAN_CONTINUE; case TLS_ST_SR_KEY_UPDATE: case TLS_ST_SW_KEY_UPDATE: st->hand_state = TLS_ST_OK; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_SESSION_TICKET: /* In a resumption we only ever send a maximum of one new ticket. * Following an initial handshake we send the number of tickets we have * been configured for. */ if (s->hit || s->num_tickets <= s->sent_tickets) { /* We've written enough tickets out. */ st->hand_state = TLS_ST_OK; } return WRITE_TRAN_CONTINUE; } } /* * ossl_statem_server_write_transition() works out what handshake state to move * to next when the server is writing messages to be sent to the client. */ WRITE_TRAN ossl_statem_server_write_transition(SSL *s) { OSSL_STATEM *st = &s->statem; /* * Note that before the ClientHello we don't know what version we are going * to negotiate yet, so we don't take this branch until later */ if (SSL_IS_TLS13(s)) return ossl_statem_server13_write_transition(s); switch (st->hand_state) { default: /* Shouldn't happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_OSSL_STATEM_SERVER_WRITE_TRANSITION, ERR_R_INTERNAL_ERROR); return WRITE_TRAN_ERROR; case TLS_ST_OK: if (st->request_state == TLS_ST_SW_HELLO_REQ) { /* We must be trying to renegotiate */ st->hand_state = TLS_ST_SW_HELLO_REQ; st->request_state = TLS_ST_BEFORE; return WRITE_TRAN_CONTINUE; } /* Must be an incoming ClientHello */ if (!tls_setup_handshake(s)) { /* SSLfatal() already called */ return WRITE_TRAN_ERROR; } /* Fall through */ case TLS_ST_BEFORE: /* Just go straight to trying to read from the client */ return WRITE_TRAN_FINISHED; case TLS_ST_SW_HELLO_REQ: st->hand_state = TLS_ST_OK; return WRITE_TRAN_CONTINUE; case TLS_ST_SR_CLNT_HELLO: if (SSL_IS_DTLS(s) && !s->d1->cookie_verified && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) { st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST; } else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) { /* We must have rejected the renegotiation */ st->hand_state = TLS_ST_OK; return WRITE_TRAN_CONTINUE; } else { st->hand_state = TLS_ST_SW_SRVR_HELLO; } return WRITE_TRAN_CONTINUE; case DTLS_ST_SW_HELLO_VERIFY_REQUEST: return WRITE_TRAN_FINISHED; case TLS_ST_SW_SRVR_HELLO: if (s->hit) { if (s->ext.ticket_expected) st->hand_state = TLS_ST_SW_SESSION_TICKET; else st->hand_state = TLS_ST_SW_CHANGE; } else { /* Check if it is anon DH or anon ECDH, */ /* normal PSK or SRP */ if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) { st->hand_state = TLS_ST_SW_CERT; } else if (send_server_key_exchange(s)) { st->hand_state = TLS_ST_SW_KEY_EXCH; } else if (send_certificate_request(s)) { st->hand_state = TLS_ST_SW_CERT_REQ; } else { st->hand_state = TLS_ST_SW_SRVR_DONE; } } return WRITE_TRAN_CONTINUE; case TLS_ST_SW_CERT: if (s->ext.status_expected) { st->hand_state = TLS_ST_SW_CERT_STATUS; return WRITE_TRAN_CONTINUE; } /* Fall through */ case TLS_ST_SW_CERT_STATUS: if (send_server_key_exchange(s)) { st->hand_state = TLS_ST_SW_KEY_EXCH; return WRITE_TRAN_CONTINUE; } /* Fall through */ case TLS_ST_SW_KEY_EXCH: if (send_certificate_request(s)) { st->hand_state = TLS_ST_SW_CERT_REQ; return WRITE_TRAN_CONTINUE; } /* Fall through */ case TLS_ST_SW_CERT_REQ: st->hand_state = TLS_ST_SW_SRVR_DONE; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_SRVR_DONE: return WRITE_TRAN_FINISHED; case TLS_ST_SR_FINISHED: if (s->hit) { st->hand_state = TLS_ST_OK; return WRITE_TRAN_CONTINUE; } else if (s->ext.ticket_expected) { st->hand_state = TLS_ST_SW_SESSION_TICKET; } else { st->hand_state = TLS_ST_SW_CHANGE; } return WRITE_TRAN_CONTINUE; case TLS_ST_SW_SESSION_TICKET: st->hand_state = TLS_ST_SW_CHANGE; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_CHANGE: st->hand_state = TLS_ST_SW_FINISHED; return WRITE_TRAN_CONTINUE; case TLS_ST_SW_FINISHED: if (s->hit) { return WRITE_TRAN_FINISHED; } st->hand_state = TLS_ST_OK; return WRITE_TRAN_CONTINUE; } } /* * Perform any pre work that needs to be done prior to sending a message from * the server to the client. */ WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { default: /* No pre work to be done */ break; case TLS_ST_SW_HELLO_REQ: s->shutdown = 0; if (SSL_IS_DTLS(s)) dtls1_clear_sent_buffer(s); break; case DTLS_ST_SW_HELLO_VERIFY_REQUEST: s->shutdown = 0; if (SSL_IS_DTLS(s)) { dtls1_clear_sent_buffer(s); /* We don't buffer this message so don't use the timer */ st->use_timer = 0; } break; case TLS_ST_SW_SRVR_HELLO: if (SSL_IS_DTLS(s)) { /* * Messages we write from now on should be buffered and * retransmitted if necessary, so we need to use the timer now */ st->use_timer = 1; } break; case TLS_ST_SW_SRVR_DONE: #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) { /* Calls SSLfatal() as required */ return dtls_wait_for_dry(s); } #endif return WORK_FINISHED_CONTINUE; case TLS_ST_SW_SESSION_TICKET: if (SSL_IS_TLS13(s) && s->sent_tickets == 0) { /* * Actually this is the end of the handshake, but we're going * straight into writing the session ticket out. So we finish off * the handshake, but keep the various buffers active. * * Calls SSLfatal as required. */ return tls_finish_handshake(s, wst, 0, 0); } if (SSL_IS_DTLS(s)) { /* * We're into the last flight. We don't retransmit the last flight * unless we need to, so we don't use the timer */ st->use_timer = 0; } break; case TLS_ST_SW_CHANGE: if (SSL_IS_TLS13(s)) break; s->session->cipher = s->s3.tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { /* SSLfatal() already called */ return WORK_ERROR; } if (SSL_IS_DTLS(s)) { /* * We're into the last flight. We don't retransmit the last flight * unless we need to, so we don't use the timer. This might have * already been set to 0 if we sent a NewSessionTicket message, * but we'll set it again here in case we didn't. */ st->use_timer = 0; } return WORK_FINISHED_CONTINUE; case TLS_ST_EARLY_DATA: if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING && (s->s3.flags & TLS1_FLAGS_STATELESS) == 0) return WORK_FINISHED_CONTINUE; /* Fall through */ case TLS_ST_OK: /* Calls SSLfatal() as required */ return tls_finish_handshake(s, wst, 1, 1); } return WORK_FINISHED_CONTINUE; } static ossl_inline int conn_is_closed(void) { switch (get_last_sys_error()) { #if defined(EPIPE) case EPIPE: return 1; #endif #if defined(ECONNRESET) case ECONNRESET: return 1; #endif #if defined(WSAECONNRESET) case WSAECONNRESET: return 1; #endif default: return 0; } } /* * Perform any work that needs to be done after sending a message from the * server to the client. */ WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst) { OSSL_STATEM *st = &s->statem; s->init_num = 0; switch (st->hand_state) { default: /* No post work to be done */ break; case TLS_ST_SW_HELLO_REQ: if (statem_flush(s) != 1) return WORK_MORE_A; if (!ssl3_init_finished_mac(s)) { /* SSLfatal() already called */ return WORK_ERROR; } break; case DTLS_ST_SW_HELLO_VERIFY_REQUEST: if (statem_flush(s) != 1) return WORK_MORE_A; /* HelloVerifyRequest resets Finished MAC */ if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) { /* SSLfatal() already called */ return WORK_ERROR; } /* * The next message should be another ClientHello which we need to * treat like it was the first packet */ s->first_packet = 1; break; case TLS_ST_SW_SRVR_HELLO: if (SSL_IS_TLS13(s) && s->hello_retry_request == SSL_HRR_PENDING) { if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0 && statem_flush(s) != 1) return WORK_MORE_A; break; } #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && s->hit) { unsigned char sctpauthkey[64]; char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)]; size_t labellen; /* * Add new shared key for SCTP-Auth, will be ignored if no * SCTP used. */ memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL, sizeof(DTLS1_SCTP_AUTH_LABEL)); /* Don't include the terminating zero. */ labellen = sizeof(labelbuffer) - 1; if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG) labellen += 1; if (SSL_export_keying_material(s, sctpauthkey, sizeof(sctpauthkey), labelbuffer, labellen, NULL, 0, 0) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_OSSL_STATEM_SERVER_POST_WORK, ERR_R_INTERNAL_ERROR); return WORK_ERROR; } BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY, sizeof(sctpauthkey), sctpauthkey); } #endif if (!SSL_IS_TLS13(s) || ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0 && s->hello_retry_request != SSL_HRR_COMPLETE)) break; /* Fall through */ case TLS_ST_SW_CHANGE: if (s->hello_retry_request == SSL_HRR_PENDING) { if (!statem_flush(s)) return WORK_MORE_A; break; } if (SSL_IS_TLS13(s)) { if (!s->method->ssl3_enc->setup_key_block(s) || !s->method->ssl3_enc->change_cipher_state(s, SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) { /* SSLfatal() already called */ return WORK_ERROR; } if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED && !s->method->ssl3_enc->change_cipher_state(s, SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ)) { /* SSLfatal() already called */ return WORK_ERROR; } /* * We don't yet know whether the next record we are going to receive * is an unencrypted alert, an encrypted alert, or an encrypted * handshake message. We temporarily tolerate unencrypted alerts. */ s->statem.enc_read_state = ENC_READ_STATE_ALLOW_PLAIN_ALERTS; break; } #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && !s->hit) { /* * Change to new shared key of SCTP-Auth, will be ignored if * no SCTP used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY, 0, NULL); } #endif if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) { /* SSLfatal() already called */ return WORK_ERROR; } if (SSL_IS_DTLS(s)) dtls1_reset_seq_numbers(s, SSL3_CC_WRITE); break; case TLS_ST_SW_SRVR_DONE: if (statem_flush(s) != 1) return WORK_MORE_A; break; case TLS_ST_SW_FINISHED: if (statem_flush(s) != 1) return WORK_MORE_A; #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && s->hit) { /* * Change to new shared key of SCTP-Auth, will be ignored if * no SCTP used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY, 0, NULL); } #endif if (SSL_IS_TLS13(s)) { if (!s->method->ssl3_enc->generate_master_secret(s, s->master_secret, s->handshake_secret, 0, &s->session->master_key_length) || !s->method->ssl3_enc->change_cipher_state(s, SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE)) /* SSLfatal() already called */ return WORK_ERROR; } break; case TLS_ST_SW_CERT_REQ: if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) { if (statem_flush(s) != 1) return WORK_MORE_A; } break; case TLS_ST_SW_KEY_UPDATE: if (statem_flush(s) != 1) return WORK_MORE_A; if (!tls13_update_key(s, 1)) { /* SSLfatal() already called */ return WORK_ERROR; } break; case TLS_ST_SW_SESSION_TICKET: clear_sys_error(); if (SSL_IS_TLS13(s) && statem_flush(s) != 1) { if (SSL_get_error(s, 0) == SSL_ERROR_SYSCALL && conn_is_closed()) { /* * We ignore connection closed errors in TLSv1.3 when sending a * NewSessionTicket and behave as if we were successful. This is * so that we are still able to read data sent to us by a client * that closes soon after the end of the handshake without * waiting to read our post-handshake NewSessionTickets. */ s->rwstate = SSL_NOTHING; break; } return WORK_MORE_A; } break; } return WORK_FINISHED_CONTINUE; } /* * Get the message construction function and message type for sending from the * server * * Valid return values are: * 1: Success * 0: Error */ int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt, confunc_f *confunc, int *mt) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { default: /* Shouldn't happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_OSSL_STATEM_SERVER_CONSTRUCT_MESSAGE, SSL_R_BAD_HANDSHAKE_STATE); return 0; case TLS_ST_SW_CHANGE: if (SSL_IS_DTLS(s)) *confunc = dtls_construct_change_cipher_spec; else *confunc = tls_construct_change_cipher_spec; *mt = SSL3_MT_CHANGE_CIPHER_SPEC; break; case DTLS_ST_SW_HELLO_VERIFY_REQUEST: *confunc = dtls_construct_hello_verify_request; *mt = DTLS1_MT_HELLO_VERIFY_REQUEST; break; case TLS_ST_SW_HELLO_REQ: /* No construction function needed */ *confunc = NULL; *mt = SSL3_MT_HELLO_REQUEST; break; case TLS_ST_SW_SRVR_HELLO: *confunc = tls_construct_server_hello; *mt = SSL3_MT_SERVER_HELLO; break; case TLS_ST_SW_CERT: *confunc = tls_construct_server_certificate; *mt = SSL3_MT_CERTIFICATE; break; case TLS_ST_SW_CERT_VRFY: *confunc = tls_construct_cert_verify; *mt = SSL3_MT_CERTIFICATE_VERIFY; break; case TLS_ST_SW_KEY_EXCH: *confunc = tls_construct_server_key_exchange; *mt = SSL3_MT_SERVER_KEY_EXCHANGE; break; case TLS_ST_SW_CERT_REQ: *confunc = tls_construct_certificate_request; *mt = SSL3_MT_CERTIFICATE_REQUEST; break; case TLS_ST_SW_SRVR_DONE: *confunc = tls_construct_server_done; *mt = SSL3_MT_SERVER_DONE; break; case TLS_ST_SW_SESSION_TICKET: *confunc = tls_construct_new_session_ticket; *mt = SSL3_MT_NEWSESSION_TICKET; break; case TLS_ST_SW_CERT_STATUS: *confunc = tls_construct_cert_status; *mt = SSL3_MT_CERTIFICATE_STATUS; break; case TLS_ST_SW_FINISHED: *confunc = tls_construct_finished; *mt = SSL3_MT_FINISHED; break; case TLS_ST_EARLY_DATA: *confunc = NULL; *mt = SSL3_MT_DUMMY; break; case TLS_ST_SW_ENCRYPTED_EXTENSIONS: *confunc = tls_construct_encrypted_extensions; *mt = SSL3_MT_ENCRYPTED_EXTENSIONS; break; case TLS_ST_SW_KEY_UPDATE: *confunc = tls_construct_key_update; *mt = SSL3_MT_KEY_UPDATE; break; } return 1; } /* * Maximum size (excluding the Handshake header) of a ClientHello message, * calculated as follows: * * 2 + # client_version * 32 + # only valid length for random * 1 + # length of session_id * 32 + # maximum size for session_id * 2 + # length of cipher suites * 2^16-2 + # maximum length of cipher suites array * 1 + # length of compression_methods * 2^8-1 + # maximum length of compression methods * 2 + # length of extensions * 2^16-1 # maximum length of extensions */ #define CLIENT_HELLO_MAX_LENGTH 131396 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048 #define NEXT_PROTO_MAX_LENGTH 514 /* * Returns the maximum allowed length for the current message that we are * reading. Excludes the message header. */ size_t ossl_statem_server_max_message_size(SSL *s) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { default: /* Shouldn't happen */ return 0; case TLS_ST_SR_CLNT_HELLO: return CLIENT_HELLO_MAX_LENGTH; case TLS_ST_SR_END_OF_EARLY_DATA: return END_OF_EARLY_DATA_MAX_LENGTH; case TLS_ST_SR_CERT: return s->max_cert_list; case TLS_ST_SR_KEY_EXCH: return CLIENT_KEY_EXCH_MAX_LENGTH; case TLS_ST_SR_CERT_VRFY: return SSL3_RT_MAX_PLAIN_LENGTH; #ifndef OPENSSL_NO_NEXTPROTONEG case TLS_ST_SR_NEXT_PROTO: return NEXT_PROTO_MAX_LENGTH; #endif case TLS_ST_SR_CHANGE: return CCS_MAX_LENGTH; case TLS_ST_SR_FINISHED: return FINISHED_MAX_LENGTH; case TLS_ST_SR_KEY_UPDATE: return KEY_UPDATE_MAX_LENGTH; } } /* * Process a message that the server has received from the client. */ MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { default: /* Shouldn't happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_OSSL_STATEM_SERVER_PROCESS_MESSAGE, ERR_R_INTERNAL_ERROR); return MSG_PROCESS_ERROR; case TLS_ST_SR_CLNT_HELLO: return tls_process_client_hello(s, pkt); case TLS_ST_SR_END_OF_EARLY_DATA: return tls_process_end_of_early_data(s, pkt); case TLS_ST_SR_CERT: return tls_process_client_certificate(s, pkt); case TLS_ST_SR_KEY_EXCH: return tls_process_client_key_exchange(s, pkt); case TLS_ST_SR_CERT_VRFY: return tls_process_cert_verify(s, pkt); #ifndef OPENSSL_NO_NEXTPROTONEG case TLS_ST_SR_NEXT_PROTO: return tls_process_next_proto(s, pkt); #endif case TLS_ST_SR_CHANGE: return tls_process_change_cipher_spec(s, pkt); case TLS_ST_SR_FINISHED: return tls_process_finished(s, pkt); case TLS_ST_SR_KEY_UPDATE: return tls_process_key_update(s, pkt); } } /* * Perform any further processing required following the receipt of a message * from the client */ WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { default: /* Shouldn't happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_OSSL_STATEM_SERVER_POST_PROCESS_MESSAGE, ERR_R_INTERNAL_ERROR); return WORK_ERROR; case TLS_ST_SR_CLNT_HELLO: return tls_post_process_client_hello(s, wst); case TLS_ST_SR_KEY_EXCH: return tls_post_process_client_key_exchange(s, wst); } } #ifndef OPENSSL_NO_SRP /* Returns 1 on success, 0 for retryable error, -1 for fatal error */ static int ssl_check_srp_ext_ClientHello(SSL *s) { int ret; int al = SSL_AD_UNRECOGNIZED_NAME; if ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) && (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) { if (s->srp_ctx.login == NULL) { /* * RFC 5054 says SHOULD reject, we do so if There is no srp * login name */ SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO, SSL_R_PSK_IDENTITY_NOT_FOUND); return -1; } else { ret = SSL_srp_server_param_with_username(s, &al); if (ret < 0) return 0; if (ret == SSL3_AL_FATAL) { SSLfatal(s, al, SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO, al == SSL_AD_UNKNOWN_PSK_IDENTITY ? SSL_R_PSK_IDENTITY_NOT_FOUND : SSL_R_CLIENTHELLO_TLSEXT); return -1; } } } return 1; } #endif int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie, size_t cookie_len) { /* Always use DTLS 1.0 version: see RFC 6347 */ if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION) || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len)) return 0; return 1; } int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt) { unsigned int cookie_leni; if (s->ctx->app_gen_cookie_cb == NULL || s->ctx->app_gen_cookie_cb(s, s->d1->cookie, &cookie_leni) == 0 || cookie_leni > 255) { SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST, SSL_R_COOKIE_GEN_CALLBACK_FAILURE); return 0; } s->d1->cookie_len = cookie_leni; if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie, s->d1->cookie_len)) { SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST, ERR_R_INTERNAL_ERROR); return 0; } return 1; } #ifndef OPENSSL_NO_EC /*- * ssl_check_for_safari attempts to fingerprint Safari using OS X * SecureTransport using the TLS extension block in |hello|. * Safari, since 10.6, sends exactly these extensions, in this order: * SNI, * elliptic_curves * ec_point_formats * signature_algorithms (for TLSv1.2 only) * * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8, * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them. * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from * 10.8..10.8.3 (which don't work). */ static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello) { static const unsigned char kSafariExtensionsBlock[] = { 0x00, 0x0a, /* elliptic_curves extension */ 0x00, 0x08, /* 8 bytes */ 0x00, 0x06, /* 6 bytes of curve ids */ 0x00, 0x17, /* P-256 */ 0x00, 0x18, /* P-384 */ 0x00, 0x19, /* P-521 */ 0x00, 0x0b, /* ec_point_formats */ 0x00, 0x02, /* 2 bytes */ 0x01, /* 1 point format */ 0x00, /* uncompressed */ /* The following is only present in TLS 1.2 */ 0x00, 0x0d, /* signature_algorithms */ 0x00, 0x0c, /* 12 bytes */ 0x00, 0x0a, /* 10 bytes */ 0x05, 0x01, /* SHA-384/RSA */ 0x04, 0x01, /* SHA-256/RSA */ 0x02, 0x01, /* SHA-1/RSA */ 0x04, 0x03, /* SHA-256/ECDSA */ 0x02, 0x03, /* SHA-1/ECDSA */ }; /* Length of the common prefix (first two extensions). */ static const size_t kSafariCommonExtensionsLength = 18; unsigned int type; PACKET sni, tmppkt; size_t ext_len; tmppkt = hello->extensions; if (!PACKET_forward(&tmppkt, 2) || !PACKET_get_net_2(&tmppkt, &type) || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) { return; } if (type != TLSEXT_TYPE_server_name) return; ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ? sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength; s->s3.is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock, ext_len); } #endif /* !OPENSSL_NO_EC */ MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt) { /* |cookie| will only be initialized for DTLS. */ PACKET session_id, compression, extensions, cookie; static const unsigned char null_compression = 0; CLIENTHELLO_MSG *clienthello = NULL; /* Check if this is actually an unexpected renegotiation ClientHello */ if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) { if (!ossl_assert(!SSL_IS_TLS13(s))) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } if ((s->options & SSL_OP_NO_RENEGOTIATION) != 0 || (!s->s3.send_connection_binding && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0)) { ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); return MSG_PROCESS_FINISHED_READING; } s->renegotiate = 1; s->new_session = 1; } clienthello = OPENSSL_zalloc(sizeof(*clienthello)); if (clienthello == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } /* * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure. */ clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer); PACKET_null_init(&cookie); if (clienthello->isv2) { unsigned int mt; if (!SSL_IS_FIRST_HANDSHAKE(s) || s->hello_retry_request != SSL_HRR_NONE) { SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE); goto err; } /*- * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 * header is sent directly on the wire, not wrapped as a TLS * record. Our record layer just processes the message length and passes * the rest right through. Its format is: * Byte Content * 0-1 msg_length - decoded by the record layer * 2 msg_type - s->init_msg points here * 3-4 version * 5-6 cipher_spec_length * 7-8 session_id_length * 9-10 challenge_length * ... ... */ if (!PACKET_get_1(pkt, &mt) || mt != SSL2_MT_CLIENT_HELLO) { /* * Should never happen. We should have tested this in the record * layer in order to have determined that this is a SSLv2 record * in the first place */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } } if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto err; } /* Parse the message and load client random. */ if (clienthello->isv2) { /* * Handle an SSLv2 backwards compatible ClientHello * Note, this is only for SSLv3+ using the backward compatible format. * Real SSLv2 is not supported, and is rejected below. */ unsigned int ciphersuite_len, session_id_len, challenge_len; PACKET challenge; if (!PACKET_get_net_2(pkt, &ciphersuite_len) || !PACKET_get_net_2(pkt, &session_id_len) || !PACKET_get_net_2(pkt, &challenge_len)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH); goto err; } if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) { SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto err; } if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites, ciphersuite_len) || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len) || !PACKET_get_sub_packet(pkt, &challenge, challenge_len) /* No extensions. */ || PACKET_remaining(pkt) != 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH); goto err; } clienthello->session_id_len = session_id_len; /* Load the client random and compression list. We use SSL3_RANDOM_SIZE * here rather than sizeof(clienthello->random) because that is the limit * for SSLv3 and it is fixed. It won't change even if * sizeof(clienthello->random) does. */ challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE : challenge_len; memset(clienthello->random, 0, SSL3_RANDOM_SIZE); if (!PACKET_copy_bytes(&challenge, clienthello->random + SSL3_RANDOM_SIZE - challenge_len, challenge_len) /* Advertise only null compression. */ || !PACKET_buf_init(&compression, &null_compression, 1)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } PACKET_null_init(&clienthello->extensions); } else { /* Regular ClientHello. */ if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE) || !PACKET_get_length_prefixed_1(pkt, &session_id) || !PACKET_copy_all(&session_id, clienthello->session_id, SSL_MAX_SSL_SESSION_ID_LENGTH, &clienthello->session_id_len)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto err; } if (SSL_IS_DTLS(s)) { if (!PACKET_get_length_prefixed_1(pkt, &cookie)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto err; } if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie, DTLS1_COOKIE_LENGTH, &clienthello->dtls_cookie_len)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } /* * If we require cookies and this ClientHello doesn't contain one, * just return since we do not want to allocate any memory yet. * So check cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { if (clienthello->dtls_cookie_len == 0) { OPENSSL_free(clienthello); return MSG_PROCESS_FINISHED_READING; } } } if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto err; } if (!PACKET_get_length_prefixed_1(pkt, &compression)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto err; } /* Could be empty. */ if (PACKET_remaining(pkt) == 0) { PACKET_null_init(&clienthello->extensions); } else { if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions) || PACKET_remaining(pkt) != 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto err; } } } if (!PACKET_copy_all(&compression, clienthello->compressions, MAX_COMPRESSIONS_SIZE, &clienthello->compressions_len)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } /* Preserve the raw extensions PACKET for later use */ extensions = clienthello->extensions; if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO, &clienthello->pre_proc_exts, &clienthello->pre_proc_exts_len, 1)) { /* SSLfatal already been called */ goto err; } s->clienthello = clienthello; return MSG_PROCESS_CONTINUE_PROCESSING; err: if (clienthello != NULL) OPENSSL_free(clienthello->pre_proc_exts); OPENSSL_free(clienthello); return MSG_PROCESS_ERROR; } static int tls_early_post_process_client_hello(SSL *s) { unsigned int j; int i, al = SSL_AD_INTERNAL_ERROR; int protverr; size_t loop; unsigned long id; #ifndef OPENSSL_NO_COMP SSL_COMP *comp = NULL; #endif const SSL_CIPHER *c; STACK_OF(SSL_CIPHER) *ciphers = NULL; STACK_OF(SSL_CIPHER) *scsvs = NULL; CLIENTHELLO_MSG *clienthello = s->clienthello; DOWNGRADE dgrd = DOWNGRADE_NONE; /* Finished parsing the ClientHello, now we can start processing it */ /* Give the ClientHello callback a crack at things */ if (s->ctx->client_hello_cb != NULL) { /* A failure in the ClientHello callback terminates the connection. */ switch (s->ctx->client_hello_cb(s, &al, s->ctx->client_hello_cb_arg)) { case SSL_CLIENT_HELLO_SUCCESS: break; case SSL_CLIENT_HELLO_RETRY: s->rwstate = SSL_CLIENT_HELLO_CB; return -1; case SSL_CLIENT_HELLO_ERROR: default: SSLfatal(s, al, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CALLBACK_FAILED); goto err; } } /* Set up the client_random */ memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE); /* Choose the version */ if (clienthello->isv2) { if (clienthello->legacy_version == SSL2_VERSION || (clienthello->legacy_version & 0xff00) != (SSL3_VERSION_MAJOR << 8)) { /* * This is real SSLv2 or something completely unknown. We don't * support it. */ SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL); goto err; } /* SSLv3/TLS */ s->client_version = clienthello->legacy_version; } /* * Do SSL/TLS version negotiation if applicable. For DTLS we just check * versions are potentially compatible. Version negotiation comes later. */ if (!SSL_IS_DTLS(s)) { protverr = ssl_choose_server_version(s, clienthello, &dgrd); } else if (s->method->version != DTLS_ANY_VERSION && DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) { protverr = SSL_R_VERSION_TOO_LOW; } else { protverr = 0; } if (protverr) { if (SSL_IS_FIRST_HANDSHAKE(s)) { /* like ssl3_get_record, send alert using remote version number */ s->version = s->client_version = clienthello->legacy_version; } SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr); goto err; } /* TLSv1.3 specifies that a ClientHello must end on a record boundary */ if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) { SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NOT_ON_RECORD_BOUNDARY); goto err; } if (SSL_IS_DTLS(s)) { /* Empty cookie was already handled above by returning early. */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { if (s->ctx->app_verify_cookie_cb != NULL) { if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie, clienthello->dtls_cookie_len) == 0) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto err; /* else cookie verification succeeded */ } /* default verification */ } else if (s->d1->cookie_len != clienthello->dtls_cookie_len || memcmp(clienthello->dtls_cookie, s->d1->cookie, s->d1->cookie_len) != 0) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto err; } s->d1->cookie_verified = 1; } if (s->method->version == DTLS_ANY_VERSION) { protverr = ssl_choose_server_version(s, clienthello, &dgrd); if (protverr != 0) { s->version = s->client_version; SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr); goto err; } } } s->hit = 0; if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites, clienthello->isv2) || !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs, clienthello->isv2, 1)) { /* SSLfatal() already called */ goto err; } s->s3.send_connection_binding = 0; /* Check what signalling cipher-suite values were received. */ if (scsvs != NULL) { for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) { c = sk_SSL_CIPHER_value(scsvs, i); if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) { if (s->renegotiate) { /* SCSV is fatal if renegotiating */ SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING); goto err; } s->s3.send_connection_binding = 1; } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV && !ssl_check_version_downgrade(s)) { /* * This SCSV indicates that the client previously tried * a higher version. We should fail if the current version * is an unexpected downgrade, as that indicates that the first * connection may have been tampered with in order to trigger * an insecure downgrade. */ SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INAPPROPRIATE_FALLBACK); goto err; } } } /* For TLSv1.3 we must select the ciphersuite *before* session resumption */ if (SSL_IS_TLS13(s)) { const SSL_CIPHER *cipher = ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(s)); if (cipher == NULL) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto err; } if (s->hello_retry_request == SSL_HRR_PENDING && (s->s3.tmp.new_cipher == NULL || s->s3.tmp.new_cipher->id != cipher->id)) { /* * A previous HRR picked a different ciphersuite to the one we * just selected. Something must have changed. */ SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_BAD_CIPHER); goto err; } s->s3.tmp.new_cipher = cipher; } /* We need to do this before getting the session */ if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret, SSL_EXT_CLIENT_HELLO, clienthello->pre_proc_exts, NULL, 0)) { /* SSLfatal() already called */ goto err; } /* * We don't allow resumption in a backwards compatible ClientHello. * TODO(openssl-team): in TLS1.1+, session_id MUST be empty. * * Versions before 0.9.7 always allow clients to resume sessions in * renegotiation. 0.9.7 and later allow this by default, but optionally * ignore resumption requests with flag * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on * this for security won't even compile against older library versions). * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to * request renegotiation but not a new session (s->new_session remains * unset): for servers, this essentially just means that the * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be * ignored. */ if (clienthello->isv2 || (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s, 1)) { /* SSLfatal() already called */ goto err; } } else { i = ssl_get_prev_session(s, clienthello); if (i == 1) { /* previous session */ s->hit = 1; } else if (i == -1) { /* SSLfatal() already called */ goto err; } else { /* i == 0 */ if (!ssl_get_new_session(s, 1)) { /* SSLfatal() already called */ goto err; } } } if (SSL_IS_TLS13(s)) { memcpy(s->tmp_session_id, s->clienthello->session_id, s->clienthello->session_id_len); s->tmp_session_id_len = s->clienthello->session_id_len; } /* * If it is a hit, check that the cipher is in the list. In TLSv1.3 we check * ciphersuite compatibility with the session as part of resumption. */ if (!SSL_IS_TLS13(s) && s->hit) { j = 0; id = s->session->cipher->id; OSSL_TRACE_BEGIN(TLS_CIPHER) { BIO_printf(trc_out, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers)); } for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) { c = sk_SSL_CIPHER_value(ciphers, i); if (trc_out != NULL) BIO_printf(trc_out, "client [%2d of %2d]:%s\n", i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); if (c->id == id) { j = 1; break; } } if (j == 0) { /* * we need to have the cipher in the cipher list if we are asked * to reuse it */ SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_REQUIRED_CIPHER_MISSING); OSSL_TRACE_CANCEL(TLS_CIPHER); goto err; } OSSL_TRACE_END(TLS_CIPHER); } for (loop = 0; loop < clienthello->compressions_len; loop++) { if (clienthello->compressions[loop] == 0) break; } if (loop >= clienthello->compressions_len) { /* no compress */ SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED); goto err; } #ifndef OPENSSL_NO_EC if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) ssl_check_for_safari(s, clienthello); #endif /* !OPENSSL_NO_EC */ /* TLS extensions */ if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO, clienthello->pre_proc_exts, NULL, 0, 1)) { /* SSLfatal() already called */ goto err; } /* * Check if we want to use external pre-shared secret for this handshake * for not reused session only. We need to generate server_random before * calling tls_session_secret_cb in order to allow SessionTicket * processing to use it in key derivation. */ { unsigned char *pos; pos = s->s3.server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } } if (!s->hit && s->version >= TLS1_VERSION && !SSL_IS_TLS13(s) && !SSL_IS_DTLS(s) && s->ext.session_secret_cb) { const SSL_CIPHER *pref_cipher = NULL; /* * s->session->master_key_length is a size_t, but this is an int for * backwards compat reasons */ int master_key_length; master_key_length = sizeof(s->session->master_key); if (s->ext.session_secret_cb(s, s->session->master_key, &master_key_length, ciphers, &pref_cipher, s->ext.session_secret_cb_arg) && master_key_length > 0) { s->session->master_key_length = master_key_length; s->hit = 1; s->peer_ciphers = ciphers; s->session->verify_result = X509_V_OK; ciphers = NULL; /* check if some cipher was preferred by call back */ if (pref_cipher == NULL) pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers, SSL_get_ciphers(s)); if (pref_cipher == NULL) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto err; } s->session->cipher = pref_cipher; sk_SSL_CIPHER_free(s->cipher_list); s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers); sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers); } } /* * Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have complen-1 compression * algorithms from the client, starting at q. */ s->s3.tmp.new_compression = NULL; if (SSL_IS_TLS13(s)) { /* * We already checked above that the NULL compression method appears in * the list. Now we check there aren't any others (which is illegal in * a TLSv1.3 ClientHello. */ if (clienthello->compressions_len != 1) { SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INVALID_COMPRESSION_ALGORITHM); goto err; } } #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ else if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; unsigned int k; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (!ssl_allow_compression(s)) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); if (comp_id == comp->id) { s->s3.tmp.new_compression = comp; break; } } if (s->s3.tmp.new_compression == NULL) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INVALID_COMPRESSION_ALGORITHM); goto err; } /* Look for resumed method in compression list */ for (k = 0; k < clienthello->compressions_len; k++) { if (clienthello->compressions[k] == comp_id) break; } if (k >= clienthello->compressions_len) { SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING); goto err; } } else if (s->hit) { comp = NULL; } else if (ssl_allow_compression(s) && s->ctx->comp_methods) { /* See if we have a match */ int m, nn, v, done = 0; unsigned int o; nn = sk_SSL_COMP_num(s->ctx->comp_methods); for (m = 0; m < nn; m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); v = comp->id; for (o = 0; o < clienthello->compressions_len; o++) { if (v == clienthello->compressions[o]) { done = 1; break; } } if (done) break; } if (done) s->s3.tmp.new_compression = comp; else comp = NULL; } #else /* * If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto err; } #endif /* * Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher */ if (!s->hit || SSL_IS_TLS13(s)) { sk_SSL_CIPHER_free(s->peer_ciphers); s->peer_ciphers = ciphers; if (ciphers == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } ciphers = NULL; } if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth = 0; #else s->session->compress_meth = (comp == NULL) ? 0 : comp->id; #endif if (!tls1_set_server_sigalgs(s)) { /* SSLfatal() already called */ goto err; } } sk_SSL_CIPHER_free(ciphers); sk_SSL_CIPHER_free(scsvs); OPENSSL_free(clienthello->pre_proc_exts); OPENSSL_free(s->clienthello); s->clienthello = NULL; return 1; err: sk_SSL_CIPHER_free(ciphers); sk_SSL_CIPHER_free(scsvs); OPENSSL_free(clienthello->pre_proc_exts); OPENSSL_free(s->clienthello); s->clienthello = NULL; return 0; } /* * Call the status request callback if needed. Upon success, returns 1. * Upon failure, returns 0. */ static int tls_handle_status_request(SSL *s) { s->ext.status_expected = 0; /* * If status request then ask callback what to do. Note: this must be * called after servername callbacks in case the certificate has changed, * and must be called after the cipher has been chosen because this may * influence which certificate is sent */ if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL && s->ctx->ext.status_cb != NULL) { int ret; /* If no certificate can't return certificate status */ if (s->s3.tmp.cert != NULL) { /* * Set current certificate to one we will use so SSL_get_certificate * et al can pick it up. */ s->cert->key = s->s3.tmp.cert; ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg); switch (ret) { /* We don't want to send a status request response */ case SSL_TLSEXT_ERR_NOACK: s->ext.status_expected = 0; break; /* status request response should be sent */ case SSL_TLSEXT_ERR_OK: if (s->ext.ocsp.resp) s->ext.status_expected = 1; break; /* something bad happened */ case SSL_TLSEXT_ERR_ALERT_FATAL: default: SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_HANDLE_STATUS_REQUEST, SSL_R_CLIENTHELLO_TLSEXT); return 0; } } } return 1; } /* * Call the alpn_select callback if needed. Upon success, returns 1. * Upon failure, returns 0. */ int tls_handle_alpn(SSL *s) { const unsigned char *selected = NULL; unsigned char selected_len = 0; if (s->ctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) { int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len, s->s3.alpn_proposed, (unsigned int)s->s3.alpn_proposed_len, s->ctx->ext.alpn_select_cb_arg); if (r == SSL_TLSEXT_ERR_OK) { OPENSSL_free(s->s3.alpn_selected); s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len); if (s->s3.alpn_selected == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_HANDLE_ALPN, ERR_R_INTERNAL_ERROR); return 0; } s->s3.alpn_selected_len = selected_len; #ifndef OPENSSL_NO_NEXTPROTONEG /* ALPN takes precedence over NPN. */ s->s3.npn_seen = 0; #endif /* Check ALPN is consistent with session */ if (s->session->ext.alpn_selected == NULL || selected_len != s->session->ext.alpn_selected_len || memcmp(selected, s->session->ext.alpn_selected, selected_len) != 0) { /* Not consistent so can't be used for early_data */ s->ext.early_data_ok = 0; if (!s->hit) { /* * This is a new session and so alpn_selected should have * been initialised to NULL. We should update it with the * selected ALPN. */ if (!ossl_assert(s->session->ext.alpn_selected == NULL)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_HANDLE_ALPN, ERR_R_INTERNAL_ERROR); return 0; } s->session->ext.alpn_selected = OPENSSL_memdup(selected, selected_len); if (s->session->ext.alpn_selected == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_HANDLE_ALPN, ERR_R_INTERNAL_ERROR); return 0; } s->session->ext.alpn_selected_len = selected_len; } } return 1; } else if (r != SSL_TLSEXT_ERR_NOACK) { SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL, SSL_F_TLS_HANDLE_ALPN, SSL_R_NO_APPLICATION_PROTOCOL); return 0; } /* * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was * present. */ } /* Check ALPN is consistent with session */ if (s->session->ext.alpn_selected != NULL) { /* Not consistent so can't be used for early_data */ s->ext.early_data_ok = 0; } return 1; } WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst) { const SSL_CIPHER *cipher; if (wst == WORK_MORE_A) { int rv = tls_early_post_process_client_hello(s); if (rv == 0) { /* SSLfatal() was already called */ goto err; } if (rv < 0) return WORK_MORE_A; wst = WORK_MORE_B; } if (wst == WORK_MORE_B) { if (!s->hit || SSL_IS_TLS13(s)) { /* Let cert callback update server certificates if required */ if (!s->hit && s->cert->cert_cb != NULL) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CERT_CB_ERROR); goto err; } if (rv < 0) { s->rwstate = SSL_X509_LOOKUP; return WORK_MORE_B; } s->rwstate = SSL_NOTHING; } /* In TLSv1.3 we selected the ciphersuite before resumption */ if (!SSL_IS_TLS13(s)) { cipher = ssl3_choose_cipher(s, s->peer_ciphers, SSL_get_ciphers(s)); if (cipher == NULL) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto err; } s->s3.tmp.new_cipher = cipher; } if (!s->hit) { if (!tls_choose_sigalg(s, 1)) { /* SSLfatal already called */ goto err; } /* check whether we should disable session resumption */ if (s->not_resumable_session_cb != NULL) s->session->not_resumable = s->not_resumable_session_cb(s, ((s->s3.tmp.new_cipher->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0)); if (s->session->not_resumable) /* do not send a session ticket */ s->ext.ticket_expected = 0; } } else { /* Session-id reuse */ s->s3.tmp.new_cipher = s->session->cipher; } /*- * we now have the following setup. * client_random * cipher_list - our preferred list of ciphers * ciphers - the clients preferred list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->s3.tmp.new_cipher - the new cipher to use. */ /* * Call status_request callback if needed. Has to be done after the * certificate callbacks etc above. */ if (!tls_handle_status_request(s)) { /* SSLfatal() already called */ goto err; } /* * Call alpn_select callback if needed. Has to be done after SNI and * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3 * we already did this because cipher negotiation happens earlier, and * we must handle ALPN before we decide whether to accept early_data. */ if (!SSL_IS_TLS13(s) && !tls_handle_alpn(s)) { /* SSLfatal() already called */ goto err; } wst = WORK_MORE_C; } #ifndef OPENSSL_NO_SRP if (wst == WORK_MORE_C) { int ret; if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) { /* * callback indicates further work to be done */ s->rwstate = SSL_X509_LOOKUP; return WORK_MORE_C; } if (ret < 0) { /* SSLfatal() already called */ goto err; } } #endif return WORK_FINISHED_STOP; err: return WORK_ERROR; } int tls_construct_server_hello(SSL *s, WPACKET *pkt) { int compm; size_t sl, len; int version; unsigned char *session_id; int usetls13 = SSL_IS_TLS13(s) || s->hello_retry_request == SSL_HRR_PENDING; version = usetls13 ? TLS1_2_VERSION : s->version; if (!WPACKET_put_bytes_u16(pkt, version) /* * Random stuff. Filling of the server_random takes place in * tls_process_client_hello() */ || !WPACKET_memcpy(pkt, s->hello_retry_request == SSL_HRR_PENDING ? hrrrandom : s->s3.server_random, SSL3_RANDOM_SIZE)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR); return 0; } /*- * There are several cases for the session ID to send * back in the server hello: * - For session reuse from the session cache, * we send back the old session ID. * - If stateless session reuse (using a session ticket) * is successful, we send back the client's "session ID" * (which doesn't actually identify the session). * - If it is a new session, we send back the new * session ID. * - However, if we want the new session to be single-use, * we send back a 0-length session ID. * - In TLSv1.3 we echo back the session id sent to us by the client * regardless * s->hit is non-zero in either case of session reuse, * so the following won't overwrite an ID that we're supposed * to send back. */ if (s->session->not_resumable || (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER) && !s->hit)) s->session->session_id_length = 0; if (usetls13) { sl = s->tmp_session_id_len; session_id = s->tmp_session_id; } else { sl = s->session->session_id_length; session_id = s->session->session_id; } if (sl > sizeof(s->session->session_id)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR); return 0; } /* set up the compression method */ #ifdef OPENSSL_NO_COMP compm = 0; #else if (usetls13 || s->s3.tmp.new_compression == NULL) compm = 0; else compm = s->s3.tmp.new_compression->id; #endif if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl) || !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, pkt, &len) || !WPACKET_put_bytes_u8(pkt, compm)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR); return 0; } if (!tls_construct_extensions(s, pkt, s->hello_retry_request == SSL_HRR_PENDING ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST : (SSL_IS_TLS13(s) ? SSL_EXT_TLS1_3_SERVER_HELLO : SSL_EXT_TLS1_2_SERVER_HELLO), NULL, 0)) { /* SSLfatal() already called */ return 0; } if (s->hello_retry_request == SSL_HRR_PENDING) { /* Ditch the session. We'll create a new one next time around */ SSL_SESSION_free(s->session); s->session = NULL; s->hit = 0; /* * Re-initialise the Transcript Hash. We're going to prepopulate it with * a synthetic message_hash in place of ClientHello1. */ if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) { /* SSLfatal() already called */ return 0; } } else if (!(s->verify_mode & SSL_VERIFY_PEER) && !ssl3_digest_cached_records(s, 0)) { /* SSLfatal() already called */; return 0; } return 1; } int tls_construct_server_done(SSL *s, WPACKET *pkt) { if (!s->s3.tmp.cert_request) { if (!ssl3_digest_cached_records(s, 0)) { /* SSLfatal() already called */ return 0; } } return 1; } int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt) { #ifndef OPENSSL_NO_DH EVP_PKEY *pkdh = NULL; #endif #ifndef OPENSSL_NO_EC unsigned char *encodedPoint = NULL; size_t encodedlen = 0; int curve_id = 0; #endif const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg; int i; unsigned long type; const BIGNUM *r[4]; EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); EVP_PKEY_CTX *pctx = NULL; size_t paramlen, paramoffset; if (!WPACKET_get_total_written(pkt, &paramoffset)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if (md_ctx == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } type = s->s3.tmp.new_cipher->algorithm_mkey; r[0] = r[1] = r[2] = r[3] = NULL; #ifndef OPENSSL_NO_PSK /* Plain PSK or RSAPSK nothing to do */ if (type & (SSL_kPSK | SSL_kRSAPSK)) { } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_DH if (type & (SSL_kDHE | SSL_kDHEPSK)) { CERT *cert = s->cert; EVP_PKEY *pkdhp = NULL; DH *dh; if (s->cert->dh_tmp_auto) { DH *dhp = ssl_get_auto_dh(s); pkdh = EVP_PKEY_new(); if (pkdh == NULL || dhp == NULL) { DH_free(dhp); SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } EVP_PKEY_assign_DH(pkdh, dhp); pkdhp = pkdh; } else { pkdhp = cert->dh_tmp; } if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) { DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024); pkdh = ssl_dh_to_pkey(dhp); if (pkdh == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } pkdhp = pkdh; } if (pkdhp == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto err; } if (!ssl_security(s, SSL_SECOP_TMP_DH, EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, SSL_R_DH_KEY_TOO_SMALL); goto err; } if (s->s3.tmp.pkey != NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } s->s3.tmp.pkey = ssl_generate_pkey(pkdhp); if (s->s3.tmp.pkey == NULL) { /* SSLfatal() already called */ goto err; } dh = EVP_PKEY_get0_DH(s->s3.tmp.pkey); if (dh == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } EVP_PKEY_free(pkdh); pkdh = NULL; DH_get0_pqg(dh, &r[0], NULL, &r[1]); DH_get0_key(dh, &r[2], NULL); } else #endif #ifndef OPENSSL_NO_EC if (type & (SSL_kECDHE | SSL_kECDHEPSK)) { if (s->s3.tmp.pkey != NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } /* Get NID of appropriate shared curve */ curve_id = tls1_shared_group(s, -2); if (curve_id == 0) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE); goto err; } s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id); /* Generate a new key for this curve */ if (s->s3.tmp.pkey == NULL) { /* SSLfatal() already called */ goto err; } /* Encode the public key. */ encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3.tmp.pkey, &encodedPoint); if (encodedlen == 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } /* * We'll generate the serverKeyExchange message explicitly so we * can set these to NULLs */ r[0] = NULL; r[1] = NULL; r[2] = NULL; r[3] = NULL; } else #endif /* !OPENSSL_NO_EC */ #ifndef OPENSSL_NO_SRP if (type & SSL_kSRP) { if ((s->srp_ctx.N == NULL) || (s->srp_ctx.g == NULL) || (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, SSL_R_MISSING_SRP_PARAM); goto err; } r[0] = s->srp_ctx.N; r[1] = s->srp_ctx.g; r[2] = s->srp_ctx.s; r[3] = s->srp_ctx.B; } else #endif { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); goto err; } if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0) || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) { lu = NULL; } else if (lu == NULL) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } #ifndef OPENSSL_NO_PSK if (type & SSL_PSK) { size_t len = (s->cert->psk_identity_hint == NULL) ? 0 : strlen(s->cert->psk_identity_hint); /* * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already * checked this when we set the identity hint - but just in case */ if (len > PSK_MAX_IDENTITY_LEN || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint, len)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } #endif for (i = 0; i < 4 && r[i] != NULL; i++) { unsigned char *binval; int res; #ifndef OPENSSL_NO_SRP if ((i == 2) && (type & SSL_kSRP)) { res = WPACKET_start_sub_packet_u8(pkt); } else #endif res = WPACKET_start_sub_packet_u16(pkt); if (!res) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } #ifndef OPENSSL_NO_DH /*- * for interoperability with some versions of the Microsoft TLS * stack, we need to zero pad the DHE pub key to the same length * as the prime */ if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) { size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]); if (len > 0) { if (!WPACKET_allocate_bytes(pkt, len, &binval)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } memset(binval, 0, len); } } #endif if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval) || !WPACKET_close(pkt)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } BN_bn2bin(r[i], binval); } #ifndef OPENSSL_NO_EC if (type & (SSL_kECDHE | SSL_kECDHEPSK)) { /* * We only support named (not generic) curves. In this situation, the * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName] * [1 byte length of encoded point], followed by the actual encoded * point itself */ if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE) || !WPACKET_put_bytes_u8(pkt, 0) || !WPACKET_put_bytes_u8(pkt, curve_id) || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } OPENSSL_free(encodedPoint); encodedPoint = NULL; } #endif /* not anonymous */ if (lu != NULL) { EVP_PKEY *pkey = s->s3.tmp.cert->privatekey; const EVP_MD *md; unsigned char *sigbytes1, *sigbytes2, *tbs; size_t siglen, tbslen; int rv; if (pkey == NULL || !tls1_lookup_md(lu, &md)) { /* Should never happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } /* Get length of the parameters we have written above */ if (!WPACKET_get_length(pkt, &paramlen)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } /* send signature algorithm */ if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } /* * Create the signature. We don't know the actual length of the sig * until after we've created it, so we reserve enough bytes for it * up front, and then properly allocate them in the WPACKET * afterwards. */ siglen = EVP_PKEY_size(pkey); if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1) || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if (lu->sig == EVP_PKEY_RSA_PSS) { if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB); goto err; } } tbslen = construct_key_exchange_tbs(s, &tbs, s->init_buf->data + paramoffset, paramlen); if (tbslen == 0) { /* SSLfatal() already called */ goto err; } rv = EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen); OPENSSL_free(tbs); if (rv <= 0 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2) || sigbytes1 != sigbytes2) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } EVP_MD_CTX_free(md_ctx); return 1; err: #ifndef OPENSSL_NO_DH EVP_PKEY_free(pkdh); #endif #ifndef OPENSSL_NO_EC OPENSSL_free(encodedPoint); #endif EVP_MD_CTX_free(md_ctx); return 0; } int tls_construct_certificate_request(SSL *s, WPACKET *pkt) { if (SSL_IS_TLS13(s)) { /* Send random context when doing post-handshake auth */ if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) { OPENSSL_free(s->pha_context); s->pha_context_len = 32; if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL || RAND_bytes(s->pha_context, s->pha_context_len) <= 0 || !WPACKET_sub_memcpy_u8(pkt, s->pha_context, s->pha_context_len)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR); return 0; } /* reset the handshake hash back to just after the ClientFinished */ if (!tls13_restore_handshake_digest_for_pha(s)) { /* SSLfatal() already called */ return 0; } } else { if (!WPACKET_put_bytes_u8(pkt, 0)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR); return 0; } } if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL, 0)) { /* SSLfatal() already called */ return 0; } goto done; } /* get the list of acceptable cert types */ if (!WPACKET_start_sub_packet_u8(pkt) || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR); return 0; } if (SSL_USE_SIGALGS(s)) { const uint16_t *psigs; size_t nl = tls12_get_psigalgs(s, 1, &psigs); if (!WPACKET_start_sub_packet_u16(pkt) || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH) || !tls12_copy_sigalgs(s, pkt, psigs, nl) || !WPACKET_close(pkt)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR); return 0; } } if (!construct_ca_names(s, get_ca_names(s), pkt)) { /* SSLfatal() already called */ return 0; } done: s->certreqs_sent++; s->s3.tmp.cert_request = 1; return 1; } static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt) { #ifndef OPENSSL_NO_PSK unsigned char psk[PSK_MAX_PSK_LEN]; size_t psklen; PACKET psk_identity; if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH); return 0; } if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG); return 0; } if (s->psk_server_callback == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_SERVER_CB); return 0; } if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR); return 0; } psklen = s->psk_server_callback(s, s->session->psk_identity, psk, sizeof(psk)); if (psklen > PSK_MAX_PSK_LEN) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR); return 0; } else if (psklen == 0) { /* * PSK related to the given identity not found */ SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_PSK_IDENTITY_NOT_FOUND); return 0; } OPENSSL_free(s->s3.tmp.psk); s->s3.tmp.psk = OPENSSL_memdup(psk, psklen); OPENSSL_cleanse(psk, psklen); if (s->s3.tmp.psk == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE); return 0; } s->s3.tmp.psklen = psklen; return 1; #else /* Should never happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR); return 0; #endif } static int tls_process_cke_rsa(SSL *s, PACKET *pkt) { #ifndef OPENSSL_NO_RSA unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH]; int decrypt_len; unsigned char decrypt_good, version_good; size_t j, padding_len; PACKET enc_premaster; RSA *rsa = NULL; unsigned char *rsa_decrypt = NULL; int ret = 0; rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey); if (rsa == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_MISSING_RSA_CERTIFICATE); return 0; } /* SSLv3 and pre-standard DTLS omit the length bytes. */ if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) { enc_premaster = *pkt; } else { if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster) || PACKET_remaining(pkt) != 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_LENGTH_MISMATCH); return 0; } } /* * We want to be sure that the plaintext buffer size makes it safe to * iterate over the entire size of a premaster secret * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because * their ciphertext cannot accommodate a premaster secret anyway. */ if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } rsa_decrypt = OPENSSL_malloc(RSA_size(rsa)); if (rsa_decrypt == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_MALLOC_FAILURE); return 0; } /* * We must not leak whether a decryption failure occurs because of * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246, * section 7.4.7.1). The code follows that advice of the TLS RFC and * generates a random premaster secret for the case that the decrypt * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */ if (RAND_priv_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR); goto err; } /* * Decrypt with no padding. PKCS#1 padding will be removed as part of * the timing-sensitive code below. */ /* TODO(size_t): Convert this function */ decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster), PACKET_data(&enc_premaster), rsa_decrypt, rsa, RSA_NO_PADDING); if (decrypt_len < 0) { SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR); goto err; } /* Check the padding. See RFC 3447, section 7.2.2. */ /* * The smallest padded premaster is 11 bytes of overhead. Small keys * are publicly invalid, so this may return immediately. This ensures * PS is at least 8 bytes. */ if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) { SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_DECRYPTION_FAILED); goto err; } padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH; decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) & constant_time_eq_int_8(rsa_decrypt[1], 2); for (j = 2; j < padding_len - 1; j++) { decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]); } decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]); /* * If the version in the decrypted pre-master secret is correct then * version_good will be 0xff, otherwise it'll be zero. The * Klima-Pokorny-Rosa extension of Bleichenbacher's attack * (http://eprint.iacr.org/2003/052/) exploits the version number * check as a "bad version oracle". Thus version checks are done in * constant time and are treated like any other decryption error. */ version_good = constant_time_eq_8(rsa_decrypt[padding_len], (unsigned)(s->client_version >> 8)); version_good &= constant_time_eq_8(rsa_decrypt[padding_len + 1], (unsigned)(s->client_version & 0xff)); /* * The premaster secret must contain the same version number as the * ClientHello to detect version rollback attacks (strangely, the * protocol does not offer such protection for DH ciphersuites). * However, buggy clients exist that send the negotiated protocol * version instead if the server does not support the requested * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such * clients. */ if (s->options & SSL_OP_TLS_ROLLBACK_BUG) { unsigned char workaround_good; workaround_good = constant_time_eq_8(rsa_decrypt[padding_len], (unsigned)(s->version >> 8)); workaround_good &= constant_time_eq_8(rsa_decrypt[padding_len + 1], (unsigned)(s->version & 0xff)); version_good |= workaround_good; } /* * Both decryption and version must be good for decrypt_good to * remain non-zero (0xff). */ decrypt_good &= version_good; /* * Now copy rand_premaster_secret over from p using * decrypt_good_mask. If decryption failed, then p does not * contain valid plaintext, however, a check above guarantees * it is still sufficiently large to read from. */ for (j = 0; j < sizeof(rand_premaster_secret); j++) { rsa_decrypt[padding_len + j] = constant_time_select_8(decrypt_good, rsa_decrypt[padding_len + j], rand_premaster_secret[j]); } if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len, sizeof(rand_premaster_secret), 0)) { /* SSLfatal() already called */ goto err; } ret = 1; err: OPENSSL_free(rsa_decrypt); return ret; #else /* Should never happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR); return 0; #endif } static int tls_process_cke_dhe(SSL *s, PACKET *pkt) { #ifndef OPENSSL_NO_DH EVP_PKEY *skey = NULL; DH *cdh; unsigned int i; BIGNUM *pub_key; const unsigned char *data; EVP_PKEY *ckey = NULL; int ret = 0; if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG); goto err; } skey = s->s3.tmp.pkey; if (skey == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY); goto err; } if (PACKET_remaining(pkt) == 0L) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY); goto err; } if (!PACKET_get_bytes(pkt, &data, i)) { /* We already checked we have enough data */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR); goto err; } ckey = EVP_PKEY_new(); if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_BN_LIB); goto err; } cdh = EVP_PKEY_get0_DH(ckey); pub_key = BN_bin2bn(data, i, NULL); if (pub_key == NULL || cdh == NULL || !DH_set0_key(cdh, pub_key, NULL)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR); BN_free(pub_key); goto err; } if (ssl_derive(s, skey, ckey, 1) == 0) { /* SSLfatal() already called */ goto err; } ret = 1; EVP_PKEY_free(s->s3.tmp.pkey); s->s3.tmp.pkey = NULL; err: EVP_PKEY_free(ckey); return ret; #else /* Should never happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR); return 0; #endif } static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt) { #ifndef OPENSSL_NO_EC EVP_PKEY *skey = s->s3.tmp.pkey; EVP_PKEY *ckey = NULL; int ret = 0; if (PACKET_remaining(pkt) == 0L) { /* We don't support ECDH client auth */ SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_MISSING_TMP_ECDH_KEY); goto err; } else { unsigned int i; const unsigned char *data; /* * Get client's public key from encoded point in the * ClientKeyExchange message. */ /* Get encoded point length */ if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i) || PACKET_remaining(pkt) != 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_LENGTH_MISMATCH); goto err; } if (skey == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_MISSING_TMP_ECDH_KEY); goto err; } ckey = EVP_PKEY_new(); if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EVP_LIB); goto err; } if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EC_LIB); goto err; } } if (ssl_derive(s, skey, ckey, 1) == 0) { /* SSLfatal() already called */ goto err; } ret = 1; EVP_PKEY_free(s->s3.tmp.pkey); s->s3.tmp.pkey = NULL; err: EVP_PKEY_free(ckey); return ret; #else /* Should never happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR); return 0; #endif } static int tls_process_cke_srp(SSL *s, PACKET *pkt) { #ifndef OPENSSL_NO_SRP unsigned int i; const unsigned char *data; if (!PACKET_get_net_2(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_A_LENGTH); return 0; } if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_BN_LIB); return 0; } if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) { SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_PARAMETERS); return 0; } OPENSSL_free(s->session->srp_username); s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_MALLOC_FAILURE); return 0; } if (!srp_generate_server_master_secret(s)) { /* SSLfatal() already called */ return 0; } return 1; #else /* Should never happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR); return 0; #endif } static int tls_process_cke_gost(SSL *s, PACKET *pkt) { #ifndef OPENSSL_NO_GOST EVP_PKEY_CTX *pkey_ctx; EVP_PKEY *client_pub_pkey = NULL, *pk = NULL; unsigned char premaster_secret[32]; const unsigned char *start; size_t outlen = 32, inlen; unsigned long alg_a; unsigned int asn1id, asn1len; int ret = 0; PACKET encdata; /* Get our certificate private key */ alg_a = s->s3.tmp.new_cipher->algorithm_auth; if (alg_a & SSL_aGOST12) { /* * New GOST ciphersuites have SSL_aGOST01 bit too */ pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey; if (pk == NULL) { pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey; } if (pk == NULL) { pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey; } } else if (alg_a & SSL_aGOST01) { pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey; } pkey_ctx = EVP_PKEY_CTX_new(pk, NULL); if (pkey_ctx == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_MALLOC_FAILURE); return 0; } if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR); return 0; } /* * If client certificate is present and is of the same type, maybe * use it for key exchange. Don't mind errors from * EVP_PKEY_derive_set_peer, because it is completely valid to use a * client certificate for authorization only. */ client_pub_pkey = X509_get0_pubkey(s->session->peer); if (client_pub_pkey) { if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0) ERR_clear_error(); } /* Decrypt session key */ if (!PACKET_get_1(pkt, &asn1id) || asn1id != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED) || !PACKET_peek_1(pkt, &asn1len)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED); goto err; } if (asn1len == 0x81) { /* * Long form length. Should only be one byte of length. Anything else * isn't supported. * We did a successful peek before so this shouldn't fail */ if (!PACKET_forward(pkt, 1)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED); goto err; } } else if (asn1len >= 0x80) { /* * Indefinite length, or more than one long form length bytes. We don't * support it */ SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED); goto err; } /* else short form length */ if (!PACKET_as_length_prefixed_1(pkt, &encdata)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED); goto err; } inlen = PACKET_remaining(&encdata); start = PACKET_data(&encdata); if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED); goto err; } /* Generate master secret */ if (!ssl_generate_master_secret(s, premaster_secret, sizeof(premaster_secret), 0)) { /* SSLfatal() already called */ goto err; } /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) s->statem.no_cert_verify = 1; ret = 1; err: EVP_PKEY_CTX_free(pkey_ctx); return ret; #else /* Should never happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR); return 0; #endif } MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt) { unsigned long alg_k; alg_k = s->s3.tmp.new_cipher->algorithm_mkey; /* For PSK parse and retrieve identity, obtain PSK key */ if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) { /* SSLfatal() already called */ goto err; } if (alg_k & SSL_kPSK) { /* Identity extracted earlier: should be nothing left */ if (PACKET_remaining(pkt) != 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH); goto err; } /* PSK handled by ssl_generate_master_secret */ if (!ssl_generate_master_secret(s, NULL, 0, 0)) { /* SSLfatal() already called */ goto err; } } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) { if (!tls_process_cke_rsa(s, pkt)) { /* SSLfatal() already called */ goto err; } } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) { if (!tls_process_cke_dhe(s, pkt)) { /* SSLfatal() already called */ goto err; } } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) { if (!tls_process_cke_ecdhe(s, pkt)) { /* SSLfatal() already called */ goto err; } } else if (alg_k & SSL_kSRP) { if (!tls_process_cke_srp(s, pkt)) { /* SSLfatal() already called */ goto err; } } else if (alg_k & SSL_kGOST) { if (!tls_process_cke_gost(s, pkt)) { /* SSLfatal() already called */ goto err; } } else { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE); goto err; } return MSG_PROCESS_CONTINUE_PROCESSING; err: #ifndef OPENSSL_NO_PSK OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen); s->s3.tmp.psk = NULL; #endif return MSG_PROCESS_ERROR; } WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst) { #ifndef OPENSSL_NO_SCTP if (wst == WORK_MORE_A) { if (SSL_IS_DTLS(s)) { unsigned char sctpauthkey[64]; char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)]; size_t labellen; /* * Add new shared key for SCTP-Auth, will be ignored if no SCTP * used. */ memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL, sizeof(DTLS1_SCTP_AUTH_LABEL)); /* Don't include the terminating zero. */ labellen = sizeof(labelbuffer) - 1; if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG) labellen += 1; if (SSL_export_keying_material(s, sctpauthkey, sizeof(sctpauthkey), labelbuffer, labellen, NULL, 0, 0) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); return WORK_ERROR; } BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY, sizeof(sctpauthkey), sctpauthkey); } } #endif if (s->statem.no_cert_verify || !s->session->peer) { /* * No certificate verify or no peer certificate so we no longer need * the handshake_buffer */ if (!ssl3_digest_cached_records(s, 0)) { /* SSLfatal() already called */ return WORK_ERROR; } return WORK_FINISHED_CONTINUE; } else { if (!s->s3.handshake_buffer) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); return WORK_ERROR; } /* * For sigalgs freeze the handshake buffer. If we support * extms we've done this already so this is a no-op */ if (!ssl3_digest_cached_records(s, 1)) { /* SSLfatal() already called */ return WORK_ERROR; } } return WORK_FINISHED_CONTINUE; } MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt) { int i; MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR; X509 *x = NULL; unsigned long l; const unsigned char *certstart, *certbytes; STACK_OF(X509) *sk = NULL; PACKET spkt, context; size_t chainidx; SSL_SESSION *new_sess = NULL; /* * To get this far we must have read encrypted data from the client. We no * longer tolerate unencrypted alerts. This value is ignored if less than * TLSv1.3 */ s->statem.enc_read_state = ENC_READ_STATE_VALID; if ((sk = sk_X509_new_null()) == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE); goto err; } if (SSL_IS_TLS13(s) && (!PACKET_get_length_prefixed_1(pkt, &context) || (s->pha_context == NULL && PACKET_remaining(&context) != 0) || (s->pha_context != NULL && !PACKET_equal(&context, s->pha_context, s->pha_context_len)))) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_INVALID_CONTEXT); goto err; } if (!PACKET_get_length_prefixed_3(pkt, &spkt) || PACKET_remaining(pkt) != 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH); goto err; } for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) { if (!PACKET_get_net_3(&spkt, &l) || !PACKET_get_bytes(&spkt, &certbytes, l)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_CERT_LENGTH_MISMATCH); goto err; } certstart = certbytes; x = d2i_X509(NULL, (const unsigned char **)&certbytes, l); if (x == NULL) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB); goto err; } if (certbytes != (certstart + l)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_CERT_LENGTH_MISMATCH); goto err; } if (SSL_IS_TLS13(s)) { RAW_EXTENSION *rawexts = NULL; PACKET extensions; if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_BAD_LENGTH); goto err; } if (!tls_collect_extensions(s, &extensions, SSL_EXT_TLS1_3_CERTIFICATE, &rawexts, NULL, chainidx == 0) || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE, rawexts, x, chainidx, PACKET_remaining(&spkt) == 0)) { OPENSSL_free(rawexts); goto err; } OPENSSL_free(rawexts); } if (!sk_X509_push(sk, x)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE); goto err; } x = NULL; } if (sk_X509_num(sk) <= 0) { /* TLS does not mind 0 certs returned */ if (s->version == SSL3_VERSION) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_NO_CERTIFICATES_RETURNED); goto err; } /* Fail for TLS only if we required a certificate */ else if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) { SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); goto err; } /* No client certificate so digest cached records */ if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) { /* SSLfatal() already called */ goto err; } } else { EVP_PKEY *pkey; i = ssl_verify_cert_chain(s, sk); if (i <= 0) { SSLfatal(s, ssl_x509err2alert(s->verify_result), SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_CERTIFICATE_VERIFY_FAILED); goto err; } if (i > 1) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i); goto err; } pkey = X509_get0_pubkey(sk_X509_value(sk, 0)); if (pkey == NULL) { SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_UNKNOWN_CERTIFICATE_TYPE); goto err; } } /* * Sessions must be immutable once they go into the session cache. Otherwise * we can get multi-thread problems. Therefore we don't "update" sessions, * we replace them with a duplicate. Here, we need to do this every time * a new certificate is received via post-handshake authentication, as the * session may have already gone into the session cache. */ if (s->post_handshake_auth == SSL_PHA_REQUESTED) { if ((new_sess = ssl_session_dup(s->session, 0)) == 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE); goto err; } SSL_SESSION_free(s->session); s->session = new_sess; } X509_free(s->session->peer); s->session->peer = sk_X509_shift(sk); s->session->verify_result = s->verify_result; sk_X509_pop_free(s->session->peer_chain, X509_free); s->session->peer_chain = sk; /* * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE * message */ if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) { /* SSLfatal() already called */ goto err; } /* * Inconsistency alert: cert_chain does *not* include the peer's own * certificate, while we do include it in statem_clnt.c */ sk = NULL; /* Save the current hash state for when we receive the CertificateVerify */ if (SSL_IS_TLS13(s)) { if (!ssl_handshake_hash(s, s->cert_verify_hash, sizeof(s->cert_verify_hash), &s->cert_verify_hash_len)) { /* SSLfatal() already called */ goto err; } /* Resend session tickets */ s->sent_tickets = 0; } ret = MSG_PROCESS_CONTINUE_READING; err: X509_free(x); sk_X509_pop_free(sk, X509_free); return ret; } int tls_construct_server_certificate(SSL *s, WPACKET *pkt) { CERT_PKEY *cpk = s->s3.tmp.cert; if (cpk == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR); return 0; } /* * In TLSv1.3 the certificate chain is always preceded by a 0 length context * for the server Certificate message */ if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR); return 0; } if (!ssl3_output_cert_chain(s, pkt, cpk)) { /* SSLfatal() already called */ return 0; } return 1; } static int create_ticket_prequel(SSL *s, WPACKET *pkt, uint32_t age_add, unsigned char *tick_nonce) { /* * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this * unspecified for resumed session (for simplicity). * In TLSv1.3 we reset the "time" field above, and always specify the * timeout. */ if (!WPACKET_put_bytes_u32(pkt, (s->hit && !SSL_IS_TLS13(s)) ? 0 : s->session->timeout)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL, ERR_R_INTERNAL_ERROR); return 0; } if (SSL_IS_TLS13(s)) { if (!WPACKET_put_bytes_u32(pkt, age_add) || !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL, ERR_R_INTERNAL_ERROR); return 0; } } /* Start the sub-packet for the actual ticket data */ if (!WPACKET_start_sub_packet_u16(pkt)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL, ERR_R_INTERNAL_ERROR); return 0; } return 1; } static int construct_stateless_ticket(SSL *s, WPACKET *pkt, uint32_t age_add, unsigned char *tick_nonce) { unsigned char *senc = NULL; EVP_CIPHER_CTX *ctx = NULL; HMAC_CTX *hctx = NULL; unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2; const unsigned char *const_p; int len, slen_full, slen, lenfinal; SSL_SESSION *sess; unsigned int hlen; SSL_CTX *tctx = s->session_ctx; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char key_name[TLSEXT_KEYNAME_LENGTH]; int iv_len, ok = 0; size_t macoffset, macendoffset; /* get session encoding length */ slen_full = i2d_SSL_SESSION(s->session, NULL); /* * Some length values are 16 bits, so forget it if session is too * long */ if (slen_full == 0 || slen_full > 0xFF00) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); goto err; } senc = OPENSSL_malloc(slen_full); if (senc == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_MALLOC_FAILURE); goto err; } ctx = EVP_CIPHER_CTX_new(); hctx = HMAC_CTX_new(); if (ctx == NULL || hctx == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_MALLOC_FAILURE); goto err; } p = senc; if (!i2d_SSL_SESSION(s->session, &p)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); goto err; } /* * create a fresh copy (not shared with other threads) to clean up */ const_p = senc; sess = d2i_SSL_SESSION(NULL, &const_p, slen_full); if (sess == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); goto err; } slen = i2d_SSL_SESSION(sess, NULL); if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */ SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); SSL_SESSION_free(sess); goto err; } p = senc; if (!i2d_SSL_SESSION(sess, &p)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); SSL_SESSION_free(sess); goto err; } SSL_SESSION_free(sess); /* * Initialize HMAC and cipher contexts. If callback present it does * all the work otherwise use generated values from parent ctx. */ if (tctx->ext.ticket_key_cb) { /* if 0 is returned, write an empty ticket */ int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx, hctx, 1); if (ret == 0) { /* Put timeout and length */ if (!WPACKET_put_bytes_u32(pkt, 0) || !WPACKET_put_bytes_u16(pkt, 0)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); goto err; } OPENSSL_free(senc); EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return 1; } if (ret < 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, SSL_R_CALLBACK_FAILED); goto err; } iv_len = EVP_CIPHER_CTX_iv_length(ctx); } else { const EVP_CIPHER *cipher = EVP_aes_256_cbc(); iv_len = EVP_CIPHER_iv_length(cipher); if (RAND_bytes(iv, iv_len) <= 0 || !EVP_EncryptInit_ex(ctx, cipher, NULL, tctx->ext.secure->tick_aes_key, iv) || !HMAC_Init_ex(hctx, tctx->ext.secure->tick_hmac_key, sizeof(tctx->ext.secure->tick_hmac_key), EVP_sha256(), NULL)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); goto err; } memcpy(key_name, tctx->ext.tick_key_name, sizeof(tctx->ext.tick_key_name)); } if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) { /* SSLfatal() already called */ goto err; } if (!WPACKET_get_total_written(pkt, &macoffset) /* Output key name */ || !WPACKET_memcpy(pkt, key_name, sizeof(key_name)) /* output IV */ || !WPACKET_memcpy(pkt, iv, iv_len) || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH, &encdata1) /* Encrypt session data */ || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen) || !WPACKET_allocate_bytes(pkt, len, &encdata2) || encdata1 != encdata2 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal) || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2) || encdata1 + len != encdata2 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH || !WPACKET_get_total_written(pkt, &macendoffset) || !HMAC_Update(hctx, (unsigned char *)s->init_buf->data + macoffset, macendoffset - macoffset) || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1) || !HMAC_Final(hctx, macdata1, &hlen) || hlen > EVP_MAX_MD_SIZE || !WPACKET_allocate_bytes(pkt, hlen, &macdata2) || macdata1 != macdata2) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); goto err; } /* Close the sub-packet created by create_ticket_prequel() */ if (!WPACKET_close(pkt)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR); goto err; } ok = 1; err: OPENSSL_free(senc); EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return ok; } static int construct_stateful_ticket(SSL *s, WPACKET *pkt, uint32_t age_add, unsigned char *tick_nonce) { if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) { /* SSLfatal() already called */ return 0; } if (!WPACKET_memcpy(pkt, s->session->session_id, s->session->session_id_length) || !WPACKET_close(pkt)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATEFUL_TICKET, ERR_R_INTERNAL_ERROR); return 0; } return 1; } int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt) { SSL_CTX *tctx = s->session_ctx; unsigned char tick_nonce[TICKET_NONCE_SIZE]; union { unsigned char age_add_c[sizeof(uint32_t)]; uint32_t age_add; } age_add_u; age_add_u.age_add = 0; if (SSL_IS_TLS13(s)) { size_t i, hashlen; uint64_t nonce; static const unsigned char nonce_label[] = "resumption"; const EVP_MD *md = ssl_handshake_md(s); int hashleni = EVP_MD_size(md); /* Ensure cast to size_t is safe */ if (!ossl_assert(hashleni >= 0)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR); goto err; } hashlen = (size_t)hashleni; /* * If we already sent one NewSessionTicket, or we resumed then * s->session may already be in a cache and so we must not modify it. * Instead we need to take a copy of it and modify that. */ if (s->sent_tickets != 0 || s->hit) { SSL_SESSION *new_sess = ssl_session_dup(s->session, 0); if (new_sess == NULL) { /* SSLfatal already called */ goto err; } SSL_SESSION_free(s->session); s->session = new_sess; } if (!ssl_generate_session_id(s, s->session)) { /* SSLfatal() already called */ goto err; } if (RAND_bytes(age_add_u.age_add_c, sizeof(age_add_u)) <= 0) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR); goto err; } s->session->ext.tick_age_add = age_add_u.age_add; nonce = s->next_ticket_nonce; for (i = TICKET_NONCE_SIZE; i > 0; i--) { tick_nonce[i - 1] = (unsigned char)(nonce & 0xff); nonce >>= 8; } if (!tls13_hkdf_expand(s, md, s->resumption_master_secret, nonce_label, sizeof(nonce_label) - 1, tick_nonce, TICKET_NONCE_SIZE, s->session->master_key, hashlen, 1)) { /* SSLfatal() already called */ goto err; } s->session->master_key_length = hashlen; s->session->time = (long)time(NULL); if (s->s3.alpn_selected != NULL) { OPENSSL_free(s->session->ext.alpn_selected); s->session->ext.alpn_selected = OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len); if (s->session->ext.alpn_selected == NULL) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE); goto err; } s->session->ext.alpn_selected_len = s->s3.alpn_selected_len; } s->session->ext.max_early_data = s->max_early_data; } if (tctx->generate_ticket_cb != NULL && tctx->generate_ticket_cb(s, tctx->ticket_cb_data) == 0) goto err; /* * If we are using anti-replay protection then we behave as if * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there * is no point in using full stateless tickets. */ if (SSL_IS_TLS13(s) && ((s->options & SSL_OP_NO_TICKET) != 0 || (s->max_early_data > 0 && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) { if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) { /* SSLfatal() already called */ goto err; } } else if (!construct_stateless_ticket(s, pkt, age_add_u.age_add, tick_nonce)) { /* SSLfatal() already called */ goto err; } if (SSL_IS_TLS13(s)) { if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_NEW_SESSION_TICKET, NULL, 0)) { /* SSLfatal() already called */ goto err; } /* * Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets| * gets reset to 0 if we send more tickets following a post-handshake * auth, but |next_ticket_nonce| does not. */ s->sent_tickets++; s->next_ticket_nonce++; ssl_update_cache(s, SSL_SESS_CACHE_SERVER); } return 1; err: return 0; } /* * In TLSv1.3 this is called from the extensions code, otherwise it is used to * create a separate message. Returns 1 on success or 0 on failure. */ int tls_construct_cert_status_body(SSL *s, WPACKET *pkt) { if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type) || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp, s->ext.ocsp.resp_len)) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY, ERR_R_INTERNAL_ERROR); return 0; } return 1; } int tls_construct_cert_status(SSL *s, WPACKET *pkt) { if (!tls_construct_cert_status_body(s, pkt)) { /* SSLfatal() already called */ return 0; } return 1; } #ifndef OPENSSL_NO_NEXTPROTONEG /* * tls_process_next_proto reads a Next Protocol Negotiation handshake message. * It sets the next_proto member in s if found */ MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt) { PACKET next_proto, padding; size_t next_proto_len; /*- * The payload looks like: * uint8 proto_len; * uint8 proto[proto_len]; * uint8 padding_len; * uint8 padding[padding_len]; */ if (!PACKET_get_length_prefixed_1(pkt, &next_proto) || !PACKET_get_length_prefixed_1(pkt, &padding) || PACKET_remaining(pkt) > 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH); return MSG_PROCESS_ERROR; } if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) { s->ext.npn_len = 0; SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO, ERR_R_INTERNAL_ERROR); return MSG_PROCESS_ERROR; } s->ext.npn_len = (unsigned char)next_proto_len; return MSG_PROCESS_CONTINUE_READING; } #endif static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt) { if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS, NULL, 0)) { /* SSLfatal() already called */ return 0; } return 1; } MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt) { if (PACKET_remaining(pkt) != 0) { SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, SSL_R_LENGTH_MISMATCH); return MSG_PROCESS_ERROR; } if (s->early_data_state != SSL_EARLY_DATA_READING && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, ERR_R_INTERNAL_ERROR); return MSG_PROCESS_ERROR; } /* * EndOfEarlyData signals a key change so the end of the message must be on * a record boundary. */ if (RECORD_LAYER_processed_read_pending(&s->rlayer)) { SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, SSL_R_NOT_ON_RECORD_BOUNDARY); return MSG_PROCESS_ERROR; } s->early_data_state = SSL_EARLY_DATA_FINISHED_READING; if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) { /* SSLfatal() already called */ return MSG_PROCESS_ERROR; } return MSG_PROCESS_CONTINUE_READING; }
649897.c
/* * Enterprise 64/128 graphics libraries * * circle(int x, int y, int radius, int skip) * * Stefano Bodrato - March 2011 * * $Id: circle.c,v 1.1 2011/04/01 06:50:45 stefano Exp $ */ #include <enterprise.h> #include <graphics.h> int circle(int x, int y, int radius, int skip) { esccmd_cmd='I'; // INK colour esccmd_x=0; exos_write_block(DEFAULT_VIDEO, 3, esccmd); esccmd_cmd='s'; // set beam off exos_write_block(DEFAULT_VIDEO, 2, esccmd); esccmd_cmd='A'; // set beam position esccmd_x=x*4; esccmd_y=972-y*4; exos_write_block(DEFAULT_VIDEO, 6, esccmd); esccmd_cmd='S'; // set beam on exos_write_block(DEFAULT_VIDEO, 2, esccmd); esccmd_cmd='I'; // INK colour esccmd_x=1; exos_write_block(DEFAULT_VIDEO, 3, esccmd); esccmd_cmd='E'; // Ellipse esccmd_x=radius*4; esccmd_y=radius*4; exos_write_block(DEFAULT_VIDEO, 6, esccmd); esccmd_cmd='s'; // set beam off exos_write_block(DEFAULT_VIDEO, 2, esccmd); }
241337.c
/* * lms283gf05.c -- support for Samsung LMS283GF05 LCD * * Copyright (c) 2009 Marek Vasut <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/device.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/gpio.h> #include <linux/lcd.h> #include <linux/spi/spi.h> #include <linux/spi/lms283gf05.h> #include <linux/module.h> struct lms283gf05_state { struct spi_device *spi; struct lcd_device *ld; }; struct lms283gf05_seq { unsigned char reg; unsigned short value; unsigned char delay; }; /* Magic sequences supplied by manufacturer, for details refer to datasheet */ static const struct lms283gf05_seq disp_initseq[] = { /* REG, VALUE, DELAY */ { 0x07, 0x0000, 0 }, { 0x13, 0x0000, 10 }, { 0x11, 0x3004, 0 }, { 0x14, 0x200F, 0 }, { 0x10, 0x1a20, 0 }, { 0x13, 0x0040, 50 }, { 0x13, 0x0060, 0 }, { 0x13, 0x0070, 200 }, { 0x01, 0x0127, 0 }, { 0x02, 0x0700, 0 }, { 0x03, 0x1030, 0 }, { 0x08, 0x0208, 0 }, { 0x0B, 0x0620, 0 }, { 0x0C, 0x0110, 0 }, { 0x30, 0x0120, 0 }, { 0x31, 0x0127, 0 }, { 0x32, 0x0000, 0 }, { 0x33, 0x0503, 0 }, { 0x34, 0x0727, 0 }, { 0x35, 0x0124, 0 }, { 0x36, 0x0706, 0 }, { 0x37, 0x0701, 0 }, { 0x38, 0x0F00, 0 }, { 0x39, 0x0F00, 0 }, { 0x40, 0x0000, 0 }, { 0x41, 0x0000, 0 }, { 0x42, 0x013f, 0 }, { 0x43, 0x0000, 0 }, { 0x44, 0x013f, 0 }, { 0x45, 0x0000, 0 }, { 0x46, 0xef00, 0 }, { 0x47, 0x013f, 0 }, { 0x48, 0x0000, 0 }, { 0x07, 0x0015, 30 }, { 0x07, 0x0017, 0 }, { 0x20, 0x0000, 0 }, { 0x21, 0x0000, 0 }, { 0x22, 0x0000, 0 } }; static const struct lms283gf05_seq disp_pdwnseq[] = { { 0x07, 0x0016, 30 }, { 0x07, 0x0004, 0 }, { 0x10, 0x0220, 20 }, { 0x13, 0x0060, 50 }, { 0x13, 0x0040, 50 }, { 0x13, 0x0000, 0 }, { 0x10, 0x0000, 0 } }; static void lms283gf05_reset(unsigned long gpio, bool inverted) { gpio_set_value(gpio, !inverted); mdelay(100); gpio_set_value(gpio, inverted); mdelay(20); gpio_set_value(gpio, !inverted); mdelay(20); } static void lms283gf05_toggle(struct spi_device *spi, const struct lms283gf05_seq *seq, int sz) { char buf[3]; int i; for (i = 0; i < sz; i++) { buf[0] = 0x74; buf[1] = 0x00; buf[2] = seq[i].reg; spi_write(spi, buf, 3); buf[0] = 0x76; buf[1] = seq[i].value >> 8; buf[2] = seq[i].value & 0xff; spi_write(spi, buf, 3); mdelay(seq[i].delay); } } static int lms283gf05_power_set(struct lcd_device *ld, int power) { struct lms283gf05_state *st = lcd_get_data(ld); struct spi_device *spi = st->spi; struct lms283gf05_pdata *pdata = dev_get_platdata(&spi->dev); if (power <= FB_BLANK_NORMAL) { if (pdata) lms283gf05_reset(pdata->reset_gpio, pdata->reset_inverted); lms283gf05_toggle(spi, disp_initseq, ARRAY_SIZE(disp_initseq)); } else { lms283gf05_toggle(spi, disp_pdwnseq, ARRAY_SIZE(disp_pdwnseq)); if (pdata) gpio_set_value(pdata->reset_gpio, pdata->reset_inverted); } return 0; } static struct lcd_ops lms_ops = { .set_power = lms283gf05_power_set, .get_power = NULL, }; static int lms283gf05_probe(struct spi_device *spi) { struct lms283gf05_state *st; struct lms283gf05_pdata *pdata = dev_get_platdata(&spi->dev); struct lcd_device *ld; int ret = 0; if (pdata != NULL) { ret = devm_gpio_request_one(&spi->dev, pdata->reset_gpio, GPIOF_DIR_OUT | (!pdata->reset_inverted ? GPIOF_INIT_HIGH : GPIOF_INIT_LOW), "LMS285GF05 RESET"); if (ret) return ret; } st = devm_kzalloc(&spi->dev, sizeof(struct lms283gf05_state), GFP_KERNEL); if (st == NULL) return -ENOMEM; ld = devm_lcd_device_register(&spi->dev, "lms283gf05", &spi->dev, st, &lms_ops); if (IS_ERR(ld)) return PTR_ERR(ld); st->spi = spi; st->ld = ld; spi_set_drvdata(spi, st); /* kick in the LCD */ if (pdata) lms283gf05_reset(pdata->reset_gpio, pdata->reset_inverted); lms283gf05_toggle(spi, disp_initseq, ARRAY_SIZE(disp_initseq)); return 0; } static struct spi_driver lms283gf05_driver = { .driver = { .name = "lms283gf05", }, .probe = lms283gf05_probe, }; module_spi_driver(lms283gf05_driver); MODULE_AUTHOR("Marek Vasut <[email protected]>"); MODULE_DESCRIPTION("LCD283GF05 LCD"); MODULE_LICENSE("GPL v2");
874806.c
/* * Copyright (C) 2011 Jaagup Repan <jrepan at gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "wmanager.h" struct window_t *panel; uint32_t current_tags; void update_tiling() { struct window_t *main_window = NULL; struct window_t *window, *last; bool others = false; int width = screen_width / 2; int height = screen_height; int count = 0; int y = 0; for (window = windows; window; window = window->next) { if (!(window->flags & FLOATING) && (window->tags & current_tags)) { if (!main_window) { main_window = window; } if (window != main_window) { if (window->flags & CONSTANT_SIZE) { height -= window->height + 2; if (screen_width - width < window->width) { width = screen_width - window->width; } } else { last = window; count++; } others = true; } } } if (!main_window) { update_screen(0, 0, screen_width, screen_height); return; } if (panel) { y += panel->height + 2; height -= panel->height + 2; } if (width < 10) { width = 10; } main_window->x = 0; main_window->y = y; if (main_window->flags & CONSTANT_SIZE) { width = main_window->width; } else { resize_window(main_window, others ? width : screen_width, height, true); } for (window = windows; window; window = window->next) { if (!(window->flags & FLOATING) && (window != main_window) && (window->tags & current_tags)) { window->x = width + 2; window->y = y; if (!(window->flags & CONSTANT_SIZE)) { resize_window(window, screen_width - width - 2, height / count + (window == last ? height % count : -2), true); } y += window->height + 2; } } activate_window(); update_screen(0, 0, screen_width, screen_height); }
266471.c
//***************************************************************************** // // dfuwrap.c - A simple command line application to generate a file system // image file from the contents of a directory. // // Copyright (c) 2008-2014 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 2.1.0.12573 of the Tiva Firmware Development Package. // //***************************************************************************** #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <dirent.h> #include <errno.h> #include <sys/stat.h> typedef unsigned char BOOL; #define FALSE 0 #define TRUE 1 //***************************************************************************** // // Globals controlled by various command line parameters. // //***************************************************************************** BOOL g_bVerbose = FALSE; BOOL g_bQuiet = FALSE; BOOL g_bOverwrite = FALSE; BOOL g_bAdd = TRUE; BOOL g_bCheck = FALSE; BOOL g_bForce = FALSE; unsigned long g_ulAddress = 0; unsigned short g_usVendorID = 0x1CBE; // Texas Instruments (Tiva) unsigned short g_usProductID = 0x00FF; // DFU boot loader unsigned short g_usDeviceID = 0x0000; char *g_pszInput = NULL; char *g_pszOutput = "image.dfu"; //***************************************************************************** // // Helpful macros for generating output depending upon verbose and quiet flags. // //***************************************************************************** #define VERBOSEPRINT(...) if(g_bVerbose) { printf(__VA_ARGS__); } #define QUIETPRINT(...) if(!g_bQuiet) { printf(__VA_ARGS__); } //***************************************************************************** // // Macros for accessing multi-byte fields in the DFU suffix and prefix. // //***************************************************************************** #define WRITE_LONG(num, ptr) \ { \ *((unsigned char *)(ptr)) = ((num) & 0xFF); \ *(((unsigned char *)(ptr)) + 1) = (((num) >> 8) & 0xFF); \ *(((unsigned char *)(ptr)) + 2) = (((num) >> 16) & 0xFF); \ *(((unsigned char *)(ptr)) + 3) = (((num) >> 24) & 0xFF); \ } #define WRITE_SHORT(num, ptr) \ { \ *((unsigned char *)(ptr)) = ((num) & 0xFF); \ *(((unsigned char *)(ptr)) + 1) = (((num) >> 8) & 0xFF); \ } #define READ_SHORT(ptr) \ (*((unsigned char *)(ptr)) | (*(((unsigned char *)(ptr)) + 1) << 8)) #define READ_LONG(ptr) \ (*((unsigned char *)(ptr)) | \ (*(((unsigned char *)(ptr)) + 1) << 8) | \ (*(((unsigned char *)(ptr)) + 2) << 16) | \ (*(((unsigned char *)(ptr)) + 3) << 24)) //***************************************************************************** // // Storage for the CRC32 calculation lookup table. // //***************************************************************************** unsigned long g_pulCRC32Table[256]; //***************************************************************************** // // The standard DFU file suffix. // //***************************************************************************** unsigned char g_pcDFUSuffix[] = { 0x00, // bcdDevice LSB 0x00, // bcdDevice MSB 0x00, // idProduct LSB 0x00, // idProduct MSB 0x00, // idVendor LSB 0x00, // idVendor MSB 0x00, // bcdDFU LSB 0x01, // bcdDFU MSB 'U', // ucDfuSignature LSB 'F', // ucDfuSignature 'D', // ucDfuSignature MSB 16, // bLength 0x00, // dwCRC LSB 0x00, // dwCRC byte 2 0x00, // dwCRC byte 3 0x00 // dwCRC MSB }; //***************************************************************************** // // The Tiva-specific binary image suffix used by the DFU driver to // determine where the image should be located in flash. // //***************************************************************************** unsigned char g_pcDFUPrefix[] = { 0x01, // TIVA_DFU_CMD_PROG 0x00, // Reserved 0x00, // LSB start address / 1024 0x20, // MSB start address / 1024 0x00, // LSB file payload length (excluding prefix and suffix) 0x00, // Byte 2 file payload length (excluding prefix and suffix) 0x00, // Byte 3 file payload length (excluding prefix and suffix) 0x00, // MSB file payload length (excluding prefix and suffix) }; //***************************************************************************** // // Initialize the CRC32 calculation table for the polynomial required by the // DFU specification. This code is based on an example found at // // http://www.createwindow.com/programming/crc32/index.htm. // //***************************************************************************** unsigned long Reflect(unsigned long ulRef, char ucCh) { unsigned long ulValue; int iLoop; ulValue = 0; // // Swap bit 0 for bit 7, bit 1 for bit 6, etc. // for(iLoop = 1; iLoop < (ucCh + 1); iLoop++) { if(ulRef & 1) ulValue |= 1 << (ucCh - iLoop); ulRef >>= 1; } return ulValue; } void InitCRC32Table() { unsigned long ulPolynomial; int i, j; // This is the ANSI X 3.66 polynomial as required by the DFU // specification. // ulPolynomial = 0x04c11db7; for(i = 0; i <= 0xFF; i++) { g_pulCRC32Table[i]=Reflect(i, 8) << 24; for (j = 0; j < 8; j++) { g_pulCRC32Table[i] = (g_pulCRC32Table[i] << 1) ^ (g_pulCRC32Table[i] & (1 << 31) ? ulPolynomial : 0); } g_pulCRC32Table[i] = Reflect(g_pulCRC32Table[i], 32); } } //***************************************************************************** // // Calculate the CRC for the supplied block of data. // //***************************************************************************** unsigned long CalculateCRC32(unsigned char *pcData, unsigned long ulLength) { unsigned long ulCRC; unsigned long ulCount; unsigned char* pcBuffer; unsigned char ucChar; // // Initialize the CRC to all 1s. // ulCRC = 0xFFFFFFFF; // // Get a pointer to the start of the data and the number of bytes to // process. // pcBuffer = pcData; ulCount = ulLength; // // Perform the algorithm on each byte in the supplied buffer using the // lookup table values calculated in InitCRC32Table(). // while(ulCount--) { ucChar = *pcBuffer++; ulCRC = (ulCRC >> 8) ^ g_pulCRC32Table[(ulCRC & 0xFF) ^ ucChar]; } // Return the result. return (ulCRC); } //***************************************************************************** // // Show the startup banner. // //***************************************************************************** void PrintWelcome(void) { QUIETPRINT("\ndfuwrap - Wrap a binary file for use in USB DFU download.\n"); QUIETPRINT("Copyright (c) 2008-2014 Texas Instruments Incorporated. All rights reserved.\n\n"); } //***************************************************************************** // // Show help on the application command line parameters. // //***************************************************************************** void ShowHelp(void) { // // Only print help if we are not in quiet mode. // if(g_bQuiet) { return; } printf("This application may be used to wrap binary files which are\n"); printf("to be flashed to a Tiva device using the USB boot loader.\n"); printf("Additionally, the application can check the validity of an\n"); printf("existing Device Firmware Upgrade (DFU) wrapper or remove the\n"); printf("wrapper to retrieve the original binary payload.\n\n"); printf("Supported parameters are:\n\n"); printf("-i <file> - The name of the input file.\n"); printf("-o <file> - The name of the output file (default image.dfu)\n"); printf("-r - Remove an existing DFU wrapper from the input file.\n"); printf("-c - Check validity of the input file's existing DFU wrapper.\n"); printf("-v <num> - Set the DFU wrapper's USB vendor ID (default 0x1CBE).\n"); printf("-p <num> - Set the DFU wrapper's USB product ID (default 0x00FF).\n"); printf("-d <num> - Set the DFU wrapper's USB device ID (default 0x0000).\n"); printf("-a <num> - Set the address the binary will be flashed to.\n"); printf("-x - Overwrite existing output file without prompting.\n"); printf("-f - Force wrapper writing even if a wrapper already exists.\n"); printf("-? or -h - Show this help.\n"); printf("-q - Quiet mode. Disable output to stdio.\n"); printf("-e - Enable verbose output\n\n"); printf("Example:\n\n"); printf(" dfuwrap -i program.bin -o program.dfu -a 0x1800\n\n"); printf("wraps program.bin in a DFU wrapper which will cause the image to\n"); printf("address 0x1800 in flash.\n\n"); } //***************************************************************************** // // Parse the command line, extracting all parameters. // // Returns 0 on failure, 1 on success. // //***************************************************************************** int ParseCommandLine(int argc, char *argv[]) { int iRetcode; BOOL bRetcode; BOOL bShowHelp; // // By default, don't show the help screen. // bShowHelp = FALSE; while(1) { // // Get the next command line parameter. // iRetcode = getopt(argc, argv, "a:i:o:v:d:p:eh?qcrfx"); if(iRetcode == -1) { break; } switch(iRetcode) { case 'i': g_pszInput = optarg; break; case 'o': g_pszOutput = optarg; break; case 'v': g_usVendorID = (unsigned short)strtol(optarg, NULL, 0); break; case 'd': g_usDeviceID = (unsigned short)strtol(optarg, NULL, 0); break; case 'p': g_usProductID = (unsigned short)strtol(optarg, NULL, 0); break; case 'a': g_ulAddress = (unsigned long)strtol(optarg, NULL, 0); break; case 'e': g_bVerbose = TRUE; break; case 'f': g_bForce = TRUE; break; case 'q': g_bQuiet = TRUE; break; case 'x': g_bOverwrite = TRUE; break; case 'c': g_bCheck = TRUE; break; case 'r': g_bAdd = FALSE; break; case '?': case 'h': bShowHelp = TRUE; break; } } // // Show the welcome banner unless we have been told to be quiet. // PrintWelcome(); // // Catch various invalid parameter cases. // if(bShowHelp || (g_pszInput == NULL) || (((g_ulAddress == 0) || (g_ulAddress & 1023)) && g_bAdd && !g_bCheck)) { ShowHelp(); // // Make sure we were given an input file. // if(g_pszInput == NULL) { QUIETPRINT("ERROR: An input file must be specified using the -i " "parameter.\n"); } // // Make sure we were given a start address. // if(g_bAdd && !g_bCheck) { if(g_ulAddress == 0) { QUIETPRINT("ERROR: The flash address of the image must be " "provided using the -a parameter.\n"); } else { QUIETPRINT("ERROR: The supplied flash address must be a " "multiple of 1024.\n"); } } // // If we get here, we exit immediately. // exit(1); } // // Tell the caller that everything is OK. // return(1); } //***************************************************************************** // // Dump the command line parameters to stdout if we are in verbose mode. // //***************************************************************************** void DumpCommandLineParameters(void) { if(!g_bQuiet && g_bVerbose) { printf("Input file: %s\n", g_pszInput); printf("Output file: %s\n", g_pszOutput); printf("Operation: %s\n", g_bCheck ? "Check" : (g_bAdd ? "Add" : "Remove")); printf("Vendor ID: 0x%04x\n", g_usVendorID); printf("Product ID: 0x%04x\n", g_usProductID); printf("Device ID: 0x%04x\n", g_usDeviceID); printf("Flash Address: 0x%08lx\n", g_ulAddress); printf("Overwrite output?: %s\n", g_bOverwrite ? "Yes" : "No"); printf("Force wrapper?: %s\n", g_bForce ? "Yes" : "No"); } } //***************************************************************************** // // Read the input file into memory, optionally leaving space before and after // it for the DFU suffix and Tiva prefix. // // On success, *pulLength is written with the length of the buffer allocated. // This will be the file size plus the prefix and suffix lengths if bHdrs is // TRUE. // // Returns a pointer to the start of the allocated buffer if successful or // NULL if there was a problem. If headers have been allocated, the file data // starts sizeof(g_pcDFUprefix) bytes into the allocated block. // //***************************************************************************** unsigned char * ReadInputFile(char *pcFilename, BOOL bHdrs, unsigned long *pulLength) { char *pcFileBuffer; int iRead; int iSize; int iSizeAlloc; FILE *fhFile; QUIETPRINT("Reading input file %s\n", pcFilename); // // Try to open the input file. // fhFile = fopen(pcFilename, "rb"); if(!fhFile) { // // File not found or cannot be opened for some reason. // QUIETPRINT("Can't open file!\n"); return(NULL); } // // Determine the file length. // fseek(fhFile, 0, SEEK_END); iSize = ftell(fhFile); fseek(fhFile, 0, SEEK_SET); // // Allocate a buffer to hold the file contents and, if requested, the // prefix and suffix structures. // iSizeAlloc = iSize + (bHdrs ? (sizeof(g_pcDFUPrefix) + sizeof(g_pcDFUSuffix)) : 0); pcFileBuffer = malloc(iSizeAlloc); if(pcFileBuffer == NULL) { QUIETPRINT("Can't allocate %d bytes of memory!\n", iSizeAlloc); return(NULL); } // // Read the file contents into the buffer at the correct position. // iRead = fread(pcFileBuffer + (bHdrs ? sizeof(g_pcDFUPrefix) : 0), 1, iSize, fhFile); // // Close the file. // fclose(fhFile); // // Did we get the whole file? // if(iSize != iRead) { // // Nope - free the buffer and return an error. // QUIETPRINT("Error reading file. Expected %d bytes, got %d!\n", iSize, iRead); free(pcFileBuffer); return(NULL); } // // If we are adding headers, copy the template structures into the buffer // before we return it to the caller. // if(bHdrs) { // // Copy the prefix. // memcpy(pcFileBuffer, g_pcDFUPrefix, sizeof(g_pcDFUPrefix)); // // Copy the suffix. // memcpy(&pcFileBuffer[iSizeAlloc] - sizeof(g_pcDFUSuffix), g_pcDFUSuffix, sizeof(g_pcDFUSuffix)); } // // Return the new buffer to the caller along with its size. // *pulLength = (unsigned long)iSizeAlloc; return(pcFileBuffer); } //***************************************************************************** // // Determine whether the supplied block of data appears to start with a valid // Tiva-specific DFU download prefix structure. // //***************************************************************************** BOOL IsPrefixValid(unsigned char *pcPrefix, unsigned char *pcEnd) { unsigned short usStartAddr; unsigned long ulLength; VERBOSEPRINT("Looking for valid prefix...\n"); // // Is the data block large enough to contain a whole prefix structure? // if((pcEnd - pcPrefix) < sizeof(g_pcDFUPrefix)) { // // Nope - prefix can't be valid. // VERBOSEPRINT("File is too short to contain a prefix.\n"); return(FALSE); } // // Check the first 2 bytes of the prefix since their values are fixed. // if((pcPrefix[0] != 0x01) || (pcPrefix[1] != 0x00)) { // // First two values are not as expected so the prefix is invalid. // VERBOSEPRINT("Prefix fixed values are incorrect.\n"); return(FALSE); } // // Read the start address and length from the supposed prefix. // ulLength = READ_LONG(pcPrefix + 4); usStartAddr = READ_SHORT(pcPrefix + 2); // // Is the length as expected? Note that we allow two cases so that we can // catch files which may or may not contain the DFU suffix in addition to // this prefix. // if((ulLength != (pcEnd - pcPrefix) - sizeof(g_pcDFUPrefix)) && (ulLength != (pcEnd - pcPrefix) - (sizeof(g_pcDFUPrefix) + sizeof(g_pcDFUSuffix)))) { // // Nope. Prefix is invalid. // VERBOSEPRINT("Length is not valid for supplied data.\n", ulLength); return(FALSE); } // // If we get here, the prefix is valid. // VERBOSEPRINT("Prefix appears valid.\n"); return(TRUE); } //***************************************************************************** // // Determine whether the supplied block of data appears to end with a valid // DFU-standard suffix structure. // //***************************************************************************** BOOL IsSuffixValid(unsigned char *pcData, unsigned char *pcEnd) { unsigned char ucSuffixLen; unsigned long ulCRCRead, ulCRCCalc; VERBOSEPRINT("Looking for valid suffix...\n"); // // Assuming there is a valid suffix, what length is it reported as being? // ucSuffixLen = *(pcEnd - 5); VERBOSEPRINT("Length reported as %d bytes\n", ucSuffixLen); // // Is the data long enough to contain this suffix and is the suffix at // at least as long as the ones we already know about? // if((ucSuffixLen < sizeof(g_pcDFUSuffix)) || ((pcEnd - pcData) < ucSuffixLen)) { // // The reported length cannot indicate a valid suffix. // VERBOSEPRINT("Suffix length is not valid.\n"); return(FALSE); } // // Now check that the "DFU" marker is in place. // if( (*(pcEnd - 6) != 'D') || (*(pcEnd - 7) != 'F') || (*(pcEnd - 8) != 'U')) { // // The DFU marker is not in place so the suffix is invalid. // VERBOSEPRINT("Suffix 'DFU' marker is not present.\n"); return(FALSE); } // // Now check that the CRC of the data matches the CRC in the supposed // suffix. // ulCRCRead = READ_LONG(pcEnd - 4); ulCRCCalc = CalculateCRC32(pcData, ((pcEnd - 4) - pcData)); // // If the CRCs match, we have a good suffix, else there is a problem. // if(ulCRCRead == ulCRCCalc) { VERBOSEPRINT("DFU suffix is valid.\n"); return(TRUE); } else { VERBOSEPRINT("Read CRC 0x%08lx, calculated 0x%08lx.\n", ulCRCRead, ulCRCCalc); VERBOSEPRINT("DFU suffix is invalid.\n"); return(FALSE); } } //***************************************************************************** // // Dump the contents of the Tiva-specfic DFU file prefix. // //***************************************************************************** void DumpPrefix(unsigned char *pcPrefix) { unsigned long ulLength; ulLength = READ_LONG(pcPrefix + 4); QUIETPRINT("\nTiva DFU Prefix\n"); QUIETPRINT("---------------\n\n"); QUIETPRINT("Flash address: 0x%08x\n", (READ_SHORT(pcPrefix + 2) * 1024)); QUIETPRINT("Payload length: %ld (0x%lx) bytes, %ldKB\n", ulLength, ulLength, ulLength / 1024); } //***************************************************************************** // // Dump the contents of the DFU-standard file suffix. Note that the pointer // passed here points to the byte one past the end of the suffix such that the // last suffix byte can be found at *(pcEnd - 1). // //***************************************************************************** void DumpSuffix(unsigned char *pcEnd) { QUIETPRINT("\nDFU File Suffix\n"); QUIETPRINT("---------------\n\n"); QUIETPRINT("Suffix Length: %d bytes\n", *(pcEnd - 5)); QUIETPRINT("Suffix Version: 0x%4x\n", READ_SHORT(pcEnd - 10)); QUIETPRINT("Device ID: 0x%04x\n", READ_SHORT(pcEnd - 16)); QUIETPRINT("Product ID: 0x%04x\n", READ_SHORT(pcEnd - 14)); QUIETPRINT("Vendor ID: 0x%04x\n", READ_SHORT(pcEnd - 12)); QUIETPRINT("CRC: 0x%08x\n", READ_LONG(pcEnd - 4)); } //***************************************************************************** // // Open the output file after checking whether it exists and getting user // permission for an overwrite (if required) then write the supplied data to // it. // // Returns 0 on success or a positive value on error. // //***************************************************************************** int WriteOutputFile(char *pszFile, unsigned char *pcData, unsigned long ulLength) { FILE *fh; int iResponse; unsigned long ulWritten; // // Have we been asked to overwrite an existing output file without // prompting? // if(!g_bOverwrite) { // // No - we need to check to see if the file exists before proceeding. // fh = fopen(pszFile, "rb"); if(fh) { VERBOSEPRINT("Output file already exists.\n"); // // The file already exists. Close it them prompt the user about // whether they want to overwrite or not. // fclose(fh); if(!g_bQuiet) { printf("File %s exists. Overwrite? ", pszFile); iResponse = getc(stdin); if((iResponse != 'y') && (iResponse != 'Y')) { // // The user didn't respond with 'y' or 'Y' so return an // error and don't overwrite the file. // VERBOSEPRINT("User chose not to overwrite output.\n"); return(6); } printf("Overwriting existing output file.\n"); } else { // // In quiet mode but -x has not been specified so don't // overwrite. // return(7); } } } // // If we reach here, it is fine to overwrite the file (or the file doesn't // already exist) so go ahead and open it. // fh = fopen(pszFile, "wb"); if(!fh) { QUIETPRINT("Error opening output file for writing\n"); return(8); } // // Write the supplied data to the file. // VERBOSEPRINT("Writing %ld (0x%lx) bytes to output file.\n", ulLength, ulLength); ulWritten = fwrite(pcData, 1, ulLength, fh); // // Close the file. // fclose(fh); // // Did we write all the data? // if(ulWritten != ulLength) { QUIETPRINT("Error writing data to output file! Wrote %ld, " "requested %ld\n", ulWritten, ulLength); return(9); } else { QUIETPRINT("Output file written successfully.\n"); } return(0); } //***************************************************************************** // // Main entry function for the application. // //***************************************************************************** int main(int argc, char *argv[]) { int iRetcode; unsigned char *pcInput; unsigned char *pcPrefix; unsigned char *pcSuffix; unsigned long ulFileLen; unsigned long ulCRC; BOOL bSuffixValid; BOOL bPrefixValid; // // Initialize the CRC32 lookup table. // InitCRC32Table(); // // Parse the command line arguments // iRetcode = ParseCommandLine(argc, argv); if(!iRetcode) { return(1); } // // Echo the command line settings to stdout in verbose mode. // DumpCommandLineParameters(); // // Read the input file into memory. // pcInput = ReadInputFile(g_pszInput, g_bAdd, &ulFileLen); if(!pcInput) { VERBOSEPRINT("Error reading input file.\n"); exit(1); } // // Does the file we just read have a DFU suffix and prefix already? // pcPrefix = pcInput + (g_bAdd ? sizeof(g_pcDFUPrefix) : 0); pcSuffix = pcInput + (ulFileLen - (g_bAdd ? sizeof(g_pcDFUSuffix) : 0)); bPrefixValid = IsPrefixValid(pcPrefix, pcSuffix); bSuffixValid = IsSuffixValid(pcPrefix, pcSuffix); // // Are we being asked to check the validity of a DFU image? // if(g_bCheck) { // // Yes - was the DFU prefix valid? // if(!bPrefixValid) { QUIETPRINT("File prefix appears to be invalid or absent.\n"); } else { DumpPrefix(pcPrefix); } // // Was the suffix valid? // if(!bSuffixValid) { QUIETPRINT("DFU suffix appears to be invalid or absent.\n"); } else { DumpSuffix(pcSuffix); } // // Set the return code to indicate whether or not the file appears // to be a valid DFU-formatted image. // iRetcode = (!bPrefixValid || !bSuffixValid) ? 2 : 0; } else { // // Were we asked to remove the existing DFU wrapper from the file? // if(!g_bAdd) { // // We can only remove the wrapper if one actually exists. // if(!bPrefixValid) { // // Without the prefix, we can't tell how much of the file to // write to the output. // QUIETPRINT("This does not appear to be a " "valid DFU-formatted file.\n"); iRetcode = 3; } else { // // Write the input file payload to the output file, this removing // the wrapper. // iRetcode = WriteOutputFile(g_pszOutput, pcPrefix + sizeof(g_pcDFUPrefix), READ_LONG(pcPrefix + 4)); } } else { // // We are adding a new DFU wrapper to the input file. First check to // see if it already appears to have a wrapper. // if(bPrefixValid && bSuffixValid && !g_bForce) { QUIETPRINT("This file already contains a valid DFU wrapper.\n"); QUIETPRINT("Use -f if you want to force the writing of " "another wrapper.\n"); iRetcode = 5; } else { // // The file is not wrapped or we have been asked to force a // new wrapper over the existing one. First fill in the // header fields. // WRITE_SHORT(g_ulAddress / 1024, pcInput + 2); WRITE_LONG(ulFileLen - (sizeof(g_pcDFUPrefix) + sizeof(g_pcDFUSuffix)), pcInput + 4); // // Now fill in the DFU suffix fields that may have been // overridden by the user. // pcSuffix = pcInput + ulFileLen; WRITE_SHORT(g_usDeviceID, pcSuffix - 16); WRITE_SHORT(g_usProductID, pcSuffix - 14); WRITE_SHORT(g_usVendorID, pcSuffix - 12); // // Calculate the new file CRC. This is calculated from all // but the last 4 bytes of the file (which will contain the // CRC itself). // ulCRC = CalculateCRC32(pcInput, ulFileLen - 4); WRITE_LONG(ulCRC, pcSuffix - 4); // // Now write the wrapped file to the output. // iRetcode = WriteOutputFile(g_pszOutput, pcInput, ulFileLen); } } } // // Free our file buffer. // free(pcInput); // // Exit the program and tell the OS that all is well. // exit(iRetcode); }
729128.c
/* * An implementation of what I call the "Sea of Stars" algorithm for * POSIX fnmatch(). The basic idea is that we factor the pattern into * a head component (which we match first and can reject without ever * measuring the length of the string), an optional tail component * (which only exists if the pattern contains at least one star), and * an optional "sea of stars", a set of star-separated components * between the head and tail. After the head and tail matches have * been removed from the input string, the components in the "sea of * stars" are matched sequentially by searching for their first * occurrence past the end of the previous match. * * - Rich Felker, April 2012 */ #include <string.h> #include <fnmatch.h> #include <stdlib.h> #include <wchar.h> #include <wctype.h> #include "locale_impl.h" #define END 0 #define UNMATCHABLE -2 #define BRACKET -3 #define QUESTION -4 #define STAR -5 static int str_next(const char *str, size_t n, size_t *step) { if (!n) { *step = 0; return 0; } if (str[0] >= 128U) { wchar_t wc; int k = mbtowc(&wc, str, n); if (k<0) { *step = 1; return -1; } *step = k; return wc; } *step = 1; return str[0]; } static int pat_next(const char *pat, size_t m, size_t *step, int flags) { int esc = 0; if (!m || !*pat) { *step = 0; return END; } *step = 1; if (pat[0]=='\\' && pat[1] && !(flags & FNM_NOESCAPE)) { *step = 2; pat++; esc = 1; goto escaped; } if (pat[0]=='[') { size_t k = 1; if (k<m) if (pat[k] == '^' || pat[k] == '!') k++; if (k<m) if (pat[k] == ']') k++; for (; k<m && pat[k] && pat[k]!=']'; k++) { if (k+1<m && pat[k+1] && pat[k]=='[' && (pat[k+1]==':' || pat[k+1]=='.' || pat[k+1]=='=')) { int z = pat[k+1]; k+=2; if (k<m && pat[k]) k++; while (k<m && pat[k] && (pat[k-1]!=z || pat[k]!=']')) k++; if (k==m || !pat[k]) break; } } if (k==m || !pat[k]) { *step = 1; return '['; } *step = k+1; return BRACKET; } if (pat[0] == '*') return STAR; if (pat[0] == '?') return QUESTION; escaped: if (pat[0] >= 128U) { wchar_t wc; int k = mbtowc(&wc, pat, m); if (k<0) { *step = 0; return UNMATCHABLE; } *step = k + esc; return wc; } return pat[0]; } static int casefold(int k) { int c = towupper(k); return c == k ? towlower(k) : c; } static int match_bracket(const char *p, int k, int kfold) { wchar_t wc; int inv = 0; p++; if (*p=='^' || *p=='!') { inv = 1; p++; } if (*p==']') { if (k==']') return !inv; p++; } else if (*p=='-') { if (k=='-') return !inv; p++; } wc = p[-1]; for (; *p != ']'; p++) { if (p[0]=='-' && p[1]!=']') { wchar_t wc2; int l = mbtowc(&wc2, p+1, 4); if (l < 0) return 0; if (wc <= wc2) if ((unsigned)k-wc <= wc2-wc || (unsigned)kfold-wc <= wc2-wc) return !inv; p += l-1; continue; } if (p[0]=='[' && (p[1]==':' || p[1]=='.' || p[1]=='=')) { const char *p0 = p+2; int z = p[1]; p+=3; while (p[-1]!=z || p[0]!=']') p++; if (z == ':' && p-1-p0 < 16) { char buf[16]; memcpy(buf, p0, p-1-p0); buf[p-1-p0] = 0; if (iswctype(k, wctype(buf)) || iswctype(kfold, wctype(buf))) return !inv; } continue; } if (*p < 128U) { wc = (unsigned char)*p; } else { int l = mbtowc(&wc, p, 4); if (l < 0) return 0; p += l-1; } if (wc==k || wc==kfold) return !inv; } return inv; } static int fnmatch_internal(const char *pat, size_t m, const char *str, size_t n, int flags) { const char *p, *ptail, *endpat; const char *s, *stail, *endstr; size_t pinc, sinc, tailcnt=0; int c, k, kfold; if (flags & FNM_PERIOD) { if (*str == '.' && *pat != '.') return FNM_NOMATCH; } for (;;) { switch ((c = pat_next(pat, m, &pinc, flags))) { case UNMATCHABLE: return FNM_NOMATCH; case STAR: pat++; m--; break; default: k = str_next(str, n, &sinc); if (k <= 0) return (c==END) ? 0 : FNM_NOMATCH; str += sinc; n -= sinc; kfold = flags & FNM_CASEFOLD ? casefold(k) : k; if (c == BRACKET) { if (!match_bracket(pat, k, kfold)) return FNM_NOMATCH; } else if (c != QUESTION && k != c && kfold != c) { return FNM_NOMATCH; } pat+=pinc; m-=pinc; continue; } break; } /* Compute real pat length if it was initially unknown/-1 */ m = strnlen(pat, m); endpat = pat + m; /* Find the last * in pat and count chars needed after it */ for (p=ptail=pat; p<endpat; p+=pinc) { switch (pat_next(p, endpat-p, &pinc, flags)) { case UNMATCHABLE: return FNM_NOMATCH; case STAR: tailcnt=0; ptail = p+1; break; default: tailcnt++; break; } } /* Past this point we need not check for UNMATCHABLE in pat, * because all of pat has already been parsed once. */ /* Compute real str length if it was initially unknown/-1 */ n = strnlen(str, n); endstr = str + n; if (n < tailcnt) return FNM_NOMATCH; /* Find the final tailcnt chars of str, accounting for UTF-8. * On illegal sequences we may get it wrong, but in that case * we necessarily have a matching failure anyway. */ for (s=endstr; s>str && tailcnt; tailcnt--) { if (s[-1] < 128U || MB_CUR_MAX==1) s--; else while ((unsigned char)*--s-0x80U<0x40 && s>str); } if (tailcnt) return FNM_NOMATCH; stail = s; /* Check that the pat and str tails match */ p = ptail; for (;;) { c = pat_next(p, endpat-p, &pinc, flags); p += pinc; if ((k = str_next(s, endstr-s, &sinc)) <= 0) { if (c != END) return FNM_NOMATCH; break; } s += sinc; kfold = flags & FNM_CASEFOLD ? casefold(k) : k; if (c == BRACKET) { if (!match_bracket(p-pinc, k, kfold)) return FNM_NOMATCH; } else if (c != QUESTION && k != c && kfold != c) { return FNM_NOMATCH; } } /* We're all done with the tails now, so throw them out */ endstr = stail; endpat = ptail; /* Match pattern components until there are none left */ while (pat<endpat) { p = pat; s = str; for (;;) { c = pat_next(p, endpat-p, &pinc, flags); p += pinc; /* Encountering * completes/commits a component */ if (c == STAR) { pat = p; str = s; break; } k = str_next(s, endstr-s, &sinc); if (!k) return FNM_NOMATCH; kfold = flags & FNM_CASEFOLD ? casefold(k) : k; if (c == BRACKET) { if (!match_bracket(p-pinc, k, kfold)) break; } else if (c != QUESTION && k != c && kfold != c) { break; } s += sinc; } if (c == STAR) continue; /* If we failed, advance str, by 1 char if it's a valid * char, or past all invalid bytes otherwise. */ k = str_next(str, endstr-str, &sinc); if (k > 0) str += sinc; else for (str++; str_next(str, endstr-str, &sinc)<0; str++); } return 0; } int fnmatch(const char *pat, const char *str, int flags) { const char *s, *p; size_t inc; int c; if (flags & FNM_PATHNAME) for (;;) { for (s=str; *s && *s!='/'; s++); for (p=pat; (c=pat_next(p, -1, &inc, flags))!=END && c!='/'; p+=inc); if (c!=*s && (!*s || !(flags & FNM_LEADING_DIR))) return FNM_NOMATCH; if (fnmatch_internal(pat, p-pat, str, s-str, flags)) return FNM_NOMATCH; if (!c) return 0; str = s+1; pat = p+inc; } else if (flags & FNM_LEADING_DIR) { for (s=str; *s; s++) { if (*s != '/') continue; if (!fnmatch_internal(pat, -1, str, s-str, flags)) return 0; } } return fnmatch_internal(pat, -1, str, -1, flags); }
461087.c
// This file implements the C preprocessor. // // The preprocessor takes a list of tokens as an input and returns a // new list of tokens as an output. // // The preprocessing language is designed in such a way that that's // guaranteed to stop even if there is a recursive macro. // Informally speaking, a macro is applied only once for each token. // That is, if a macro token T appears in a result of direct or // indirect macro expansion of T, T won't be expanded any further. // For example, if T is defined as U, and U is defined as T, then // token T is expanded to U and then to T and the macro expansion // stops at that point. // // To achieve the above behavior, we attach for each token a set of // macro names from which the token is expanded. The set is called // "hideset". Hideset is initially empty, and every time we expand a // macro, the macro name is added to the resulting tokens' hidesets. // // The above macro expansion algorithm is explained in this document // written by Dave Prossor, which is used as a basis for the // standard's wording: // https://github.com/rui314/chibicc/wiki/cpp.algo.pdf #include "chibicc.h" typedef struct MacroParam MacroParam; struct MacroParam { MacroParam *next; char *name; }; typedef struct MacroArg MacroArg; struct MacroArg { MacroArg *next; char *name; bool is_va_args; Token *tok; }; typedef Token *macro_handler_fn(Token *); typedef struct Macro Macro; struct Macro { char *name; bool is_objlike; // Object-like or function-like MacroParam *params; char *va_args_name; Token *body; macro_handler_fn *handler; }; // `#if` can be nested, so we use a stack to manage nested `#if`s. typedef struct CondIncl CondIncl; struct CondIncl { CondIncl *next; enum { IN_THEN, IN_ELIF, IN_ELSE } ctx; Token *tok; bool included; }; typedef struct Hideset Hideset; struct Hideset { Hideset *next; char *name; }; static HashMap macros; static CondIncl *cond_incl; static HashMap pragma_once; static int include_next_idx; static Token *preprocess2(Token *tok); static Macro *find_macro(Token *tok); static bool is_hash(Token *tok) { return tok->at_bol && equal(tok, "#"); } // Some preprocessor directives such as #include allow extraneous // tokens before newline. This function skips such tokens. static Token *skip_line(Token *tok) { if (tok->at_bol) return tok; warn_tok(tok, "extra token"); while (tok->at_bol) tok = tok->next; return tok; } static Token *copy_token(Token *tok) { Token *t = calloc(1, sizeof(Token)); *t = *tok; t->next = NULL; return t; } static Token *new_eof(Token *tok) { Token *t = copy_token(tok); t->kind = TK_EOF; t->len = 0; return t; } static Hideset *new_hideset(char *name) { Hideset *hs = calloc(1, sizeof(Hideset)); hs->name = name; return hs; } static Hideset *hideset_union(Hideset *hs1, Hideset *hs2) { Hideset head = {}; Hideset *cur = &head; for (; hs1; hs1 = hs1->next) cur = cur->next = new_hideset(hs1->name); cur->next = hs2; return head.next; } static bool hideset_contains(Hideset *hs, char *s, int len) { for (; hs; hs = hs->next) if (strlen(hs->name) == len && !strncmp(hs->name, s, len)) return true; return false; } static Hideset *hideset_intersection(Hideset *hs1, Hideset *hs2) { Hideset head = {}; Hideset *cur = &head; for (; hs1; hs1 = hs1->next) if (hideset_contains(hs2, hs1->name, strlen(hs1->name))) cur = cur->next = new_hideset(hs1->name); return head.next; } static Token *add_hideset(Token *tok, Hideset *hs) { Token head = {}; Token *cur = &head; for (; tok; tok = tok->next) { Token *t = copy_token(tok); t->hideset = hideset_union(t->hideset, hs); cur = cur->next = t; } return head.next; } // Append tok2 to the end of tok1. static Token *append(Token *tok1, Token *tok2) { if (tok1->kind == TK_EOF) return tok2; Token head = {}; Token *cur = &head; for (; tok1->kind != TK_EOF; tok1 = tok1->next) cur = cur->next = copy_token(tok1); cur->next = tok2; return head.next; } static Token *skip_cond_incl2(Token *tok) { while (tok->kind != TK_EOF) { if (is_hash(tok) && (equal(tok->next, "if") || equal(tok->next, "ifdef") || equal(tok->next, "ifndef"))) { tok = skip_cond_incl2(tok->next->next); continue; } if (is_hash(tok) && equal(tok->next, "endif")) return tok->next->next; tok = tok->next; } return tok; } // Skip until next `#else`, `#elif` or `#endif`. // Nested `#if` and `#endif` are skipped. static Token *skip_cond_incl(Token *tok) { while (tok->kind != TK_EOF) { if (is_hash(tok) && (equal(tok->next, "if") || equal(tok->next, "ifdef") || equal(tok->next, "ifndef"))) { tok = skip_cond_incl2(tok->next->next); continue; } if (is_hash(tok) && (equal(tok->next, "elif") || equal(tok->next, "else") || equal(tok->next, "endif"))) break; tok = tok->next; } return tok; } // Double-quote a given string and returns it. static char *quote_string(char *str) { int bufsize = 3; for (int i = 0; str[i]; i++) { if (str[i] == '\\' || str[i] == '"') bufsize++; bufsize++; } char *buf = calloc(1, bufsize); char *p = buf; *p++ = '"'; for (int i = 0; str[i]; i++) { if (str[i] == '\\' || str[i] == '"') *p++ = '\\'; *p++ = str[i]; } *p++ = '"'; *p++ = '\0'; return buf; } static Token *new_str_token(char *str, Token *tmpl) { char *buf = quote_string(str); return tokenize(new_file(tmpl->file->name, tmpl->file->file_no, buf)); } // Copy all tokens until the next newline, terminate them with // an EOF token and then returns them. This function is used to // create a new list of tokens for `#if` arguments. static Token *copy_line(Token **rest, Token *tok) { Token head = {}; Token *cur = &head; for (; !tok->at_bol; tok = tok->next) cur = cur->next = copy_token(tok); cur->next = new_eof(tok); *rest = tok; return head.next; } static Token *new_num_token(int val, Token *tmpl) { char *buf = format("%d\n", val); return tokenize(new_file(tmpl->file->name, tmpl->file->file_no, buf)); } static Token *read_const_expr(Token **rest, Token *tok) { tok = copy_line(rest, tok); Token head = {}; Token *cur = &head; while (tok->kind != TK_EOF) { // "defined(foo)" or "defined foo" becomes "1" if macro "foo" // is defined. Otherwise "0". if (equal(tok, "defined")) { Token *start = tok; bool has_paren = consume(&tok, tok->next, "("); if (tok->kind != TK_IDENT) error_tok(start, "macro name must be an identifier"); Macro *m = find_macro(tok); tok = tok->next; if (has_paren) tok = skip(tok, ")"); cur = cur->next = new_num_token(m ? 1 : 0, start); continue; } cur = cur->next = tok; tok = tok->next; } cur->next = tok; return head.next; } // Read and evaluate a constant expression. static long eval_const_expr(Token **rest, Token *tok) { Token *start = tok; Token *expr = read_const_expr(rest, tok->next); expr = preprocess2(expr); if (expr->kind == TK_EOF) error_tok(start, "no expression"); // [https://www.sigbus.info/n1570#6.10.1p4] The standard requires // we replace remaining non-macro identifiers with "0" before // evaluating a constant expression. For example, `#if foo` is // equivalent to `#if 0` if foo is not defined. for (Token *t = expr; t->kind != TK_EOF; t = t->next) { if (t->kind == TK_IDENT) { Token *next = t->next; *t = *new_num_token(0, t); t->next = next; } } // Convert pp-numbers to regular numbers convert_pp_tokens(expr); Token *rest2; long val = const_expr(&rest2, expr); if (rest2->kind != TK_EOF) error_tok(rest2, "extra token"); return val; } static CondIncl *push_cond_incl(Token *tok, bool included) { CondIncl *ci = calloc(1, sizeof(CondIncl)); ci->next = cond_incl; ci->ctx = IN_THEN; ci->tok = tok; ci->included = included; cond_incl = ci; return ci; } static Macro *find_macro(Token *tok) { if (tok->kind != TK_IDENT) return NULL; return hashmap_get2(&macros, tok->loc, tok->len); } static Macro *add_macro(char *name, bool is_objlike, Token *body) { Macro *m = calloc(1, sizeof(Macro)); m->name = name; m->is_objlike = is_objlike; m->body = body; hashmap_put(&macros, name, m); return m; } static MacroParam *read_macro_params(Token **rest, Token *tok, char **va_args_name) { MacroParam head = {}; MacroParam *cur = &head; while (!equal(tok, ")")) { if (cur != &head) tok = skip(tok, ","); if (equal(tok, "...")) { *va_args_name = "__VA_ARGS__"; *rest = skip(tok->next, ")"); return head.next; } if (tok->kind != TK_IDENT) error_tok(tok, "expected an identifier"); if (equal(tok->next, "...")) { *va_args_name = strndup(tok->loc, tok->len); *rest = skip(tok->next->next, ")"); return head.next; } MacroParam *m = calloc(1, sizeof(MacroParam)); m->name = strndup(tok->loc, tok->len); cur = cur->next = m; tok = tok->next; } *rest = tok->next; return head.next; } static void read_macro_definition(Token **rest, Token *tok) { if (tok->kind != TK_IDENT) error_tok(tok, "macro name must be an identifier"); char *name = strndup(tok->loc, tok->len); tok = tok->next; if (!tok->has_space && equal(tok, "(")) { // Function-like macro char *va_args_name = NULL; MacroParam *params = read_macro_params(&tok, tok->next, &va_args_name); Macro *m = add_macro(name, false, copy_line(rest, tok)); m->params = params; m->va_args_name = va_args_name; } else { // Object-like macro add_macro(name, true, copy_line(rest, tok)); } } static MacroArg *read_macro_arg_one(Token **rest, Token *tok, bool read_rest) { Token head = {}; Token *cur = &head; int level = 0; for (;;) { if (level == 0 && equal(tok, ")")) break; if (level == 0 && !read_rest && equal(tok, ",")) break; if (tok->kind == TK_EOF) error_tok(tok, "premature end of input"); if (equal(tok, "(")) level++; else if (equal(tok, ")")) level--; cur = cur->next = copy_token(tok); tok = tok->next; } cur->next = new_eof(tok); MacroArg *arg = calloc(1, sizeof(MacroArg)); arg->tok = head.next; *rest = tok; return arg; } static MacroArg * read_macro_args(Token **rest, Token *tok, MacroParam *params, char *va_args_name) { Token *start = tok; tok = tok->next->next; MacroArg head = {}; MacroArg *cur = &head; MacroParam *pp = params; for (; pp; pp = pp->next) { if (cur != &head) tok = skip(tok, ","); cur = cur->next = read_macro_arg_one(&tok, tok, false); cur->name = pp->name; } if (va_args_name) { MacroArg *arg; if (equal(tok, ")")) { arg = calloc(1, sizeof(MacroArg)); arg->tok = new_eof(tok); } else { if (pp != params) tok = skip(tok, ","); arg = read_macro_arg_one(&tok, tok, true); } arg->name = va_args_name;; arg->is_va_args = true; cur = cur->next = arg; } else if (pp) { error_tok(start, "too many arguments"); } skip(tok, ")"); *rest = tok; return head.next; } static MacroArg *find_arg(MacroArg *args, Token *tok) { for (MacroArg *ap = args; ap; ap = ap->next) if (tok->len == strlen(ap->name) && !strncmp(tok->loc, ap->name, tok->len)) return ap; return NULL; } // Concatenates all tokens in `tok` and returns a new string. static char *join_tokens(Token *tok, Token *end) { // Compute the length of the resulting token. int len = 1; for (Token *t = tok; t != end && t->kind != TK_EOF; t = t->next) { if (t != tok && t->has_space) len++; len += t->len; } char *buf = calloc(1, len); // Copy token texts. int pos = 0; for (Token *t = tok; t != end && t->kind != TK_EOF; t = t->next) { if (t != tok && t->has_space) buf[pos++] = ' '; strncpy(buf + pos, t->loc, t->len); pos += t->len; } buf[pos] = '\0'; return buf; } // Concatenates all tokens in `arg` and returns a new string token. // This function is used for the stringizing operator (#). static Token *stringize(Token *hash, Token *arg) { // Create a new string token. We need to set some value to its // source location for error reporting function, so we use a macro // name token as a template. char *s = join_tokens(arg, NULL); return new_str_token(s, hash); } // Concatenate two tokens to create a new token. static Token *paste(Token *lhs, Token *rhs) { // Paste the two tokens. char *buf = format("%.*s%.*s", lhs->len, lhs->loc, rhs->len, rhs->loc); // Tokenize the resulting string. Token *tok = tokenize(new_file(lhs->file->name, lhs->file->file_no, buf)); if (tok->next->kind != TK_EOF) error_tok(lhs, "pasting forms '%s', an invalid token", buf); return tok; } static bool has_varargs(MacroArg *args) { for (MacroArg *ap = args; ap; ap = ap->next) if (!strcmp(ap->name, "__VA_ARGS__")) return ap->tok->kind != TK_EOF; return false; } // Replace func-like macro parameters with given arguments. static Token *subst(Token *tok, MacroArg *args) { Token head = {}; Token *cur = &head; while (tok->kind != TK_EOF) { // "#" followed by a parameter is replaced with stringized actuals. if (equal(tok, "#")) { MacroArg *arg = find_arg(args, tok->next); if (!arg) error_tok(tok->next, "'#' is not followed by a macro parameter"); cur = cur->next = stringize(tok, arg->tok); tok = tok->next->next; continue; } // [GNU] If __VA_ARG__ is empty, `,##__VA_ARGS__` is expanded // to the empty token list. Otherwise, its expaned to `,` and // __VA_ARGS__. if (equal(tok, ",") && equal(tok->next, "##")) { MacroArg *arg = find_arg(args, tok->next->next); if (arg && arg->is_va_args) { if (arg->tok->kind == TK_EOF) { tok = tok->next->next->next; } else { cur = cur->next = copy_token(tok); tok = tok->next->next; } continue; } } if (equal(tok, "##")) { if (cur == &head) error_tok(tok, "'##' cannot appear at start of macro expansion"); if (tok->next->kind == TK_EOF) error_tok(tok, "'##' cannot appear at end of macro expansion"); MacroArg *arg = find_arg(args, tok->next); if (arg) { if (arg->tok->kind != TK_EOF) { *cur = *paste(cur, arg->tok); for (Token *t = arg->tok->next; t->kind != TK_EOF; t = t->next) cur = cur->next = copy_token(t); } tok = tok->next->next; continue; } *cur = *paste(cur, tok->next); tok = tok->next->next; continue; } MacroArg *arg = find_arg(args, tok); if (arg && equal(tok->next, "##")) { Token *rhs = tok->next->next; if (arg->tok->kind == TK_EOF) { MacroArg *arg2 = find_arg(args, rhs); if (arg2) { for (Token *t = arg2->tok; t->kind != TK_EOF; t = t->next) cur = cur->next = copy_token(t); } else { cur = cur->next = copy_token(rhs); } tok = rhs->next; continue; } for (Token *t = arg->tok; t->kind != TK_EOF; t = t->next) cur = cur->next = copy_token(t); tok = tok->next; continue; } // If __VA_ARG__ is empty, __VA_OPT__(x) is expanded to the // empty token list. Otherwise, __VA_OPT__(x) is expanded to x. if (equal(tok, "__VA_OPT__") && equal(tok->next, "(")) { MacroArg *arg = read_macro_arg_one(&tok, tok->next->next, true); if (has_varargs(args)) for (Token *t = arg->tok; t->kind != TK_EOF; t = t->next) cur = cur->next = t; tok = skip(tok, ")"); continue; } // Handle a macro token. Macro arguments are completely macro-expanded // before they are substituted into a macro body. if (arg) { Token *t = preprocess2(arg->tok); t->at_bol = tok->at_bol; t->has_space = tok->has_space; for (; t->kind != TK_EOF; t = t->next) cur = cur->next = copy_token(t); tok = tok->next; continue; } // Handle a non-macro token. cur = cur->next = copy_token(tok); tok = tok->next; continue; } cur->next = tok; return head.next; } // If tok is a macro, expand it and return true. // Otherwise, do nothing and return false. static bool expand_macro(Token **rest, Token *tok) { if (hideset_contains(tok->hideset, tok->loc, tok->len)) return false; Macro *m = find_macro(tok); if (!m) return false; // Built-in dynamic macro application such as __LINE__ if (m->handler) { *rest = m->handler(tok); (*rest)->next = tok->next; return true; } // Object-like macro application if (m->is_objlike) { Hideset *hs = hideset_union(tok->hideset, new_hideset(m->name)); Token *body = add_hideset(m->body, hs); for (Token *t = body; t->kind != TK_EOF; t = t->next) t->origin = tok; *rest = append(body, tok->next); (*rest)->at_bol = tok->at_bol; (*rest)->has_space = tok->has_space; return true; } // If a funclike macro token is not followed by an argument list, // treat it as a normal identifier. if (!equal(tok->next, "(")) return false; // Function-like macro application Token *macro_token = tok; MacroArg *args = read_macro_args(&tok, tok, m->params, m->va_args_name); Token *rparen = tok; // Tokens that consist a func-like macro invocation may have different // hidesets, and if that's the case, it's not clear what the hideset // for the new tokens should be. We take the interesection of the // macro token and the closing parenthesis and use it as a new hideset // as explained in the Dave Prossor's algorithm. Hideset *hs = hideset_intersection(macro_token->hideset, rparen->hideset); hs = hideset_union(hs, new_hideset(m->name)); Token *body = subst(m->body, args); body = add_hideset(body, hs); for (Token *t = body; t->kind != TK_EOF; t = t->next) t->origin = macro_token; *rest = append(body, tok->next); (*rest)->at_bol = macro_token->at_bol; (*rest)->has_space = macro_token->has_space; return true; } char *search_include_paths(char *filename) { if (filename[0] == '/') return filename; static HashMap cache; char *cached = hashmap_get(&cache, filename); if (cached) return cached; // Search a file from the include paths. for (int i = 0; i < include_paths.len; i++) { char *path = format("%s/%s", include_paths.data[i], filename); if (!file_exists(path)) continue; hashmap_put(&cache, filename, path); include_next_idx = i + 1; return path; } return NULL; } static char *search_include_next(char *filename) { for (; include_next_idx < include_paths.len; include_next_idx++) { char *path = format("%s/%s", include_paths.data[include_next_idx], filename); if (file_exists(path)) return path; } return NULL; } // Read an #include argument. static char *read_include_filename(Token **rest, Token *tok, bool *is_dquote) { // Pattern 1: #include "foo.h" if (tok->kind == TK_STR) { // A double-quoted filename for #include is a special kind of // token, and we don't want to interpret any escape sequences in it. // For example, "\f" in "C:\foo" is not a formfeed character but // just two non-control characters, backslash and f. // So we don't want to use token->str. *is_dquote = true; *rest = skip_line(tok->next); return strndup(tok->loc + 1, tok->len - 2); } // Pattern 2: #include <foo.h> if (equal(tok, "<")) { // Reconstruct a filename from a sequence of tokens between // "<" and ">". Token *start = tok; // Find closing ">". for (; !equal(tok, ">"); tok = tok->next) if (tok->at_bol || tok->kind == TK_EOF) error_tok(tok, "expected '>'"); *is_dquote = false; *rest = skip_line(tok->next); return join_tokens(start->next, tok); } // Pattern 3: #include FOO // In this case FOO must be macro-expanded to either // a single string token or a sequence of "<" ... ">". if (tok->kind == TK_IDENT) { Token *tok2 = preprocess2(copy_line(rest, tok)); return read_include_filename(&tok2, tok2, is_dquote); } error_tok(tok, "expected a filename"); } // Detect the following "include guard" pattern. // // #ifndef FOO_H // #define FOO_H // ... // #endif static char *detect_include_guard(Token *tok) { // Detect the first two lines. if (!is_hash(tok) || !equal(tok->next, "ifndef")) return NULL; tok = tok->next->next; if (tok->kind != TK_IDENT) return NULL; char *macro = strndup(tok->loc, tok->len); tok = tok->next; if (!is_hash(tok) || !equal(tok->next, "define") || !equal(tok->next->next, macro)) return NULL; // Read until the end of the file. while (tok->kind != TK_EOF) { if (!is_hash(tok)) { tok = tok->next; continue; } if (equal(tok->next, "endif") && tok->next->next->kind == TK_EOF) return macro; if (equal(tok, "if") || equal(tok, "ifdef") || equal(tok, "ifndef")) tok = skip_cond_incl(tok->next); else tok = tok->next; } return NULL; } static Token *include_file(Token *tok, char *path, Token *filename_tok) { // Check for "#pragma once" if (hashmap_get(&pragma_once, path)) return tok; // If we read the same file before, and if the file was guarded // by the usual #ifndef ... #endif pattern, we may be able to // skip the file without opening it. static HashMap include_guards; char *guard_name = hashmap_get(&include_guards, path); if (guard_name && hashmap_get(&macros, guard_name)) return tok; Token *tok2 = tokenize_file(path); if (!tok2) error_tok(filename_tok, "%s: cannot open file: %s", path, strerror(errno)); guard_name = detect_include_guard(tok2); if (guard_name) hashmap_put(&include_guards, path, guard_name); return append(tok2, tok); } // Read #line arguments static void read_line_marker(Token **rest, Token *tok) { Token *start = tok; tok = preprocess(copy_line(rest, tok)); if (tok->kind != TK_NUM || tok->ty->kind != TY_INT) error_tok(tok, "invalid line marker"); start->file->line_delta = tok->val - start->line_no; tok = tok->next; if (tok->kind == TK_EOF) return; if (tok->kind != TK_STR) error_tok(tok, "filename expected"); start->file->display_name = tok->str; } // Visit all tokens in `tok` while evaluating preprocessing // macros and directives. static Token *preprocess2(Token *tok) { Token head = {}; Token *cur = &head; while (tok->kind != TK_EOF) { // If it is a macro, expand it. if (expand_macro(&tok, tok)) continue; // Pass through if it is not a "#". if (!is_hash(tok)) { tok->line_delta = tok->file->line_delta; tok->filename = tok->file->display_name; cur = cur->next = tok; tok = tok->next; continue; } Token *start = tok; tok = tok->next; if (equal(tok, "include")) { bool is_dquote; char *filename = read_include_filename(&tok, tok->next, &is_dquote); if (filename[0] != '/' && is_dquote) { char *path = format("%s/%s", dirname(strdup(start->file->name)), filename); if (file_exists(path)) { tok = include_file(tok, path, start->next->next); continue; } } char *path = search_include_paths(filename); tok = include_file(tok, path ? path : filename, start->next->next); continue; } if (equal(tok, "include_next")) { bool ignore; char *filename = read_include_filename(&tok, tok->next, &ignore); char *path = search_include_next(filename); tok = include_file(tok, path ? path : filename, start->next->next); continue; } if (equal(tok, "define")) { read_macro_definition(&tok, tok->next); continue; } if (equal(tok, "undef")) { tok = tok->next; if (tok->kind != TK_IDENT) error_tok(tok, "macro name must be an identifier"); undef_macro(strndup(tok->loc, tok->len)); tok = skip_line(tok->next); continue; } if (equal(tok, "if")) { long val = eval_const_expr(&tok, tok); push_cond_incl(start, val); if (!val) tok = skip_cond_incl(tok); continue; } if (equal(tok, "ifdef")) { bool defined = find_macro(tok->next); push_cond_incl(tok, defined); tok = skip_line(tok->next->next); if (!defined) tok = skip_cond_incl(tok); continue; } if (equal(tok, "ifndef")) { bool defined = find_macro(tok->next); push_cond_incl(tok, !defined); tok = skip_line(tok->next->next); if (defined) tok = skip_cond_incl(tok); continue; } if (equal(tok, "elif")) { if (!cond_incl || cond_incl->ctx == IN_ELSE) error_tok(start, "stray #elif"); cond_incl->ctx = IN_ELIF; if (!cond_incl->included && eval_const_expr(&tok, tok)) cond_incl->included = true; else tok = skip_cond_incl(tok); continue; } if (equal(tok, "else")) { if (!cond_incl || cond_incl->ctx == IN_ELSE) error_tok(start, "stray #else"); cond_incl->ctx = IN_ELSE; tok = skip_line(tok->next); if (cond_incl->included) tok = skip_cond_incl(tok); continue; } if (equal(tok, "endif")) { if (!cond_incl) error_tok(start, "stray #endif"); cond_incl = cond_incl->next; tok = skip_line(tok->next); continue; } if (equal(tok, "line")) { read_line_marker(&tok, tok->next); continue; } if (tok->kind == TK_PP_NUM) { read_line_marker(&tok, tok); continue; } if (equal(tok, "pragma") && equal(tok->next, "once")) { hashmap_put(&pragma_once, tok->file->name, (void *)1); tok = skip_line(tok->next->next); continue; } if (equal(tok, "pragma")) { do { tok = tok->next; } while (!tok->at_bol); continue; } if (equal(tok, "error")) error_tok(tok, "error"); // `#`-only line is legal. It's called a null directive. if (tok->at_bol) continue; error_tok(tok, "invalid preprocessor directive"); } cur->next = tok; return head.next; } void define_macro(char *name, char *buf) { Token *tok = tokenize(new_file("<built-in>", 1, buf)); add_macro(name, true, tok); } void undef_macro(char *name) { hashmap_delete(&macros, name); } static Macro *add_builtin(char *name, macro_handler_fn *fn) { Macro *m = add_macro(name, true, NULL); m->handler = fn; return m; } static Token *file_macro(Token *tmpl) { while (tmpl->origin) tmpl = tmpl->origin; return new_str_token(tmpl->file->display_name, tmpl); } static Token *line_macro(Token *tmpl) { while (tmpl->origin) tmpl = tmpl->origin; int i = tmpl->line_no + tmpl->file->line_delta; return new_num_token(i, tmpl); } // __COUNTER__ is expanded to serial values starting from 0. static Token *counter_macro(Token *tmpl) { static int i = 0; return new_num_token(i++, tmpl); } // __TIMESTAMP__ is expanded to a string describing the last // modification time of the current file. E.g. // "Fri Jul 24 01:32:50 2020" static Token *timestamp_macro(Token *tmpl) { struct stat st; if (stat(tmpl->file->name, &st) != 0) return new_str_token("??? ??? ?? ??:??:?? ????", tmpl); char buf[30]; ctime_r(&st.st_mtime, buf); buf[24] = '\0'; return new_str_token(buf, tmpl); } static Token *base_file_macro(Token *tmpl) { return new_str_token(base_file, tmpl); } // __DATE__ is expanded to the current date, e.g. "May 17 2020". static char *format_date(struct tm *tm) { static char mon[][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; return format("\"%s %2d %d\"", mon[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900); } // __TIME__ is expanded to the current time, e.g. "13:34:03". static char *format_time(struct tm *tm) { return format("\"%02d:%02d:%02d\"", tm->tm_hour, tm->tm_min, tm->tm_sec); } void init_macros(void) { // Define predefined macros define_macro("_LP64", "1"); define_macro("__C99_MACRO_WITH_VA_ARGS", "1"); define_macro("__ELF__", "1"); define_macro("__LP64__", "1"); define_macro("__SIZEOF_DOUBLE__", "8"); define_macro("__SIZEOF_FLOAT__", "4"); define_macro("__SIZEOF_INT__", "4"); define_macro("__SIZEOF_LONG_DOUBLE__", "8"); define_macro("__SIZEOF_LONG_LONG__", "8"); define_macro("__SIZEOF_LONG__", "8"); define_macro("__SIZEOF_POINTER__", "4"); define_macro("__SIZEOF_PTRDIFF_T__", "8"); define_macro("__SIZEOF_SHORT__", "2"); define_macro("__SIZEOF_SIZE_T__", "8"); define_macro("__SIZE_TYPE__", "unsigned long"); define_macro("__STDC_HOSTED__", "1"); define_macro("__STDC_NO_COMPLEX__", "1"); define_macro("__STDC_UTF_16__", "1"); define_macro("__STDC_UTF_32__", "1"); define_macro("__STDC_VERSION__", "201112L"); define_macro("__STDC__", "1"); define_macro("__USER_LABEL_PREFIX__", ""); define_macro("__alignof__", "_Alignof"); define_macro("__amd64", "1"); define_macro("__amd64__", "1"); define_macro("__chibicc__", "1"); define_macro("__const__", "const"); define_macro("__gnu_linux__", "1"); define_macro("__inline__", "inline"); define_macro("__linux", "1"); define_macro("__linux__", "1"); define_macro("__signed__", "signed"); define_macro("__typeof__", "typeof"); define_macro("__unix", "1"); define_macro("__unix__", "1"); define_macro("__volatile__", "volatile"); define_macro("__x86_64", "1"); define_macro("__x86_64__", "1"); define_macro("linux", "1"); define_macro("unix", "1"); add_builtin("__FILE__", file_macro); add_builtin("__LINE__", line_macro); add_builtin("__COUNTER__", counter_macro); add_builtin("__TIMESTAMP__", timestamp_macro); add_builtin("__BASE_FILE__", base_file_macro); time_t now = time(NULL); struct tm *tm = localtime(&now); define_macro("__DATE__", format_date(tm)); define_macro("__TIME__", format_time(tm)); } typedef enum { STR_NONE, STR_UTF8, STR_UTF16, STR_UTF32, STR_WIDE, } StringKind; static StringKind getStringKind(Token *tok) { if (!strcmp(tok->loc, "u8")) return STR_UTF8; switch (tok->loc[0]) { case '"': return STR_NONE; case 'u': return STR_UTF16; case 'U': return STR_UTF32; case 'L': return STR_WIDE; } unreachable(); } // Concatenate adjacent string literals into a single string literal // as per the C spec. static void join_adjacent_string_literals(Token *tok) { // First pass: If regular string literals are adjacent to wide // string literals, regular string literals are converted to a wide // type before concatenation. In this pass, we do the conversion. for (Token *tok1 = tok; tok1->kind != TK_EOF;) { if (tok1->kind != TK_STR || tok1->next->kind != TK_STR) { tok1 = tok1->next; continue; } StringKind kind = getStringKind(tok1); Type *basety = tok1->ty->base; for (Token *t = tok1->next; t->kind == TK_STR; t = t->next) { StringKind k = getStringKind(t); if (kind == STR_NONE) { kind = k; basety = t->ty->base; } else if (k != STR_NONE && kind != k) { error_tok(t, "unsupported non-standard concatenation of string literals"); } } if (basety->size > 1) for (Token *t = tok1; t->kind == TK_STR; t = t->next) if (t->ty->base->size == 1) *t = *tokenize_string_literal(t, basety); while (tok1->kind == TK_STR) tok1 = tok1->next; } // Second pass: concatenate adjacent string literals. for (Token *tok1 = tok; tok1->kind != TK_EOF;) { if (tok1->kind != TK_STR || tok1->next->kind != TK_STR) { tok1 = tok1->next; continue; } Token *tok2 = tok1->next; while (tok2->kind == TK_STR) tok2 = tok2->next; int len = tok1->ty->array_len; for (Token *t = tok1->next; t != tok2; t = t->next) len = len + t->ty->array_len - 1; char *buf = calloc(tok1->ty->base->size, len); int i = 0; for (Token *t = tok1; t != tok2; t = t->next) { memcpy(buf + i, t->str, t->ty->size); i = i + t->ty->size - t->ty->base->size; } *tok1 = *copy_token(tok1); tok1->ty = array_of(tok1->ty->base, len); tok1->str = buf; tok1->next = tok2; tok1 = tok2; } } // Entry point function of the preprocessor. Token *preprocess(Token *tok) { tok = preprocess2(tok); if (cond_incl) error_tok(cond_incl->tok, "unterminated conditional directive"); convert_pp_tokens(tok); join_adjacent_string_literals(tok); for (Token *t = tok; t; t = t->next) t->line_no += t->line_delta; return tok; }
606593.c
#include "cs_mex.h" /* cs_randperm: random permutation. p=cs_randperm(n,0) is 1:n, * p=cs_randperm(n,-1) is n:-1:1. p = cs_randperm (n,seed) is a random * permutation using the given seed (where seed is not 0 or -1). * seed defaults to 1. A single seed always gives a repeatable permutation. * Use p = cs_randperm(n,rand) to get a permutation that varies with each use. */ void mexFunction ( int nargout, mxArray *pargout [ ], int nargin, const mxArray *pargin [ ] ) { double seed ; int iseed, n, *p ; if (nargout > 1 || nargin < 1 || nargin > 2) { mexErrMsgTxt ("Usage: p = cs_randperm(n,seed)") ; } seed = (nargin > 1) ? mxGetScalar (pargin [1]) : 1 ; iseed = (seed > 0 && seed < 1) ? (seed * RAND_MAX) : seed ; n = mxGetScalar (pargin [0]) ; n = CS_MAX (n, 0) ; p = cs_randperm (n, iseed) ; pargout [0] = cs_mex_put_int (p, n, 1, 1) ; /* return p */ }
109298.c
/* -== XE-Loader ==- * * Load [.exe .elf / .dll .so] from memory and remap functions * Run your binaries on any x86 hardware * * @autors * - Maeiky * * Copyright (c) 2021 - V·Liance * * The contents of this file are subject to the Apache License Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * If a copy of the Apache License Version 2.0 was not distributed with this file, * You can obtain one at https://www.apache.org/licenses/LICENSE-2.0.html * */ #include "XE.h" #include "XE/Module/PE/PE_Loader.h" #include "XE/Module/ELF/ELF_Loader.h" void GDB_Send_AddSymbolFile(const char* _path, void* _text_adress); #include <unistd.h> #include <stdio.h> #include <errno.h> #include "Xternal/xFile.inc" //Can be overrided //#include "Xternal/xDebug.inc" //Can be overrided extern FILE* stdout_; extern FILE* stderr_; int xe_arg_nb = 0; char* xe_arg = "\0\0"; XE_aModule aModule = {}; typedef int (*main_func)(); typedef int (*mainArg_func)(int argc, char* argv[]); typedef int (CallType_Std *winMain_func)(void* hInstance, void* hPrevInstance, void* pCmdLine, int nCmdShow); int Xe_ExecuteMain(XE_Module* _module) { #define _set(call) _module->exe_ret = call if(!_module)return 0; #ifndef VirtualLoadPE if(!_module->have_reloc){ err_print("Cannot start executable without .reloc section, when Virtual allocation is not supported"); return 1; } #endif switch (_module->type.val) { _case XE_Type_EXE: { #ifdef SearchFor_CustomMain { _printl("Research 'main_entry()' entry point... "); main_func dMain = (main_func)MemGetProcAddress(_module->handle, "main_entry"); _printl("--=== Execute EXE main_entry ===---"); if(dMain){return _set( dMain() );} } { _printl("Research 'main()' entry point... "); mainArg_func dMain = (mainArg_func)MemGetProcAddress(_module->handle, "main"); _printl("--=== Execute EXE main ===---"); if(dMain){return _set( dMain(xe_arg_nb, &xe_arg) );} } { _printl("Research 'WinMain@16()' entry point... "); winMain_func dMain = (winMain_func)MemGetProcAddress(_module->handle, "WinMain@16"); wchar_t* winMainArg = (wchar_t* )L"Test WinMain ARG"; _printl("--=== Execute EXE WinMain ===---"); if(dMain){return _set( dMain(0, 0, winMainArg, 0) );} } #endif //No export? try calling gentry point _printl("Call entry point... "); _printl("--=== Execute EXE ===---"); return _set( MemCallEntryPoint(_module->handle) ); } _case XE_Type_DLL: { MEMORYMODULE* memm = (MEMORYMODULE*)_module->handle; //_printl("EXECUTION DllMain..... %p", memm->dllEntry); _printl("--=== Execute DllMain (TODO) ===---"); //!BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpReserved ) void* _lpReserved = 0; return _set(! memm->dllEntry((HINSTANCE)memm, DLL_PROCESS_ATTACH, _lpReserved) ); } _case XE_Type_ELF: { //_printl("--=== Execute ELF ===---"); //try calling gentry point return _set(CallEntryPoint_ELF(_module->handle) ); } } #undef _set } export XE_Module* Xe_Load(const char* _sPath) { setbuf(stdout, NULL);//Required to see every printf setbuf(stderr, NULL);//Required to see every printf stdout_ = (FILE*)stdout; stderr_ = (FILE*)stderr; dbg_printl(" -stdout_ [%p]", stdout_); dbg_printl(" -stderr_ [%p]", stderr_); dbg_printl(" -- Xe_Load -- [%s]", _sPath); if(strlen(_sPath) <= 0){ err_printl("No Input files"); return false; } for(int i = 0; i < aModule.size; i++){ XE_Module _module = aModule.data[i]; if(_module.name != NULL){ if(strcmp(_module.name, _sPath) == 0){ err_printl("File [%s] already loaded", _sPath); return false; } } } File _file = Xe_LoadFile(_sPath); if(!_file.data) return false; //==-- New Module --==// XE_Module* _module = aModule(add, (XE_Module){.file=_file}); //==-- PE : if(*((uint16_t*)_file.data) == 0x5A4D ){ dbg_printl("EXE FILE!!"); _module->type=XE_Type_(EXE); //Or .dll? Load_Module_PE(_module); } else //==-- ELF : if(*((uint32_t*)_file.data) == 0x464C457f ){ //'0x7f'ELF dbg_printl("ELF FILE!!"); _module->type=XE_Type_(ELF); //Or .so? Load_Module_ELF(_module); } else{ //==-- UNKNOW : dbg_printl("UNKNOW FILE!!"); return false; } if(_module->section_text != 0){ GDB_Send_AddSymbolFile(_sPath, _module->section_text ); } return _module; } funcPtr_bool _dFunc_wglSwapBuffers = 0; funcPtrPtr_int _dFunc_wglChoosePixelFormat = 0; funcPtrIntPtr_bool _dFunc_wglSetPixelFormat = 0; funcPtr_int _dFunc_wglGetPixelFormat = 0; funcPtrIntIntPtr_int _dFunc_wglDescribePixelFormat = 0; void GetLibraryExportTable(MEMORYMODULE* module) { unsigned char *codeBase = ((MEMORYMODULE*)module)->codeBase; DWORD idx = 0; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((MEMORYMODULE*)module, IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found #ifdef USE_Window_LastError SetLastError(ERROR_PROC_NOT_FOUND); #endif return; } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything #ifdef USE_Window_LastError SetLastError(ERROR_PROC_NOT_FOUND); #endif return; } // search function name in list of exported names DWORD i; DWORD *nameRef = (DWORD *) (codeBase + exports->AddressOfNames); WORD *ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); BOOL found = false; for (i=0; i < exports->NumberOfNames; i++, nameRef++, ordinal++) { LPCSTR funcName = (const char *) (codeBase + (*nameRef)); _printl( "/===: %s", funcName); //// Special Function /// if (strcmp("wglChoosePixelFormat", funcName) == 0) { FARPROC _dFunc = (FARPROC)(LPVOID)(codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + ((*ordinal)*4)))); _printl("FOUND Special function:%s",funcName); _dFunc_wglChoosePixelFormat = (funcPtrPtr_int)_dFunc; } if (strcmp("wglSetPixelFormat", funcName) == 0) { FARPROC _dFunc = (FARPROC)(LPVOID)(codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + ((*ordinal)*4)))); _printl("FOUND Special function:%s",funcName); _dFunc_wglSetPixelFormat = (funcPtrIntPtr_bool)_dFunc; } if (strcmp("wglGetPixelFormat", funcName) == 0) { FARPROC _dFunc = (FARPROC)(LPVOID)(codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + ((*ordinal)*4)))); _printl("FOUND Special function:%s",funcName); _dFunc_wglGetPixelFormat = (funcPtr_int)_dFunc; } if (strcmp("wglDescribePixelFormat", funcName) == 0) { FARPROC _dFunc = (FARPROC)(LPVOID)(codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + ((*ordinal)*4)))); _printl("FOUND Special function:%s",funcName); _dFunc_wglDescribePixelFormat = (funcPtrIntIntPtr_int)_dFunc; } if (strcmp("wglSwapBuffers", funcName) == 0) { FARPROC _dFunc = (FARPROC)(LPVOID)(codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + ((*ordinal)*4)))); _printl("FOUND Special function:%s",funcName); _dFunc_wglSwapBuffers = (funcPtr_bool)_dFunc; } } } XE_Module* Xe_AddLibrary(const char* _sPath) { _printl("///===============================================================================================================///"); _printl("///========= AddLibrary: %s", _sPath); _printl("///===============================================================================================================///"); // Charger le fichier en memoire XE_Module* m = Xe_Load(_sPath); _printl("///===============================================================================================================///"); if(!m || !m->handle){ err_print("///====== ERROR: Unable to load DLL: %s", _sPath); _printl("///===============================================================================================================///"); return 0; } MEMORYMODULE* memm = (MEMORYMODULE*)m->handle; _printl("///====== Loaded: %s", _sPath); _printl("///====== Export function table:"); GetLibraryExportTable(memm); _printl("///===============================================================================================================///"); Xe_ExecuteMain(m); return m; }
932577.c
/* flac - Command-line FLAC encoder/decoder * Copyright (C) 2002-2009 Josh Coalson * Copyright (C) 2011-2014 Xiph.Org Foundation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "vorbiscomment.h" #include "FLAC/assert.h" #include "FLAC/metadata.h" #include "share/grabbag.h" /* for grabbag__file_get_filesize() */ #include "share/utf8.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "share/compat.h" /* * This struct and the following 4 static functions are copied from * ../metaflac/. Maybe someday there will be a convenience * library for Vorbis comment parsing. */ typedef struct { char *field; /* the whole field as passed on the command line, i.e. "NAME=VALUE" */ char *field_name; /* according to the vorbis spec, field values can contain \0 so simple C strings are not enough here */ unsigned field_value_length; char *field_value; FLAC__bool field_value_from_file; /* true if field_value holds a filename for the value, false for plain value */ } Argument_VcField; static void die(const char *message) { FLAC__ASSERT(0 != message); fprintf(stderr, "ERROR: %s\n", message); exit(1); } static char *local_strdup(const char *source) { char *ret; FLAC__ASSERT(0 != source); if(0 == (ret = strdup(source))) die("out of memory during strdup()"); return ret; } static FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length, const char **violation) { static const char * const violations[] = { "field name contains invalid character", "field contains no '=' character" }; char *p, *q, *s; if(0 != field) *field = local_strdup(field_ref); s = local_strdup(field_ref); if(0 == (p = strchr(s, '='))) { free(s); *violation = violations[1]; return false; } *p++ = '\0'; for(q = s; *q; q++) { if(*q < 0x20 || *q > 0x7d || *q == 0x3d) { free(s); *violation = violations[0]; return false; } } *name = local_strdup(s); *value = local_strdup(p); *length = strlen(p); free(s); return true; } /* slight modification: no 'filename' arg, and errors are passed back in 'violation' instead of printed to stderr */ static FLAC__bool set_vc_field(FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write, FLAC__bool raw, const char **violation) { FLAC__StreamMetadata_VorbisComment_Entry entry; char *converted; FLAC__ASSERT(0 != block); FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); FLAC__ASSERT(0 != field); FLAC__ASSERT(0 != needs_write); if(field->field_value_from_file) { /* read the file into 'data' */ FILE *f = 0; char *data = 0; const FLAC__off_t size = grabbag__file_get_filesize(field->field_value); if(size < 0) { *violation = "can't open file for tag value"; return false; } if(size >= 0x100000) { /* magic arbitrary limit, actual format limit is near 16MB */ *violation = "file for tag value is too large"; return false; } if(0 == (data = malloc(size+1))) die("out of memory allocating tag value"); data[size] = '\0'; if(0 == (f = flac_fopen(field->field_value, "rb")) || fread(data, 1, size, f) != (size_t)size) { free(data); if(f) fclose(f); *violation = "error while reading file for tag value"; return false; } fclose(f); if(strlen(data) != (size_t)size) { free(data); *violation = "file for tag value has embedded NULs"; return false; } /* move 'data' into 'converted', converting to UTF-8 if necessary */ if(raw) { converted = data; } else if(utf8_encode(data, &converted) >= 0) { free(data); } else { free(data); *violation = "error converting file contents to UTF-8 for tag value"; return false; } /* create and entry and append it */ if(!FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, field->field_name, converted)) { free(converted); *violation = "file for tag value is not valid UTF-8"; return false; } free(converted); if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/false)) { *violation = "memory allocation failure"; return false; } *needs_write = true; return true; } else { FLAC__bool needs_free = false; #ifdef _WIN32 /* everything in UTF-8 already. Must not alter */ entry.entry = (FLAC__byte *)field->field; #else if(raw) { entry.entry = (FLAC__byte *)field->field; } else if(utf8_encode(field->field, &converted) >= 0) { entry.entry = (FLAC__byte *)converted; needs_free = true; } else { *violation = "error converting comment to UTF-8"; return false; } #endif entry.length = strlen((const char *)entry.entry); if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length)) { if(needs_free) free(converted); /* * our previous parsing has already established that the field * name is OK, so it must be the field value */ *violation = "tag value for is not valid UTF-8"; return false; } if(!FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true)) { if(needs_free) free(converted); *violation = "memory allocation failure"; return false; } *needs_write = true; if(needs_free) free(converted); return true; } } /* * The rest of the code is novel */ static void free_field(Argument_VcField *obj) { if(0 != obj->field) free(obj->field); if(0 != obj->field_name) free(obj->field_name); if(0 != obj->field_value) free(obj->field_value); } FLAC__bool flac__vorbiscomment_add(FLAC__StreamMetadata *block, const char *comment, FLAC__bool value_from_file, FLAC__bool raw, const char **violation) { Argument_VcField parsed; FLAC__bool dummy; FLAC__ASSERT(0 != block); FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT); FLAC__ASSERT(0 != comment); memset(&parsed, 0, sizeof(parsed)); parsed.field_value_from_file = value_from_file; if(!parse_vorbis_comment_field(comment, &(parsed.field), &(parsed.field_name), &(parsed.field_value), &(parsed.field_value_length), violation)) { free_field(&parsed); return false; } if(parsed.field_value_length > 0 && !set_vc_field(block, &parsed, &dummy, raw, violation)) { free_field(&parsed); return false; } else { free_field(&parsed); return true; } }
915231.c
/*- * Copyright (c) 2016 Andriy Voskoboinyk <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include "opt_wlan.h" #include <sys/param.h> #include <sys/lock.h> #include <sys/mutex.h> #include <sys/mbuf.h> #include <sys/kernel.h> #include <sys/socket.h> #include <sys/systm.h> #include <sys/malloc.h> #include <sys/queue.h> #include <sys/taskqueue.h> #include <sys/bus.h> #include <sys/endian.h> #include <sys/linker.h> #include <net/if.h> #include <net/ethernet.h> #include <net/if_media.h> #include <net80211/ieee80211_var.h> #include <net80211/ieee80211_radiotap.h> #include <dev/rtwn/if_rtwnreg.h> #include <dev/rtwn/if_rtwnvar.h> #include <dev/rtwn/if_rtwn_nop.h> #include <dev/rtwn/usb/rtwn_usb_var.h> #include <dev/rtwn/rtl8192c/r92c.h> #include <dev/rtwn/rtl8188e/r88e.h> #include <dev/rtwn/rtl8812a/r12a_var.h> #include <dev/rtwn/rtl8812a/usb/r12au.h> #include <dev/rtwn/rtl8812a/usb/r12au_tx_desc.h> #include <dev/rtwn/rtl8821a/r21a_reg.h> #include <dev/rtwn/rtl8821a/r21a_priv.h> #include <dev/rtwn/rtl8821a/usb/r21au.h> void r21au_attach(struct rtwn_usb_softc *); static void r21a_postattach(struct rtwn_softc *sc) { struct ieee80211com *ic = &sc->sc_ic; struct r12a_softc *rs = sc->sc_priv; if (rs->board_type == R92C_BOARD_TYPE_MINICARD || rs->board_type == R92C_BOARD_TYPE_SOLO || rs->board_type == R92C_BOARD_TYPE_COMBO) sc->sc_set_led = r88e_set_led; else sc->sc_set_led = r21a_set_led; TIMEOUT_TASK_INIT(taskqueue_thread, &rs->rs_chan_check, 0, r21au_chan_check, sc); /* RXCKSUM */ ic->ic_ioctl = r12a_ioctl_net; /* DFS */ rs->rs_scan_start = ic->ic_scan_start; ic->ic_scan_start = r21au_scan_start; rs->rs_scan_end = ic->ic_scan_end; ic->ic_scan_end = r21au_scan_end; } static void r21au_vap_preattach(struct rtwn_softc *sc, struct ieee80211vap *vap) { struct rtwn_vap *rvp = RTWN_VAP(vap); struct r12a_softc *rs = sc->sc_priv; r12a_vap_preattach(sc, vap); /* Install DFS newstate handler (non-monitor vaps only). */ if (rvp->id != RTWN_VAP_ID_INVALID) { KASSERT(rvp->id >= 0 && rvp->id <= nitems(rs->rs_newstate), ("%s: wrong vap id %d\n", __func__, rvp->id)); rs->rs_newstate[rvp->id] = vap->iv_newstate; vap->iv_newstate = r21au_newstate; } } static void r21a_attach_private(struct rtwn_softc *sc) { struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev); struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev); struct r12a_softc *rs; rs = malloc(sizeof(struct r12a_softc), M_RTWN_PRIV, M_WAITOK | M_ZERO); rs->rs_flags = R12A_RXCKSUM_EN | R12A_RXCKSUM6_EN; rs->rs_radar = 0; SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "radar_detection", CTLFLAG_RDTUN, &rs->rs_radar, rs->rs_radar, "Enable radar detection (untested)"); rs->rs_fix_spur = rtwn_nop_softc_chan; rs->rs_set_band_2ghz = r21a_set_band_2ghz; rs->rs_set_band_5ghz = r21a_set_band_5ghz; rs->rs_init_burstlen = r12au_init_burstlen_usb2; rs->rs_init_ampdu_fwhw = r21a_init_ampdu_fwhw; rs->rs_crystalcap_write = r21a_crystalcap_write; #ifndef RTWN_WITHOUT_UCODE rs->rs_iq_calib_fw_supported = r21a_iq_calib_fw_supported; #endif rs->rs_iq_calib_sw = r21a_iq_calib_sw; rs->ampdu_max_time = 0x5e; rs->ac_usb_dma_size = 0x01; rs->ac_usb_dma_time = 0x10; sc->sc_priv = rs; } static void r21au_adj_devcaps(struct rtwn_softc *sc) { struct ieee80211com *ic = &sc->sc_ic; struct r12a_softc *rs = sc->sc_priv; ic->ic_htcaps |= IEEE80211_HTC_TXLDPC; if (rs->rs_radar != 0) ic->ic_caps |= IEEE80211_C_DFS; /* TODO: VHT */ } void r21au_attach(struct rtwn_usb_softc *uc) { struct rtwn_softc *sc = &uc->uc_sc; /* USB part. */ uc->uc_align_rx = r12au_align_rx; uc->tx_agg_desc_num = 6; /* Common part. */ sc->sc_flags = RTWN_FLAG_EXT_HDR; sc->sc_set_chan = r12a_set_chan; sc->sc_fill_tx_desc = r12a_fill_tx_desc; sc->sc_fill_tx_desc_raw = r12a_fill_tx_desc_raw; sc->sc_fill_tx_desc_null = r12a_fill_tx_desc_null; sc->sc_dump_tx_desc = r12au_dump_tx_desc; sc->sc_tx_radiotap_flags = r12a_tx_radiotap_flags; sc->sc_rx_radiotap_flags = r12a_rx_radiotap_flags; sc->sc_get_rx_stats = r12a_get_rx_stats; sc->sc_get_rssi_cck = r21a_get_rssi_cck; sc->sc_get_rssi_ofdm = r88e_get_rssi_ofdm; sc->sc_classify_intr = r12au_classify_intr; sc->sc_handle_tx_report = r12a_ratectl_tx_complete; sc->sc_handle_c2h_report = r12a_handle_c2h_report; sc->sc_check_frame = r12a_check_frame_checksum; sc->sc_rf_read = r12a_c_cut_rf_read; sc->sc_rf_write = r12a_rf_write; sc->sc_check_condition = r21a_check_condition; sc->sc_efuse_postread = rtwn_nop_softc; sc->sc_parse_rom = r21a_parse_rom; sc->sc_power_on = r21a_power_on; sc->sc_power_off = r21a_power_off; #ifndef RTWN_WITHOUT_UCODE sc->sc_fw_reset = r21a_fw_reset; sc->sc_fw_download_enable = r12a_fw_download_enable; #endif sc->sc_llt_init = r92c_llt_init; sc->sc_set_page_size = rtwn_nop_int_softc; sc->sc_lc_calib = rtwn_nop_softc; /* XXX not used */ sc->sc_iq_calib = r12a_iq_calib; sc->sc_read_chipid_vendor = rtwn_nop_softc_uint32; sc->sc_adj_devcaps = r21au_adj_devcaps; sc->sc_vap_preattach = r21au_vap_preattach; sc->sc_postattach = r21a_postattach; sc->sc_detach_private = r12a_detach_private; #ifndef RTWN_WITHOUT_UCODE sc->sc_set_media_status = r12a_set_media_status; sc->sc_set_rsvd_page = r88e_set_rsvd_page; sc->sc_set_pwrmode = r12a_set_pwrmode; sc->sc_set_rssi = rtwn_nop_softc; /* XXX TODO */ #else sc->sc_set_media_status = rtwn_nop_softc_int; #endif sc->sc_beacon_init = r21a_beacon_init; sc->sc_beacon_enable = r92c_beacon_enable; sc->sc_beacon_set_rate = r12a_beacon_set_rate; sc->sc_beacon_select = r21a_beacon_select; sc->sc_temp_measure = r88e_temp_measure; sc->sc_temp_read = r88e_temp_read; sc->sc_init_tx_agg = r21au_init_tx_agg; sc->sc_init_rx_agg = r12au_init_rx_agg; sc->sc_init_ampdu = r12au_init_ampdu; sc->sc_init_intr = r12a_init_intr; sc->sc_init_edca = r12a_init_edca; sc->sc_init_bb = r12a_init_bb; sc->sc_init_rf = r12a_init_rf; sc->sc_init_antsel = r12a_init_antsel; sc->sc_post_init = r12au_post_init; sc->sc_init_bcnq1_boundary = r21a_init_bcnq1_boundary; sc->chan_list_5ghz[0] = r12a_chan_5ghz_0; sc->chan_list_5ghz[1] = r12a_chan_5ghz_1; sc->chan_list_5ghz[2] = r12a_chan_5ghz_2; sc->chan_num_5ghz[0] = nitems(r12a_chan_5ghz_0); sc->chan_num_5ghz[1] = nitems(r12a_chan_5ghz_1); sc->chan_num_5ghz[2] = nitems(r12a_chan_5ghz_2); sc->mac_prog = &rtl8821au_mac[0]; sc->mac_size = nitems(rtl8821au_mac); sc->bb_prog = &rtl8821au_bb[0]; sc->bb_size = nitems(rtl8821au_bb); sc->agc_prog = &rtl8821au_agc[0]; sc->agc_size = nitems(rtl8821au_agc); sc->rf_prog = &rtl8821au_rf[0]; sc->name = "RTL8821AU"; sc->fwname = "rtwn-rtl8821aufw"; sc->fwsig = 0x210; sc->page_count = R21A_TX_PAGE_COUNT; sc->pktbuf_count = R12A_TXPKTBUF_COUNT; sc->ackto = 0x80; sc->npubqpages = R12A_PUBQ_NPAGES; sc->page_size = R21A_TX_PAGE_SIZE; sc->txdesc_len = sizeof(struct r12au_tx_desc); sc->efuse_maxlen = R12A_EFUSE_MAX_LEN; sc->efuse_maplen = R12A_EFUSE_MAP_LEN; sc->rx_dma_size = R12A_RX_DMA_BUFFER_SIZE; sc->macid_limit = R12A_MACID_MAX + 1; sc->cam_entry_limit = R12A_CAM_ENTRY_COUNT; sc->fwsize_limit = R12A_MAX_FW_SIZE; sc->temp_delta = R88E_CALIB_THRESHOLD; sc->bcn_status_reg[0] = R92C_TDECTRL; sc->bcn_status_reg[1] = R21A_DWBCN1_CTRL; sc->rcr = R12A_RCR_DIS_CHK_14 | R12A_RCR_VHT_ACK | R12A_RCR_TCP_OFFLD_EN; sc->ntxchains = 1; sc->nrxchains = 1; r21a_attach_private(sc); }
320900.c
#include <stdio.h> /* Input/Output */ int main(int argc, char const *argv[]) { puts("Hello"); return 5; }
480649.c
/* ** pex.c for pex in /Users/noboud_n/Documents/Share/PSU_2015_zappy/Network/src/ ** ** Made by Nyrandone Noboud-Inpeng ** Login <[email protected]> ** ** Started on Mon Jun 20 15:51:07 2016 Nyrandone Noboud-Inpeng ** Last update Sat Jun 25 16:50:47 2016 Nyrandone Noboud-Inpeng */ #include <string.h> #include "server.h" #include "errors.h" #include "replies.h" int pex(t_server *server, t_player *player) { char buffer[20]; if (!server || !player) { fprintf(stderr, INTERNAL_ERR); return (-1); } if (memset(buffer, 0, 20) == NULL || snprintf(buffer, 20, PEX, player->id) == -1) return (fprintf(stderr, ERR_MEMSET), -1); return (send_all_graphics(server, strdup(buffer))); }
76948.c
#include "clothManager.h" #include "cloth.h" #include "text.h" #include "config.h" #include "renderer.h" #include "player.h" #include <stdbool.h> #include <stdlib.h> #include <string.h> #include "text.h" static s32 _clothsPerDay = 2; static Cloth _masterClothList[CLOTH_MASTER_LIST_SIZE]; static s32 _clothListLength; static Cloth* _clothQueue[CLOTH_QUEUE_SIZE]; static s32 _queueIndex = 0; #define DRYING_SIZE 6 // Initially simple, will increase in complexity as turnCount increases. DryingState DryingDie[DRYING_SIZE] = { DRYING_SPUN, DRYING_SPUN, DRYING_SPUN, DRYING_SPUN, DRYING_SPUN, DRYING_SPUN }; #define SIZE_SIZE 8 s32 SizeDie[SIZE_SIZE] = { 1, 1, 1, 1, 1, 1, 1, 1 }; #define GROWTH_TYPE_SIZE 4 // No growth quadratic until I can be arsed sorting out the algorithm for it. s32 GrowthTypeDie[GROWTH_TYPE_SIZE]= { GROWTH_LINEAR, GROWTH_LINEAR, GROWTH_LINEAR, GROWTH_LINEAR }; #define FACTOR_SIZE 8 s32 LinearFactorDie[FACTOR_SIZE] = { 0, 0, 0, 0, 0, 0 }; const s32 QuadraticFactorDie[FACTOR_SIZE] = { -2, -2, +2, +2, +2, +2 }; void drawQueue() { s32 y = QUEUE_MARGIN_TOP; drawText("NEXT", QUEUE_MARGIN_LEFT, y, 1); y += TILE_WIDTH ; // Draw the full details of the next cloth Cloth* next = _clothQueue[0]; if (next && next->size) { drawCloth(next, QUEUE_MARGIN_LEFT + TILE_WIDTH + 2, y); } // And then the glowing pile of pending cloths. // The outline of the pile. y += TILE_WIDTH * 3; drawSprite(CURSOR_TOP_LEFT_SPRITE, QUEUE_MARGIN_LEFT, y, 0, 1); drawSprite(CURSOR_TOP_SPRITE, QUEUE_MARGIN_LEFT + (TILE_WIDTH / 2), y, 0, 1); drawSprite(CURSOR_TOP_RIGHT_SPRITE, QUEUE_MARGIN_LEFT + TILE_WIDTH, y, 0, 1); y += TILE_WIDTH / 2; for (s32 i = 1; i < (CLOTH_QUEUE_SIZE - 3) / 3; i++) { drawSprite(CURSOR_LEFT_SPRITE, QUEUE_MARGIN_LEFT, y, 0, 1); drawSprite(CURSOR_RIGHT_SPRITE, QUEUE_MARGIN_LEFT + TILE_WIDTH, y, 0, 1); y += TILE_WIDTH; } y -= TILE_WIDTH / 2; drawSprite(CURSOR_BOTTOM_LEFT_SPRITE, QUEUE_MARGIN_LEFT, y, 0, 1); drawSprite(CURSOR_BOTTOM_SPRITE, QUEUE_MARGIN_LEFT + (TILE_WIDTH / 2), y, 0, 1); drawSprite(CURSOR_BOTTOM_RIGHT_SPRITE, QUEUE_MARGIN_LEFT + TILE_WIDTH, y, 0, 1); // Then fill it up with cloths from the bottom up. y -= TILE_WIDTH / 4; SpriteCode spriteId = QUEUED_GREEN_SPRITE; if (getPlayer()->state != STATE_GAMEOVER) { for (s32 i = 0; i < _queueIndex; i++) { if (i == CLOTH_QUEUE_SIZE / 6 * 5) { spriteId = QUEUED_RED_SPRITE;; } else if (i == CLOTH_QUEUE_SIZE / 2) { spriteId = QUEUED_AMBER_SPRITE; } drawScaledSprite(spriteId, QUEUE_MARGIN_LEFT + 2, y, 0, 2, 1); y -= TILE_WIDTH / 4; } } else { spriteId = QUEUED_RED_SPRITE;; // A few extras to show we busted out of the container for (s32 i = 0; i < _queueIndex + 2; i++) { drawScaledSprite(spriteId, QUEUE_MARGIN_LEFT + 2, y, 0, 2, 1); y -= TILE_WIDTH / 4; } } } /** * Return the cloth at the head of the queue and shuffle the rest along. */ Cloth* dequeueCloth() { Cloth* result = _clothQueue[0]; // The queue is empty. if (!result || !result->size) { return 0; } for (s32 i = 0; i < CLOTH_QUEUE_SIZE - 1; i++) { _clothQueue[i] = _clothQueue[i+1]; } _clothQueue[CLOTH_QUEUE_SIZE - 1] = 0; _queueIndex--; return result; } /** * Should be called every turn as we update the dice. * * Turn 1 Basic placement * * Turn 2, 3 Teach growth * * Turn 4, 5 Start mixing things up * * Turn 6 First size increase (just two instead of three cloths this turn) * * Turn 7, 8, 9 Continue mixing things up * * Turn 10 A big mother with full dampness (just one) * * Turn 11 - 15 Things mixed up but with the possibility of a big mother every now and then * * Turn 16 - introduce reverse growth * * Turn 17 - 20 mix up with reverse growth a possibility. * * Turn 21 - Cloth with Double growth rate * * Turn 25 - increase cloths per turn * * Turn 30 - Triple growth rate * * Every 5 turns onwards - increase cloths per turn until it's half the max each turn. */ void increaseComplexity(s32 turnCount) { switch (turnCount) { case 1: _clothsPerDay = 3; DryingDie[0] = DRYING_SPUN; DryingDie[1] = DRYING_SPUN; DryingDie[2] = DRYING_SPUN; DryingDie[3] = DRYING_SPUN; DryingDie[4] = DRYING_SPUN; DryingDie[5] = DRYING_SPUN; SizeDie[0] = 1; SizeDie[1] = 1; SizeDie[2] = 1; SizeDie[3] = 1; SizeDie[4] = 1; SizeDie[5] = 1; SizeDie[6] = 1; SizeDie[7] = 1; GrowthTypeDie[0] = GROWTH_LINEAR; GrowthTypeDie[1] = GROWTH_LINEAR; GrowthTypeDie[2] = GROWTH_LINEAR; GrowthTypeDie[3] = GROWTH_LINEAR; LinearFactorDie[0] = 0; LinearFactorDie[1] = 0; LinearFactorDie[2] = 0; LinearFactorDie[3] = 0; LinearFactorDie[4] = 0; LinearFactorDie[5] = 0; LinearFactorDie[6] = 0; LinearFactorDie[7] = 0; break; // Turn 2, 3 Teach growth case 2: LinearFactorDie[0] = 1; LinearFactorDie[1] = 1; LinearFactorDie[2] = 1; LinearFactorDie[3] = 1; LinearFactorDie[4] = 1; LinearFactorDie[5] = 1; LinearFactorDie[6] = 1; LinearFactorDie[7] = 1; break; // Turn 4, 5 Start mixing things up case 4: _clothsPerDay = 2; LinearFactorDie[0] = 0; LinearFactorDie[1] = 0; LinearFactorDie[2] = 0; LinearFactorDie[3] = 0; break; // Turn 6 First size increase case 6: SizeDie[0] = 2; SizeDie[1] = 2; SizeDie[2] = 2; SizeDie[3] = 2; SizeDie[4] = 2; SizeDie[5] = 2; SizeDie[6] = 2; SizeDie[7] = 2; LinearFactorDie[0] = 1; LinearFactorDie[1] = 1; LinearFactorDie[2] = 1; LinearFactorDie[3] = 1; break; // Turn 7, 8, 9 Continue mixing things up case 7: SizeDie[0] = 1; SizeDie[1] = 1; SizeDie[2] = 1; SizeDie[3] = 1; SizeDie[4] = 1; SizeDie[5] = 1; SizeDie[6] = 2; SizeDie[7] = 2; LinearFactorDie[0] = 0; LinearFactorDie[1] = 0; LinearFactorDie[2] = 0; LinearFactorDie[3] = 0; break; // Turn 10 A big mother with full dampness (just one) case 10: _clothsPerDay = 1; SizeDie[0] = 3; SizeDie[1] = 3; SizeDie[2] = 3; SizeDie[3] = 3; SizeDie[4] = 3; SizeDie[5] = 3; SizeDie[6] = 3; SizeDie[7] = 3; LinearFactorDie[0] = 1; LinearFactorDie[1] = 1; LinearFactorDie[2] = 1; LinearFactorDie[3] = 1; DryingDie[0] = DRYING_DRENCHED; DryingDie[1] = DRYING_DRENCHED; DryingDie[2] = DRYING_DRENCHED; DryingDie[3] = DRYING_DRENCHED; DryingDie[4] = DRYING_DRENCHED; DryingDie[5] = DRYING_DRENCHED; break; // Turn 11 - 15 Things mixed up but with the possibility of a big mother every now and then case 11: _clothsPerDay = 2; SizeDie[0] = 1; SizeDie[1] = 1; SizeDie[2] = 1; SizeDie[3] = 1; SizeDie[4] = 1; SizeDie[5] = 1; SizeDie[6] = 2; SizeDie[7] = 3; LinearFactorDie[0] = 0; LinearFactorDie[1] = 0; LinearFactorDie[2] = 0; LinearFactorDie[3] = 0; DryingDie[0] = DRYING_DAMP; DryingDie[1] = DRYING_MOIST; DryingDie[2] = DRYING_SPUN; DryingDie[3] = DRYING_SPUN; DryingDie[4] = DRYING_SPUN; DryingDie[5] = DRYING_DRENCHED; break; // Turn 16 - introduce reverse growth case 16: LinearFactorDie[0] = -1; LinearFactorDie[1] = -1; LinearFactorDie[2] = -1; LinearFactorDie[3] = -1; LinearFactorDie[4] = -1; LinearFactorDie[5] = -1; LinearFactorDie[6] = -1; LinearFactorDie[7] = -1; SizeDie[0] = 2; SizeDie[1] = 2; SizeDie[2] = 2; SizeDie[3] = 2; SizeDie[4] = 2; SizeDie[5] = 2; SizeDie[6] = 3; SizeDie[7] = 3; break; // Turn 17 - 20 mix up with reverse growth a possibility. case 17: SizeDie[0] = 1; SizeDie[1] = 1; SizeDie[2] = 1; SizeDie[3] = 1; SizeDie[4] = 1; SizeDie[5] = 1; SizeDie[6] = 2; SizeDie[7] = 3; LinearFactorDie[0] = 0; LinearFactorDie[1] = 0; LinearFactorDie[2] = 1; LinearFactorDie[3] = 1; LinearFactorDie[4] = 1; LinearFactorDie[5] = 1; LinearFactorDie[6] = -1; LinearFactorDie[7] = -1; DryingDie[0] = DRYING_DAMP; DryingDie[1] = DRYING_MOIST; DryingDie[2] = DRYING_SPUN; DryingDie[3] = DRYING_SPUN; DryingDie[4] = DRYING_SPUN; DryingDie[5] = DRYING_DRENCHED; break; // Turn 21 - Cloth with Double growth rate case 21: _clothsPerDay = 1; LinearFactorDie[0] = 2; LinearFactorDie[1] = 2; LinearFactorDie[2] = 2; LinearFactorDie[3] = 2; LinearFactorDie[4] = 2; LinearFactorDie[5] = 2; LinearFactorDie[6] = 2; LinearFactorDie[7] = 2; SizeDie[0] = 1; SizeDie[1] = 1; SizeDie[2] = 1; SizeDie[3] = 1; SizeDie[4] = 1; SizeDie[5] = 1; SizeDie[6] = 1; SizeDie[7] = 1; break; case 22: _clothsPerDay = 2; SizeDie[0] = 1; SizeDie[1] = 1; SizeDie[2] = 1; SizeDie[3] = 1; SizeDie[4] = 1; SizeDie[5] = 1; SizeDie[6] = 2; SizeDie[7] = 3; LinearFactorDie[0] = 2; LinearFactorDie[1] = 0; LinearFactorDie[2] = 1; LinearFactorDie[3] = 1; LinearFactorDie[4] = 1; LinearFactorDie[5] = 1; LinearFactorDie[6] = -1; LinearFactorDie[7] = -1; break; // A little breather here. case 25: break; // Turn 30 - Triple growth rate case 30: _clothsPerDay = 1; LinearFactorDie[0] = 3; LinearFactorDie[1] = 3; LinearFactorDie[2] = 3; LinearFactorDie[3] = 3; LinearFactorDie[4] = 3; LinearFactorDie[5] = 3; LinearFactorDie[6] = 3; LinearFactorDie[7] = 3; SizeDie[0] = 1; SizeDie[1] = 1; SizeDie[2] = 1; SizeDie[3] = 1; SizeDie[4] = 1; SizeDie[5] = 1; SizeDie[6] = 1; SizeDie[7] = 1; break; case 31: SizeDie[0] = 1; SizeDie[1] = 1; SizeDie[2] = 1; SizeDie[3] = 1; SizeDie[4] = 1; SizeDie[5] = 1; SizeDie[6] = 2; SizeDie[7] = 3; LinearFactorDie[0] = -1; LinearFactorDie[1] = -1; LinearFactorDie[2] = 0; LinearFactorDie[3] = 1; LinearFactorDie[4] = 1; LinearFactorDie[5] = 1; LinearFactorDie[6] = 2; LinearFactorDie[7] = 3; break; default: if (turnCount > 31 && !(turnCount % 5) && _clothsPerDay < (CLOTH_QUEUE_SIZE - 1)) { _clothsPerDay++; } // Just continue with whatever the last setting was. break; } } /** * Add a specific cloth to the end of the queue */ bool enqueueCloth(Cloth* cloth) { if (_queueIndex > CLOTH_QUEUE_SIZE) { return false; } _clothQueue[_queueIndex] = cloth; _queueIndex++; return true; } /** * Create a new cloth and add it to the upcoming queue * @return true if successful, false if the queue has overflowed. */ bool enqueueNewCloth() { if (_queueIndex > CLOTH_QUEUE_SIZE) { return false; } Cloth* cloth = &_masterClothList[_clothListLength]; initCloth( cloth, SizeDie[rand() % SIZE_SIZE], DryingDie[rand() % DRYING_SIZE] ); cloth->growthType = GrowthTypeDie[rand() % GROWTH_TYPE_SIZE]; switch(cloth->growthType) { case GROWTH_LINEAR: cloth->growthFactor = LinearFactorDie[rand() % FACTOR_SIZE]; break; case GROWTH_QUADRATIC: cloth->growthFactor = QuadraticFactorDie[rand() % FACTOR_SIZE]; break; case GROWTH_NONE: cloth->growthFactor = 0; break; } _clothListLength++; enqueueCloth(cloth); return true; } bool enqueueClothsPerDay() { if (_queueIndex + _clothsPerDay > CLOTH_QUEUE_SIZE) { return false; } for (s32 i = 0; i < _clothsPerDay; i++) { Cloth* cloth = &_masterClothList[_clothListLength]; initCloth(cloth, SizeDie[rand() % SIZE_SIZE], DryingDie[rand() % DRYING_SIZE]); cloth->growthType = GrowthTypeDie[rand() % GROWTH_TYPE_SIZE]; switch(cloth->growthType) { case GROWTH_LINEAR: cloth->growthFactor = LinearFactorDie[rand() % FACTOR_SIZE]; break; case GROWTH_QUADRATIC: cloth->growthFactor = QuadraticFactorDie[rand() % FACTOR_SIZE]; break; case GROWTH_NONE: cloth->growthFactor = 0; break; } _clothListLength++; enqueueCloth(cloth); } return true; } void initClothManager() { _queueIndex = 0; memset(_masterClothList, 0, sizeof(Cloth) * CLOTH_MASTER_LIST_SIZE); increaseComplexity(1); _clothListLength = 0; for (s32 i = 0; i < INIT_TURN_CLOTHS; i++) { enqueueNewCloth(); } }
501938.c
/* * GPL HEADER START * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 only, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is included * in the LICENSE file that accompanied this code). * * GPL HEADER END */ /* * Copyright (c) 2012, 2015, Intel Corporation. */ /* * This file is part of Lustre, http://www.lustre.org/ * Lustre is a trademark of Sun Microsystems, Inc. * * lnet/lnet/lib-ptl.c * * portal & match routines * * Author: [email protected] */ #define DEBUG_SUBSYSTEM S_LNET #include "../../include/linux/lnet/lib-lnet.h" /* NB: add /proc interfaces in upcoming patches */ int portal_rotor = LNET_PTL_ROTOR_HASH_RT; module_param(portal_rotor, int, 0644); MODULE_PARM_DESC(portal_rotor, "redirect PUTs to different cpu-partitions"); static int lnet_ptl_match_type(unsigned int index, lnet_process_id_t match_id, __u64 mbits, __u64 ignore_bits) { struct lnet_portal *ptl = the_lnet.ln_portals[index]; int unique; unique = !ignore_bits && match_id.nid != LNET_NID_ANY && match_id.pid != LNET_PID_ANY; LASSERT(!lnet_ptl_is_unique(ptl) || !lnet_ptl_is_wildcard(ptl)); /* prefer to check w/o any lock */ if (likely(lnet_ptl_is_unique(ptl) || lnet_ptl_is_wildcard(ptl))) goto match; /* unset, new portal */ lnet_ptl_lock(ptl); /* check again with lock */ if (unlikely(lnet_ptl_is_unique(ptl) || lnet_ptl_is_wildcard(ptl))) { lnet_ptl_unlock(ptl); goto match; } /* still not set */ if (unique) lnet_ptl_setopt(ptl, LNET_PTL_MATCH_UNIQUE); else lnet_ptl_setopt(ptl, LNET_PTL_MATCH_WILDCARD); lnet_ptl_unlock(ptl); return 1; match: if ((lnet_ptl_is_unique(ptl) && !unique) || (lnet_ptl_is_wildcard(ptl) && unique)) return 0; return 1; } static void lnet_ptl_enable_mt(struct lnet_portal *ptl, int cpt) { struct lnet_match_table *mtable = ptl->ptl_mtables[cpt]; int i; /* with hold of both lnet_res_lock(cpt) and lnet_ptl_lock */ LASSERT(lnet_ptl_is_wildcard(ptl)); mtable->mt_enabled = 1; ptl->ptl_mt_maps[ptl->ptl_mt_nmaps] = cpt; for (i = ptl->ptl_mt_nmaps - 1; i >= 0; i--) { LASSERT(ptl->ptl_mt_maps[i] != cpt); if (ptl->ptl_mt_maps[i] < cpt) break; /* swap to order */ ptl->ptl_mt_maps[i + 1] = ptl->ptl_mt_maps[i]; ptl->ptl_mt_maps[i] = cpt; } ptl->ptl_mt_nmaps++; } static void lnet_ptl_disable_mt(struct lnet_portal *ptl, int cpt) { struct lnet_match_table *mtable = ptl->ptl_mtables[cpt]; int i; /* with hold of both lnet_res_lock(cpt) and lnet_ptl_lock */ LASSERT(lnet_ptl_is_wildcard(ptl)); if (LNET_CPT_NUMBER == 1) return; /* never disable the only match-table */ mtable->mt_enabled = 0; LASSERT(ptl->ptl_mt_nmaps > 0 && ptl->ptl_mt_nmaps <= LNET_CPT_NUMBER); /* remove it from mt_maps */ ptl->ptl_mt_nmaps--; for (i = 0; i < ptl->ptl_mt_nmaps; i++) { if (ptl->ptl_mt_maps[i] >= cpt) /* overwrite it */ ptl->ptl_mt_maps[i] = ptl->ptl_mt_maps[i + 1]; } } static int lnet_try_match_md(lnet_libmd_t *md, struct lnet_match_info *info, struct lnet_msg *msg) { /* * ALWAYS called holding the lnet_res_lock, and can't lnet_res_unlock; * lnet_match_blocked_msg() relies on this to avoid races */ unsigned int offset; unsigned int mlength; lnet_me_t *me = md->md_me; /* MD exhausted */ if (lnet_md_exhausted(md)) return LNET_MATCHMD_NONE | LNET_MATCHMD_EXHAUSTED; /* mismatched MD op */ if (!(md->md_options & info->mi_opc)) return LNET_MATCHMD_NONE; /* mismatched ME nid/pid? */ if (me->me_match_id.nid != LNET_NID_ANY && me->me_match_id.nid != info->mi_id.nid) return LNET_MATCHMD_NONE; if (me->me_match_id.pid != LNET_PID_ANY && me->me_match_id.pid != info->mi_id.pid) return LNET_MATCHMD_NONE; /* mismatched ME matchbits? */ if ((me->me_match_bits ^ info->mi_mbits) & ~me->me_ignore_bits) return LNET_MATCHMD_NONE; /* Hurrah! This _is_ a match; check it out... */ if (!(md->md_options & LNET_MD_MANAGE_REMOTE)) offset = md->md_offset; else offset = info->mi_roffset; if (md->md_options & LNET_MD_MAX_SIZE) { mlength = md->md_max_size; LASSERT(md->md_offset + mlength <= md->md_length); } else { mlength = md->md_length - offset; } if (info->mi_rlength <= mlength) { /* fits in allowed space */ mlength = info->mi_rlength; } else if (!(md->md_options & LNET_MD_TRUNCATE)) { /* this packet _really_ is too big */ CERROR("Matching packet from %s, match %llu length %d too big: %d left, %d allowed\n", libcfs_id2str(info->mi_id), info->mi_mbits, info->mi_rlength, md->md_length - offset, mlength); return LNET_MATCHMD_DROP; } /* Commit to this ME/MD */ CDEBUG(D_NET, "Incoming %s index %x from %s of length %d/%d into md %#llx [%d] + %d\n", (info->mi_opc == LNET_MD_OP_PUT) ? "put" : "get", info->mi_portal, libcfs_id2str(info->mi_id), mlength, info->mi_rlength, md->md_lh.lh_cookie, md->md_niov, offset); lnet_msg_attach_md(msg, md, offset, mlength); md->md_offset = offset + mlength; if (!lnet_md_exhausted(md)) return LNET_MATCHMD_OK; /* * Auto-unlink NOW, so the ME gets unlinked if required. * We bumped md->md_refcount above so the MD just gets flagged * for unlink when it is finalized. */ if (md->md_flags & LNET_MD_FLAG_AUTO_UNLINK) lnet_md_unlink(md); return LNET_MATCHMD_OK | LNET_MATCHMD_EXHAUSTED; } static struct lnet_match_table * lnet_match2mt(struct lnet_portal *ptl, lnet_process_id_t id, __u64 mbits) { if (LNET_CPT_NUMBER == 1) return ptl->ptl_mtables[0]; /* the only one */ /* if it's a unique portal, return match-table hashed by NID */ return lnet_ptl_is_unique(ptl) ? ptl->ptl_mtables[lnet_cpt_of_nid(id.nid)] : NULL; } struct lnet_match_table * lnet_mt_of_attach(unsigned int index, lnet_process_id_t id, __u64 mbits, __u64 ignore_bits, lnet_ins_pos_t pos) { struct lnet_portal *ptl; struct lnet_match_table *mtable; /* NB: called w/o lock */ LASSERT(index < the_lnet.ln_nportals); if (!lnet_ptl_match_type(index, id, mbits, ignore_bits)) return NULL; ptl = the_lnet.ln_portals[index]; mtable = lnet_match2mt(ptl, id, mbits); if (mtable) /* unique portal or only one match-table */ return mtable; /* it's a wildcard portal */ switch (pos) { default: return NULL; case LNET_INS_BEFORE: case LNET_INS_AFTER: /* * posted by no affinity thread, always hash to specific * match-table to avoid buffer stealing which is heavy */ return ptl->ptl_mtables[ptl->ptl_index % LNET_CPT_NUMBER]; case LNET_INS_LOCAL: /* posted by cpu-affinity thread */ return ptl->ptl_mtables[lnet_cpt_current()]; } } static struct lnet_match_table * lnet_mt_of_match(struct lnet_match_info *info, struct lnet_msg *msg) { struct lnet_match_table *mtable; struct lnet_portal *ptl; unsigned int nmaps; unsigned int rotor; unsigned int cpt; bool routed; /* NB: called w/o lock */ LASSERT(info->mi_portal < the_lnet.ln_nportals); ptl = the_lnet.ln_portals[info->mi_portal]; LASSERT(lnet_ptl_is_wildcard(ptl) || lnet_ptl_is_unique(ptl)); mtable = lnet_match2mt(ptl, info->mi_id, info->mi_mbits); if (mtable) return mtable; /* it's a wildcard portal */ routed = LNET_NIDNET(msg->msg_hdr.src_nid) != LNET_NIDNET(msg->msg_hdr.dest_nid); if (portal_rotor == LNET_PTL_ROTOR_OFF || (portal_rotor != LNET_PTL_ROTOR_ON && !routed)) { cpt = lnet_cpt_current(); if (ptl->ptl_mtables[cpt]->mt_enabled) return ptl->ptl_mtables[cpt]; } rotor = ptl->ptl_rotor++; /* get round-robin factor */ if (portal_rotor == LNET_PTL_ROTOR_HASH_RT && routed) cpt = lnet_cpt_of_nid(msg->msg_hdr.src_nid); else cpt = rotor % LNET_CPT_NUMBER; if (!ptl->ptl_mtables[cpt]->mt_enabled) { /* is there any active entry for this portal? */ nmaps = ptl->ptl_mt_nmaps; /* map to an active mtable to avoid heavy "stealing" */ if (nmaps) { /* * NB: there is possibility that ptl_mt_maps is being * changed because we are not under protection of * lnet_ptl_lock, but it shouldn't hurt anything */ cpt = ptl->ptl_mt_maps[rotor % nmaps]; } } return ptl->ptl_mtables[cpt]; } static int lnet_mt_test_exhausted(struct lnet_match_table *mtable, int pos) { __u64 *bmap; int i; if (!lnet_ptl_is_wildcard(the_lnet.ln_portals[mtable->mt_portal])) return 0; if (pos < 0) { /* check all bits */ for (i = 0; i < LNET_MT_EXHAUSTED_BMAP; i++) { if (mtable->mt_exhausted[i] != (__u64)(-1)) return 0; } return 1; } LASSERT(pos <= LNET_MT_HASH_IGNORE); /* mtable::mt_mhash[pos] is marked as exhausted or not */ bmap = &mtable->mt_exhausted[pos >> LNET_MT_BITS_U64]; pos &= (1 << LNET_MT_BITS_U64) - 1; return (*bmap & (1ULL << pos)); } static void lnet_mt_set_exhausted(struct lnet_match_table *mtable, int pos, int exhausted) { __u64 *bmap; LASSERT(lnet_ptl_is_wildcard(the_lnet.ln_portals[mtable->mt_portal])); LASSERT(pos <= LNET_MT_HASH_IGNORE); /* set mtable::mt_mhash[pos] as exhausted/non-exhausted */ bmap = &mtable->mt_exhausted[pos >> LNET_MT_BITS_U64]; pos &= (1 << LNET_MT_BITS_U64) - 1; if (!exhausted) *bmap &= ~(1ULL << pos); else *bmap |= 1ULL << pos; } struct list_head * lnet_mt_match_head(struct lnet_match_table *mtable, lnet_process_id_t id, __u64 mbits) { struct lnet_portal *ptl = the_lnet.ln_portals[mtable->mt_portal]; unsigned long hash = mbits; if (!lnet_ptl_is_wildcard(ptl)) { hash += id.nid + id.pid; LASSERT(lnet_ptl_is_unique(ptl)); hash = hash_long(hash, LNET_MT_HASH_BITS); } return &mtable->mt_mhash[hash & LNET_MT_HASH_MASK]; } int lnet_mt_match_md(struct lnet_match_table *mtable, struct lnet_match_info *info, struct lnet_msg *msg) { struct list_head *head; lnet_me_t *me; lnet_me_t *tmp; int exhausted = 0; int rc; /* any ME with ignore bits? */ if (!list_empty(&mtable->mt_mhash[LNET_MT_HASH_IGNORE])) head = &mtable->mt_mhash[LNET_MT_HASH_IGNORE]; else head = lnet_mt_match_head(mtable, info->mi_id, info->mi_mbits); again: /* NB: only wildcard portal needs to return LNET_MATCHMD_EXHAUSTED */ if (lnet_ptl_is_wildcard(the_lnet.ln_portals[mtable->mt_portal])) exhausted = LNET_MATCHMD_EXHAUSTED; list_for_each_entry_safe(me, tmp, head, me_list) { /* ME attached but MD not attached yet */ if (!me->me_md) continue; LASSERT(me == me->me_md->md_me); rc = lnet_try_match_md(me->me_md, info, msg); if (!(rc & LNET_MATCHMD_EXHAUSTED)) exhausted = 0; /* mlist is not empty */ if (rc & LNET_MATCHMD_FINISH) { /* * don't return EXHAUSTED bit because we don't know * whether the mlist is empty or not */ return rc & ~LNET_MATCHMD_EXHAUSTED; } } if (exhausted == LNET_MATCHMD_EXHAUSTED) { /* @head is exhausted */ lnet_mt_set_exhausted(mtable, head - mtable->mt_mhash, 1); if (!lnet_mt_test_exhausted(mtable, -1)) exhausted = 0; } if (!exhausted && head == &mtable->mt_mhash[LNET_MT_HASH_IGNORE]) { head = lnet_mt_match_head(mtable, info->mi_id, info->mi_mbits); goto again; /* re-check MEs w/o ignore-bits */ } if (info->mi_opc == LNET_MD_OP_GET || !lnet_ptl_is_lazy(the_lnet.ln_portals[info->mi_portal])) return exhausted | LNET_MATCHMD_DROP; return exhausted | LNET_MATCHMD_NONE; } static int lnet_ptl_match_early(struct lnet_portal *ptl, struct lnet_msg *msg) { int rc; /* * message arrived before any buffer posting on this portal, * simply delay or drop this message */ if (likely(lnet_ptl_is_wildcard(ptl) || lnet_ptl_is_unique(ptl))) return 0; lnet_ptl_lock(ptl); /* check it again with hold of lock */ if (lnet_ptl_is_wildcard(ptl) || lnet_ptl_is_unique(ptl)) { lnet_ptl_unlock(ptl); return 0; } if (lnet_ptl_is_lazy(ptl)) { if (msg->msg_rx_ready_delay) { msg->msg_rx_delayed = 1; list_add_tail(&msg->msg_list, &ptl->ptl_msg_delayed); } rc = LNET_MATCHMD_NONE; } else { rc = LNET_MATCHMD_DROP; } lnet_ptl_unlock(ptl); return rc; } static int lnet_ptl_match_delay(struct lnet_portal *ptl, struct lnet_match_info *info, struct lnet_msg *msg) { int first = ptl->ptl_mt_maps[0]; /* read w/o lock */ int rc = 0; int i; /** * Steal buffer from other CPTs, and delay msg if nothing to * steal. This function is more expensive than a regular * match, but we don't expect it can happen a lot. The return * code contains one of LNET_MATCHMD_OK, LNET_MATCHMD_DROP, or * LNET_MATCHMD_NONE. */ LASSERT(lnet_ptl_is_wildcard(ptl)); for (i = 0; i < LNET_CPT_NUMBER; i++) { struct lnet_match_table *mtable; int cpt; cpt = (first + i) % LNET_CPT_NUMBER; mtable = ptl->ptl_mtables[cpt]; if (i && i != LNET_CPT_NUMBER - 1 && !mtable->mt_enabled) continue; lnet_res_lock(cpt); lnet_ptl_lock(ptl); if (!i) { /* The first try, add to stealing list. */ list_add_tail(&msg->msg_list, &ptl->ptl_msg_stealing); } if (!list_empty(&msg->msg_list)) { /* On stealing list. */ rc = lnet_mt_match_md(mtable, info, msg); if ((rc & LNET_MATCHMD_EXHAUSTED) && mtable->mt_enabled) lnet_ptl_disable_mt(ptl, cpt); if (rc & LNET_MATCHMD_FINISH) { /* Match found, remove from stealing list. */ list_del_init(&msg->msg_list); } else if (i == LNET_CPT_NUMBER - 1 || /* (1) */ !ptl->ptl_mt_nmaps || /* (2) */ (ptl->ptl_mt_nmaps == 1 && /* (3) */ ptl->ptl_mt_maps[0] == cpt)) { /** * No match found, and this is either * (1) the last cpt to check, or * (2) there is no active cpt, or * (3) this is the only active cpt. * There is nothing to steal: delay or * drop the message. */ list_del_init(&msg->msg_list); if (lnet_ptl_is_lazy(ptl)) { msg->msg_rx_delayed = 1; list_add_tail(&msg->msg_list, &ptl->ptl_msg_delayed); rc = LNET_MATCHMD_NONE; } else { rc = LNET_MATCHMD_DROP; } } else { /* Do another iteration. */ rc = 0; } } else { /** * No longer on stealing list: another thread * matched the message in lnet_ptl_attach_md(). * We are now expected to handle the message. */ rc = !msg->msg_md ? LNET_MATCHMD_DROP : LNET_MATCHMD_OK; } lnet_ptl_unlock(ptl); lnet_res_unlock(cpt); /** * Note that test (1) above ensures that we always * exit the loop through this break statement. * * LNET_MATCHMD_NONE means msg was added to the * delayed queue, and we may no longer reference it * after lnet_ptl_unlock() and lnet_res_unlock(). */ if (rc & (LNET_MATCHMD_FINISH | LNET_MATCHMD_NONE)) break; } return rc; } int lnet_ptl_match_md(struct lnet_match_info *info, struct lnet_msg *msg) { struct lnet_match_table *mtable; struct lnet_portal *ptl; int rc; CDEBUG(D_NET, "Request from %s of length %d into portal %d MB=%#llx\n", libcfs_id2str(info->mi_id), info->mi_rlength, info->mi_portal, info->mi_mbits); if (info->mi_portal >= the_lnet.ln_nportals) { CERROR("Invalid portal %d not in [0-%d]\n", info->mi_portal, the_lnet.ln_nportals); return LNET_MATCHMD_DROP; } ptl = the_lnet.ln_portals[info->mi_portal]; rc = lnet_ptl_match_early(ptl, msg); if (rc) /* matched or delayed early message */ return rc; mtable = lnet_mt_of_match(info, msg); lnet_res_lock(mtable->mt_cpt); if (the_lnet.ln_shutdown) { rc = LNET_MATCHMD_DROP; goto out1; } rc = lnet_mt_match_md(mtable, info, msg); if ((rc & LNET_MATCHMD_EXHAUSTED) && mtable->mt_enabled) { lnet_ptl_lock(ptl); lnet_ptl_disable_mt(ptl, mtable->mt_cpt); lnet_ptl_unlock(ptl); } if (rc & LNET_MATCHMD_FINISH) /* matched or dropping */ goto out1; if (!msg->msg_rx_ready_delay) goto out1; LASSERT(lnet_ptl_is_lazy(ptl)); LASSERT(!msg->msg_rx_delayed); /* NB: we don't expect "delay" can happen a lot */ if (lnet_ptl_is_unique(ptl) || LNET_CPT_NUMBER == 1) { lnet_ptl_lock(ptl); msg->msg_rx_delayed = 1; list_add_tail(&msg->msg_list, &ptl->ptl_msg_delayed); lnet_ptl_unlock(ptl); lnet_res_unlock(mtable->mt_cpt); rc = LNET_MATCHMD_NONE; } else { lnet_res_unlock(mtable->mt_cpt); rc = lnet_ptl_match_delay(ptl, info, msg); } /* LNET_MATCHMD_NONE means msg was added to the delay queue */ if (rc & LNET_MATCHMD_NONE) { CDEBUG(D_NET, "Delaying %s from %s ptl %d MB %#llx off %d len %d\n", info->mi_opc == LNET_MD_OP_PUT ? "PUT" : "GET", libcfs_id2str(info->mi_id), info->mi_portal, info->mi_mbits, info->mi_roffset, info->mi_rlength); } goto out0; out1: lnet_res_unlock(mtable->mt_cpt); out0: /* EXHAUSTED bit is only meaningful for internal functions */ return rc & ~LNET_MATCHMD_EXHAUSTED; } void lnet_ptl_detach_md(lnet_me_t *me, lnet_libmd_t *md) { LASSERT(me->me_md == md && md->md_me == me); me->me_md = NULL; md->md_me = NULL; } /* called with lnet_res_lock held */ void lnet_ptl_attach_md(lnet_me_t *me, lnet_libmd_t *md, struct list_head *matches, struct list_head *drops) { struct lnet_portal *ptl = the_lnet.ln_portals[me->me_portal]; struct lnet_match_table *mtable; struct list_head *head; lnet_msg_t *tmp; lnet_msg_t *msg; int exhausted = 0; int cpt; LASSERT(!md->md_refcount); /* a brand new MD */ me->me_md = md; md->md_me = me; cpt = lnet_cpt_of_cookie(md->md_lh.lh_cookie); mtable = ptl->ptl_mtables[cpt]; if (list_empty(&ptl->ptl_msg_stealing) && list_empty(&ptl->ptl_msg_delayed) && !lnet_mt_test_exhausted(mtable, me->me_pos)) return; lnet_ptl_lock(ptl); head = &ptl->ptl_msg_stealing; again: list_for_each_entry_safe(msg, tmp, head, msg_list) { struct lnet_match_info info; struct lnet_hdr *hdr; int rc; LASSERT(msg->msg_rx_delayed || head == &ptl->ptl_msg_stealing); hdr = &msg->msg_hdr; info.mi_id.nid = hdr->src_nid; info.mi_id.pid = hdr->src_pid; info.mi_opc = LNET_MD_OP_PUT; info.mi_portal = hdr->msg.put.ptl_index; info.mi_rlength = hdr->payload_length; info.mi_roffset = hdr->msg.put.offset; info.mi_mbits = hdr->msg.put.match_bits; rc = lnet_try_match_md(md, &info, msg); exhausted = (rc & LNET_MATCHMD_EXHAUSTED); if (rc & LNET_MATCHMD_NONE) { if (exhausted) break; continue; } /* Hurrah! This _is_ a match */ LASSERT(rc & LNET_MATCHMD_FINISH); list_del_init(&msg->msg_list); if (head == &ptl->ptl_msg_stealing) { if (exhausted) break; /* stealing thread will handle the message */ continue; } if (rc & LNET_MATCHMD_OK) { list_add_tail(&msg->msg_list, matches); CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d match %llu offset %d length %d.\n", libcfs_id2str(info.mi_id), info.mi_portal, info.mi_mbits, info.mi_roffset, info.mi_rlength); } else { list_add_tail(&msg->msg_list, drops); } if (exhausted) break; } if (!exhausted && head == &ptl->ptl_msg_stealing) { head = &ptl->ptl_msg_delayed; goto again; } if (lnet_ptl_is_wildcard(ptl) && !exhausted) { lnet_mt_set_exhausted(mtable, me->me_pos, 0); if (!mtable->mt_enabled) lnet_ptl_enable_mt(ptl, cpt); } lnet_ptl_unlock(ptl); } static void lnet_ptl_cleanup(struct lnet_portal *ptl) { struct lnet_match_table *mtable; int i; if (!ptl->ptl_mtables) /* uninitialized portal */ return; LASSERT(list_empty(&ptl->ptl_msg_delayed)); LASSERT(list_empty(&ptl->ptl_msg_stealing)); cfs_percpt_for_each(mtable, i, ptl->ptl_mtables) { struct list_head *mhash; lnet_me_t *me; int j; if (!mtable->mt_mhash) /* uninitialized match-table */ continue; mhash = mtable->mt_mhash; /* cleanup ME */ for (j = 0; j < LNET_MT_HASH_SIZE + 1; j++) { while (!list_empty(&mhash[j])) { me = list_entry(mhash[j].next, lnet_me_t, me_list); CERROR("Active ME %p on exit\n", me); list_del(&me->me_list); lnet_me_free(me); } } /* the extra entry is for MEs with ignore bits */ LIBCFS_FREE(mhash, sizeof(*mhash) * (LNET_MT_HASH_SIZE + 1)); } cfs_percpt_free(ptl->ptl_mtables); ptl->ptl_mtables = NULL; } static int lnet_ptl_setup(struct lnet_portal *ptl, int index) { struct lnet_match_table *mtable; struct list_head *mhash; int i; int j; ptl->ptl_mtables = cfs_percpt_alloc(lnet_cpt_table(), sizeof(struct lnet_match_table)); if (!ptl->ptl_mtables) { CERROR("Failed to create match table for portal %d\n", index); return -ENOMEM; } ptl->ptl_index = index; INIT_LIST_HEAD(&ptl->ptl_msg_delayed); INIT_LIST_HEAD(&ptl->ptl_msg_stealing); spin_lock_init(&ptl->ptl_lock); cfs_percpt_for_each(mtable, i, ptl->ptl_mtables) { /* the extra entry is for MEs with ignore bits */ LIBCFS_CPT_ALLOC(mhash, lnet_cpt_table(), i, sizeof(*mhash) * (LNET_MT_HASH_SIZE + 1)); if (!mhash) { CERROR("Failed to create match hash for portal %d\n", index); goto failed; } memset(&mtable->mt_exhausted[0], -1, sizeof(mtable->mt_exhausted[0]) * LNET_MT_EXHAUSTED_BMAP); mtable->mt_mhash = mhash; for (j = 0; j < LNET_MT_HASH_SIZE + 1; j++) INIT_LIST_HEAD(&mhash[j]); mtable->mt_portal = index; mtable->mt_cpt = i; } return 0; failed: lnet_ptl_cleanup(ptl); return -ENOMEM; } void lnet_portals_destroy(void) { int i; if (!the_lnet.ln_portals) return; for (i = 0; i < the_lnet.ln_nportals; i++) lnet_ptl_cleanup(the_lnet.ln_portals[i]); cfs_array_free(the_lnet.ln_portals); the_lnet.ln_portals = NULL; } int lnet_portals_create(void) { int size; int i; size = offsetof(struct lnet_portal, ptl_mt_maps[LNET_CPT_NUMBER]); the_lnet.ln_nportals = MAX_PORTALS; the_lnet.ln_portals = cfs_array_alloc(the_lnet.ln_nportals, size); if (!the_lnet.ln_portals) { CERROR("Failed to allocate portals table\n"); return -ENOMEM; } for (i = 0; i < the_lnet.ln_nportals; i++) { if (lnet_ptl_setup(the_lnet.ln_portals[i], i)) { lnet_portals_destroy(); return -ENOMEM; } } return 0; } /** * Turn on the lazy portal attribute. Use with caution! * * This portal attribute only affects incoming PUT requests to the portal, * and is off by default. By default, if there's no matching MD for an * incoming PUT request, it is simply dropped. With the lazy attribute on, * such requests are queued indefinitely until either a matching MD is * posted to the portal or the lazy attribute is turned off. * * It would prevent dropped requests, however it should be regarded as the * last line of defense - i.e. users must keep a close watch on active * buffers on a lazy portal and once it becomes too low post more buffers as * soon as possible. This is because delayed requests usually have detrimental * effects on underlying network connections. A few delayed requests often * suffice to bring an underlying connection to a complete halt, due to flow * control mechanisms. * * There's also a DOS attack risk. If users don't post match-all MDs on a * lazy portal, a malicious peer can easily stop a service by sending some * PUT requests with match bits that won't match any MD. A routed server is * especially vulnerable since the connections to its neighbor routers are * shared among all clients. * * \param portal Index of the portal to enable the lazy attribute on. * * \retval 0 On success. * \retval -EINVAL If \a portal is not a valid index. */ int LNetSetLazyPortal(int portal) { struct lnet_portal *ptl; if (portal < 0 || portal >= the_lnet.ln_nportals) return -EINVAL; CDEBUG(D_NET, "Setting portal %d lazy\n", portal); ptl = the_lnet.ln_portals[portal]; lnet_res_lock(LNET_LOCK_EX); lnet_ptl_lock(ptl); lnet_ptl_setopt(ptl, LNET_PTL_LAZY); lnet_ptl_unlock(ptl); lnet_res_unlock(LNET_LOCK_EX); return 0; } EXPORT_SYMBOL(LNetSetLazyPortal); int lnet_clear_lazy_portal(struct lnet_ni *ni, int portal, char *reason) { struct lnet_portal *ptl; LIST_HEAD(zombies); if (portal < 0 || portal >= the_lnet.ln_nportals) return -EINVAL; ptl = the_lnet.ln_portals[portal]; lnet_res_lock(LNET_LOCK_EX); lnet_ptl_lock(ptl); if (!lnet_ptl_is_lazy(ptl)) { lnet_ptl_unlock(ptl); lnet_res_unlock(LNET_LOCK_EX); return 0; } if (ni) { struct lnet_msg *msg, *tmp; /* grab all messages which are on the NI passed in */ list_for_each_entry_safe(msg, tmp, &ptl->ptl_msg_delayed, msg_list) { if (msg->msg_rxpeer->lp_ni == ni) list_move(&msg->msg_list, &zombies); } } else { if (the_lnet.ln_shutdown) CWARN("Active lazy portal %d on exit\n", portal); else CDEBUG(D_NET, "clearing portal %d lazy\n", portal); /* grab all the blocked messages atomically */ list_splice_init(&ptl->ptl_msg_delayed, &zombies); lnet_ptl_unsetopt(ptl, LNET_PTL_LAZY); } lnet_ptl_unlock(ptl); lnet_res_unlock(LNET_LOCK_EX); lnet_drop_delayed_msg_list(&zombies, reason); return 0; } /** * Turn off the lazy portal attribute. Delayed requests on the portal, * if any, will be all dropped when this function returns. * * \param portal Index of the portal to disable the lazy attribute on. * * \retval 0 On success. * \retval -EINVAL If \a portal is not a valid index. */ int LNetClearLazyPortal(int portal) { return lnet_clear_lazy_portal(NULL, portal, "Clearing lazy portal attr"); } EXPORT_SYMBOL(LNetClearLazyPortal);
229975.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE195_Signed_To_Unsigned_Conversion__fscanf_strncpy_53c.c Label Definition File: CWE195_Signed_To_Unsigned_Conversion.label.xml Template File: sources-sink-53c.tmpl.c */ /* * @description * CWE: 195 Signed to Unsigned Conversion * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Positive integer * Sink: strncpy * BadSink : Copy strings using strncpy() with the length of data * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files * * */ #include "std_testcase.h" /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD /* bad function declaration */ void CWE195_Signed_To_Unsigned_Conversion__fscanf_strncpy_53d_bad_sink(int data); void CWE195_Signed_To_Unsigned_Conversion__fscanf_strncpy_53c_bad_sink(int data) { CWE195_Signed_To_Unsigned_Conversion__fscanf_strncpy_53d_bad_sink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declaration */ void CWE195_Signed_To_Unsigned_Conversion__fscanf_strncpy_53d_goodG2B_sink(int data); /* goodG2B uses the GoodSource with the BadSink */ void CWE195_Signed_To_Unsigned_Conversion__fscanf_strncpy_53c_goodG2B_sink(int data) { CWE195_Signed_To_Unsigned_Conversion__fscanf_strncpy_53d_goodG2B_sink(data); } #endif /* OMITGOOD */
286137.c
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : usb_device.c * @version : v2.0_Cube * @brief : This file implements the USB Device ****************************************************************************** * @attention * * Copyright (c) 2022 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "usb_device.h" #include "usbd_core.h" #include "usbd_desc.h" #include "usbd_cdc.h" #include "usbd_cdc_if.h" /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ /* USER CODE END PV */ /* USER CODE BEGIN PFP */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE END PFP */ /* USB Device Core handle declaration. */ USBD_HandleTypeDef hUsbDeviceFS; /* * -- Insert your variables declaration here -- */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* * -- Insert your external function declaration here -- */ /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /** * Init USB device Library, add supported class and start the library * @retval None */ void MX_USB_DEVICE_Init(void) { /* USER CODE BEGIN USB_DEVICE_Init_PreTreatment */ /* USER CODE END USB_DEVICE_Init_PreTreatment */ /* Init Device Library, add supported class and start the library. */ if (USBD_Init(&hUsbDeviceFS, &FS_Desc, DEVICE_FS) != USBD_OK) { Error_Handler(); } if (USBD_RegisterClass(&hUsbDeviceFS, &USBD_CDC) != USBD_OK) { Error_Handler(); } if (USBD_CDC_RegisterInterface(&hUsbDeviceFS, &USBD_Interface_fops_FS) != USBD_OK) { Error_Handler(); } if (USBD_Start(&hUsbDeviceFS) != USBD_OK) { Error_Handler(); } /* USER CODE BEGIN USB_DEVICE_Init_PostTreatment */ /* USER CODE END USB_DEVICE_Init_PostTreatment */ } /** * @} */ /** * @} */
9854.c
/* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include <stdio.h> #include "f2c.h" /* Common Block Declarations */ struct sccsttcal0_1_ { char sccsid[80]; }; #define sccsttcal0_1 (*(struct sccsttcal0_1_ *) &sccsttcal0_) /* Initialized data */ struct { char e_1[80]; } sccsttcal0_ = { {'@', '(', '#', ')', 't', 't', 'c', 'a', 'l', '0', '.', 'f', '\t', '4', '4', '.', '2', '\t', '1', '0', '/', '3', '1', '/', '9', '1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '} }; /* Table of constant values */ static real c_b2 = (float)-1.; /* NAME */ /* ttcal0 -- Compute travel times and their partial derivatives. */ /* FILE */ /* ttcal0.f */ /* SYNOPSIS */ /* Compute travel times and their partial derivatives for a fixed */ /* hypocenter. */ /* DESCRIPTION */ /* Subroutine. Travel times and partials are determined via inter/ */ /* extrapolation of pre-calculated travel-time curves. A point in a */ /* hole is rejected. */ /* ---- On entry ---- */ /* radius: Radius of Earth (km) */ /* delta: Distance from the event to the station (deg) */ /* azi: Forward-azimuth from event to station (deg) */ /* zfoc: Event focal depth (km below sea level) */ /* maxtbd: Maximum dimension of i'th position in tbd(), tbtt() */ /* maxtbz: Maximum dimension of j'th position in tbz(), tbtt() */ /* ntbd: Number of distance samples in tables */ /* ntbz: Number of depth samples in tables */ /* tbd(i): Distance samples for tables (deg) */ /* tbz(j): Depth samples in tables (km) */ /* tbtt(i,j): Travel-time tables (sec) */ /* ---- On return ---- */ /* dcalx: Calculated slownesses (sec/deg) */ /* atx(4): Partial derivatives (sec/km/deg) */ /* iterr: Error code for n'th observation */ /* = 0, No problem, normal interpolation */ /* = 11, Distance-depth point (x0,z0) in hole of T-T curve */ /* = 12, x0 < x(1) */ /* = 13, x0 > x(max) */ /* = 14, z0 < z(1) */ /* = 15, z0 > z(max) */ /* = 16, x0 < x(1) and z0 < z(1) */ /* = 17, x0 > x(max) and z0 < z(1) */ /* = 18, x0 < x(1) and z0 > z(max) */ /* = 19, x0 > x(max) and z0 > z(max) */ /* [NOTE: If any of these codes are negative (e.g., iderr = -17), */ /* then, the datum was used to compute the event location] */ /* ---- Subroutines called ---- */ /* From libinterp */ /* brack: Bracket travel-time data via bisection */ /* holint2: Quadratic interpolation function */ /* DIAGNOSTICS */ /* Currently assumes a constant radius Earth (i.e., it ignores */ /* ellipicity of the Earth. */ /* NOTES */ /* Future plans include dealing with ellipicity and higher-order */ /* derivatives. */ /* SEE ALSO */ /* Subroutines azcal0, and slocal0 are parallel routines for computing */ /* azimuthal and slowness partial derivatives, respectively. */ /* AUTHOR */ /* Steve Bratt, December 1988. */ /* Subroutine */ int ttcal0_(phase_id__, zfoc, radius, delta, azi, maxtbd, maxtbz, ntbd, ntbz, tbd, tbz, tbtt, dcalx, atx, iterr) integer *phase_id__; real *zfoc, *radius, *delta, *azi; integer *maxtbd, *maxtbz, *ntbd, *ntbz; real *tbd, *tbz, *tbtt, *dcalx; doublereal *atx; integer *iterr; { /* System generated locals */ integer tbtt_dim1, tbtt_offset, i__1, i__2; /* Builtin functions */ double sin(), cos(); /* Local variables */ static real dtdz; static doublereal azir; static integer iext, jext; extern /* Subroutine */ int brack_(); static integer ileft, do_extrap__; static real dtddel; static integer jz, nz; static doublereal cosazi; static real dcross; static doublereal sinazi; extern /* Subroutine */ int holint2_(); static doublereal pd12; static integer ibad; /* K.S. 1-Dec-97, changed 'undefined' to 'none' */ /* ---- Parameter declaration ---- */ /* Convert radians to degrees */ /* Max. number of permissable parameters */ /* ---- On entry ---- */ /* ---- On return ---- */ /* ---- Internal variables ---- */ /* Permit extrapolation */ /* Parameter adjustments */ --tbd; tbtt_dim1 = *maxtbd; tbtt_offset = 1 + tbtt_dim1 * 1; tbtt -= tbtt_offset; --tbz; --atx; /* Function Body */ do_extrap__ = 0; /* Find relevant range of table depths */ brack_(ntbz, &tbz[1], zfoc, &ileft); /* Computing MAX */ i__1 = 1, i__2 = ileft - 1; jz = max(i__1,i__2); /* Computing MIN */ i__1 = *ntbz, i__2 = ileft + 2; nz = min(i__1,i__2) - jz + 1; /* Subroutine HOLIN2 performs bivariate interpolation */ i__1 = *phase_id__ - 1; holint2_(&i__1, &do_extrap__, ntbd, &nz, &tbd[1], &tbz[jz], &tbtt[jz * tbtt_dim1 + 1], maxtbd, &c_b2, delta, zfoc, dcalx, &dtddel, &dtdz, &dcross, &iext, &jext, &ibad); /* Interpolate point in hole of curve -- Value no good */ if (ibad != 0) { *iterr = 11; /* Interpolate point less than first distance point in curve */ } else if (iext < 0 && jext == 0) { *iterr = 12; /* Interpolate point greater than last distance point in curve */ } else if (iext > 0 && jext == 0) { *iterr = 13; /* Interpolate point less than first depth point in curve */ } else if (iext == 0 && jext < 0) { *iterr = 14; /* Interpolate point greater than last depth point in curve */ } else if (iext == 0 && jext > 0) { *iterr = 15; /* Interpolate point less than first distance point in curve and */ /* less than first depth point in curve */ } else if (iext < 0 && jext < 0) { *iterr = 16; /* Interpolate point greater than last distance point in curve and */ /* less than first depth point in curve */ } else if (iext > 0 && jext < 0) { *iterr = 17; /* Interpolate point less than first distance point in curve and */ /* greater than first depth point in curve */ } else if (iext < 0 && jext > 0) { *iterr = 18; /* Interpolate point greater than last distance point in curve and */ /* greater than first depth point in curve */ } else if (iext > 0 && jext > 0) { *iterr = 19; /* Reset error code to 0 if valid table interpolation */ } else { *iterr = 0; } /* Compute partial derivatives if point is not in a hole. The local */ /* cartesian coordinate system is such that, */ if (ibad == 0) { azir = *azi * (float).017453293; sinazi = sin(azir); cosazi = cos(azir); pd12 = dtddel / ((*radius - *zfoc) * (float).017453293); /* Axis 1 */ atx[1] = (float)1.; /* Axis 2 points east */ atx[2] = -pd12 * sinazi; /* Axis 3 points north */ atx[3] = -pd12 * cosazi; /* Axis 4 points up */ atx[4] = -dtdz; } return 0; } /* ttcal0_ */ /* NAME */ /* ttcal1 -- Compute travel times and their partial derivatives. */ /* FILE */ /* ttcal1.f */ /* SYNOPSIS */ /* Compute travel times and their partial derivatives for a fixed */ /* hypocenter. */ /* DESCRIPTION */ /* Subroutine. Travel times and partials are determined via inter/ */ /* extrapolation of pre-calculated travel-time curves. A point in a */ /* hole is rejected. */ /* ---- On entry ---- */ /* radius: Radius of Earth (km) */ /* delta: Distance from the event to the station (deg) */ /* azi: Forward-azimuth from event to station (deg) */ /* zfoc: Event focal depth (km below sea level) */ /* maxtbd: Maximum dimension of i'th position in tbd(), tbtt() */ /* maxtbz: Maximum dimension of j'th position in tbz(), tbtt() */ /* ntbd: Number of distance samples in tables */ /* ntbz: Number of depth samples in tables */ /* tbd(i): Distance samples for tables (deg) */ /* tbz(j): Depth samples in tables (km) */ /* tbtt(i,j): Travel-time tables (sec) */ /* ---- On return ---- */ /* dcalx: Calculated slownesses (sec/deg) */ /* atx(4): Partial derivatives (sec/km/deg) */ /* iterr: Error code for n'th observation */ /* = 0, No problem, normal interpolation */ /* = 11, Distance-depth point (x0,z0) in hole of T-T curve */ /* = 12, x0 < x(1) */ /* = 13, x0 > x(max) */ /* = 14, z0 < z(1) */ /* = 15, z0 > z(max) */ /* = 16, x0 < x(1) and z0 < z(1) */ /* = 17, x0 > x(max) and z0 < z(1) */ /* = 18, x0 < x(1) and z0 > z(max) */ /* = 19, x0 > x(max) and z0 > z(max) */ /* [NOTE: If any of these codes are negative (e.g., iderr = -17), */ /* then, the datum was used to compute the event location] */ /* ---- Subroutines called ---- */ /* From libinterp */ /* brack: Bracket travel-time data via bisection */ /* holin2: Quadratic interpolation function */ /* DIAGNOSTICS */ /* Currently assumes a constant radius Earth (i.e., it ignores */ /* ellipicity of the Earth. */ /* NOTES */ /* Future plans include dealing with ellipicity and higher-order */ /* derivatives. */ /* SEE ALSO */ /* Subroutines azcal0, and slocal0 are parallel routines for computing */ /* azimuthal and slowness partial derivatives, respectively. */ /* AUTHOR */ /* Steve Bratt, December 1988. */ /* Subroutine */ int ttcal1_(zfoc, radius, delta, azi, maxtbd, maxtbz, ntbd, ntbz, tbd, tbz, tbtt, dcalx, atx, iterr) real *zfoc, *radius, *delta, *azi; integer *maxtbd, *maxtbz, *ntbd, *ntbz; real *tbd, *tbz, *tbtt, *dcalx; doublereal *atx; integer *iterr; { /* System generated locals */ integer tbtt_dim1, tbtt_offset, i__1, i__2; /* Builtin functions */ double sin(), cos(); /* Local variables */ static real dtdz; static doublereal azir; static integer iext, jext; extern /* Subroutine */ int brack_(); static integer ileft; extern /* Subroutine */ int holin2_(); static real dtddel; static integer jz, nz; static doublereal cosazi; static real dcross; static doublereal sinazi, pd12; static integer ibad; /* ---- Parameter declaration ---- */ /* K.S. 1-Dec-97, changed 'undefined' to 'none' */ /* Convert radians to degrees */ /* Max. number of permissable parameters */ /* ---- On entry ---- */ /* ---- On return ---- */ /* ---- Internal variables ---- */ /* Find relevant range of table depths */ /* Parameter adjustments */ --tbd; tbtt_dim1 = *maxtbd; tbtt_offset = 1 + tbtt_dim1 * 1; tbtt -= tbtt_offset; --tbz; --atx; /* Function Body */ brack_(ntbz, &tbz[1], zfoc, &ileft); /* Computing MAX */ i__1 = 1, i__2 = ileft - 1; jz = max(i__1,i__2); /* Computing MIN */ i__1 = *ntbz, i__2 = ileft + 2; nz = min(i__1,i__2) - jz + 1; /* Subroutine HOLIN2 performs bivariate interpolation */ holin2_(ntbd, &nz, &tbd[1], &tbz[jz], &tbtt[jz * tbtt_dim1 + 1], maxtbd, & c_b2, delta, zfoc, dcalx, &dtddel, &dtdz, &dcross, &iext, &jext, & ibad); /* Interpolate point in hole of curve -- Value no good */ if (ibad != 0) { *iterr = 11; /* Interpolate point less than first distance point in curve */ } else if (iext < 0 && jext == 0) { *iterr = 12; /* Interpolate point greater than last distance point in curve */ } else if (iext > 0 && jext == 0) { *iterr = 13; /* Interpolate point less than first depth point in curve */ } else if (iext == 0 && jext < 0) { *iterr = 14; /* Interpolate point greater than last depth point in curve */ } else if (iext == 0 && jext > 0) { *iterr = 15; /* Interpolate point less than first distance point in curve and */ /* less than first depth point in curve */ } else if (iext < 0 && jext < 0) { *iterr = 16; /* Interpolate point greater than last distance point in curve and */ /* less than first depth point in curve */ } else if (iext > 0 && jext < 0) { *iterr = 17; /* Interpolate point less than first distance point in curve and */ /* greater than first depth point in curve */ } else if (iext < 0 && jext > 0) { *iterr = 18; /* Interpolate point greater than last distance point in curve and */ /* greater than first depth point in curve */ } else if (iext > 0 && jext > 0) { *iterr = 19; /* Reset error code to 0 if valid table interpolation */ } else { *iterr = 0; } /* Compute partial derivatives if point is not in a hole. The local */ /* cartesian coordinate system is such that, */ if (ibad == 0) { azir = *azi * (float).017453293; sinazi = sin(azir); cosazi = cos(azir); pd12 = dtddel / ((*radius - *zfoc) * (float).017453293); /* Axis 1 */ atx[1] = (float)1.; /* Axis 2 points east */ atx[2] = -pd12 * sinazi; /* Axis 3 points north */ atx[3] = -pd12 * cosazi; /* Axis 4 points up */ atx[4] = -dtdz; } return 0; } /* ttcal1_ */
784439.c
/****************************************************************************** * drivers/wireless/spirit/lib/spirit_aes.c * Configuration and management of SPIRIT AES Engine. * * Copyright(c) 2015 STMicroelectronics * Author: VMA division - AMS * Version 3.2.2 08-July-2015 * * Adapted for NuttX by: * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ /****************************************************************************** * Included Files ******************************************************************************/ #include <assert.h> #include "spirit_aes.h" #include "spirit_spi.h" /****************************************************************************** * Public Functions ******************************************************************************/ /****************************************************************************** * Name: spirit_aes_enable * * Description: * Enables or Disables the AES engine. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * newstate new state for AES engine. * This parameter can be: S_ENABLE or S_DISABLE. * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_enable(FAR struct spirit_library_s *spirit, enum spirit_functional_state_e newstate) { uint8_t regval = 0; int ret; /* Check the parameters */ DEBUGASSERT(IS_SPIRIT_FUNCTIONAL_STATE(newstate)); /* Modifies the register value */ ret = spirit_reg_read(spirit, ANA_FUNC_CONF0_BASE, &regval, 1); if (ret >= 0) { if (newstate == S_ENABLE) { regval |= AES_MASK; } else { regval &= ~AES_MASK; } /* Write to the ANA_FUNC_CONF0 register to enable or disable the AES * engine */ ret = spirit_reg_write(spirit, ANA_FUNC_CONF0_BASE, &regval, 1); } return ret; } /****************************************************************************** * Name: * * Description: * Writes the data to encrypt or decrypt, or the encryption key for the * derive decryption key operation into the AES_DATA_IN registers. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * buffer - Pointer to the user data buffer. The first byte of the array * must be the MSB byte and it will be put in the AES_DATA_IN[0] * register, while the last one must be the LSB and it will be * put in the AES_DATA_IN[buflen-1] register. If data to write * are less than 16 bytes the remaining AES_DATA_IN registers * will be filled with bytes equal to 0. * buflen - Length of data in bytes. * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_write_datain(FAR struct spirit_library_s *spirit, FAR const uint8_t *buffer, uint8_t buflen) { uint8_t datain[16]; uint8_t i; /* Verifies that there are no more than 16 bytes */ (buflen > 16) ? (buflen = 16) : buflen; /* Fill the datain with the data buffer, using padding */ for (i = 0; i < 16; i++) { if (i < (16 - buflen)) { datain[i] = 0; } else { datain[i] = buffer[15 - i]; } } /* Writes the AES_DATA_IN registers */ return spirit_reg_write(spirit, AES_DATA_IN_15_BASE, datain, 16); } /****************************************************************************** * Name: * * Description: * Returns the encrypted or decrypted data or the decription key from the * AES_DATA_OUT register. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * buffer - pointer to the user data buffer. The AES_DATA_OUT[0] * register value will be put as first element of the buffer * (MSB), while the AES_DAT_OUT[buflen-1] register value will be * put as last element of the buffer (LSB). * buflen - Length of data to read in bytes. * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_read_dataout(FAR struct spirit_library_s *spirit, FAR uint8_t *buffer, uint8_t buflen) { uint8_t dataout[16]; uint8_t address; int ret; /* Verifies that there are no more than 16 bytes */ if (buflen > 16) { buflen = 16; } /* Evaluates the address of AES_DATA_OUT from which start to read */ address = AES_DATA_OUT_15_BASE + 16 - buflen; /* Reads the exact number of AES_DATA_OUT registers */ ret = spirit_reg_read(spirit, address, dataout, buflen); if (ret >= 0) { int i; /* Copy in the user buffer the read values changing the order */ for (i = buflen - 1; i >= 0; i--) { *buffer++ = dataout[i]; } } return ret; } /****************************************************************************** * Name: spirit_aes_write_key * * Description: * Writes the encryption key into the AES_KEY_IN register. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * key - Pointer to the buffer of 4 words containing the AES key. * The first byte of the buffer must be the most significant byte * AES_KEY_0 of the AES key. The last byte of the buffer must be * the less significant byte AES_KEY_15 of the AES key. * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_write_key(FAR struct spirit_library_s *spirit, FAR const uint8_t *key) { uint8_t tmp[16]; int i; for (i = 0; i < 16; i++) { tmp[15 - i] = key[i]; } /* Write to the AES_DATA_IN registers */ return spirit_reg_write(spirit, AES_KEY_IN_15_BASE, tmp, 16); } /****************************************************************************** * Name: * * Description: * Returns the encryption/decryption key from the AES_KEY_IN register. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * key pointer to the buffer of 4 words (16 bytes) containing the AES key. * The first byte of the buffer shall be the most significant byte AES_KEY_0 of the AES key. * The last byte of the buffer shall be the less significant byte AES_KEY_15 of the AES key. * This parameter is an uint8_t*. * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_read_key(FAR struct spirit_library_s *spirit, FAR uint8_t *key) { uint8_t tmp[16]; int ret; int i; /* Reads the AES_DATA_IN registers */ ret = spirit_reg_read(spirit, AES_KEY_IN_15_BASE, tmp, 16); if (ret >= 0) { for (i = 0; i < 16; i++) { key[i] = tmp[15 - i]; } } return ret; } /****************************************************************************** * Name: spirit_aes_enc2deckey * * Description: * Derives the decryption key from a given encryption key. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_enc2deckey(FAR struct spirit_library_s *spirit) { /* Sends the COMMAND_AES_KEY command */ return spirit_command(spirit, COMMAND_AES_KEY); } /****************************************************************************** * Name: spirit_aes_encrypt * * Description: * Executes the encryption operation. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_encrypt(FAR struct spirit_library_s *spirit) { /* Sends the COMMAND_AES_ENC command */ return spirit_command(spirit, COMMAND_AES_ENC); } /****************************************************************************** * Name: * * Description: * Executes the decryption operation. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_decrypt(FAR struct spirit_library_s *spirit) { /* Sends the COMMAND_AES_DEC command */ return spirit_command(spirit, COMMAND_AES_DEC); } /****************************************************************************** * Name: spirit_aes_derivekey_decrypt * * Description: * Executes the key derivation and the decryption operation. * * Input Parameters: * spirit - Reference to a Spirit library state structure instance * * Returned Value: * Zero (OK) on success; a negated errno value on any failure. * ******************************************************************************/ int spirit_aes_derivekey_decrypt(FAR struct spirit_library_s *spirit) { /* Sends the COMMAND_AES_KEY_DEC command */ return spirit_command(spirit, COMMAND_AES_KEY_DEC); }
75793.c
/*========================================================================= Program: Visualization Toolkit Module: vtkWrapPythonOverload.c Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* When wrapping overloaded C++ methods, it is necessary to provide hints so that Python can choose which overload to call (see vtkPythonOverload.cxx for the code that is used to do this). Where possible, overloads are resolved based on the number of arguments that are passed. When this isn't possible, the overloads must be resolved based on argument types. So, for each overload, we store the parameter types as a string. The "parameter type" string can start with one of the following: - (hyphen) marks a method as an explicit constructor @ placeholder for "self" in a method (i.e. method is not static) For each parameter, one of the following codes is used: q bool c char b signed char B unsigned char h signed short H unsigned short i int I unsigned int l long L unsigned long k long long K unsigned long long f float d double v void * z char * s string u unicode F callable object E enum type O python object Q Qt object V VTK object W VTK special type P Pointer to numeric type A Multi-dimensional array of numeric type | marks the end of required parameters, following parameters are optional If the parameter is E, O, Q, V, W, then a type name must follow the type codes. The type name must be preceded by '*' if the type is a non-const reference or a pointer. For example, func(vtkArray *, vtkVariant &, int) -> "VWi *vtkArray &vtkVariant" If the parameter is P, then the type of the array or pointer must follow the type codes. For example, func(int *p, double a[10]) -> "PP *i *d" If the parameter is A, then both the type and all dimensions after the first dimension must be provided: func(double a[3][4]) -> "A *d[4]" */ #include "vtkWrapPythonOverload.h" #include "vtkWrapPythonMethod.h" #include "vtkWrapPythonTemplate.h" #include "vtkWrap.h" #include "vtkWrapText.h" /* required for VTK_USE_64BIT_IDS */ #include "vtkConfigure.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /* -------------------------------------------------------------------- */ /* prototypes for utility methods */ /* create a parameter format char for the give type */ static char vtkWrapPython_FormatChar( unsigned int argtype); /* create a string for checking arguments against available signatures */ static char *vtkWrapPython_ArgCheckString( ClassInfo *data, FunctionInfo *currentFunction); /* -------------------------------------------------------------------- */ /* Get the python format char for the give type, after retrieving the * base type from the type */ static char vtkWrapPython_FormatChar(unsigned int argtype) { char typeChar = 'O'; switch ( (argtype & VTK_PARSE_BASE_TYPE) ) { case VTK_PARSE_FLOAT: typeChar = 'f'; break; case VTK_PARSE_DOUBLE: typeChar = 'd'; break; case VTK_PARSE_UNSIGNED_INT: typeChar = 'I'; break; case VTK_PARSE_INT: typeChar = 'i'; break; case VTK_PARSE_UNSIGNED_SHORT: typeChar = 'H'; break; case VTK_PARSE_SHORT: typeChar = 'h'; break; case VTK_PARSE_UNSIGNED_LONG: typeChar = 'L'; break; case VTK_PARSE_LONG: typeChar = 'l'; break; case VTK_PARSE_UNSIGNED_ID_TYPE: #ifdef VTK_USE_64BIT_IDS typeChar = 'K'; #else typeChar = 'I'; #endif case VTK_PARSE_ID_TYPE: #ifdef VTK_USE_64BIT_IDS typeChar = 'k'; #else typeChar = 'i'; #endif break; case VTK_PARSE_SIZE_T: case VTK_PARSE_UNSIGNED_LONG_LONG: case VTK_PARSE_UNSIGNED___INT64: typeChar = 'K'; break; case VTK_PARSE_SSIZE_T: case VTK_PARSE_LONG_LONG: case VTK_PARSE___INT64: typeChar = 'k'; break; case VTK_PARSE_SIGNED_CHAR: typeChar = 'b'; break; case VTK_PARSE_CHAR: typeChar = 'c'; break; case VTK_PARSE_UNSIGNED_CHAR: typeChar = 'B'; break; case VTK_PARSE_VOID: typeChar = 'v'; break; case VTK_PARSE_BOOL: typeChar = 'q'; break; case VTK_PARSE_STRING: typeChar = 's'; break; case VTK_PARSE_UNICODE_STRING: typeChar = 'u'; break; } return typeChar; } /* -------------------------------------------------------------------- */ /* Create a string to describe the signature of a method. */ static char *vtkWrapPython_ArgCheckString( ClassInfo *data, FunctionInfo *currentFunction) { static char result[2048]; /* max literal string length */ char classname[1024]; size_t currPos = 0; size_t endPos; ValueInfo *arg; unsigned int argtype; int i, j, k; int totalArgs, requiredArgs; char c = '\0'; totalArgs = vtkWrap_CountWrappedParameters(currentFunction); requiredArgs = vtkWrap_CountRequiredArguments(currentFunction); if (currentFunction->IsExplicit) { /* used to mark constructors as 'explicit' */ result[currPos++] = '-'; } /* placeholder for 'self' in method calls */ if (!currentFunction->IsStatic) { result[currPos++] = '@'; } /* position for insertion after format chars */ endPos = currPos + totalArgs; if (totalArgs > requiredArgs) { /* add one for the "|" that marks the end of required args */ endPos++; } /* create a format character for each argument */ for (i = 0; i < totalArgs; i++) { arg = currentFunction->Parameters[i]; argtype = (arg->Type & VTK_PARSE_UNQUALIFIED_TYPE); if (i == requiredArgs) { /* make all following arguments optional */ result[currPos++] = '|'; } /* will store the classname for objects */ classname[0] = '\0'; if (vtkWrap_IsEnumMember(data, arg)) { c = 'E'; sprintf(classname, "%.200s.%.200s", data->Name, arg->Class); } else if (arg->IsEnum) { c = 'E'; vtkWrapText_PythonName(arg->Class, classname); } else if (vtkWrap_IsPythonObject(arg)) { c = 'O'; vtkWrapText_PythonName(arg->Class, classname); } else if (vtkWrap_IsVTKObject(arg)) { c = 'V'; vtkWrapText_PythonName(arg->Class, classname); } else if (vtkWrap_IsSpecialObject(arg)) { c = 'W'; vtkWrapText_PythonName(arg->Class, classname); } else if (vtkWrap_IsQtEnum(arg) || vtkWrap_IsQtObject(arg)) { c = 'Q'; vtkWrapText_PythonName(arg->Class, classname); } else if (vtkWrap_IsFunction(arg)) { c = 'F'; } else if (vtkWrap_IsVoidPointer(arg)) { c = 'v'; } else if (vtkWrap_IsString(arg)) { c = 's'; if ((argtype & VTK_PARSE_BASE_TYPE) == VTK_PARSE_UNICODE_STRING) { c = 'u'; } } else if (vtkWrap_IsCharPointer(arg)) { c = 'z'; } else if (vtkWrap_IsNumeric(arg) && vtkWrap_IsScalar(arg)) { c = vtkWrapPython_FormatChar(argtype); } else if (vtkWrap_IsArray(arg) || vtkWrap_IsPODPointer(arg)) { c = 'P'; result[endPos++] = ' '; result[endPos++] = '*'; result[endPos++] = vtkWrapPython_FormatChar(argtype); } else if (vtkWrap_IsNArray(arg)) { c = 'A'; result[endPos++] = ' '; result[endPos++] = '*'; result[endPos++] = vtkWrapPython_FormatChar(argtype); if (vtkWrap_IsNArray(arg)) { for (j = 1; j < arg->NumberOfDimensions; j++) { result[endPos++] = '['; for (k = 0; arg->Dimensions[j][k]; k++) { result[endPos++] = arg->Dimensions[j][k]; } result[endPos++] = ']'; } } } /* add the format char to the string */ result[currPos++] = c; if (classname[0] != '\0') { result[endPos++] = ' '; if ((argtype == VTK_PARSE_OBJECT_REF || argtype == VTK_PARSE_QOBJECT_REF || argtype == VTK_PARSE_UNKNOWN_REF) && (arg->Type & VTK_PARSE_CONST) == 0) { result[endPos++] = '&'; } else if (argtype == VTK_PARSE_OBJECT_PTR || argtype == VTK_PARSE_UNKNOWN_PTR || argtype == VTK_PARSE_QOBJECT_PTR) { result[endPos++] = '*'; } strcpy(&result[endPos], classname); endPos += strlen(classname); } } result[endPos] = '\0'; return result; } /* -------------------------------------------------------------------- */ /* Generate an int array that maps arg counts to overloads. * Each element in the array will either contain the index of the * overload that it maps to, or -1 if it maps to multiple overloads, * or zero if it does not map to any. The length of the array is * returned in "nmax". The value of "overlap" is set to 1 if there * are some arg counts that map to more than one method. */ int *vtkWrapPython_ArgCountToOverloadMap( FunctionInfo **wrappedFunctions, int numberOfWrappedFunctions, int fnum, int is_vtkobject, int *nmax, int *overlap) { static int overloadMap[512]; int totalArgs, requiredArgs; int occ, occCounter; FunctionInfo *theOccurrence; FunctionInfo *theFunc; int mixed_static, any_static; int i; *nmax = 0; *overlap = 0; theFunc = wrappedFunctions[fnum]; any_static = 0; mixed_static = 0; for (i = fnum; i < numberOfWrappedFunctions; i++) { if (wrappedFunctions[i]->Name && strcmp(wrappedFunctions[i]->Name, theFunc->Name) == 0) { if (wrappedFunctions[i]->IsStatic) { any_static = 1; } else if (any_static) { mixed_static = 1; } } } for (i = 0; i < 100; i++) { overloadMap[i] = 0; } occCounter = 0; for (occ = fnum; occ < numberOfWrappedFunctions; occ++) { theOccurrence = wrappedFunctions[occ]; if (theOccurrence->Name == 0 || strcmp(theOccurrence->Name, theFunc->Name) != 0) { continue; } occCounter++; totalArgs = vtkWrap_CountWrappedParameters(theOccurrence); requiredArgs = vtkWrap_CountRequiredArguments(theOccurrence); /* vtkobject calls might have an extra "self" arg in front */ if (mixed_static && is_vtkobject && !theOccurrence->IsStatic) { totalArgs++; } if (totalArgs > *nmax) { *nmax = totalArgs; } for (i = requiredArgs; i <= totalArgs && i < 100; i++) { if (overloadMap[i] == 0) { overloadMap[i] = occCounter; } else { overloadMap[i] = -1; *overlap = 1; } } } return overloadMap; } /* -------------------------------------------------------------------- */ /* output the method table for all overloads of a particular method, * this is also used to write out all constructors for the class */ void vtkWrapPython_OverloadMethodDef( FILE *fp, const char *classname, ClassInfo *data, int *overloadMap, FunctionInfo **wrappedFunctions, int numberOfWrappedFunctions, int fnum, int numberOfOccurrences, int all_legacy) { char occSuffix[8]; int occ, occCounter; FunctionInfo *theOccurrence; FunctionInfo *theFunc; int totalArgs, requiredArgs; int i; int putInTable; theFunc = wrappedFunctions[fnum]; if (all_legacy) { fprintf(fp, "#if !defined(VTK_LEGACY_REMOVE)\n"); } fprintf(fp, "static PyMethodDef Py%s_%s_Methods[] = {\n", classname, theFunc->Name); occCounter = 0; for (occ = fnum; occ < numberOfWrappedFunctions; occ++) { theOccurrence = wrappedFunctions[occ]; if (theOccurrence->Name == 0 || strcmp(theOccurrence->Name, theFunc->Name) != 0) { continue; } occCounter++; totalArgs = vtkWrap_CountWrappedParameters(theOccurrence); requiredArgs = vtkWrap_CountRequiredArguments(theOccurrence); putInTable = 0; /* all conversion constructors must go into the table */ if (vtkWrap_IsConstructor(data, theOccurrence) && requiredArgs <= 1 && totalArgs >= 1 && !theOccurrence->IsExplicit) { putInTable = 1; } /* all methods that overlap with others must go in the table */ for (i = requiredArgs; i <= totalArgs; i++) { if (overloadMap[i] == -1) { putInTable = 1; } } if (!putInTable) { continue; } if (theOccurrence->IsLegacy && !all_legacy) { fprintf(fp, "#if !defined(VTK_LEGACY_REMOVE)\n"); } /* method suffix to distinguish between signatures */ occSuffix[0] = '\0'; if (numberOfOccurrences > 1) { sprintf(occSuffix, "_s%d", occCounter); } fprintf(fp, " {NULL, Py%s_%s%s, METH_VARARGS%s,\n" " \"%s\"},\n", classname, theOccurrence->Name, occSuffix, theOccurrence->IsStatic ? " | METH_STATIC" : "", vtkWrapPython_ArgCheckString(data, theOccurrence)); if (theOccurrence->IsLegacy && !all_legacy) { fprintf(fp, "#endif\n"); } } fprintf(fp, " {NULL, NULL, 0, NULL}\n" "};\n"); if (all_legacy) { fprintf(fp, "#endif\n"); } fprintf(fp, "\n"); } /* -------------------------------------------------------------------- */ /* make a method that will choose which overload to call */ void vtkWrapPython_OverloadMasterMethod( FILE *fp, const char *classname, int *overloadMap, int maxArgs, FunctionInfo **wrappedFunctions, int numberOfWrappedFunctions, int fnum, int is_vtkobject, int all_legacy) { FunctionInfo *currentFunction; FunctionInfo *theOccurrence; int overlap = 0; int occ, occCounter; int i; int foundOne; int any_static = 0; currentFunction = wrappedFunctions[fnum]; for (i = fnum; i < numberOfWrappedFunctions; i++) { if (wrappedFunctions[i]->Name && strcmp(wrappedFunctions[i]->Name, currentFunction->Name) == 0) { if (wrappedFunctions[i]->IsStatic) { any_static = 1; } } } for (i = 0; i <= maxArgs; i++) { if (overloadMap[i] == -1) { overlap = 1; } } if (all_legacy) { fprintf(fp, "#if !defined(VTK_LEGACY_REMOVE)\n"); } fprintf(fp, "static PyObject *\n" "Py%s_%s(PyObject *self, PyObject *args)\n" "{\n", classname, currentFunction->Name); if (overlap) { fprintf(fp, " PyMethodDef *methods = Py%s_%s_Methods;\n", classname, currentFunction->Name); } fprintf(fp, " int nargs = vtkPythonArgs::GetArgCount(%sargs);\n" "\n", ((is_vtkobject && !any_static) ? "self, " : "")); fprintf(fp, " switch(nargs)\n" " {\n"); /* find all occurrences of this method */ occCounter = 0; for (occ = fnum; occ < numberOfWrappedFunctions; occ++) { theOccurrence = wrappedFunctions[occ]; /* is it the same name */ if (theOccurrence->Name && strcmp(currentFunction->Name, theOccurrence->Name) == 0) { occCounter++; foundOne = 0; for (i = 0; i <= maxArgs; i++) { if (overloadMap[i] == occCounter) { if (!foundOne && theOccurrence->IsLegacy && !all_legacy) { fprintf(fp, "#if !defined(VTK_LEGACY_REMOVE)\n"); } fprintf(fp, " case %d:\n", i); foundOne = 1; } } if (foundOne) { fprintf(fp, " return Py%s_%s_s%d(self, args);\n", classname, currentFunction->Name, occCounter); if (theOccurrence->IsLegacy && !all_legacy) { fprintf(fp, "#endif\n"); } } } } if (overlap) { for (i = 0; i <= maxArgs; i++) { if (overloadMap[i] == -1) { fprintf(fp, " case %d:\n", i); } } fprintf(fp, " return vtkPythonOverload::CallMethod(methods, self, args);\n"); } fprintf(fp, " }\n" "\n"); fprintf(fp, " vtkPythonArgs::ArgCountError(nargs, \"%.200s\");\n", currentFunction->Name); fprintf(fp, " return NULL;\n" "}\n" "\n"); if (all_legacy) { fprintf(fp, "#endif\n"); } fprintf(fp,"\n"); }
876555.c
/***************************************************************************//** * \file system_psoc6_cm4.c * \version 2.20 * * The device system-source file. * ******************************************************************************** * \copyright * Copyright 2016-2018, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include <stdbool.h> #include "system_psoc6.h" #include "cy_device.h" #include "cy_device_headers.h" #include "cy_syslib.h" #include "cy_wdt.h" #if !defined(CY_IPC_DEFAULT_CFG_DISABLE) #include "cy_ipc_sema.h" #include "cy_ipc_pipe.h" #include "cy_ipc_drv.h" #if defined(CY_DEVICE_PSOC6ABLE2) #include "cy_flash.h" #endif /* defined(CY_DEVICE_PSOC6ABLE2) */ #endif /* !defined(CY_IPC_DEFAULT_CFG_DISABLE) */ /******************************************************************************* * SystemCoreClockUpdate() *******************************************************************************/ /** Default HFClk frequency in Hz */ #define CY_CLK_HFCLK0_FREQ_HZ_DEFAULT (8000000UL) /** Default PeriClk frequency in Hz */ #define CY_CLK_PERICLK_FREQ_HZ_DEFAULT (4000000UL) /** Default SlowClk system core frequency in Hz */ #define CY_CLK_SYSTEM_FREQ_HZ_DEFAULT (8000000UL) /** IMO frequency in Hz */ #define CY_CLK_IMO_FREQ_HZ (8000000UL) /** HVILO frequency in Hz */ #define CY_CLK_HVILO_FREQ_HZ (32000UL) /** PILO frequency in Hz */ #define CY_CLK_PILO_FREQ_HZ (32768UL) /** WCO frequency in Hz */ #define CY_CLK_WCO_FREQ_HZ (32768UL) /** ALTLF frequency in Hz */ #define CY_CLK_ALTLF_FREQ_HZ (32768UL) /** * Holds the SlowClk (Cortex-M0+) or FastClk (Cortex-M4) system core clock, * which is the system clock frequency supplied to the SysTick timer and the * processor core clock. * This variable implements CMSIS Core global variable. * Refer to the [CMSIS documentation] * (http://www.keil.com/pack/doc/CMSIS/Core/html/group__system__init__gr.html "System and Clock Configuration") * for more details. * This variable can be used by debuggers to query the frequency * of the debug timer or to configure the trace clock speed. * * \attention Compilers must be configured to avoid removing this variable in case * the application program is not using it. Debugging systems require the variable * to be physically present in memory so that it can be examined to configure the debugger. */ uint32_t SystemCoreClock = CY_CLK_SYSTEM_FREQ_HZ_DEFAULT; /** Holds the HFClk0 clock frequency. Updated by \ref SystemCoreClockUpdate(). */ uint32_t cy_Hfclk0FreqHz = CY_CLK_HFCLK0_FREQ_HZ_DEFAULT; /** Holds the PeriClk clock frequency. Updated by \ref SystemCoreClockUpdate(). */ uint32_t cy_PeriClkFreqHz = CY_CLK_PERICLK_FREQ_HZ_DEFAULT; /** Holds the Alternate high frequency clock in Hz. Updated by \ref SystemCoreClockUpdate(). */ #if (defined (CY_IP_MXBLESS) && (CY_IP_MXBLESS == 1UL)) || defined (CY_DOXYGEN) uint32_t cy_BleEcoClockFreqHz = CY_CLK_ALTHF_FREQ_HZ; #endif /* (defined (CY_IP_MXBLESS) && (CY_IP_MXBLESS == 1UL)) || defined (CY_DOXYGEN) */ /* SCB->CPACR */ #define SCB_CPACR_CP10_CP11_ENABLE (0xFUL << 20u) /******************************************************************************* * SystemInit() *******************************************************************************/ /* CLK_FLL_CONFIG default values */ #define CY_FB_CLK_FLL_CONFIG_VALUE (0x01000000u) #define CY_FB_CLK_FLL_CONFIG2_VALUE (0x00020001u) #define CY_FB_CLK_FLL_CONFIG3_VALUE (0x00002800u) #define CY_FB_CLK_FLL_CONFIG4_VALUE (0x000000FFu) /******************************************************************************* * SystemCoreClockUpdate (void) *******************************************************************************/ /* Do not use these definitions directly in your application */ #define CY_DELAY_MS_OVERFLOW_THRESHOLD (0x8000u) #define CY_DELAY_1K_THRESHOLD (1000u) #define CY_DELAY_1K_MINUS_1_THRESHOLD (CY_DELAY_1K_THRESHOLD - 1u) #define CY_DELAY_1M_THRESHOLD (1000000u) #define CY_DELAY_1M_MINUS_1_THRESHOLD (CY_DELAY_1M_THRESHOLD - 1u) uint32_t cy_delayFreqHz = CY_CLK_SYSTEM_FREQ_HZ_DEFAULT; uint32_t cy_delayFreqKhz = (CY_CLK_SYSTEM_FREQ_HZ_DEFAULT + CY_DELAY_1K_MINUS_1_THRESHOLD) / CY_DELAY_1K_THRESHOLD; uint8_t cy_delayFreqMhz = (uint8_t)((CY_CLK_SYSTEM_FREQ_HZ_DEFAULT + CY_DELAY_1M_MINUS_1_THRESHOLD) / CY_DELAY_1M_THRESHOLD); uint32_t cy_delay32kMs = CY_DELAY_MS_OVERFLOW_THRESHOLD * ((CY_CLK_SYSTEM_FREQ_HZ_DEFAULT + CY_DELAY_1K_MINUS_1_THRESHOLD) / CY_DELAY_1K_THRESHOLD); #define CY_ROOT_PATH_SRC_IMO (0UL) #define CY_ROOT_PATH_SRC_EXT (1UL) #if (SRSS_ECO_PRESENT == 1U) #define CY_ROOT_PATH_SRC_ECO (2UL) #endif /* (SRSS_ECO_PRESENT == 1U) */ #if (SRSS_ALTHF_PRESENT == 1U) #define CY_ROOT_PATH_SRC_ALTHF (3UL) #endif /* (SRSS_ALTHF_PRESENT == 1U) */ #define CY_ROOT_PATH_SRC_DSI_MUX (4UL) #define CY_ROOT_PATH_SRC_DSI_MUX_HVILO (16UL) #define CY_ROOT_PATH_SRC_DSI_MUX_WCO (17UL) #if (SRSS_ALTLF_PRESENT == 1U) #define CY_ROOT_PATH_SRC_DSI_MUX_ALTLF (18UL) #endif /* (SRSS_ALTLF_PRESENT == 1U) */ #if (SRSS_PILO_PRESENT == 1U) #define CY_ROOT_PATH_SRC_DSI_MUX_PILO (19UL) #endif /* (SRSS_PILO_PRESENT == 1U) */ /******************************************************************************* * Function Name: SystemInit ****************************************************************************//** * \cond * Initializes the system: * - Restores FLL registers to the default state for single core devices. * - Unlocks and disables WDT. * - Calls Cy_PDL_Init() function to define the driver library. * - Calls the Cy_SystemInit() function, if compiled from PSoC Creator. * - Calls \ref SystemCoreClockUpdate(). * \endcond *******************************************************************************/ void SystemInit(void) { Cy_PDL_Init(CY_DEVICE_CFG); #ifdef __CM0P_PRESENT #if (__CM0P_PRESENT == 0) /* Restore FLL registers to the default state as they are not restored by the ROM code */ uint32_t copy = SRSS->CLK_FLL_CONFIG; copy &= ~SRSS_CLK_FLL_CONFIG_FLL_ENABLE_Msk; SRSS->CLK_FLL_CONFIG = copy; copy = SRSS->CLK_ROOT_SELECT[0u]; copy &= ~SRSS_CLK_ROOT_SELECT_ROOT_DIV_Msk; /* Set ROOT_DIV = 0*/ SRSS->CLK_ROOT_SELECT[0u] = copy; SRSS->CLK_FLL_CONFIG = CY_FB_CLK_FLL_CONFIG_VALUE; SRSS->CLK_FLL_CONFIG2 = CY_FB_CLK_FLL_CONFIG2_VALUE; SRSS->CLK_FLL_CONFIG3 = CY_FB_CLK_FLL_CONFIG3_VALUE; SRSS->CLK_FLL_CONFIG4 = CY_FB_CLK_FLL_CONFIG4_VALUE; /* Unlock and disable WDT */ Cy_WDT_Unlock(); Cy_WDT_Disable(); #endif /* (__CM0P_PRESENT == 0) */ #endif /* __CM0P_PRESENT */ Cy_SystemInit(); SystemCoreClockUpdate(); #if !defined(CY_IPC_DEFAULT_CFG_DISABLE) #ifdef __CM0P_PRESENT #if (__CM0P_PRESENT == 0) /* Allocate and initialize semaphores for the system operations. */ static uint32_t ipcSemaArray[CY_IPC_SEMA_COUNT / CY_IPC_SEMA_PER_WORD]; (void) Cy_IPC_Sema_Init(CY_IPC_CHAN_SEMA, CY_IPC_SEMA_COUNT, ipcSemaArray); #else (void) Cy_IPC_Sema_Init(CY_IPC_CHAN_SEMA, 0ul, NULL); #endif /* (__CM0P_PRESENT) */ #else (void) Cy_IPC_Sema_Init(CY_IPC_CHAN_SEMA, 0ul, NULL); #endif /* __CM0P_PRESENT */ /******************************************************************************** * * Initializes the system pipes. The system pipes are used by BLE and Flash. * * If the default startup file is not used, or SystemInit() is not called in your * project, call the following three functions prior to executing any flash or * EmEEPROM write or erase operation: * -# Cy_IPC_Sema_Init() * -# Cy_IPC_Pipe_Config() * -# Cy_IPC_Pipe_Init() * -# Cy_Flash_Init() * *******************************************************************************/ /* Create an array of endpoint structures */ static cy_stc_ipc_pipe_ep_t systemIpcPipeEpArray[CY_IPC_MAX_ENDPOINTS]; Cy_IPC_Pipe_Config(systemIpcPipeEpArray); static cy_ipc_pipe_callback_ptr_t systemIpcPipeSysCbArray[CY_SYS_CYPIPE_CLIENT_CNT]; static const cy_stc_ipc_pipe_config_t systemIpcPipeConfigCm4 = { /* .ep0ConfigData */ { /* .ipcNotifierNumber */ CY_IPC_INTR_CYPIPE_EP0, /* .ipcNotifierPriority */ CY_SYS_INTR_CYPIPE_PRIOR_EP0, /* .ipcNotifierMuxNumber */ CY_SYS_INTR_CYPIPE_MUX_EP0, /* .epAddress */ CY_IPC_EP_CYPIPE_CM0_ADDR, /* .epConfig */ CY_SYS_CYPIPE_CONFIG_EP0 }, /* .ep1ConfigData */ { /* .ipcNotifierNumber */ CY_IPC_INTR_CYPIPE_EP1, /* .ipcNotifierPriority */ CY_SYS_INTR_CYPIPE_PRIOR_EP1, /* .ipcNotifierMuxNumber */ 0u, /* .epAddress */ CY_IPC_EP_CYPIPE_CM4_ADDR, /* .epConfig */ CY_SYS_CYPIPE_CONFIG_EP1 }, /* .endpointClientsCount */ CY_SYS_CYPIPE_CLIENT_CNT, /* .endpointsCallbacksArray */ systemIpcPipeSysCbArray, /* .userPipeIsrHandler */ &Cy_SysIpcPipeIsrCm4 }; if (cy_device->flashPipeRequired != 0u) { Cy_IPC_Pipe_Init(&systemIpcPipeConfigCm4); } #if defined(CY_DEVICE_PSOC6ABLE2) Cy_Flash_Init(); #endif /* defined(CY_DEVICE_PSOC6ABLE2) */ #endif /* !defined(CY_IPC_DEFAULT_CFG_DISABLE) */ } /******************************************************************************* * Function Name: Cy_SystemInit ****************************************************************************//** * * The function is called during device startup. Once project compiled as part of * the PSoC Creator project, the Cy_SystemInit() function is generated by the * PSoC Creator. * * The function generated by PSoC Creator performs all of the necessary device * configuration based on the design settings. This includes settings from the * Design Wide Resources (DWR) such as Clocks and Pins as well as any component * configuration that is necessary. * *******************************************************************************/ __WEAK void Cy_SystemInit(void) { /* Empty weak function. The actual implementation to be in the PSoC Creator * generated strong function. */ } /******************************************************************************* * Function Name: SystemCoreClockUpdate ****************************************************************************//** * * Gets core clock frequency and updates \ref SystemCoreClock, \ref * cy_Hfclk0FreqHz, and \ref cy_PeriClkFreqHz. * * Updates global variables used by the \ref Cy_SysLib_Delay(), \ref * Cy_SysLib_DelayUs(), and \ref Cy_SysLib_DelayCycles(). * *******************************************************************************/ void SystemCoreClockUpdate (void) { uint32_t srcFreqHz; uint32_t pathFreqHz; uint32_t fastClkDiv; uint32_t periClkDiv; uint32_t rootPath; uint32_t srcClk; /* Get root path clock for the high-frequency clock # 0 */ rootPath = _FLD2VAL(SRSS_CLK_ROOT_SELECT_ROOT_MUX, SRSS->CLK_ROOT_SELECT[0u]); /* Get source of the root path clock */ srcClk = _FLD2VAL(SRSS_CLK_PATH_SELECT_PATH_MUX, SRSS->CLK_PATH_SELECT[rootPath]); /* Get frequency of the source */ switch (srcClk) { case CY_ROOT_PATH_SRC_IMO: srcFreqHz = CY_CLK_IMO_FREQ_HZ; break; case CY_ROOT_PATH_SRC_EXT: srcFreqHz = CY_CLK_EXT_FREQ_HZ; break; #if (SRSS_ECO_PRESENT == 1U) case CY_ROOT_PATH_SRC_ECO: srcFreqHz = CY_CLK_ECO_FREQ_HZ; break; #endif /* (SRSS_ECO_PRESENT == 1U) */ #if defined (CY_IP_MXBLESS) && (CY_IP_MXBLESS == 1UL) && (SRSS_ALTHF_PRESENT == 1U) case CY_ROOT_PATH_SRC_ALTHF: srcFreqHz = cy_BleEcoClockFreqHz; break; #endif /* defined (CY_IP_MXBLESS) && (CY_IP_MXBLESS == 1UL) && (SRSS_ALTHF_PRESENT == 1U) */ case CY_ROOT_PATH_SRC_DSI_MUX: { uint32_t dsi_src; dsi_src = _FLD2VAL(SRSS_CLK_DSI_SELECT_DSI_MUX, SRSS->CLK_DSI_SELECT[rootPath]); switch (dsi_src) { case CY_ROOT_PATH_SRC_DSI_MUX_HVILO: srcFreqHz = CY_CLK_HVILO_FREQ_HZ; break; case CY_ROOT_PATH_SRC_DSI_MUX_WCO: srcFreqHz = CY_CLK_WCO_FREQ_HZ; break; #if (SRSS_ALTLF_PRESENT == 1U) case CY_ROOT_PATH_SRC_DSI_MUX_ALTLF: srcFreqHz = CY_CLK_ALTLF_FREQ_HZ; break; #endif /* (SRSS_ALTLF_PRESENT == 1U) */ #if (SRSS_PILO_PRESENT == 1U) case CY_ROOT_PATH_SRC_DSI_MUX_PILO: srcFreqHz = CY_CLK_PILO_FREQ_HZ; break; #endif /* (SRSS_PILO_PRESENT == 1U) */ default: srcFreqHz = CY_CLK_HVILO_FREQ_HZ; break; } } break; default: srcFreqHz = CY_CLK_EXT_FREQ_HZ; break; } if (rootPath == 0UL) { /* FLL */ bool fllLocked = ( 0UL != _FLD2VAL(SRSS_CLK_FLL_STATUS_LOCKED, SRSS->CLK_FLL_STATUS)); bool fllOutputOutput = ( 3UL == _FLD2VAL(SRSS_CLK_FLL_CONFIG3_BYPASS_SEL, SRSS->CLK_FLL_CONFIG3)); bool fllOutputAuto = ((0UL == _FLD2VAL(SRSS_CLK_FLL_CONFIG3_BYPASS_SEL, SRSS->CLK_FLL_CONFIG3)) || (1UL == _FLD2VAL(SRSS_CLK_FLL_CONFIG3_BYPASS_SEL, SRSS->CLK_FLL_CONFIG3))); if ((fllOutputAuto && fllLocked) || fllOutputOutput) { uint32_t fllMult; uint32_t refDiv; uint32_t outputDiv; fllMult = _FLD2VAL(SRSS_CLK_FLL_CONFIG_FLL_MULT, SRSS->CLK_FLL_CONFIG); refDiv = _FLD2VAL(SRSS_CLK_FLL_CONFIG2_FLL_REF_DIV, SRSS->CLK_FLL_CONFIG2); outputDiv = _FLD2VAL(SRSS_CLK_FLL_CONFIG_FLL_OUTPUT_DIV, SRSS->CLK_FLL_CONFIG) + 1UL; pathFreqHz = ((srcFreqHz / refDiv) * fllMult) / outputDiv; } else { pathFreqHz = srcFreqHz; } } else if (rootPath == 1UL) { /* PLL */ bool pllLocked = ( 0UL != _FLD2VAL(SRSS_CLK_PLL_STATUS_LOCKED, SRSS->CLK_PLL_STATUS[0UL])); bool pllOutputOutput = ( 3UL == _FLD2VAL(SRSS_CLK_PLL_CONFIG_BYPASS_SEL, SRSS->CLK_PLL_CONFIG[0UL])); bool pllOutputAuto = ((0UL == _FLD2VAL(SRSS_CLK_PLL_CONFIG_BYPASS_SEL, SRSS->CLK_PLL_CONFIG[0UL])) || (1UL == _FLD2VAL(SRSS_CLK_PLL_CONFIG_BYPASS_SEL, SRSS->CLK_PLL_CONFIG[0UL]))); if ((pllOutputAuto && pllLocked) || pllOutputOutput) { uint32_t feedbackDiv; uint32_t referenceDiv; uint32_t outputDiv; feedbackDiv = _FLD2VAL(SRSS_CLK_PLL_CONFIG_FEEDBACK_DIV, SRSS->CLK_PLL_CONFIG[0UL]); referenceDiv = _FLD2VAL(SRSS_CLK_PLL_CONFIG_REFERENCE_DIV, SRSS->CLK_PLL_CONFIG[0UL]); outputDiv = _FLD2VAL(SRSS_CLK_PLL_CONFIG_OUTPUT_DIV, SRSS->CLK_PLL_CONFIG[0UL]); pathFreqHz = ((srcFreqHz * feedbackDiv) / referenceDiv) / outputDiv; } else { pathFreqHz = srcFreqHz; } } else { /* Direct */ pathFreqHz = srcFreqHz; } /* Get frequency after hf_clk pre-divider */ pathFreqHz = pathFreqHz >> _FLD2VAL(SRSS_CLK_ROOT_SELECT_ROOT_DIV, SRSS->CLK_ROOT_SELECT[0u]); cy_Hfclk0FreqHz = pathFreqHz; /* Fast Clock Divider */ fastClkDiv = 1u + _FLD2VAL(CPUSS_CM4_CLOCK_CTL_FAST_INT_DIV, CPUSS->CM4_CLOCK_CTL); /* Peripheral Clock Divider */ periClkDiv = 1u + _FLD2VAL(CPUSS_CM0_CLOCK_CTL_PERI_INT_DIV, CPUSS->CM0_CLOCK_CTL); cy_PeriClkFreqHz = pathFreqHz / periClkDiv; pathFreqHz = pathFreqHz / fastClkDiv; SystemCoreClock = pathFreqHz; /* Sets clock frequency for Delay API */ cy_delayFreqHz = SystemCoreClock; cy_delayFreqMhz = (uint8_t)((cy_delayFreqHz + CY_DELAY_1M_MINUS_1_THRESHOLD) / CY_DELAY_1M_THRESHOLD); cy_delayFreqKhz = (cy_delayFreqHz + CY_DELAY_1K_MINUS_1_THRESHOLD) / CY_DELAY_1K_THRESHOLD; cy_delay32kMs = CY_DELAY_MS_OVERFLOW_THRESHOLD * cy_delayFreqKhz; } /******************************************************************************* * Function Name: Cy_SystemInitFpuEnable ****************************************************************************//** * * Enables the FPU if it is used. The function is called from the startup file. * *******************************************************************************/ void Cy_SystemInitFpuEnable(void) { #if defined (__FPU_USED) && (__FPU_USED == 1U) uint32_t interruptState; interruptState = Cy_SysLib_EnterCriticalSection(); SCB->CPACR |= SCB_CPACR_CP10_CP11_ENABLE; __DSB(); __ISB(); Cy_SysLib_ExitCriticalSection(interruptState); #endif /* (__FPU_USED) && (__FPU_USED == 1U) */ } #if !defined(CY_IPC_DEFAULT_CFG_DISABLE) /******************************************************************************* * Function Name: Cy_SysIpcPipeIsrCm4 ****************************************************************************//** * * This is the interrupt service routine for the system pipe. * *******************************************************************************/ void Cy_SysIpcPipeIsrCm4(void) { Cy_IPC_Pipe_ExecuteCallback(CY_IPC_EP_CYPIPE_CM4_ADDR); } #endif /******************************************************************************* * Function Name: Cy_MemorySymbols ****************************************************************************//** * * The intention of the function is to declare boundaries of the memories for the * MDK compilers. For the rest of the supported compilers, this is done using * linker configuration files. The following symbols used by the cymcuelftool. * *******************************************************************************/ #if defined (__ARMCC_VERSION) __asm void Cy_MemorySymbols(void) { /* Flash */ EXPORT __cy_memory_0_start EXPORT __cy_memory_0_length EXPORT __cy_memory_0_row_size /* Working Flash */ EXPORT __cy_memory_1_start EXPORT __cy_memory_1_length EXPORT __cy_memory_1_row_size /* Supervisory Flash */ EXPORT __cy_memory_2_start EXPORT __cy_memory_2_length EXPORT __cy_memory_2_row_size /* XIP */ EXPORT __cy_memory_3_start EXPORT __cy_memory_3_length EXPORT __cy_memory_3_row_size /* eFuse */ EXPORT __cy_memory_4_start EXPORT __cy_memory_4_length EXPORT __cy_memory_4_row_size /* Flash */ __cy_memory_0_start EQU __cpp(CY_FLASH_BASE) __cy_memory_0_length EQU __cpp(CY_FLASH_SIZE) __cy_memory_0_row_size EQU 0x200 /* Flash region for EEPROM emulation */ __cy_memory_1_start EQU __cpp(CY_EM_EEPROM_BASE) __cy_memory_1_length EQU __cpp(CY_EM_EEPROM_SIZE) __cy_memory_1_row_size EQU 0x200 /* Supervisory Flash */ __cy_memory_2_start EQU __cpp(CY_SFLASH_BASE) __cy_memory_2_length EQU __cpp(CY_SFLASH_SIZE) __cy_memory_2_row_size EQU 0x200 /* XIP */ __cy_memory_3_start EQU __cpp(CY_XIP_BASE) __cy_memory_3_length EQU __cpp(CY_XIP_SIZE) __cy_memory_3_row_size EQU 0x200 /* eFuse */ __cy_memory_4_start EQU __cpp(0x90700000) __cy_memory_4_length EQU __cpp(0x100000) __cy_memory_4_row_size EQU __cpp(1) } #endif /* defined (__ARMCC_VERSION) */ /* [] END OF FILE */
851213.c
/* * FreeRTOS V202107.00 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /****************************************************************************** * This project provides two demo applications. A simple blinky style project, * and a more comprehensive test and demo application. The * mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting (defined in this file) is used to * select between the two. The simply blinky demo is implemented and described * in main_blinky.c. The more comprehensive test and demo application is * implemented and described in main_full.c. * * This file implements the code that is not demo specific, including the * hardware setup and FreeRTOS hook functions. * * * Additional code: * * This demo does not contain a non-kernel interrupt service routine that * can be used as an example for application writers to use as a reference. * Therefore, the framework of a dummy (not installed) handler is provided * in this file. The dummy function is called Dummy_IRQHandler(). Please * ensure to read the comments in the function itself, but more importantly, * the notes on the function contained on the documentation page for this demo * that is found on the FreeRTOS.org web site. */ /* * The following #error directive is to remind users that a batch file must be * executed prior to this project being built. The batch file *cannot* be * executed from within the IDE! Once it has been executed, re-open or refresh * the Eclipse project and remove the #error line below. */ #error Ensure CreateProjectDirectoryStructure.bat has been executed before building. See comment immediately above. /* Standard includes. */ #include <stdio.h> /* Kernel includes. */ #include "FreeRTOS.h" #include "task.h" /* Standard demo includes. */ #include "QueueSet.h" #include "QueueOverwrite.h" /* Set mainCREATE_SIMPLE_BLINKY_DEMO_ONLY to one to run the simple blinky demo, or 0 to run the more comprehensive test and demo application. */ #define mainCREATE_SIMPLE_BLINKY_DEMO_ONLY 1 /*-----------------------------------------------------------*/ /* * Set up the hardware ready to run this demo. */ static void prvSetupHardware( void ); /* * main_blinky() is used when mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 1. * main_full() is used when mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 0. */ extern void main_blinky( void ); extern void main_full( void ); /*-----------------------------------------------------------*/ int main( void ) { /* Prepare the hardware to run this demo. */ prvSetupHardware(); /* The mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting is described at the top of this file. */ #if mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 1 { main_blinky(); } #else { main_full(); } #endif return 0; } /*-----------------------------------------------------------*/ static void prvSetupHardware( void ) { configCONFIGURE_LED(); /* Ensure all priority bits are assigned as preemption priority bits. */ NVIC_SetPriorityGrouping( 0 ); } /*-----------------------------------------------------------*/ void vApplicationMallocFailedHook( void ) { /* vApplicationMallocFailedHook() will only be called if configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. It is a hook function that will get called if a call to pvPortMalloc() fails. pvPortMalloc() is called internally by the kernel whenever a task, queue, timer or semaphore is created. It is also called by various parts of the demo application. If heap_1.c or heap_2.c are used, then the size of the heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used to query the size of free heap space that remains (although it does not provide information on how the remaining heap might be fragmented). */ taskDISABLE_INTERRUPTS(); for( ;; ) { __asm volatile( "NOP" ); }; } /*-----------------------------------------------------------*/ void vApplicationIdleHook( void ) { /* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set to 1 in FreeRTOSConfig.h. It will be called on each iteration of the idle task. It is essential that code added to this hook function never attempts to block in any way (for example, call xQueueReceive() with a block time specified, or call vTaskDelay()). If the application makes use of the vTaskDelete() API function (as this demo application does) then it is also important that vApplicationIdleHook() is permitted to return to its calling function, because it is the responsibility of the idle task to clean up memory allocated by the kernel to any task that has since been deleted. */ } /*-----------------------------------------------------------*/ void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName ) { ( void ) pcTaskName; ( void ) pxTask; /* Run time stack overflow checking is performed if configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook function is called if a stack overflow is detected. */ taskDISABLE_INTERRUPTS(); for( ;; ) { __asm volatile( "NOP" ); } } /*-----------------------------------------------------------*/ void vApplicationTickHook( void ) { /* This function will be called by each tick interrupt if configUSE_TICK_HOOK is set to 1 in FreeRTOSConfig.h. User code can be added here, but the tick hook is called from an interrupt context, so code must not attempt to block, and only the interrupt safe FreeRTOS API functions can be used (those that end in FromISR()). */ #if mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 0 { /* Write to a queue that is in use as part of the queue set demo to demonstrate using queue sets from an ISR. */ vQueueSetAccessQueueSetFromISR(); /* Test the ISR safe queue overwrite functions. */ vQueueOverwritePeriodicISRDemo(); } #endif /* mainCREATE_SIMPLE_BLINKY_DEMO_ONLY */ } /*-----------------------------------------------------------*/ #ifdef JUST_AN_EXAMPLE_ISR void Dummy_IRQHandler(void) { long lHigherPriorityTaskWoken = pdFALSE; /* Clear the interrupt if necessary. */ Dummy_ClearITPendingBit(); /* This interrupt does nothing more than demonstrate how to synchronise a task with an interrupt. A semaphore is used for this purpose. Note lHigherPriorityTaskWoken is initialised to zero. */ xSemaphoreGiveFromISR( xTestSemaphore, &lHigherPriorityTaskWoken ); /* If there was a task that was blocked on the semaphore, and giving the semaphore caused the task to unblock, and the unblocked task has a priority higher than the current Running state task (the task that this interrupt interrupted), then lHigherPriorityTaskWoken will have been set to pdTRUE internally within xSemaphoreGiveFromISR(). Passing pdTRUE into the portEND_SWITCHING_ISR() macro will result in a context switch being pended to ensure this interrupt returns directly to the unblocked, higher priority, task. Passing pdFALSE into portEND_SWITCHING_ISR() has no effect. */ portEND_SWITCHING_ISR( lHigherPriorityTaskWoken ); } #endif /* JUST_AN_EXAMPLE_ISR */
264922.c
/* MDH WCET BENCHMARK SUITE */ /* 2012/09/28, Jan Gustafsson <[email protected]> * Changes: * - Missing braces around initialization of subobject added * - This program redefines the standard C function fabs. Therefore, the * function has been renamed to minver_fabs. */ /*************************************************************************/ /* */ /* SNU-RT Benchmark Suite for Worst Case Timing Analysis */ /* ===================================================== */ /* Collected and Modified by S.-S. Lim */ /* [email protected] */ /* Real-Time Research Group */ /* Seoul National University */ /* */ /* */ /* < Features > - restrictions for our experimental environment */ /* */ /* 1. Completely structured. */ /* - There are no unconditional jumps. */ /* - There are no exit from loop bodies. */ /* (There are no 'break' or 'return' in loop bodies) */ /* 2. No 'switch' statements. */ /* 3. No 'do..while' statements. */ /* 4. Expressions are restricted. */ /* - There are no multiple expressions joined by 'or', */ /* 'and' operations. */ /* 5. No library calls. */ /* - All the functions needed are implemented in the */ /* source file. */ /* */ /* */ /*************************************************************************/ /* */ /* FILE: minver.c */ /* SOURCE : Turbo C Programming for Engineering by Hyun Soo Ahn */ /* */ /* DESCRIPTION : */ /* */ /* Matrix inversion for 3x3 floating point matrix. */ /* */ /* REMARK : */ /* */ /* EXECUTION TIME : */ /* */ /* */ /*************************************************************************/ int minver(int row, int col, double eps); int mmul(int row_a, int col_a, int row_b, int col_b); static double a[3][3] = { {3.0, -6.0, 7.0}, {9.0, 0.0, -5.0}, {5.0, -8.0, 6.0}, }; double b[3][3], c[3][3], aa[3][3], a_i[3][3], e[3][3], det; double minver_fabs(double n) { double f; if (n >= 0) f = n; else f = -n; return f; } int main() { int i, j; double eps; eps = 1.0e-6; for(i = 0; i < 3; i++) for(j = 0; j < 3; j++) aa[i][j] = a[i][j]; minver(3, 3, eps); for(i = 0; i < 3; i++) for(j = 0; j < 3; j++) a_i[i][j] = a[i][j]; mmul(3, 3, 3, 3); return 0; } int mmul(int row_a, int col_a, int row_b, int col_b) { int i, j, k, row_c, col_c; double w; row_c = row_a; col_c = col_b; if(row_c < 1 || row_b < 1 || col_c < 1 || col_a != row_b) return(999); for(i = 0; i < row_c; i++) { for(j = 0; j < col_c; j++) { w = 0.0; for(k = 0; k < row_b; k++) w += a[i][k] * b[k][j]; c[i][j] = w; } } return(0); } int minver(int row, int col, double eps) { int work[500], i, j, k, r, iw, s, t, u, v; double w, wmax, pivot, api, w1; if(row < 2 || row > 500 || eps <= 0.0) return(999); w1 = 1.0; for(i = 0; i < row; i++) work[i] = i; for(k = 0; k < row; k++) { wmax = 0.0; for(i = k; i < row; i++) { w = minver_fabs(a[i][k]); if(w > wmax) { wmax = w; r = i; } } pivot = a[r][k]; api = minver_fabs(pivot); if(api <= eps) { det = w1; return(1); } w1 *= pivot; u = k * col; v = r * col; if(r != k) { w1 = -w; iw = work[k]; work[k] = work[r]; work[r] = iw; for(j = 0; j < row; j++) { s = u + j; t = v + j; w = a[k][j]; a[k][j] = a[r][j]; a[r][j] = w; } } for(i = 0; i < row; i++) a[k][i] /= pivot; for(i = 0; i < row; i++) { if(i != k) { v = i * col; s = v + k; w = a[i][k]; if(w != 0.0) { for(j = 0; j < row; j++) if(j != k) a[i][j] -= w * a[k][j]; a[i][k] = -w / pivot; } } } a[k][k] = 1.0 / pivot; } for(i = 0; i < row; i++) { while(1) { k = work[i]; if(k == i) break; iw = work[k]; work[k] = work[i]; work[i] = iw; for(j = 0; j < row; j++) { u = j * col; s = u + i; t = u + k; w = a[k][i]; a[k][i] = a[k][k]; a[k][k] = w; } } } det = w1; return(0); }
163589.c
/* Copyright (c) 2019, Ameer Haj Ali (UC Berkeley), and Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "header.h" int ia[8]; int G[512][64]; int G2[512+8][64]; __attribute__((noinline)) void example14(int in[][64], int coeff[][64], int *result) { int k,j,i=0; for (k = 0; k < 8; k++) { int sum = 0; for (i = 0; i < 512; i++) for (j = 0; j < 64; j++) sum += in[i+k][j] * coeff[i][j]; result[k] = sum; } } int main(int argc,char* argv[]){ init_memory(&ia[0], &ia[8]); init_memory(&G[0][0], &G[0][64]); init_memory(&G2[0][0],&G2[0][64]); BENCH("Example14", example14(G2,G,ia), 8192, digest_memory(&ia[0], &ia[8])); return 0; }
958266.c
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the terms found in the LICENSE file in the root of this source tree. * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * [email protected] */ /*! \file s11_ie_formatter.c \brief \author Sebastien ROUX, Lionel Gauthier \company Eurecom \email: [email protected] */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <inttypes.h> #include <pthread.h> #include "lte/gateway/c/core/oai/lib/bstr/bstrlib.h" #include "lte/gateway/c/core/common/assertions.h" #include "lte/gateway/c/core/common/common_defs.h" #include "lte/gateway/c/core/common/dynamic_memory_check.h" #include "lte/gateway/c/core/oai/common/common_types.h" #include "lte/gateway/c/core/oai/common/conversions.h" #include "lte/gateway/c/core/oai/common/gcc_diag.h" #include "lte/gateway/c/core/oai/common/log.h" #include "lte/gateway/c/core/oai/common/security_types.h" #include "lte/gateway/c/core/oai/include/s11_messages_types.h" #include "lte/gateway/c/core/oai/include/sgw_ie_defs.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_23.003.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_24.007.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_24.008.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_29.274.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_33.401.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_36.413.h" #include "lte/gateway/c/core/oai/lib/gtpv2-c/gtpv2c_ie_formatter/shared/gtpv2c_ie_formatter.h" #include "lte/gateway/c/core/oai/lib/gtpv2-c/nwgtpv2c-0.11/include/NwGtpv2c.h" #include "lte/gateway/c/core/oai/lib/gtpv2-c/nwgtpv2c-0.11/shared/NwGtpv2cIe.h" #include "lte/gateway/c/core/oai/lib/gtpv2-c/nwgtpv2c-0.11/shared/NwGtpv2cMsg.h" #include "lte/gateway/c/core/oai/lib/gtpv2-c/nwgtpv2c-0.11/shared/NwGtpv2cMsgParser.h" #include "lte/gateway/c/core/oai/lib/message_utils/ie_to_bytes.h" #include "lte/gateway/c/core/oai/tasks/nas/ies/PdnType.h" #include "lte/gateway/c/core/oai/tasks/s11/s11_common.h" #include "lte/gateway/c/core/oai/tasks/s11/s11_ie_formatter.h" //------------------------------------------------------------------------------ nw_rc_t gtpv2c_msisdn_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { Msisdn_t* msisdn; uint8_t i; uint8_t mask = 0x0F; uint8_t msisdn_length = 2 * ieLength; DevAssert(arg); msisdn = (Msisdn_t*)arg; for (i = 0; i < ieLength * 2; i++) { if (mask == 0x0F) { msisdn->digit[i] = (ieValue[i / 2] & (mask)); } else { msisdn->digit[i] = (ieValue[i / 2] & (mask)) >> 4; } msisdn->digit[i] += '0'; mask = ~mask; } if (msisdn->digit[msisdn_length - 1] == (0x0f + '0')) { msisdn->digit[msisdn_length - 1] = 0; msisdn_length--; } msisdn->length = msisdn_length; OAILOG_DEBUG(LOG_S11, "\t- MSISDN length %d\n", msisdn->length); OAILOG_DEBUG(LOG_S11, "\t- value %*s\n", msisdn->length, (char*)msisdn->digit); return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_mei_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { Mei_t* mei = (Mei_t*)arg; DevAssert(mei); return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_node_type_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { node_type_t* node_type = (node_type_t*)arg; DevAssert(node_type); if (*ieValue == 0) { *node_type = NODE_TYPE_MME; } else if (*ieValue == 1) { *node_type = NODE_TYPE_SGSN; } else { OAILOG_ERROR(LOG_S11, "Received unknown value for Node Type: %u\n", *ieValue); return NW_GTPV2C_IE_INCORRECT; } OAILOG_DEBUG(LOG_S11, "\t- Node type %u\n", *node_type); return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_node_type_ie_set(nw_gtpv2c_msg_handle_t* msg, const node_type_t* node_type) { nw_rc_t rc; uint8_t value; DevAssert(node_type); DevAssert(msg); switch (*node_type) { case NODE_TYPE_MME: value = 0; break; case NODE_TYPE_SGSN: value = 1; break; default: OAILOG_ERROR(LOG_S11, "Invalid Node type received: %d\n", *node_type); return RETURNerror; } rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_NODE_TYPE, 1, 0, (uint8_t*)&value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_pdn_type_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { pdn_type_t* pdn_type = (pdn_type_t*)arg; DevAssert(pdn_type); if (*ieValue == 1) { *pdn_type = IPv4; // Only IPv4 } else if (*ieValue == 2) { *pdn_type = IPv6; // Only IPv6 } else if (*ieValue == 3) { *pdn_type = IPv4_AND_v6; // IPv4 and/or IPv6 } else { OAILOG_ERROR(LOG_S11, "Received unknown value for PDN Type: %u\n", *ieValue); return NW_GTPV2C_IE_INCORRECT; } OAILOG_DEBUG(LOG_S11, "\t- PDN type %u\n", *pdn_type); return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_pdn_type_ie_set(nw_gtpv2c_msg_handle_t* msg, const pdn_type_t* pdn_type) { nw_rc_t rc; uint8_t value; DevAssert(pdn_type); DevAssert(msg); switch (*pdn_type) { case IPv4: value = 1; break; case IPv6: value = 2; break; case IPv4_AND_v6: case IPv4_OR_v6: value = 3; break; default: OAILOG_ERROR(LOG_S11, "Invalid PDN type received: %d\n", *pdn_type); return RETURNerror; } rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_PDN_TYPE, 1, 0, (uint8_t*)&value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_rat_type_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { rat_type_t* rat_type = (rat_type_t*)arg; DevAssert(rat_type); switch (*ieValue) { case 1: *rat_type = RAT_UTRAN; break; case 2: *rat_type = RAT_GERAN; break; case 3: *rat_type = RAT_WLAN; break; case 4: *rat_type = RAT_GAN; break; case 5: *rat_type = RAT_HSPA_EVOLUTION; break; case 6: *rat_type = RAT_EUTRAN; break; default: OAILOG_ERROR(LOG_S11, "Can't map GTP RAT type %u to EPC definition\n" "\tCheck TS.29.274 #8.17 for possible values\n", *ieValue); return NW_GTPV2C_IE_INCORRECT; } OAILOG_DEBUG(LOG_S11, "\t- RAT type (%d): %d\n", *ieValue, *rat_type); return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_rat_type_ie_set(nw_gtpv2c_msg_handle_t* msg, const rat_type_t* rat_type) { nw_rc_t rc; uint8_t value; DevAssert(rat_type); DevAssert(msg); switch (*rat_type) { case RAT_UTRAN: value = 1; break; case RAT_GERAN: value = 2; break; case RAT_WLAN: value = 3; break; case RAT_GAN: value = 4; break; case RAT_HSPA_EVOLUTION: value = 5; break; case RAT_EUTRAN: value = 6; break; default: OAILOG_ERROR(LOG_S11, "Can't map RAT type %d to GTP RAT type\n" "\tCheck TS.29.274 #8.17 for possible values\n", *rat_type); return RETURNerror; } rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_RAT_TYPE, 1, 0, (uint8_t*)&value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_ebi_ie_get_list(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { ebi_list_t* ebi_list = (ebi_list_t*)arg; DevAssert(ebi_list); DevAssert(RELEASE_ACCESS_BEARER_MAX_BEARERS > ebi_list->num_ebi); uint8_t* ebi = (uint8_t*)&ebi_list->ebis[ebi_list->num_ebi]; DevAssert(ebi); *ebi = ieValue[0] & 0x0F; OAILOG_DEBUG(LOG_S11, "\t- EBI %u\n", *ebi); ebi_list->num_ebi += 1; return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_pti_ie_set(nw_gtpv2c_msg_handle_t* msg, const pti_t pti, const uint8_t instance) { nw_rc_t rc; rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_PROCEDURE_TRANSACTION_ID, 1, instance, (pti_t*)(&pti)); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_pti_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { uint8_t* pti = (uint8_t*)arg; DevAssert(pti); *pti = ieValue[0]; OAILOG_DEBUG(LOG_S11, "\t- PTI %u\n", *pti); return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_to_create_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_to_create_t* bearer_to_create) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_to_create); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_to_create->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); // End section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_to_be_created_within_create_bearer_request_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_to_be_created_t* bearer_contexts = (bearer_contexts_to_be_created_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_CREATE_BEARER_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_to_be_created_t* bearer_context = &bearer_contexts->bearer_contexts[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_BEARER_LEVEL_QOS: rc = gtpv2c_bearer_qos_ie_get( ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->bearer_level_qos); break; case NW_GTPV2C_IE_BEARER_TFT: rc = gtpv2c_tft_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->tft); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_PCO: rc = gtpv2c_pco_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->pco); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_FTEID: switch (ie_p->i) { case 0: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s1u_sgw_fteid); break; case 1: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s5_s8_u_pgw_fteid); break; case 2: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s12_rnc_fteid); break; case 3: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s4u_sgsn_fteid); break; case 4: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s2b_u_epdg_fteid); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u instance %u\n", ie_p->t, ie_p->i); return NW_GTPV2C_IE_INCORRECT; } DevAssert(NW_OK == rc); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_to_be_created_within_create_bearer_request_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_to_be_created_t* bearer_context) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_context); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_context->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); if (bearer_context->pco.num_protocol_or_container_id) { gtpv2c_pco_ie_set(msg, &bearer_context->pco); } if (bearer_context->s1u_sgw_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s1u_sgw_fteid, 0); } if (bearer_context->s5_s8_u_pgw_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s5_s8_u_pgw_fteid, 1); } if (bearer_context->s12_rnc_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s12_rnc_fteid, 2); } if (bearer_context->s4u_sgsn_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s4u_sgsn_fteid, 3); } if (bearer_context->s2b_u_epdg_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s2b_u_epdg_fteid, 4); } gtpv2c_bearer_qos_ie_set(msg, &bearer_context->bearer_level_qos); gtpv2c_tft_ie_set(msg, &bearer_context->tft); // End section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_within_create_bearer_response_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_within_create_bearer_response_t* bearer_context) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_context); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_context->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); gtpv2c_cause_ie_set(msg, &bearer_context->cause); gtpv2c_fteid_ie_set(msg, &bearer_context->s1u_enb_fteid, 0); gtpv2c_fteid_ie_set(msg, &bearer_context->s1u_sgw_fteid, 1); if (bearer_context->s5_s8_u_sgw_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s5_s8_u_sgw_fteid, 2); } if (bearer_context->s5_s8_u_pgw_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s5_s8_u_pgw_fteid, 3); } if (bearer_context->s12_rnc_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s12_rnc_fteid, 4); } if (bearer_context->s12_sgw_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s12_sgw_fteid, 5); } if (bearer_context->s4_u_sgsn_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s4_u_sgsn_fteid, 6); } if (bearer_context->s4_u_sgw_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s4_u_sgw_fteid, 7); } if (bearer_context->s2b_u_epdg_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s2b_u_epdg_fteid, 8); } if (bearer_context->s2b_u_pgw_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s2b_u_pgw_fteid, 9); } if (bearer_context->pco.num_protocol_or_container_id) { gtpv2c_pco_ie_set(msg, &bearer_context->pco); } // End section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_within_create_bearer_response_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_within_create_bearer_response_t* bearer_contexts = (bearer_contexts_within_create_bearer_response_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_MODIFY_BEARER_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_within_create_bearer_response_t* bearer_context = &bearer_contexts->bearer_contexts[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; DevAssert(bearer_context); while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_CAUSE: rc = gtpv2c_cause_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->cause); break; case NW_GTPV2C_IE_PCO: rc = gtpv2c_pco_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->pco); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_FTEID: switch (ie_p->i) { case 0: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s1u_enb_fteid); break; case 1: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s1u_sgw_fteid); break; case 2: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s5_s8_u_sgw_fteid); break; case 3: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s5_s8_u_pgw_fteid); break; case 4: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s12_rnc_fteid); break; case 5: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s12_sgw_fteid); break; case 6: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s4_u_sgsn_fteid); break; case 7: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s4_u_sgw_fteid); break; case 8: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s2b_u_epdg_fteid); break; case 9: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s2b_u_pgw_fteid); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected instance %u for fteid\n", ie_p->i); } break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_to_be_updated_within_update_bearer_request_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_to_be_updated_t* bearer_contexts = (bearer_contexts_to_be_updated_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_UPDATE_BEARER_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_to_be_updated_t* bearer_context = &bearer_contexts->bearer_context[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_BEARER_LEVEL_QOS: DevAssert(!bearer_context->bearer_level_qos); bearer_context->bearer_level_qos = calloc(1, sizeof(bearer_qos_t)); rc = gtpv2c_bearer_qos_ie_get( ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], bearer_context->bearer_level_qos); break; case NW_GTPV2C_IE_BEARER_TFT: if (!bearer_context->tft) bearer_context->tft = calloc(1, sizeof(traffic_flow_template_t)); rc = gtpv2c_tft_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], bearer_context->tft); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_PCO: rc = gtpv2c_pco_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->pco); DevAssert(NW_OK == rc); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_to_be_updated_within_update_bearer_request_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_to_be_updated_t* bearer_context) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_context); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_context->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); if (bearer_context->pco.num_protocol_or_container_id) { gtpv2c_pco_ie_set(msg, &bearer_context->pco); } gtpv2c_bearer_qos_ie_set( msg, (const bearer_qos_t* const) & bearer_context->bearer_level_qos); gtpv2c_tft_ie_set( msg, (const traffic_flow_template_t* const) & bearer_context->tft); // End section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_within_update_bearer_response_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_within_update_bearer_response_t* bearer_context) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_context); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_context->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); gtpv2c_cause_ie_set(msg, &bearer_context->cause); if (bearer_context->s12_rnc_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s12_rnc_fteid, 0); } if (bearer_context->s4_u_sgsn_fteid.teid) { gtpv2c_fteid_ie_set(msg, &bearer_context->s4_u_sgsn_fteid, 1); } if (bearer_context->pco.num_protocol_or_container_id) { gtpv2c_pco_ie_set(msg, &bearer_context->pco); } rc = nwGtpv2cMsgGroupedIeEnd( *msg); // End section for grouped IE: bearer context to create DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_within_update_bearer_response_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_within_update_bearer_response_t* bearer_contexts = (bearer_contexts_within_update_bearer_response_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_MODIFY_BEARER_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_within_update_bearer_response_t* bearer_context = &bearer_contexts->bearer_context[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; DevAssert(bearer_context); while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_CAUSE: rc = gtpv2c_cause_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->cause); break; case NW_GTPV2C_IE_PCO: rc = gtpv2c_pco_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->pco); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_FTEID: switch (ie_p->i) { case 0: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s4_u_sgsn_fteid); break; case 1: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s12_rnc_fteid); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected instance %u for fteid\n", ie_p->i); } break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_failed_bearer_contexts_within_delete_bearer_request_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_to_be_removed_t* bearer_contexts = (bearer_contexts_to_be_removed_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_DELETE_BEARER_REQUEST_MAX_FAILED_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_to_be_removed_t* bearer_context = &bearer_contexts->bearer_contexts[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_CAUSE: rc = gtpv2c_cause_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->cause); DevAssert(NW_OK == rc); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_failed_bearer_context_within_delete_bearer_request_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_to_be_removed_t* bearer_context) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_context); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_context->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); gtpv2c_cause_ie_set(msg, &bearer_context->cause); rc = nwGtpv2cMsgGroupedIeEnd( *msg); // End section for grouped IE: bearer context to create DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ status_code_e gtpv2c_ebis_within_delete_bearer_request_ie_set( nw_gtpv2c_msg_handle_t* msg, const ebis_to_be_deleted_t* ebis_tbd) { int rc = RETURNok; DevAssert(ebis_tbd); for (int num_ebi = 0; num_ebi < ebis_tbd->num_ebis; num_ebi++) { /** Add EBIs. */ ebi_t ebi = ebis_tbd->eps_bearer_id[num_ebi]; rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_EBI, 1, 1, &ebi); DevAssert(NW_OK == rc); } return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_ebis_to_be_deleted_within_delete_bearer_request_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { ebis_to_be_deleted_t* ebis_tbd = (ebis_to_be_deleted_t*)arg; DevAssert(ebis_tbd); DevAssert(0 <= ebis_tbd->num_ebis); DevAssert(MSG_DELETE_BEARER_REQUEST_MAX_EBIS_TO_BE_DELETED >= ebis_tbd->num_ebis); ebi_t* ebi = &ebis_tbd->eps_bearer_id[ebis_tbd->num_ebis]; *ebi = ieValue[0] & 0x0F; OAILOG_DEBUG(LOG_S11, "\t- EBI %u\n", *ebi); ebis_tbd->num_ebis++; return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_within_delete_bearer_response_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_within_delete_bearer_response_t* bearer_context) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_context); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_context->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); gtpv2c_cause_ie_set(msg, &bearer_context->cause); if (bearer_context->pco.num_protocol_or_container_id) { gtpv2c_pco_ie_set(msg, &bearer_context->pco); } // End section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_within_delete_bearer_response_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_within_delete_bearer_response_t* bearer_contexts = (bearer_contexts_within_delete_bearer_response_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_MODIFY_BEARER_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_within_delete_bearer_response_t* bearer_context = &bearer_contexts->bearer_context[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; DevAssert(bearer_context); while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_CAUSE: rc = gtpv2c_cause_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->cause); break; case NW_GTPV2C_IE_PCO: rc = gtpv2c_pco_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->pco); DevAssert(NW_OK == rc); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_ebi_only_ie_set( nw_gtpv2c_msg_handle_t* const msg, const ebi_t ebi) { nw_rc_t rc; DevAssert(msg); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, ebi, NW_GTPV2C_IE_INSTANCE_ZERO); // End section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_to_be_modified_within_modify_bearer_request_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_to_be_modified_t* bearer_context) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_context); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ZERO); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_context->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); gtpv2c_fteid_ie_set(msg, &bearer_context->s1_eNB_fteid, 0); // End section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_to_be_modified_within_modify_bearer_request_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_to_be_modified_t* bearer_contexts = (bearer_contexts_to_be_modified_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_MODIFY_BEARER_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_to_be_modified_t* bearer_context = &bearer_contexts->bearer_contexts[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; DevAssert(bearer_context); while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_FTEID: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s1_eNB_fteid); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_to_be_removed_within_modify_bearer_request_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_to_be_removed_t* bearer_context) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer_context); // Start section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ONE); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer_context->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ZERO); // End section for grouped IE: bearer context to create rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_to_be_removed_within_modify_bearer_request_ie_get( uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_to_be_removed_t* bearer_contexts = (bearer_contexts_to_be_removed_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_MODIFY_BEARER_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_to_be_removed_t* bearer_context = &bearer_contexts->bearer_contexts[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_modified_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_modified_t* bearer_contexts = (bearer_contexts_modified_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_MODIFY_BEARER_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_modified_t* bearer_context = &bearer_contexts->bearer_contexts[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_FTEID: switch (ie_p->i) { case 0: rc = gtpv2c_fteid_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->s1u_sgw_fteid); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u instance %u\n", ie_p->t, ie_p->i); return NW_GTPV2C_IE_INCORRECT; } DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_CAUSE: rc = gtpv2c_cause_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->cause); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_context_marked_for_removal_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_contexts_marked_for_removal_t* bearer_contexts = (bearer_contexts_marked_for_removal_t*)arg; DevAssert(bearer_contexts); DevAssert(0 <= bearer_contexts->num_bearer_context); DevAssert(MSG_CREATE_SESSION_REQUEST_MAX_BEARER_CONTEXTS >= bearer_contexts->num_bearer_context); bearer_context_marked_for_removal_t* bearer_context = &bearer_contexts->bearer_contexts[bearer_contexts->num_bearer_context]; uint16_t read = 0; nw_rc_t rc; while (ieLength > read) { nw_gtpv2c_ie_tlv_t* ie_p; ie_p = (nw_gtpv2c_ie_tlv_t*)&ieValue[read]; switch (ie_p->t) { case NW_GTPV2C_IE_EBI: rc = gtpv2c_ebi_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->eps_bearer_id); DevAssert(NW_OK == rc); break; case NW_GTPV2C_IE_CAUSE: rc = gtpv2c_cause_ie_get(ie_p->t, ntohs(ie_p->l), ie_p->i, &ieValue[read + sizeof(nw_gtpv2c_ie_tlv_t)], &bearer_context->cause); break; default: OAILOG_ERROR(LOG_S11, "Received unexpected IE %u\n", ie_p->t); return NW_GTPV2C_IE_INCORRECT; } read += (ntohs(ie_p->l) + sizeof(nw_gtpv2c_ie_tlv_t)); } bearer_contexts->num_bearer_context += 1; return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_context_marked_for_removal_ie_set( nw_gtpv2c_msg_handle_t* msg, const bearer_context_marked_for_removal_t* const bearer) { nw_rc_t rc; DevAssert(msg); DevAssert(bearer); // Start section for grouped IE: bearer context marked for removal rc = nwGtpv2cMsgGroupedIeStart(*msg, NW_GTPV2C_IE_BEARER_CONTEXT, NW_GTPV2C_IE_INSTANCE_ONE); DevAssert(NW_OK == rc); gtpv2c_ebi_ie_set(msg, bearer->eps_bearer_id, NW_GTPV2C_IE_INSTANCE_ONE); rc = gtpv2c_cause_ie_set(msg, &bearer->cause); DevAssert(NW_OK == rc); // End section for grouped IE: bearer context marked for removal rc = nwGtpv2cMsgGroupedIeEnd(*msg); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_apn_restriction_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { APNRestriction_t* apn_restriction = (APNRestriction_t*)arg; OAILOG_DEBUG(LOG_S11, "\t- APN restriction 0x%02x\n", *apn_restriction); return NW_OK; } //------------------------------------------------------------------------------ /* This IE shall be included in the E-UTRAN initial attach, PDP Context Activation and UE Requested PDN connectivity procedures. This IE denotes the most stringent restriction as required by any already active bearer context. If there are no already active bearer contexts, this value is set to the least restrictive type. */ status_code_e gtpv2c_apn_restriction_ie_set(nw_gtpv2c_msg_handle_t* msg, const uint8_t apn_restriction) { nw_rc_t rc; DevAssert(msg); rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_APN_RESTRICTION, 1, 0, (uint8_t*)&apn_restriction); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_serving_network_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { ServingNetwork_t* serving_net = (ServingNetwork_t*)arg; DevAssert(serving_net); serving_net->mcc[1] = (ieValue[0] & 0xF0) >> 4; serving_net->mcc[0] = (ieValue[0] & 0x0F); serving_net->mcc[2] = (ieValue[1] & 0x0F); if ((ieValue[1] & 0xF0) == 0xF0) { // Two digits MNC serving_net->mnc[0] = 0; serving_net->mnc[1] = (ieValue[2] & 0x0F); serving_net->mnc[2] = (ieValue[2] & 0xF0) >> 4; } else { serving_net->mnc[0] = (ieValue[2] & 0x0F); serving_net->mnc[1] = (ieValue[2] & 0xF0) >> 4; serving_net->mnc[2] = (ieValue[1] & 0xF0) >> 4; } OAILOG_DEBUG(LOG_S11, "\t- Serving network %d.%d\n", serving_net->mcc[0] * 100 + serving_net->mcc[1] * 10 + serving_net->mcc[2], serving_net->mnc[0] * 100 + serving_net->mnc[1] * 10 + serving_net->mnc[2]); return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_serving_network_ie_set( nw_gtpv2c_msg_handle_t* msg, const ServingNetwork_t* serving_network) { nw_rc_t rc; uint8_t value[3]; DevAssert(msg); DevAssert(serving_network); // MCC Decimal | MCC Hundreds value[0] = ((serving_network->mcc[1] & 0x0F) << 4) | (serving_network->mcc[0] & 0x0F); value[1] = serving_network->mcc[2] & 0x0F; if ((serving_network->mnc[0] & 0xF) == 0xF) { // Only two digits value[1] |= 0xF0; value[2] = ((serving_network->mnc[2] & 0x0F) << 4) | (serving_network->mnc[1] & 0x0F); } else { value[1] |= (serving_network->mnc[2] & 0x0F) << 4; value[2] = ((serving_network->mnc[1] & 0x0F) << 4) | (serving_network->mnc[0] & 0x0F); } rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_SERVING_NETWORK, 3, 0, value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_pco_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { uint8_t offset = 0; protocol_configuration_options_t* pco = (protocol_configuration_options_t*)arg; DevAssert(pco); offset = decode_protocol_configuration_options(pco, ieValue, ieLength); if ((0 < offset) && (PROTOCOL_CONFIGURATION_OPTIONS_IE_MAX_LENGTH >= offset)) return NW_OK; else return NW_GTPV2C_IE_INCORRECT; } //------------------------------------------------------------------------------ status_code_e gtpv2c_pco_ie_set(nw_gtpv2c_msg_handle_t* msg, const protocol_configuration_options_t* pco) { uint8_t temp[PROTOCOL_CONFIGURATION_OPTIONS_IE_MAX_LENGTH]; uint8_t offset = 0; nw_rc_t rc = NW_OK; DevAssert(pco); offset = encode_protocol_configuration_options( pco, temp, PROTOCOL_CONFIGURATION_OPTIONS_IE_MAX_LENGTH); rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_PCO, offset, 0, temp); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ /* The encoding of the APN shall follow the Name Syntax defined in RFC 2181, RFC 1035 and RFC 1123. The APN consists of one or more labels. Each label is coded as a one octet length field followed by that number of octets coded as 8 bit ASCII characters. Following RFC 1035 the labels shall consist only of the alphabetic characters (A-Z and a-z), digits (0-9) and the hyphen (-). */ nw_rc_t gtpv2c_apn_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { uint8_t read = 1; uint8_t word_length; char* apn = (char*)arg; DevAssert(apn); DevCheck(ieLength <= ACCESS_POINT_NAME_MAX_LENGTH, ieLength, ACCESS_POINT_NAME_MAX_LENGTH, 0); word_length = ieValue[0]; while (read < ieLength) { if (word_length > 0) { apn[read - 1] = ieValue[read]; word_length--; } else { word_length = ieValue[read]; // This is not an alphanumeric character apn[read - 1] = '.'; // Replace the length attribute by '.' } read++; } apn[read - 1] = '\0'; OAILOG_DEBUG(LOG_S11, "\t- APN %s\n", apn); return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_apn_ie_set(nw_gtpv2c_msg_handle_t* msg, const char* apn) { nw_rc_t rc; uint8_t* value; uint8_t apn_length; uint8_t offset = 0; uint8_t* last_size; uint8_t word_length = 0; DevAssert(apn); DevAssert(msg); apn_length = strlen(apn); value = calloc(apn_length + 1, sizeof(uint8_t)); last_size = &value[0]; while (apn[offset]) { // We replace the . by the length of the word if (apn[offset] == '.') { *last_size = word_length; word_length = 0; last_size = &value[offset + 1]; } else { word_length++; value[offset + 1] = apn[offset]; } offset++; } *last_size = word_length; rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_APN, apn_length + 1, 0, value); DevAssert(NW_OK == rc); free_wrapper((void**)&value); return RETURNok; } status_code_e gtpv2c_apn_plmn_ie_set(nw_gtpv2c_msg_handle_t* msg, const char* apn, const ServingNetwork_t* serving_network) { nw_rc_t rc; uint8_t* value; uint8_t apn_length; uint8_t* last_size; DevAssert(serving_network); DevAssert(apn); DevAssert(msg); apn_length = strlen(apn); value = calloc(apn_length + 20, sizeof(uint8_t)); //"default" + neu: ".mncXXX.mccXXX.gprs" last_size = &value[0]; memcpy(&value[1], apn, apn_length); memcpy(&value[apn_length + 1], ".mnc", 4); memcpy(&value[apn_length + 8], ".mcc", 4); memcpy(&value[apn_length + 15], ".gprs", 5); if (serving_network->mnc[2] == 0x0F) { /* * Two digits MNC */ value[apn_length + 5] = '0'; value[apn_length + 6] = serving_network->mnc[0] + '0'; value[apn_length + 7] = serving_network->mnc[1] + '0'; } else { value[apn_length + 5] = serving_network->mnc[0] + '0'; value[apn_length + 6] = serving_network->mnc[1] + '0'; value[apn_length + 7] = serving_network->mnc[2] + '0'; } value[apn_length + 12] = serving_network->mcc[0] + '0'; value[apn_length + 13] = serving_network->mcc[1] + '0'; value[apn_length + 14] = serving_network->mcc[2] + '0'; *last_size = apn_length + 19; rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_APN, apn_length + 20, 0, value); DevAssert(NW_OK == rc); free_wrapper((void**)&value); return RETURNok; } status_code_e gtpv2c_uli_ie_set(nw_gtpv2c_msg_handle_t* msg, const Uli_t* uli) { nw_rc_t rc; uint8_t value[22]; uint8_t* current = NULL; uint8_t length = 1; // present field DevAssert(uli); DevAssert(msg); value[0] = uli->present; current = &value[1]; if (ULI_CGI & uli->present) { current[0] = (uli->s.cgi.mcc[1] << 4) | (uli->s.cgi.mcc[0]); current[1] = (uli->s.cgi.mnc[2] << 4) | (uli->s.cgi.mcc[2]); current[2] = (uli->s.cgi.mnc[1] << 4) | (uli->s.cgi.mnc[0]); current[3] = (uint8_t)((uli->s.cgi.lac & 0xFF00) >> 8); current[4] = (uint8_t)(uli->s.cgi.lac & 0x00FF); current[5] = (uint8_t)((uli->s.cgi.ci & 0xFF00) >> 8); current[6] = (uint8_t)(uli->s.cgi.ci & 0x00FF); current = &current[7]; length += 7; } if (ULI_TAI & uli->present) { tai_to_bytes(&uli->s.tai, (char*)current); current = &current[5]; length += 5; } if (ULI_ECGI & uli->present) { current[0] = (uli->s.ecgi.plmn.mcc_digit2 << 4) | (uli->s.ecgi.plmn.mcc_digit1); current[1] = (uli->s.ecgi.plmn.mnc_digit3 << 4) | (uli->s.ecgi.plmn.mcc_digit3); current[2] = (uli->s.ecgi.plmn.mnc_digit2 << 4) | (uli->s.ecgi.plmn.mnc_digit1); current[3] = (uint8_t)((uli->s.ecgi.cell_identity.enb_id & 0x000F0000) >> 16); current[4] = (uint8_t)((uli->s.ecgi.cell_identity.enb_id & 0x0000FF00) >> 8); current[5] = (uint8_t)(uli->s.ecgi.cell_identity.enb_id & 0x000000FF); current[6] = (uint8_t)(uli->s.ecgi.cell_identity.cell_id); current = &current[7]; length += 7; } current = NULL; rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_ULI, length, 0, value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_uli_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { Uli_t* uli = (Uli_t*)arg; DevAssert(uli); uli->present = ieValue[0]; if (uli->present & ULI_CGI) { } return NW_OK; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_ip_address_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { gtp_ip_address_t* ip_address = (gtp_ip_address_t*)arg; DevAssert(ip_address); if (ieLength == 4) { ip_address->present = GTP_IP_ADDR_v4; // This is an IPv4 Address memcpy(ip_address->address.v4, ieValue, 4); } else if (ieLength == 16) { ip_address->present = GTP_IP_ADDR_v6; // This is an IPv6 Address memcpy(ip_address->address.v6, ieValue, 16); } else { return NW_GTPV2C_IE_INCORRECT; // Length doesn't lie in possible values } return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_ip_address_ie_set(nw_gtpv2c_msg_handle_t* msg, const gtp_ip_address_t* ip_address) { return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_delay_value_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { DelayValue_t* delay_value = (DelayValue_t*)arg; DevAssert(arg); if (ieLength != 1) { return NW_GTPV2C_IE_INCORRECT; } *delay_value = ieValue[0]; OAILOG_DEBUG(LOG_S11, "\t - Delay Value %u\n", *delay_value); return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_delay_value_ie_set(nw_gtpv2c_msg_handle_t* msg, const DelayValue_t* delay_value) { uint8_t value; nw_rc_t rc; DevAssert(msg); DevAssert(delay_value); value = *delay_value; rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_DELAY_VALUE, 1, 0, (uint8_t*)&value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_ue_time_zone_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { UETimeZone_t* ue_time_zone = (UETimeZone_t*)arg; DevAssert(ue_time_zone); if (ieLength != 2) { return NW_GTPV2C_IE_INCORRECT; } ue_time_zone->time_zone = ieValue[0]; ue_time_zone->daylight_saving_time = ieValue[1] & 0x03; OAILOG_DEBUG(LOG_S11, "\t - Time Zone %u\n", ue_time_zone->time_zone); OAILOG_DEBUG(LOG_S11, "\t - Daylight SVT %u\n", ue_time_zone->daylight_saving_time); return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_ue_time_zone_ie_set(nw_gtpv2c_msg_handle_t* msg, const UETimeZone_t* ue_time_zone) { uint8_t value[2]; nw_rc_t rc; DevAssert(msg); DevAssert(ue_time_zone); value[0] = ue_time_zone->time_zone; value[1] = ue_time_zone->daylight_saving_time; rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_UE_TIME_ZONE, 2, 0, value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_bearer_flags_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { bearer_flags_t* bearer_flags = (bearer_flags_t*)arg; DevAssert(arg); if (ieLength != 1) { return NW_GTPV2C_IE_INCORRECT; } bearer_flags->ppc = ieValue[0] & 0x01; bearer_flags->vb = ieValue[0] & 0x02; return NW_OK; } //------------------------------------------------------------------------------ status_code_e gtpv2c_bearer_flags_ie_set(nw_gtpv2c_msg_handle_t* msg, const bearer_flags_t* bearer_flags) { nw_rc_t rc; uint8_t value; DevAssert(msg); DevAssert(bearer_flags); value = (bearer_flags->vb << 1) | bearer_flags->ppc; rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_BEARER_FLAGS, 1, 0, (uint8_t*)&value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_indication_flags_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { indication_flags_t* indication_flags = (indication_flags_t*)arg; DevAssert(indication_flags); if (2 <= ieLength) { // think about more than 3 later indication_flags->daf = (ieValue[0] >> DAF_FLAG_BIT_POS) & 0x01; indication_flags->dtf = (ieValue[0] >> DTF_FLAG_BIT_POS) & 0x01; indication_flags->hi = (ieValue[0] >> HI_FLAG_BIT_POS) & 0x01; indication_flags->dfi = (ieValue[0] >> DFI_FLAG_BIT_POS) & 0x01; indication_flags->oi = (ieValue[0] >> OI_FLAG_BIT_POS) & 0x01; indication_flags->isrsi = (ieValue[0] >> ISRSI_FLAG_BIT_POS) & 0x01; indication_flags->israi = (ieValue[0] >> ISRAI_FLAG_BIT_POS) & 0x01; indication_flags->sgwci = (ieValue[0] >> SGWCI_FLAG_BIT_POS) & 0x01; indication_flags->sqci = (ieValue[1] >> SQSI_FLAG_BIT_POS) & 0x01; indication_flags->uimsi = (ieValue[1] >> UIMSI_FLAG_BIT_POS) & 0x01; indication_flags->cfsi = (ieValue[1] >> CFSI_FLAG_BIT_POS) & 0x01; indication_flags->crsi = (ieValue[1] >> CRSI_FLAG_BIT_POS) & 0x01; indication_flags->p = (ieValue[1] >> P_FLAG_BIT_POS) & 0x01; indication_flags->pt = (ieValue[1] >> PT_FLAG_BIT_POS) & 0x01; indication_flags->si = (ieValue[1] >> SI_FLAG_BIT_POS) & 0x01; indication_flags->msv = (ieValue[1] >> MSV_FLAG_BIT_POS) & 0x01; if (2 == ieLength) { return NW_OK; } if (3 == ieLength) { indication_flags->spare1 = 0; indication_flags->spare2 = 0; indication_flags->spare3 = 0; indication_flags->s6af = (ieValue[2] >> S6AF_FLAG_BIT_POS) & 0x01; indication_flags->s4af = (ieValue[2] >> S4AF_FLAG_BIT_POS) & 0x01; indication_flags->mbmdt = (ieValue[2] >> MBMDT_FLAG_BIT_POS) & 0x01; indication_flags->israu = (ieValue[2] >> ISRAU_FLAG_BIT_POS) & 0x01; indication_flags->ccrsi = (ieValue[2] >> CRSI_FLAG_BIT_POS) & 0x01; return NW_OK; } } return NW_GTPV2C_IE_INCORRECT; } //------------------------------------------------------------------------------ status_code_e gtpv2c_indication_flags_ie_set( nw_gtpv2c_msg_handle_t* msg, const indication_flags_t* indication_flags) { nw_rc_t rc; uint8_t value[3]; DevAssert(msg); DevAssert(indication_flags); value[0] = (indication_flags->daf << DAF_FLAG_BIT_POS) | (indication_flags->dtf << DTF_FLAG_BIT_POS) | (indication_flags->hi << HI_FLAG_BIT_POS) | (indication_flags->dfi << DFI_FLAG_BIT_POS) | (indication_flags->oi << OI_FLAG_BIT_POS) | (indication_flags->isrsi << ISRSI_FLAG_BIT_POS) | (indication_flags->israi << ISRAI_FLAG_BIT_POS) | (indication_flags->sgwci << SGWCI_FLAG_BIT_POS); value[1] = (indication_flags->sqci << SQSI_FLAG_BIT_POS) | (indication_flags->uimsi << UIMSI_FLAG_BIT_POS) | (indication_flags->cfsi << CFSI_FLAG_BIT_POS) | (indication_flags->crsi << CRSI_FLAG_BIT_POS) | (indication_flags->p << P_FLAG_BIT_POS) | (indication_flags->pt << PT_FLAG_BIT_POS) | (indication_flags->si << SI_FLAG_BIT_POS) | (indication_flags->msv << MSV_FLAG_BIT_POS); value[2] = (indication_flags->s6af << S6AF_FLAG_BIT_POS) | (indication_flags->s4af << S4AF_FLAG_BIT_POS) | (indication_flags->mbmdt << MBMDT_FLAG_BIT_POS) | (indication_flags->israu << ISRAU_FLAG_BIT_POS) | (indication_flags->ccrsi << CCRSI_FLAG_BIT_POS); rc = nwGtpv2cMsgAddIe(*msg, NW_GTPV2C_IE_INDICATION, 3, 0, (uint8_t*)value); DevAssert(NW_OK == rc); return RETURNok; } //------------------------------------------------------------------------------ nw_rc_t gtpv2c_fqcsid_ie_get(uint8_t ieType, uint16_t ieLength, uint8_t ieInstance, uint8_t* ieValue, void* arg) { FQ_CSID_t* fq_csid = (FQ_CSID_t*)arg; DevAssert(fq_csid); fq_csid->node_id_type = (ieValue[0] & 0xF0) >> 4; OAILOG_DEBUG(LOG_S11, "\t- FQ-CSID type %u\n", fq_csid->node_id_type); /* * NOTE: Values of Number of CSID other than 1 are only employed in the * * * * Delete PDN Connection Set Request and Response. */ if ((ieValue[0] & 0x0F) != 1) { return NW_GTPV2C_IE_INCORRECT; } switch (fq_csid->node_id_type) { case GLOBAL_UNICAST_IPv4: { char ipv4[INET_ADDRSTRLEN]; if (ieLength != 7) { return NW_GTPV2C_IE_INCORRECT; } int addr = (((uint32_t)ieValue[1]) << 24) | (((uint32_t)ieValue[2]) << 16) | (((uint32_t)ieValue[3]) << 8) | ((uint32_t)ieValue[4]); fq_csid->node_id.unicast_ipv4.s_addr = addr; fq_csid->csid = (ieValue[5] << 8) | ieValue[6]; inet_ntop(AF_INET, (void*)&fq_csid->node_id.unicast_ipv4, ipv4, INET_ADDRSTRLEN); OAILOG_DEBUG(LOG_S11, "\t- v4 address [%s]\n", ipv4); } break; case GLOBAL_UNICAST_IPv6: { char ipv6[INET6_ADDRSTRLEN]; if (ieLength != 19) { return NW_GTPV2C_IE_INCORRECT; } memcpy(fq_csid->node_id.unicast_ipv6.__in6_u.__u6_addr8, &ieValue[1], 16); fq_csid->csid = (ieValue[17] << 8) | ieValue[18]; // Convert the ipv6 to printable string inet_ntop(AF_INET6, (void*)&fq_csid->node_id.unicast_ipv6, ipv6, INET6_ADDRSTRLEN); OAILOG_DEBUG(LOG_S11, "\t- v6 address [%s]\n", ipv6); } break; default: return NW_GTPV2C_IE_INCORRECT; } OAILOG_DEBUG(LOG_S11, "\t- CSID 0x%04x\n", fq_csid->csid); return NW_OK; }
483892.c
/* Remote debugging interface to m32r and mon2000 ROM monitors for GDB, the GNU debugger. Copyright (C) 1996-2014 Free Software Foundation, Inc. Adapted by Michael Snyder of Cygnus Support. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* This module defines communication with the Renesas m32r monitor. */ #include "defs.h" #include "gdbcore.h" #include "target.h" #include "exceptions.h" #include "monitor.h" #include "serial.h" #include "symtab.h" #include "command.h" #include "gdbcmd.h" #include "symfile.h" /* for generic load */ #include <sys/time.h> #include <time.h> /* for time_t */ #include <string.h> #include "objfiles.h" /* for ALL_OBJFILES etc. */ #include "inferior.h" #include <ctype.h> #include "regcache.h" #include "gdb_bfd.h" #include "cli/cli-utils.h" /* * All this stuff just to get my host computer's IP address! */ #ifdef __MINGW32__ #include <winsock2.h> #else #include <sys/types.h> #include <netdb.h> /* for hostent */ #include <netinet/in.h> /* for struct in_addr */ #if 1 #include <arpa/inet.h> /* for inet_ntoa */ #endif #endif static char *board_addr; /* user-settable IP address for M32R-EVA */ static char *server_addr; /* user-settable IP address for gdb host */ static char *download_path; /* user-settable path for SREC files */ /* REGNUM */ #define PSW_REGNUM 16 #define SPI_REGNUM 18 #define SPU_REGNUM 19 #define ACCL_REGNUM 22 #define ACCH_REGNUM 23 /* * Function: m32r_load_1 (helper function) */ static void m32r_load_section (bfd *abfd, asection *s, void *obj) { unsigned int *data_count = obj; if (s->flags & SEC_LOAD) { int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8; bfd_size_type section_size = bfd_section_size (abfd, s); bfd_vma section_base = bfd_section_lma (abfd, s); unsigned int buffer, i; *data_count += section_size; printf_filtered ("Loading section %s, size 0x%lx lma ", bfd_section_name (abfd, s), (unsigned long) section_size); fputs_filtered (paddress (target_gdbarch (), section_base), gdb_stdout); printf_filtered ("\n"); gdb_flush (gdb_stdout); monitor_printf ("%s mw\r", phex_nz (section_base, addr_size)); for (i = 0; i < section_size; i += 4) { QUIT; monitor_expect (" -> ", NULL, 0); bfd_get_section_contents (abfd, s, (char *) &buffer, i, 4); monitor_printf ("%x\n", buffer); } monitor_expect (" -> ", NULL, 0); monitor_printf ("q\n"); monitor_expect_prompt (NULL, 0); } } static int m32r_load_1 (void *dummy) { int data_count = 0; bfd_map_over_sections ((bfd *) dummy, m32r_load_section, &data_count); return data_count; } /* * Function: m32r_load (an alternate way to load) */ static void m32r_load (char *filename, int from_tty) { bfd *abfd; unsigned int data_count = 0; struct timeval start_time, end_time; struct cleanup *cleanup; if (filename == NULL || filename[0] == 0) filename = get_exec_file (1); abfd = gdb_bfd_open (filename, NULL, -1); if (!abfd) error (_("Unable to open file %s."), filename); cleanup = make_cleanup_bfd_unref (abfd); if (bfd_check_format (abfd, bfd_object) == 0) error (_("File is not an object file.")); gettimeofday (&start_time, NULL); #if 0 for (s = abfd->sections; s; s = s->next) if (s->flags & SEC_LOAD) { bfd_size_type section_size = bfd_section_size (abfd, s); bfd_vma section_base = bfd_section_vma (abfd, s); unsigned int buffer; data_count += section_size; printf_filtered ("Loading section %s, size 0x%lx vma ", bfd_section_name (abfd, s), section_size); fputs_filtered (paddress (target_gdbarch (), section_base), gdb_stdout); printf_filtered ("\n"); gdb_flush (gdb_stdout); monitor_printf ("%x mw\r", section_base); for (i = 0; i < section_size; i += 4) { monitor_expect (" -> ", NULL, 0); bfd_get_section_contents (abfd, s, (char *) &buffer, i, 4); monitor_printf ("%x\n", buffer); } monitor_expect (" -> ", NULL, 0); monitor_printf ("q\n"); monitor_expect_prompt (NULL, 0); } #else if (!(catch_errors (m32r_load_1, abfd, "Load aborted!\n", RETURN_MASK_ALL))) { monitor_printf ("q\n"); do_cleanups (cleanup); return; } #endif gettimeofday (&end_time, NULL); printf_filtered ("Start address 0x%lx\n", (unsigned long) bfd_get_start_address (abfd)); print_transfer_performance (gdb_stdout, data_count, 0, &start_time, &end_time); /* Finally, make the PC point at the start address. */ if (exec_bfd) regcache_write_pc (get_current_regcache (), bfd_get_start_address (exec_bfd)); inferior_ptid = null_ptid; /* No process now. */ /* This is necessary because many things were based on the PC at the time that we attached to the monitor, which is no longer valid now that we have loaded new code (and just changed the PC). Another way to do this might be to call normal_stop, except that the stack may not be valid, and things would get horribly confused... */ clear_symtab_users (0); do_cleanups (cleanup); } static void m32r_load_gen (struct target_ops *self, char *filename, int from_tty) { generic_load (filename, from_tty); } static void m32r_open (char *args, int from_tty); static void mon2000_open (char *args, int from_tty); /* This array of registers needs to match the indexes used by GDB. The whole reason this exists is because the various ROM monitors use different names than GDB does, and don't support all the registers either. So, typing "info reg sp" becomes an "A7". */ static char *m32r_regnames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "psw", "cbr", "spi", "spu", "bpc", "pc", "accl", "acch", }; static void m32r_supply_register (struct regcache *regcache, char *regname, int regnamelen, char *val, int vallen) { int regno; int num_regs = sizeof (m32r_regnames) / sizeof (m32r_regnames[0]); struct gdbarch *gdbarch = get_regcache_arch (regcache); for (regno = 0; regno < num_regs; regno++) if (strncmp (regname, m32r_regnames[regno], regnamelen) == 0) break; if (regno >= num_regs) return; /* no match */ if (regno == ACCL_REGNUM) { /* Special handling for 64-bit acc reg. */ monitor_supply_register (regcache, ACCH_REGNUM, val); val = strchr (val, ':'); /* Skip past ':' to get 2nd word. */ if (val != NULL) monitor_supply_register (regcache, ACCL_REGNUM, val + 1); } else { monitor_supply_register (regcache, regno, val); if (regno == PSW_REGNUM) { #if (defined SM_REGNUM || defined BSM_REGNUM || defined IE_REGNUM \ || defined BIE_REGNUM || defined COND_REGNUM || defined CBR_REGNUM \ || defined BPC_REGNUM || defined BCARRY_REGNUM) unsigned long psw = strtoul (val, NULL, 16); char *zero = "00000000", *one = "00000001"; #endif #ifdef SM_REGNUM /* Stack mode bit */ monitor_supply_register (regcache, SM_REGNUM, (psw & 0x80) ? one : zero); #endif #ifdef BSM_REGNUM /* Backup stack mode bit */ monitor_supply_register (regcache, BSM_REGNUM, (psw & 0x8000) ? one : zero); #endif #ifdef IE_REGNUM /* Interrupt enable bit */ monitor_supply_register (regcache, IE_REGNUM, (psw & 0x40) ? one : zero); #endif #ifdef BIE_REGNUM /* Backup interrupt enable bit */ monitor_supply_register (regcache, BIE_REGNUM, (psw & 0x4000) ? one : zero); #endif #ifdef COND_REGNUM /* Condition bit (carry etc.) */ monitor_supply_register (regcache, COND_REGNUM, (psw & 0x1) ? one : zero); #endif #ifdef CBR_REGNUM monitor_supply_register (regcache, CBR_REGNUM, (psw & 0x1) ? one : zero); #endif #ifdef BPC_REGNUM monitor_supply_register (regcache, BPC_REGNUM, zero); /* KLUDGE: (???????) */ #endif #ifdef BCARRY_REGNUM monitor_supply_register (regcache, BCARRY_REGNUM, zero); /* KLUDGE: (??????) */ #endif } if (regno == SPI_REGNUM || regno == SPU_REGNUM) { /* special handling for stack pointer (spu or spi). */ ULONGEST stackmode, psw; regcache_cooked_read_unsigned (regcache, PSW_REGNUM, &psw); stackmode = psw & 0x80; if (regno == SPI_REGNUM && !stackmode) /* SP == SPI */ monitor_supply_register (regcache, gdbarch_sp_regnum (gdbarch), val); else if (regno == SPU_REGNUM && stackmode) /* SP == SPU */ monitor_supply_register (regcache, gdbarch_sp_regnum (gdbarch), val); } } } /* m32r RevC board monitor */ static struct target_ops m32r_ops; static char *m32r_inits[] = { "\r", NULL }; static struct monitor_ops m32r_cmds; static void init_m32r_cmds (void) { m32r_cmds.flags = MO_CLR_BREAK_USES_ADDR | MO_REGISTER_VALUE_FIRST; m32r_cmds.init = m32r_inits; /* Init strings */ m32r_cmds.cont = "go\r"; /* continue command */ m32r_cmds.step = "step\r"; /* single step */ m32r_cmds.stop = NULL; /* interrupt command */ m32r_cmds.set_break = "%x +bp\r"; /* set a breakpoint */ m32r_cmds.clr_break = "%x -bp\r"; /* clear a breakpoint */ m32r_cmds.clr_all_break = "bpoff\r"; /* clear all breakpoints */ m32r_cmds.fill = "%x %x %x fill\r"; /* fill (start length val) */ m32r_cmds.setmem.cmdb = "%x 1 %x fill\r"; /* setmem.cmdb (addr, value) */ m32r_cmds.setmem.cmdw = "%x 1 %x fillh\r"; /* setmem.cmdw (addr, value) */ m32r_cmds.setmem.cmdl = "%x 1 %x fillw\r"; /* setmem.cmdl (addr, value) */ m32r_cmds.setmem.cmdll = NULL; /* setmem.cmdll (addr, value) */ m32r_cmds.setmem.resp_delim = NULL; /* setmem.resp_delim */ m32r_cmds.setmem.term = NULL; /* setmem.term */ m32r_cmds.setmem.term_cmd = NULL; /* setmem.term_cmd */ m32r_cmds.getmem.cmdb = "%x %x dump\r"; /* getmem.cmdb (addr, len) */ m32r_cmds.getmem.cmdw = NULL; /* getmem.cmdw (addr, len) */ m32r_cmds.getmem.cmdl = NULL; /* getmem.cmdl (addr, len) */ m32r_cmds.getmem.cmdll = NULL; /* getmem.cmdll (addr, len) */ m32r_cmds.getmem.resp_delim = ": "; /* getmem.resp_delim */ m32r_cmds.getmem.term = NULL; /* getmem.term */ m32r_cmds.getmem.term_cmd = NULL; /* getmem.term_cmd */ m32r_cmds.setreg.cmd = "%x to %%%s\r"; /* setreg.cmd (name, value) */ m32r_cmds.setreg.resp_delim = NULL; /* setreg.resp_delim */ m32r_cmds.setreg.term = NULL; /* setreg.term */ m32r_cmds.setreg.term_cmd = NULL; /* setreg.term_cmd */ m32r_cmds.getreg.cmd = NULL; /* getreg.cmd (name) */ m32r_cmds.getreg.resp_delim = NULL; /* getreg.resp_delim */ m32r_cmds.getreg.term = NULL; /* getreg.term */ m32r_cmds.getreg.term_cmd = NULL; /* getreg.term_cmd */ m32r_cmds.dump_registers = ".reg\r"; /* dump_registers */ /* register_pattern */ m32r_cmds.register_pattern = "\\(\\w+\\) += \\([0-9a-fA-F]+\\b\\)"; m32r_cmds.supply_register = m32r_supply_register; m32r_cmds.load = NULL; /* download command */ m32r_cmds.loadresp = NULL; /* load response */ m32r_cmds.prompt = "ok "; /* monitor command prompt */ m32r_cmds.line_term = "\r"; /* end-of-line terminator */ m32r_cmds.cmd_end = NULL; /* optional command terminator */ m32r_cmds.target = &m32r_ops; /* target operations */ m32r_cmds.stopbits = SERIAL_1_STOPBITS; /* number of stop bits */ m32r_cmds.regnames = m32r_regnames; /* registers names */ m32r_cmds.magic = MONITOR_OPS_MAGIC; /* magic */ } /* init_m32r_cmds */ static void m32r_open (char *args, int from_tty) { monitor_open (args, &m32r_cmds, from_tty); } /* Mon2000 monitor (MSA2000 board) */ static struct target_ops mon2000_ops; static struct monitor_ops mon2000_cmds; static void init_mon2000_cmds (void) { mon2000_cmds.flags = MO_CLR_BREAK_USES_ADDR | MO_REGISTER_VALUE_FIRST; mon2000_cmds.init = m32r_inits; /* Init strings */ mon2000_cmds.cont = "go\r"; /* continue command */ mon2000_cmds.step = "step\r"; /* single step */ mon2000_cmds.stop = NULL; /* interrupt command */ mon2000_cmds.set_break = "%x +bp\r"; /* set a breakpoint */ mon2000_cmds.clr_break = "%x -bp\r"; /* clear a breakpoint */ mon2000_cmds.clr_all_break = "bpoff\r"; /* clear all breakpoints */ mon2000_cmds.fill = "%x %x %x fill\r"; /* fill (start length val) */ mon2000_cmds.setmem.cmdb = "%x 1 %x fill\r"; /* setmem.cmdb (addr, value) */ mon2000_cmds.setmem.cmdw = "%x 1 %x fillh\r"; /* setmem.cmdw (addr, value) */ mon2000_cmds.setmem.cmdl = "%x 1 %x fillw\r"; /* setmem.cmdl (addr, value) */ mon2000_cmds.setmem.cmdll = NULL; /* setmem.cmdll (addr, value) */ mon2000_cmds.setmem.resp_delim = NULL; /* setmem.resp_delim */ mon2000_cmds.setmem.term = NULL; /* setmem.term */ mon2000_cmds.setmem.term_cmd = NULL; /* setmem.term_cmd */ mon2000_cmds.getmem.cmdb = "%x %x dump\r"; /* getmem.cmdb (addr, len) */ mon2000_cmds.getmem.cmdw = NULL; /* getmem.cmdw (addr, len) */ mon2000_cmds.getmem.cmdl = NULL; /* getmem.cmdl (addr, len) */ mon2000_cmds.getmem.cmdll = NULL; /* getmem.cmdll (addr, len) */ mon2000_cmds.getmem.resp_delim = ": "; /* getmem.resp_delim */ mon2000_cmds.getmem.term = NULL; /* getmem.term */ mon2000_cmds.getmem.term_cmd = NULL; /* getmem.term_cmd */ mon2000_cmds.setreg.cmd = "%x to %%%s\r"; /* setreg.cmd (name, value) */ mon2000_cmds.setreg.resp_delim = NULL; /* setreg.resp_delim */ mon2000_cmds.setreg.term = NULL; /* setreg.term */ mon2000_cmds.setreg.term_cmd = NULL; /* setreg.term_cmd */ mon2000_cmds.getreg.cmd = NULL; /* getreg.cmd (name) */ mon2000_cmds.getreg.resp_delim = NULL; /* getreg.resp_delim */ mon2000_cmds.getreg.term = NULL; /* getreg.term */ mon2000_cmds.getreg.term_cmd = NULL; /* getreg.term_cmd */ mon2000_cmds.dump_registers = ".reg\r"; /* dump_registers */ /* register_pattern */ mon2000_cmds.register_pattern = "\\(\\w+\\) += \\([0-9a-fA-F]+\\b\\)"; mon2000_cmds.supply_register = m32r_supply_register; mon2000_cmds.load = NULL; /* download command */ mon2000_cmds.loadresp = NULL; /* load response */ mon2000_cmds.prompt = "Mon2000>"; /* monitor command prompt */ mon2000_cmds.line_term = "\r"; /* end-of-line terminator */ mon2000_cmds.cmd_end = NULL; /* optional command terminator */ mon2000_cmds.target = &mon2000_ops; /* target operations */ mon2000_cmds.stopbits = SERIAL_1_STOPBITS; /* number of stop bits */ mon2000_cmds.regnames = m32r_regnames; /* registers names */ mon2000_cmds.magic = MONITOR_OPS_MAGIC; /* magic */ } /* init_mon2000_cmds */ static void mon2000_open (char *args, int from_tty) { monitor_open (args, &mon2000_cmds, from_tty); } static void m32r_upload_command (char *args, int from_tty) { bfd *abfd; asection *s; struct timeval start_time, end_time; int resp_len, data_count = 0; char buf[1024]; struct hostent *hostent; struct in_addr inet_addr; struct cleanup *cleanup; /* First check to see if there's an ethernet port! */ monitor_printf ("ust\r"); resp_len = monitor_expect_prompt (buf, sizeof (buf)); if (!strchr (buf, ':')) error (_("No ethernet connection!")); if (board_addr == 0) { /* Scan second colon in the output from the "ust" command. */ char *myIPaddress = strchr (strchr (buf, ':') + 1, ':') + 1; myIPaddress = skip_spaces (myIPaddress); if (!strncmp (myIPaddress, "0.0.", 4)) /* empty */ error (_("Please use 'set board-address' to " "set the M32R-EVA board's IP address.")); if (strchr (myIPaddress, '(')) *(strchr (myIPaddress, '(')) = '\0'; /* delete trailing junk */ board_addr = xstrdup (myIPaddress); } if (server_addr == 0) { #ifdef __MINGW32__ WSADATA wd; /* Winsock initialization. */ if (WSAStartup (MAKEWORD (1, 1), &wd)) error (_("Couldn't initialize WINSOCK.")); #endif buf[0] = 0; gethostname (buf, sizeof (buf)); if (buf[0] != 0) { hostent = gethostbyname (buf); if (hostent != 0) { #if 1 memcpy (&inet_addr.s_addr, hostent->h_addr, sizeof (inet_addr.s_addr)); server_addr = (char *) inet_ntoa (inet_addr); #else server_addr = (char *) inet_ntoa (hostent->h_addr); #endif } } if (server_addr == 0) /* failed? */ error (_("Need to know gdb host computer's " "IP address (use 'set server-address')")); } if (args == 0 || args[0] == 0) /* No args: upload the current file. */ args = get_exec_file (1); if (args[0] != '/' && download_path == 0) { if (current_directory) download_path = xstrdup (current_directory); else error (_("Need to know default download " "path (use 'set download-path')")); } gettimeofday (&start_time, NULL); monitor_printf ("uhip %s\r", server_addr); resp_len = monitor_expect_prompt (buf, sizeof (buf)); /* parse result? */ monitor_printf ("ulip %s\r", board_addr); resp_len = monitor_expect_prompt (buf, sizeof (buf)); /* parse result? */ if (args[0] != '/') monitor_printf ("up %s\r", download_path); /* use default path */ else monitor_printf ("up\r"); /* rooted filename/path */ resp_len = monitor_expect_prompt (buf, sizeof (buf)); /* parse result? */ if (strrchr (args, '.') && !strcmp (strrchr (args, '.'), ".srec")) monitor_printf ("ul %s\r", args); else /* add ".srec" suffix */ monitor_printf ("ul %s.srec\r", args); resp_len = monitor_expect_prompt (buf, sizeof (buf)); /* parse result? */ if (buf[0] == 0 || strstr (buf, "complete") == 0) error (_("Upload file not found: %s.srec\n" "Check IP addresses and download path."), args); else printf_filtered (" -- Ethernet load complete.\n"); gettimeofday (&end_time, NULL); abfd = gdb_bfd_open (args, NULL, -1); cleanup = make_cleanup_bfd_unref (abfd); if (abfd != NULL) { /* Download is done -- print section statistics. */ if (bfd_check_format (abfd, bfd_object) == 0) { printf_filtered ("File is not an object file\n"); } for (s = abfd->sections; s; s = s->next) if (s->flags & SEC_LOAD) { bfd_size_type section_size = bfd_section_size (abfd, s); bfd_vma section_base = bfd_section_lma (abfd, s); data_count += section_size; printf_filtered ("Loading section %s, size 0x%lx lma ", bfd_section_name (abfd, s), (unsigned long) section_size); fputs_filtered (paddress (target_gdbarch (), section_base), gdb_stdout); printf_filtered ("\n"); gdb_flush (gdb_stdout); } /* Finally, make the PC point at the start address. */ regcache_write_pc (get_current_regcache (), bfd_get_start_address (abfd)); printf_filtered ("Start address 0x%lx\n", (unsigned long) bfd_get_start_address (abfd)); print_transfer_performance (gdb_stdout, data_count, 0, &start_time, &end_time); } inferior_ptid = null_ptid; /* No process now. */ /* This is necessary because many things were based on the PC at the time that we attached to the monitor, which is no longer valid now that we have loaded new code (and just changed the PC). Another way to do this might be to call normal_stop, except that the stack may not be valid, and things would get horribly confused... */ clear_symtab_users (0); do_cleanups (cleanup); } /* Provide a prototype to silence -Wmissing-prototypes. */ extern initialize_file_ftype _initialize_m32r_rom; void _initialize_m32r_rom (void) { /* Initialize m32r RevC monitor target. */ init_m32r_cmds (); init_monitor_ops (&m32r_ops); m32r_ops.to_shortname = "m32r"; m32r_ops.to_longname = "m32r monitor"; m32r_ops.to_load = m32r_load_gen; /* Monitor lacks a download command. */ m32r_ops.to_doc = "Debug via the m32r monitor.\n\ Specify the serial device it is connected to (e.g. /dev/ttya)."; m32r_ops.to_open = m32r_open; add_target (&m32r_ops); /* Initialize mon2000 monitor target */ init_mon2000_cmds (); init_monitor_ops (&mon2000_ops); mon2000_ops.to_shortname = "mon2000"; mon2000_ops.to_longname = "Mon2000 monitor"; mon2000_ops.to_load = m32r_load_gen; /* Monitor lacks a download command. */ mon2000_ops.to_doc = "Debug via the Mon2000 monitor.\n\ Specify the serial device it is connected to (e.g. /dev/ttya)."; mon2000_ops.to_open = mon2000_open; add_target (&mon2000_ops); add_setshow_string_cmd ("download-path", class_obscure, &download_path, _("\ Set the default path for downloadable SREC files."), _("\ Show the default path for downloadable SREC files."), _("\ Determines the default path for downloadable SREC files."), NULL, NULL, /* FIXME: i18n: The default path for downloadable SREC files is %s. */ &setlist, &showlist); add_setshow_string_cmd ("board-address", class_obscure, &board_addr, _("\ Set IP address for M32R-EVA target board."), _("\ Show IP address for M32R-EVA target board."), _("\ Determine the IP address for M32R-EVA target board."), NULL, NULL, /* FIXME: i18n: IP address for M32R-EVA target board is %s. */ &setlist, &showlist); add_setshow_string_cmd ("server-address", class_obscure, &server_addr, _("\ Set IP address for download server (GDB's host computer)."), _("\ Show IP address for download server (GDB's host computer)."), _("\ Determine the IP address for download server (GDB's host computer)."), NULL, NULL, /* FIXME: i18n: IP address for download server (GDB's host computer) is %s. */ &setlist, &showlist); add_com ("upload", class_obscure, m32r_upload_command, _("\ Upload the srec file via the monitor's Ethernet upload capability.")); add_com ("tload", class_obscure, m32r_load, _("test upload command.")); }
182347.c
/*- * BSD LICENSE * * Copyright (c) Intel Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "env_internal.h" #include "spdk/pci_ids.h" static struct rte_pci_id nvme_pci_driver_id[] = { #if RTE_VERSION >= RTE_VERSION_NUM(16, 7, 0, 1) { .class_id = SPDK_PCI_CLASS_NVME, .vendor_id = PCI_ANY_ID, .device_id = PCI_ANY_ID, .subsystem_vendor_id = PCI_ANY_ID, .subsystem_device_id = PCI_ANY_ID, }, #else {RTE_PCI_DEVICE(0x8086, 0x0953)}, #endif { .vendor_id = 0, /* sentinel */ }, }; static struct spdk_pci_enum_ctx g_nvme_pci_drv = { .driver = { .drv_flags = RTE_PCI_DRV_NEED_MAPPING #if RTE_VERSION >= RTE_VERSION_NUM(18, 8, 0, 0) | RTE_PCI_DRV_WC_ACTIVATE #endif , .id_table = nvme_pci_driver_id, #if RTE_VERSION >= RTE_VERSION_NUM(16, 11, 0, 0) .probe = spdk_pci_device_init, .remove = spdk_pci_device_fini, .driver.name = "spdk_nvme", #else .devinit = spdk_pci_device_init, .devuninit = spdk_pci_device_fini, .name = "spdk_nvme", #endif }, .cb_fn = NULL, .cb_arg = NULL, .mtx = PTHREAD_MUTEX_INITIALIZER, .is_registered = false, }; int spdk_pci_nvme_device_attach(spdk_pci_enum_cb enum_cb, void *enum_ctx, struct spdk_pci_addr *pci_address) { return spdk_pci_device_attach(&g_nvme_pci_drv, enum_cb, enum_ctx, pci_address); } int spdk_pci_nvme_enumerate(spdk_pci_enum_cb enum_cb, void *enum_ctx) { return spdk_pci_enumerate(&g_nvme_pci_drv, enum_cb, enum_ctx); }
743639.c
/***************************************************************************** Copyright (c) 2011-2016, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ #include <stdio.h> #define CTEST_MAIN #define CTEST_SEGFAULT #include "openblas_utest.h" int main(int argc, const char ** argv){ int num_fail=0; num_fail=ctest_main(argc, argv); return num_fail; }
896013.c
#ifdef HAVE_CONFIG_H #include "../../../ext_config.h" #endif #include <php.h> #include "../../../php_ext.h" #include "../../../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" #include "kernel/object.h" #include "kernel/operators.h" #include "kernel/memory.h" #include "kernel/fcall.h" #include "kernel/concat.h" #include "kernel/array.h" #include "kernel/exception.h" /** * Phalcon\Queue\Beanstalk\Job * * Represents a job in a beanstalk queue */ ZEPHIR_INIT_CLASS(Phalcon_Queue_Beanstalk_Job) { ZEPHIR_REGISTER_CLASS(Phalcon\\Queue\\Beanstalk, Job, phalcon, queue_beanstalk_job, phalcon_queue_beanstalk_job_method_entry, 0); /** * @var string */ zend_declare_property_null(phalcon_queue_beanstalk_job_ce, SL("_id"), ZEND_ACC_PROTECTED TSRMLS_CC); /** * @var mixed */ zend_declare_property_null(phalcon_queue_beanstalk_job_ce, SL("_body"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_queue_beanstalk_job_ce, SL("_queue"), ZEND_ACC_PROTECTED TSRMLS_CC); return SUCCESS; } /** */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, getId) { RETURN_MEMBER(getThis(), "_id"); } /** */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, getBody) { RETURN_MEMBER(getThis(), "_body"); } /** * Phalcon\Queue\Beanstalk\Job */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, __construct) { zval *id = NULL; zval *queue, *id_param = NULL, *body; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 3, 0, &queue, &id_param, &body); zephir_get_strval(id, id_param); zephir_update_property_this(getThis(), SL("_queue"), queue TSRMLS_CC); zephir_update_property_this(getThis(), SL("_id"), id TSRMLS_CC); zephir_update_property_this(getThis(), SL("_body"), body TSRMLS_CC); ZEPHIR_MM_RESTORE(); } /** * Removes a job from the server entirely */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, delete) { zval *queue = NULL, *_0, *_1, *_2 = NULL, *_3; zend_long ZEPHIR_LAST_CALL_STATUS; ZEPHIR_MM_GROW(); ZEPHIR_OBS_VAR(queue); zephir_read_property_this(&queue, this_ptr, SL("_queue"), PH_NOISY_CC); _0 = zephir_fetch_nproperty_this(this_ptr, SL("_id"), PH_NOISY_CC); ZEPHIR_INIT_VAR(_1); ZEPHIR_CONCAT_SV(_1, "delete ", _0); ZEPHIR_CALL_METHOD(NULL, queue, "write", NULL, 0, _1); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&_2, queue, "readstatus", NULL, 0); zephir_check_call_status(); zephir_array_fetch_long(&_3, _2, 0, PH_NOISY | PH_READONLY, "phalcon/queue/beanstalk/job.zep", 64 TSRMLS_CC); RETURN_MM_BOOL(ZEPHIR_IS_STRING(_3, "DELETED")); } /** * The release command puts a reserved job back into the ready queue (and marks * its state as "ready") to be run by any client. It is normally used when the job * fails because of a transitory error. */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, release) { zval *priority_param = NULL, *delay_param = NULL, *queue = NULL, *_0, _1, _2, *_3, *_4 = NULL, *_5; zend_long priority, delay, ZEPHIR_LAST_CALL_STATUS; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 0, 2, &priority_param, &delay_param); if (!priority_param) { priority = 100; } else { priority = zephir_get_intval(priority_param); } if (!delay_param) { delay = 0; } else { delay = zephir_get_intval(delay_param); } ZEPHIR_OBS_VAR(queue); zephir_read_property_this(&queue, this_ptr, SL("_queue"), PH_NOISY_CC); _0 = zephir_fetch_nproperty_this(this_ptr, SL("_id"), PH_NOISY_CC); ZEPHIR_SINIT_VAR(_1); ZVAL_LONG(&_1, priority); ZEPHIR_SINIT_VAR(_2); ZVAL_LONG(&_2, delay); ZEPHIR_INIT_VAR(_3); ZEPHIR_CONCAT_SVSVSV(_3, "release ", _0, " ", &_1, " ", &_2); ZEPHIR_CALL_METHOD(NULL, queue, "write", NULL, 0, _3); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&_4, queue, "readstatus", NULL, 0); zephir_check_call_status(); zephir_array_fetch_long(&_5, _4, 0, PH_NOISY | PH_READONLY, "phalcon/queue/beanstalk/job.zep", 78 TSRMLS_CC); RETURN_MM_BOOL(ZEPHIR_IS_STRING(_5, "RELEASED")); } /** * The bury command puts a job into the "buried" state. Buried jobs are put into * a FIFO linked list and will not be touched by the server again until a client * kicks them with the "kick" command. */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, bury) { zval *priority_param = NULL, *queue = NULL, *_0, _1, *_2, *_3 = NULL, *_4; zend_long priority, ZEPHIR_LAST_CALL_STATUS; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 0, 1, &priority_param); if (!priority_param) { priority = 100; } else { priority = zephir_get_intval(priority_param); } ZEPHIR_OBS_VAR(queue); zephir_read_property_this(&queue, this_ptr, SL("_queue"), PH_NOISY_CC); _0 = zephir_fetch_nproperty_this(this_ptr, SL("_id"), PH_NOISY_CC); ZEPHIR_SINIT_VAR(_1); ZVAL_LONG(&_1, priority); ZEPHIR_INIT_VAR(_2); ZEPHIR_CONCAT_SVSV(_2, "bury ", _0, " ", &_1); ZEPHIR_CALL_METHOD(NULL, queue, "write", NULL, 0, _2); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&_3, queue, "readstatus", NULL, 0); zephir_check_call_status(); zephir_array_fetch_long(&_4, _3, 0, PH_NOISY | PH_READONLY, "phalcon/queue/beanstalk/job.zep", 92 TSRMLS_CC); RETURN_MM_BOOL(ZEPHIR_IS_STRING(_4, "BURIED")); } /** * The `touch` command allows a worker to request more time to work on a job. * This is useful for jobs that potentially take a long time, but you still * want the benefits of a TTR pulling a job away from an unresponsive worker. * A worker may periodically tell the server that it's still alive and processing * a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto * release of a reserved job until TTR seconds from when the command is issued. */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, touch) { zval *queue = NULL, *_0, *_1, *_2 = NULL, *_3; zend_long ZEPHIR_LAST_CALL_STATUS; ZEPHIR_MM_GROW(); ZEPHIR_OBS_VAR(queue); zephir_read_property_this(&queue, this_ptr, SL("_queue"), PH_NOISY_CC); _0 = zephir_fetch_nproperty_this(this_ptr, SL("_id"), PH_NOISY_CC); ZEPHIR_INIT_VAR(_1); ZEPHIR_CONCAT_SV(_1, "touch ", _0); ZEPHIR_CALL_METHOD(NULL, queue, "write", NULL, 0, _1); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&_2, queue, "readstatus", NULL, 0); zephir_check_call_status(); zephir_array_fetch_long(&_3, _2, 0, PH_NOISY | PH_READONLY, "phalcon/queue/beanstalk/job.zep", 109 TSRMLS_CC); RETURN_MM_BOOL(ZEPHIR_IS_STRING(_3, "TOUCHED")); } /** * Move the job to the ready queue if it is delayed or buried. */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, kick) { zval *queue = NULL, *_0, *_1, *_2 = NULL, *_3; zend_long ZEPHIR_LAST_CALL_STATUS; ZEPHIR_MM_GROW(); ZEPHIR_OBS_VAR(queue); zephir_read_property_this(&queue, this_ptr, SL("_queue"), PH_NOISY_CC); _0 = zephir_fetch_nproperty_this(this_ptr, SL("_id"), PH_NOISY_CC); ZEPHIR_INIT_VAR(_1); ZEPHIR_CONCAT_SV(_1, "kick-job ", _0); ZEPHIR_CALL_METHOD(NULL, queue, "write", NULL, 0, _1); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&_2, queue, "readstatus", NULL, 0); zephir_check_call_status(); zephir_array_fetch_long(&_3, _2, 0, PH_NOISY | PH_READONLY, "phalcon/queue/beanstalk/job.zep", 121 TSRMLS_CC); RETURN_MM_BOOL(ZEPHIR_IS_STRING(_3, "KICKED")); } /** * Gives statistical information about the specified job if it exists. */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, stats) { zval *queue = NULL, *response = NULL, *_0, *_1, *_2, *_3; zend_long ZEPHIR_LAST_CALL_STATUS; ZEPHIR_MM_GROW(); ZEPHIR_OBS_VAR(queue); zephir_read_property_this(&queue, this_ptr, SL("_queue"), PH_NOISY_CC); _0 = zephir_fetch_nproperty_this(this_ptr, SL("_id"), PH_NOISY_CC); ZEPHIR_INIT_VAR(_1); ZEPHIR_CONCAT_SV(_1, "stats-job ", _0); ZEPHIR_CALL_METHOD(NULL, queue, "write", NULL, 0, _1); zephir_check_call_status(); ZEPHIR_CALL_METHOD(&response, queue, "readyaml", NULL, 0); zephir_check_call_status(); zephir_array_fetch_long(&_2, response, 0, PH_NOISY | PH_READONLY, "phalcon/queue/beanstalk/job.zep", 135 TSRMLS_CC); if (ZEPHIR_IS_STRING(_2, "NOT_FOUND")) { RETURN_MM_BOOL(0); } zephir_array_fetch_long(&_3, response, 2, PH_NOISY | PH_READONLY, "phalcon/queue/beanstalk/job.zep", 139 TSRMLS_CC); RETURN_CTOR(_3); } /** * Checks if the job has been modified after unserializing the object */ PHP_METHOD(Phalcon_Queue_Beanstalk_Job, __wakeup) { zval *_0; ZEPHIR_MM_GROW(); ZEPHIR_OBS_VAR(_0); zephir_read_property_this(&_0, this_ptr, SL("_id"), PH_NOISY_CC); if (Z_TYPE_P(_0) != IS_STRING) { ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_queue_beanstalk_exception_ce, "Unexpected inconsistency in Phalcon\\Queue\\Beanstalk\\Job::__wakeup() - possible break-in attempt!", "phalcon/queue/beanstalk/job.zep", 150); return; } ZEPHIR_MM_RESTORE(); }
839851.c
/* Cubesat Space Protocol - A small network-layer protocol designed for Cubesats Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com) Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <pthread.h> #include <unistd.h> #include <errno.h> #include <termios.h> #include <fcntl.h> #include <sys/time.h> #include <i2c_usart_linux.h> #include <csp_if_i2c_uart.h> static int fd = -1; static i2c_usart_callback_t i2c_usart_callback = NULL; static csp_bin_sem_handle_t *i2c_uart_ans_lock = NULL; static void *serial_rx_thread(void *vptr_args); static void i2c_usart_close_fd(void) { if (fd >= 0) { close(fd); } fd = -1; } int i2c_usart_init(const struct i2c_usart_conf * conf) { int brate = 0; switch(conf->baudrate) { case 4800: brate=B4800; break; case 9600: brate=B9600; break; case 19200: brate=B19200; break; case 38400: brate=B38400; break; case 57600: brate=B57600; break; case 115200: brate=B115200; break; case 230400: brate=B230400; break; #ifndef CSP_MACOSX case 460800: brate=B460800; break; case 500000: brate=B500000; break; case 576000: brate=B576000; break; case 921600: brate=B921600; break; case 1000000: brate=B1000000; break; case 1152000: brate=B1152000; break; case 1500000: brate=B1500000; break; case 2000000: brate=B2000000; break; case 2500000: brate=B2500000; break; case 3000000: brate=B3000000; break; case 3500000: brate=B3500000; break; case 4000000: brate=B4000000; break; #endif default: csp_log_error("%s: Unsupported baudrate: %u", __FUNCTION__, conf->baudrate); return CSP_ERR_INVAL; } fd = open(conf->device, O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd < 0) { csp_log_error("%s: failed to open device: [%s], errno: %s", __FUNCTION__, conf->device, strerror(errno)); return CSP_ERR_INVAL; } struct termios options; tcgetattr(fd, &options); cfsetispeed(&options, brate); cfsetospeed(&options, brate); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; options.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG); options.c_iflag &= ~(IGNBRK | BRKINT | ICRNL | INLCR | PARMRK | INPCK | ISTRIP | IXON); options.c_oflag &= ~(OCRNL | ONLCR | ONLRET | ONOCR | OFILL | OPOST); options.c_cc[VTIME] = 0; options.c_cc[VMIN] = 1; /* tcsetattr() succeeds if just one attribute was changed, should read back attributes and check all has been changed */ if (tcsetattr(fd, TCSANOW, &options) != 0) { csp_log_error("%s: Failed to set attributes on device: [%s], errno: %s", __FUNCTION__, conf->device, strerror(errno)); i2c_usart_close_fd(); return CSP_ERR_DRIVER; } fcntl(fd, F_SETFL, 0); /* Flush old transmissions */ if (tcflush(fd, TCIOFLUSH) != 0) { csp_log_error("%s: Error flushing device: [%s], errno: %s", __FUNCTION__, conf->device, strerror(errno)); i2c_usart_close_fd(); return CSP_ERR_DRIVER; } i2c_uart_ans_lock = conf->uart_ans_lock; pthread_t rx_thread; if (pthread_create(&rx_thread, NULL, serial_rx_thread, NULL) != 0) { csp_log_error("%s: pthread_create() failed to create Rx thread for device: [%s], errno: %s", __FUNCTION__, conf->device, strerror(errno)); i2c_usart_close_fd(); return CSP_ERR_NOMEM; } return CSP_ERR_NONE; } void i2c_usart_set_callback(i2c_usart_callback_t callback) { i2c_usart_callback = callback; } void i2c_usart_insert(char c, void * pxTaskWoken) { printf("%c", c); } void i2c_usart_putstr(const char * buf, int len) { if (write(fd, buf, len) != len) return; } void i2c_usart_putc(char c) { if (write(fd, &c, 1) != 1) return; } char i2c_usart_getc(void) { char c; if (read(fd, &c, 1) != 1) return 0; return c; } static void *serial_rx_thread(void *vptr_args) { uint8_t * cbuf = malloc(sizeof(i2c_uart_frame_t)); // Receive loop while (1) { /** printf("UART READING ...\n"); */ memset(cbuf, 0, sizeof(i2c_uart_frame_t)); int nbytes = 0; /* SYNC */ read(fd, cbuf+1, 1); //putchar(cbuf[1]); while(1) { if(cbuf[0] == 'O' && cbuf[1] == 'K') goto new_frame; if(cbuf[0] == 'T' && cbuf[1] == 'X') goto sync_tx; else { cbuf[0] = cbuf[1]; read(fd, cbuf+1, 1); //putchar(cbuf[1]); } } sync_tx: /** printf("[I2C_UART] Releasing lock...\n"); */ csp_bin_sem_post(i2c_uart_ans_lock); continue; new_frame: nbytes += 2; /* Read the rest of the packet */ while(nbytes < sizeof(i2c_uart_frame_t)) { nbytes += read(fd, cbuf+nbytes, sizeof(i2c_uart_frame_t)-2); } if (nbytes <= 0) { csp_log_error("%s: read() failed, returned: %d", __FUNCTION__, nbytes); exit(1); } if (i2c_usart_callback) { i2c_usart_callback(cbuf, nbytes, NULL); } continue; } return NULL; }
305315.c
/* * Copyright (c) 2011, Tom Distler (http://tdistler.com) * All rights reserved. * * The BSD License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the tdistler.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "math_utils.h" extern IQA_INLINE int _round(float a) { int sign_a = a > 0.0f ? 1 : -1; return a-(int)a >= 0.5 ? (int)a + sign_a : (int)a; } extern IQA_INLINE int _max(int x, int y) { return x >= y ? x : y; } extern IQA_INLINE int _min(int x, int y) { return x <= y ? x : y; } extern IQA_INLINE int _cmp_float(float a, float b, int digits) { /* Round */ int sign_a = a > 0.0f ? 1 : -1; int sign_b = b > 0.0f ? 1 : -1; double scale = pow(10.0, (double)digits); double ax = a * scale; double bx = b * scale; int ai = ax-(int)ax >= 0.5 ? (int)ax + sign_a : (int)ax; int bi = bx-(int)bx >= 0.5 ? (int)bx + sign_b : (int)bx; /* Compare */ return ai == bi ? 0 : 1; } extern IQA_INLINE int _matrix_cmp(const float *a, const float *b, int w, int h, int digits) { int offset; int result=0; int len=w*h; for (offset=0; offset<len; ++offset) { if (_cmp_float(a[offset], b[offset], digits)) { result = 1; break; } } return result; }
930824.c
//------------------------------------------------------------------------------ // GB_AxB: hard-coded functions for semiring: C<M>=A*B or A'*B //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_bracket.h" #include "GB_iterator.h" #include "GB_sort.h" #include "GB_atomics.h" #include "GB_AxB_saxpy3.h" #include "GB_AxB__include.h" // The C=A*B semiring is defined by the following types and operators: // A'*B function (dot2): GB_Adot2B__lor_ge_int32 // A'*B function (dot3): GB_Adot3B__lor_ge_int32 // C+=A'*B function (dot4): GB_Adot4B__lor_ge_int32 // A*B function (saxpy3): GB_Asaxpy3B__lor_ge_int32 // C type: bool // A type: int32_t // B type: int32_t // Multiply: z = (aik >= bkj) // Add: cij |= z // 'any' monoid? 0 // atomic? 1 // OpenMP atomic? 1 // MultAdd: cij |= (aik >= bkj) // Identity: false // Terminal: if (cij == true) break ; #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ bool // aik = Ax [pA] #define GB_GETA(aik,Ax,pA) \ int32_t aik = Ax [pA] // bkj = Bx [pB] #define GB_GETB(bkj,Bx,pB) \ int32_t bkj = Bx [pB] #define GB_CX(p) Cx [p] // multiply operator #define GB_MULT(z, x, y) \ z = (x >= y) // multiply-add #define GB_MULTADD(z, x, y) \ z |= (x >= y) // monoid identity value #define GB_IDENTITY \ false // break if cij reaches the terminal value (dot product only) #define GB_DOT_TERMINAL(cij) \ if (cij == true) break ; // simd pragma for dot-product loop vectorization #define GB_PRAGMA_VECTORIZE_DOT \ ; // simd pragma for other loop vectorization #define GB_PRAGMA_VECTORIZE GB_PRAGMA_SIMD // declare the cij scalar #define GB_CIJ_DECLARE(cij) \ bool cij // save the value of C(i,j) #define GB_CIJ_SAVE(cij,p) Cx [p] = cij // cij = Cx [pC] #define GB_GETC(cij,pC) \ cij = Cx [pC] // Cx [pC] = cij #define GB_PUTC(cij,pC) \ Cx [pC] = cij // Cx [p] = t #define GB_CIJ_WRITE(p,t) Cx [p] = t // C(i,j) += t #define GB_CIJ_UPDATE(p,t) \ Cx [p] |= t // x + y #define GB_ADD_FUNCTION(x,y) \ x | y // type with size of GB_CTYPE, and can be used in compare-and-swap #define GB_CTYPE_PUN \ bool // bit pattern for bool, 8-bit, 16-bit, and 32-bit integers #define GB_CTYPE_BITS \ 0x1L // 1 if monoid update can skipped entirely (the ANY monoid) #define GB_IS_ANY_MONOID \ 0 // 1 if monoid update is EQ #define GB_IS_EQ_MONOID \ 0 // 1 if monoid update can be done atomically, 0 otherwise #define GB_HAS_ATOMIC \ 1 // 1 if monoid update can be done with an OpenMP atomic update, 0 otherwise #if GB_MICROSOFT #define GB_HAS_OMP_ATOMIC \ 0 #else #define GB_HAS_OMP_ATOMIC \ 1 #endif // 1 for the ANY_PAIR semirings #define GB_IS_ANY_PAIR_SEMIRING \ 0 // 1 if PAIR is the multiply operator #define GB_IS_PAIR_MULTIPLIER \ 0 // atomic compare-exchange #define GB_ATOMIC_COMPARE_EXCHANGE(target, expected, desired) \ GB_ATOMIC_COMPARE_EXCHANGE_8 (target, expected, desired) #if GB_IS_ANY_PAIR_SEMIRING // result is purely symbolic; no numeric work to do. Hx is not used. #define GB_HX_WRITE(i,t) #define GB_CIJ_GATHER(p,i) #define GB_HX_UPDATE(i,t) #define GB_CIJ_MEMCPY(p,i,len) #else // Hx [i] = t #define GB_HX_WRITE(i,t) Hx [i] = t // Cx [p] = Hx [i] #define GB_CIJ_GATHER(p,i) Cx [p] = Hx [i] // Hx [i] += t #define GB_HX_UPDATE(i,t) \ Hx [i] |= t // memcpy (&(Cx [p]), &(Hx [i]), len) #define GB_CIJ_MEMCPY(p,i,len) \ memcpy (Cx +(p), Hx +(i), (len) * sizeof(bool)) #endif // disable this semiring and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LOR || GxB_NO_GE || GxB_NO_INT32 || GxB_NO_LOR_BOOL || GxB_NO_GE_INT32 || GxB_NO_LOR_GE_INT32) //------------------------------------------------------------------------------ // C=A'*B or C<!M>=A'*B: dot product (phase 2) //------------------------------------------------------------------------------ GrB_Info GB_Adot2B__lor_ge_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix *Aslice, bool A_is_pattern, const GrB_Matrix B, bool B_is_pattern, int64_t *GB_RESTRICT B_slice, int64_t *GB_RESTRICT *C_counts, int nthreads, int naslice, int nbslice ) { // C<M>=A'*B now uses dot3 #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_AxB_dot2_meta.c" #undef GB_PHASE_2_OF_2 return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C<M>=A'*B: masked dot product method (phase 2) //------------------------------------------------------------------------------ GrB_Info GB_Adot3B__lor_ge_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix B, bool B_is_pattern, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_dot3_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C+=A'*B: dense dot product //------------------------------------------------------------------------------ GrB_Info GB_Adot4B__lor_ge_int32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, int64_t *GB_RESTRICT A_slice, int naslice, const GrB_Matrix B, bool B_is_pattern, int64_t *GB_RESTRICT B_slice, int nbslice, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_dot4_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C=A*B, C<M>=A*B, C<!M>=A*B: saxpy3 method (Gustavson + Hash) //------------------------------------------------------------------------------ #include "GB_AxB_saxpy3_template.h" GrB_Info GB_Asaxpy3B__lor_ge_int32 ( GrB_Matrix C, const GrB_Matrix M, bool Mask_comp, const bool Mask_struct, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix B, bool B_is_pattern, GB_saxpy3task_struct *GB_RESTRICT TaskList, const int ntasks, const int nfine, const int nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_saxpy3_template.c" return (GrB_SUCCESS) ; #endif } #endif
322453.c
/**************************************************************************** * * Copyright 2018 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #include <debug.h> #include <string.h> #include <tinyara/mm/mm.h> #ifdef CONFIG_MM_KERNEL_HEAP #include <tinyara/sched.h> #endif #ifdef CONFIG_APP_BINARY_SEPARATION #include <tinyara/binary_manager.h> #endif #if defined(CONFIG_BUILD_PROTECTED) && defined(__KERNEL__) #include <tinyara/userspace.h> #ifdef CONFIG_APP_BINARY_SEPARATION #include <tinyara/sched.h> #define USR_HEAP_TCB ((struct mm_heap_s *)((struct tcb_s*)sched_self())->uheap) #define USR_HEAP_CFG ((struct mm_heap_s *)(*(uint32_t *)(CONFIG_TINYARA_USERSPACE + sizeof(struct userspace_s)))) #define USR_HEAP (USR_HEAP_TCB == NULL ? USR_HEAP_CFG : USR_HEAP_TCB) #else #define USR_HEAP ((struct mm_heap_s *)(*(uint32_t *)(CONFIG_TINYARA_USERSPACE + sizeof(struct userspace_s)))) #endif #elif defined(CONFIG_BUILD_PROTECTED) && !defined(__KERNEL__) extern uint32_t _stext; #define USR_HEAP ((struct mm_heap_s *)_stext) #else extern struct mm_heap_s g_mmheap[CONFIG_MM_NHEAPS]; #define USR_HEAP g_mmheap #endif /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Public Variables ****************************************************************************/ #if defined(CONFIG_APP_BINARY_SEPARATION) && defined(__KERNEL__) #include <queue.h> typedef struct app_heap_s { struct app_heap_s *flink; struct app_heap_s *blink; char app_name[BIN_NAME_MAX]; struct mm_heap_s *heap; } app_heap_s; static dq_queue_t app_heap_q; #endif /**************************************************************************** * Public Functions ****************************************************************************/ #if defined(CONFIG_APP_BINARY_SEPARATION) && defined(__KERNEL__) void mm_initialize_app_heap() { dq_init(&app_heap_q); } void mm_add_app_heap_list(struct mm_heap_s *heap, char *app_name) { app_heap_s *node = (app_heap_s *)kmm_malloc(sizeof(app_heap_s)); if (!node) { mdbg("Error allocating heap node\n"); return; } node->heap = heap; strncpy(node->app_name, app_name, BIN_NAME_MAX); /* Add the new heap node to the head of the list*/ dq_addfirst((dq_entry_t *)node, &app_heap_q); } void mm_remove_app_heap_list(struct mm_heap_s *heap) { app_heap_s *node = (app_heap_s *)dq_peek(&app_heap_q); /* Search the heap node in the list */ while (node) { if (node->heap == heap) { /* Remove and free the matching node */ dq_rem((dq_entry_t *)node, &app_heap_q); kmm_free(node); return; } node = dq_next(node); } } static struct mm_heap_s *mm_get_app_heap(void *address) { /* First, search the address in list of app heaps */ app_heap_s *node = (app_heap_s *)dq_peek(&app_heap_q); while (node) { if ((address > (void *)node->heap->mm_heapstart[0]) && (address < (void *)node->heap->mm_heapend[0])) { return node->heap; } node = dq_next(node); } return NULL; } struct mm_heap_s *mm_get_app_heap_with_name(char *app_name) { app_heap_s *node = (app_heap_s *)dq_peek(&app_heap_q); /* Search the heap */ while (node) { if (strncmp(node->app_name, app_name, BIN_NAME_MAX) == 0) { return node->heap; } node = dq_next(node); } /* There is no app which matched with app_name. */ return NULL; } char *mm_get_app_heap_name(void *address) { /* First, search the address in list of app heaps */ app_heap_s *node = (app_heap_s *)dq_peek(&app_heap_q); while (node) { if ((address > (void *)node->heap->mm_heapstart[0]) && (address < (void *)node->heap->mm_heapend[0])) { return node->app_name; } node = dq_next(node); } mdbg("address 0x%x is not in any app heap region.\n", address); return NULL; } #endif /**************************************************************************** * Name: mm_get_heap * * Description: * returns a heap which type is matched with ttype * ****************************************************************************/ struct mm_heap_s *mm_get_heap(void *address) { #if defined(CONFIG_APP_BINARY_SEPARATION) && defined(__KERNEL__) /* If address was not found in kernel or user heap, search for it in app heaps */ struct mm_heap_s *heap = mm_get_app_heap(address); if (heap) { return heap; } #endif #ifdef CONFIG_MM_KERNEL_HEAP int kheap_idx; int region_idx; struct mm_heap_s *kheap = kmm_get_heap(); for (kheap_idx = 0; kheap_idx < CONFIG_KMM_NHEAPS; kheap_idx++) { for (region_idx = 0; region_idx < CONFIG_KMM_REGIONS; region_idx++) { if (address >= (FAR void *)kheap[kheap_idx].mm_heapstart[region_idx] && address < (FAR void *)kheap[kheap_idx].mm_heapend[region_idx]) { return &kheap[kheap_idx]; } } } #endif int heap_idx; heap_idx = mm_get_heapindex(address); if (heap_idx == INVALID_HEAP_IDX) { mdbg("address 0x%x is not in heap region.\n", address); return NULL; } return &USR_HEAP[heap_idx]; } /**************************************************************************** * Name: mm_get_heap_with_index ****************************************************************************/ struct mm_heap_s *mm_get_heap_with_index(int index) { if (index >= CONFIG_MM_NHEAPS) { mdbg("heap index is out of range.\n"); return NULL; } return &USR_HEAP[index]; } /**************************************************************************** * Name: mm_get_heapindex ****************************************************************************/ int mm_get_heapindex(void *mem) { int heap_idx; if (mem == NULL) { return 0; } for (heap_idx = 0; heap_idx < CONFIG_MM_NHEAPS; heap_idx++) { int region = 0; #if CONFIG_MM_REGIONS > 1 for (; region < USR_HEAP[heap_idx].mm_nregions; region++) #endif { /* A valid address from the user heap for this region would have to lie * between the region's two guard nodes. */ if ((mem > (void *)USR_HEAP[heap_idx].mm_heapstart[region]) && (mem < (void *)USR_HEAP[heap_idx].mm_heapend[region])) { return heap_idx; } } } /* The address does not lie in the user heaps */ return INVALID_HEAP_IDX; }
162601.c
/* * (Interrupt handlers go here) */ // Standard library includes. #include <stdint.h> // Vendor-provided device header file. #include "stm32l4xx.h" // HAL includes. #include "hal/rcc.h" #include "hal/tim.h" // BSP includes. #include "ili9341.h" #include "ringbuf.h" #include "ufb.h" // Project includes. #include "app.h" #include "global.h" // DMA1, Channel 3: SPI transmit. void DMA1_chan3_IRQ_handler( void ) { // Since the DMA peripheral can only handle buffers up to 64KWords, // we can't sent the whole 75KWord framebuffer at once. So instead, // we send one half at a time and update the source address every // time that a 'transfer complete' interrupt triggers. if ( DMA1->ISR & DMA_ISR_TCIF3 ) { // Acknowledge the interrupt. DMA1->IFCR |= ( DMA_IFCR_CTCIF3 ); // Disable the DMA channel. DMA1_Channel3->CCR &= ~( DMA_CCR_EN ); // Update the 'transfer length' field. DMA1_Channel3->CNDTR = ( uint16_t )( ILI9341_A / 2 ); // Update the source address and refill the 'count' register. if ( DMA1_Channel3->CMAR >= ( uint32_t )&( FRAMEBUFFER[ ILI9341_A / 2 ] ) ) { DMA1_Channel3->CMAR = ( uint32_t )&FRAMEBUFFER; // Transfer is complete; wait for a trigger to re-draw. } else { DMA1_Channel3->CMAR = ( uint32_t )&( FRAMEBUFFER[ ILI9341_A / 2 ] ); // Re-enable the DMA channel to resume the transfer. DMA1_Channel3->CCR |= ( DMA_CCR_EN ); } } } // UART4: Communication with GPS transceiver. void UART4_IRQ_handler( void ) { // 'Receive register not empty' interrupt. if ( UART4->ISR & USART_ISR_RXNE ) { // Copy new data into the ringbuffer. char c = UART4->RDR; ringbuf_write( gps_rb, c ); } // 'Receive timeout' interrupt. if ( UART4->ISR & USART_ISR_RTOF ) { // Mark the end of the message in the ringbuffer and reset // its position/extent to 0. ringbuf_write( gps_rb, '\0' ); gps_rb.pos = 0; gps_rb.ext = 0; // Mark that new GPS messages are ready. new_gps_messages = 1; // Acknowledge the interrupt. UART4->ICR |= ( USART_ICR_RTOCF ); } } // EXTI channel 3: Nav switch 'down'. void EXTI3_IRQ_handler( void ) { if ( EXTI->PR1 & ( 1 << 3 ) ) { // Mark the button press. register_button_press( BTN_DOWN ); // Clear the status flag. EXTI->PR1 |= ( 1 << 3 ); } } // EXTI channel 4: Nav switch 'up'. void EXTI4_IRQ_handler( void ) { if ( EXTI->PR1 & ( 1 << 4 ) ) { // Mark the button press. register_button_press( BTN_UP ); // Clear the status flag. EXTI->PR1 |= ( 1 << 4 ); } } // EXTI channels 5-9: Nav switch 'right / left / press', and 'mode'. void EXTI5_9_IRQ_handler( void ) { // PB5: Nav switch 'right'. if ( EXTI->PR1 & ( 1 << 5 ) ) { // Mark the button press. register_button_press( BTN_RIGHT ); // Clear the status flag. EXTI->PR1 |= ( 1 << 5 ); } // PC6: Nav switch 'left'. else if ( EXTI->PR1 & ( 1 << 6 ) ) { // Mark the button press. register_button_press( BTN_LEFT ); // Clear the status flag. EXTI->PR1 |= ( 1 << 6 ); } // PC7: Nav switch 'press / center'. else if ( EXTI->PR1 & ( 1 << 7 ) ) { // Mark the button press. register_button_press( BTN_CENTER ); // Clear the status flag. EXTI->PR1 |= ( 1 << 7 ); } // PA8: 'Mode' else if ( EXTI->PR1 & ( 1 << 8 ) ) { // Mark the button press. register_button_press( BTN_MODE ); // Clear the status flag. EXTI->PR1 |= ( 1 << 8 ); } } // EXTI channels 10-15: 'back'. void EXTI10_15_IRQ_handler( void ) { if ( EXTI->PR1 & ( 1 << 14 ) ) { // Mark the button press. register_button_press( BTN_BACK ); // Clear the status flag. EXTI->PR1 |= ( 1 << 14 ); } }
145147.c
/* SPDX-License-Identifier: BSD-3-Clause * Copyright (c) 2009-2012,2016 Microsoft Corp. * Copyright (c) 2012 NetApp Inc. * Copyright (c) 2012 Citrix Inc. * All rights reserved. */ #include <unistd.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <sys/uio.h> #include <rte_eal.h> #include <rte_tailq.h> #include <rte_log.h> #include <rte_malloc.h> #include <rte_bus.h> #include <rte_atomic.h> #include <rte_memory.h> #include <rte_pause.h> #include <rte_bus_vmbus.h> #include "private.h" /* Increase bufring index by inc with wraparound */ static inline uint32_t vmbus_br_idxinc(uint32_t idx, uint32_t inc, uint32_t sz) { idx += inc; if (idx >= sz) idx -= sz; return idx; } void vmbus_br_setup(struct vmbus_br *br, void *buf, unsigned int blen) { br->vbr = buf; br->windex = br->vbr->windex; br->dsize = blen - sizeof(struct vmbus_bufring); } /* * When we write to the ring buffer, check if the host needs to be * signaled. * * The contract: * - The host guarantees that while it is draining the TX bufring, * it will set the br_imask to indicate it does not need to be * interrupted when new data are added. * - The host guarantees that it will completely drain the TX bufring * before exiting the read loop. Further, once the TX bufring is * empty, it will clear the br_imask and re-check to see if new * data have arrived. */ static inline bool vmbus_txbr_need_signal(const struct vmbus_br *tbr, uint32_t old_windex) { rte_smp_mb(); if (tbr->vbr->imask) return false; rte_smp_rmb(); /* * This is the only case we need to signal when the * ring transitions from being empty to non-empty. */ return old_windex == tbr->vbr->rindex; } static inline uint32_t vmbus_txbr_copyto(const struct vmbus_br *tbr, uint32_t windex, const void *src0, uint32_t cplen) { uint8_t *br_data = tbr->vbr->data; uint32_t br_dsize = tbr->dsize; const uint8_t *src = src0; /* XXX use double mapping like Linux kernel? */ if (cplen > br_dsize - windex) { uint32_t fraglen = br_dsize - windex; /* Wrap-around detected */ memcpy(br_data + windex, src, fraglen); memcpy(br_data, src + fraglen, cplen - fraglen); } else { memcpy(br_data + windex, src, cplen); } return vmbus_br_idxinc(windex, cplen, br_dsize); } /* * Write scattered channel packet to TX bufring. * * The offset of this channel packet is written as a 64bits value * immediately after this channel packet. * * The write goes through three stages: * 1. Reserve space in ring buffer for the new data. * Writer atomically moves priv_write_index. * 2. Copy the new data into the ring. * 3. Update the tail of the ring (visible to host) that indicates * next read location. Writer updates write_index */ int vmbus_txbr_write(struct vmbus_br *tbr, const struct iovec iov[], int iovlen, bool *need_sig) { struct vmbus_bufring *vbr = tbr->vbr; uint32_t ring_size = tbr->dsize; uint32_t old_windex, next_windex, windex, total; uint64_t save_windex; int i; total = 0; for (i = 0; i < iovlen; i++) total += iov[i].iov_len; total += sizeof(save_windex); /* Reserve space in ring */ do { uint32_t avail; /* Get current free location */ old_windex = tbr->windex; /* Prevent compiler reordering this with calculation */ rte_compiler_barrier(); avail = vmbus_br_availwrite(tbr, old_windex); /* If not enough space in ring, then tell caller. */ if (avail <= total) return -EAGAIN; next_windex = vmbus_br_idxinc(old_windex, total, ring_size); /* Atomic update of next write_index for other threads */ } while (!rte_atomic32_cmpset(&tbr->windex, old_windex, next_windex)); /* Space from old..new is now reserved */ windex = old_windex; for (i = 0; i < iovlen; i++) { windex = vmbus_txbr_copyto(tbr, windex, iov[i].iov_base, iov[i].iov_len); } /* Set the offset of the current channel packet. */ save_windex = ((uint64_t)old_windex) << 32; windex = vmbus_txbr_copyto(tbr, windex, &save_windex, sizeof(save_windex)); /* The region reserved should match region used */ RTE_ASSERT(windex == next_windex); /* Ensure that data is available before updating host index */ rte_smp_wmb(); /* Checkin for our reservation. wait for our turn to update host */ while (!rte_atomic32_cmpset(&vbr->windex, old_windex, next_windex)) rte_pause(); /* If host had read all data before this, then need to signal */ *need_sig |= vmbus_txbr_need_signal(tbr, old_windex); return 0; } static inline uint32_t vmbus_rxbr_copyfrom(const struct vmbus_br *rbr, uint32_t rindex, void *dst0, size_t cplen) { const uint8_t *br_data = rbr->vbr->data; uint32_t br_dsize = rbr->dsize; uint8_t *dst = dst0; if (cplen > br_dsize - rindex) { uint32_t fraglen = br_dsize - rindex; /* Wrap-around detected. */ memcpy(dst, br_data + rindex, fraglen); memcpy(dst + fraglen, br_data, cplen - fraglen); } else { memcpy(dst, br_data + rindex, cplen); } return vmbus_br_idxinc(rindex, cplen, br_dsize); } /* Copy data from receive ring but don't change index */ int vmbus_rxbr_peek(const struct vmbus_br *rbr, void *data, size_t dlen) { uint32_t avail; /* * The requested data and the 64bits channel packet * offset should be there at least. */ avail = vmbus_br_availread(rbr); if (avail < dlen + sizeof(uint64_t)) return -EAGAIN; vmbus_rxbr_copyfrom(rbr, rbr->vbr->rindex, data, dlen); return 0; } /* * Copy data from receive ring and change index * NOTE: * We assume (dlen + skip) == sizeof(channel packet). */ int vmbus_rxbr_read(struct vmbus_br *rbr, void *data, size_t dlen, size_t skip) { struct vmbus_bufring *vbr = rbr->vbr; uint32_t br_dsize = rbr->dsize; uint32_t rindex; if (vmbus_br_availread(rbr) < dlen + skip + sizeof(uint64_t)) return -EAGAIN; /* Record where host was when we started read (for debug) */ rbr->windex = rbr->vbr->windex; /* * Copy channel packet from RX bufring. */ rindex = vmbus_br_idxinc(rbr->vbr->rindex, skip, br_dsize); rindex = vmbus_rxbr_copyfrom(rbr, rindex, data, dlen); /* * Discard this channel packet's 64bits offset, which is useless to us. */ rindex = vmbus_br_idxinc(rindex, sizeof(uint64_t), br_dsize); /* Update the read index _after_ the channel packet is fetched. */ rte_compiler_barrier(); vbr->rindex = rindex; return 0; }
869419.c
#include "Ft_Esd.h" #include "Ft_Esd_RadioGroup.h" ESD_TYPE(Ft_Esd_RadioGroup *, Native = Pointer, Edit = None) ESD_TYPE(Ft_Esd_RadioButton *, Native = Pointer, Edit = None) ESD_METHOD(Ft_Esd_RadioGroup_Reset_Signal, Context = Ft_Esd_RadioGroup) void Ft_Esd_RadioGroup_Reset_Signal(Ft_Esd_RadioGroup *context) { context->Checked = 0; } ESD_METHOD(Ft_Esd_RadioGroup_GetPointer, Context = Ft_Esd_RadioGroup, Type = Ft_Esd_RadioGroup *) Ft_Esd_RadioGroup *Ft_Esd_RadioGroup_GetPointer(Ft_Esd_RadioGroup *context) { return context; }
553823.c
/* * Floating point AAN IDCT * Copyright (c) 2008 Michael Niedermayer <[email protected]> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "faanidct.h" #include "libavutil/common.h" /* To allow switching to double. */ #define FLOAT float #define B0 1.0000000000000000000000 #define B1 1.3870398453221474618216 // cos(pi*1/16)sqrt(2) #define B2 1.3065629648763765278566 // cos(pi*2/16)sqrt(2) #define B3 1.1758756024193587169745 // cos(pi*3/16)sqrt(2) #define B4 1.0000000000000000000000 // cos(pi*4/16)sqrt(2) #define B5 0.7856949583871021812779 // cos(pi*5/16)sqrt(2) #define B6 0.5411961001461969843997 // cos(pi*6/16)sqrt(2) #define B7 0.2758993792829430123360 // cos(pi*7/16)sqrt(2) #define A4 0.70710678118654752438 // cos(pi*4/16) #define A2 0.92387953251128675613 // cos(pi*2/16) static const FLOAT prescale[64]={ B0*B0/8, B0*B1/8, B0*B2/8, B0*B3/8, B0*B4/8, B0*B5/8, B0*B6/8, B0*B7/8, B1*B0/8, B1*B1/8, B1*B2/8, B1*B3/8, B1*B4/8, B1*B5/8, B1*B6/8, B1*B7/8, B2*B0/8, B2*B1/8, B2*B2/8, B2*B3/8, B2*B4/8, B2*B5/8, B2*B6/8, B2*B7/8, B3*B0/8, B3*B1/8, B3*B2/8, B3*B3/8, B3*B4/8, B3*B5/8, B3*B6/8, B3*B7/8, B4*B0/8, B4*B1/8, B4*B2/8, B4*B3/8, B4*B4/8, B4*B5/8, B4*B6/8, B4*B7/8, B5*B0/8, B5*B1/8, B5*B2/8, B5*B3/8, B5*B4/8, B5*B5/8, B5*B6/8, B5*B7/8, B6*B0/8, B6*B1/8, B6*B2/8, B6*B3/8, B6*B4/8, B6*B5/8, B6*B6/8, B6*B7/8, B7*B0/8, B7*B1/8, B7*B2/8, B7*B3/8, B7*B4/8, B7*B5/8, B7*B6/8, B7*B7/8, }; static inline void p8idct(int16_t data[64], FLOAT temp[64], uint8_t *dest, int stride, int x, int y, int type){ int i; FLOAT s04, d04, s17, d17, s26, d26, s53, d53; FLOAT os07, os16, os25, os34; FLOAT od07, od16, od25, od34; for(i=0; i<y*8; i+=y){ s17= temp[1*x + i] + temp[7*x + i]; d17= temp[1*x + i] - temp[7*x + i]; s53= temp[5*x + i] + temp[3*x + i]; d53= temp[5*x + i] - temp[3*x + i]; od07= s17 + s53; od25= (s17 - s53)*(2*A4); #if 0 //these 2 are equivalent { FLOAT tmp0; tmp0 = (d17 + d53) * (2 * A2); od34 = d17 * (2 * B6) - tmp0; od16 = d53 * (-2 * B2) + tmp0; } #else od34= d17*(2*(B6-A2)) - d53*(2*A2); od16= d53*(2*(A2-B2)) + d17*(2*A2); #endif od16 -= od07; od25 -= od16; od34 += od25; s26 = temp[2*x + i] + temp[6*x + i]; d26 = temp[2*x + i] - temp[6*x + i]; d26*= 2*A4; d26-= s26; s04= temp[0*x + i] + temp[4*x + i]; d04= temp[0*x + i] - temp[4*x + i]; os07= s04 + s26; os34= s04 - s26; os16= d04 + d26; os25= d04 - d26; if(type==0){ temp[0*x + i]= os07 + od07; temp[7*x + i]= os07 - od07; temp[1*x + i]= os16 + od16; temp[6*x + i]= os16 - od16; temp[2*x + i]= os25 + od25; temp[5*x + i]= os25 - od25; temp[3*x + i]= os34 - od34; temp[4*x + i]= os34 + od34; }else if(type==1){ data[0*x + i]= lrintf(os07 + od07); data[7*x + i]= lrintf(os07 - od07); data[1*x + i]= lrintf(os16 + od16); data[6*x + i]= lrintf(os16 - od16); data[2*x + i]= lrintf(os25 + od25); data[5*x + i]= lrintf(os25 - od25); data[3*x + i]= lrintf(os34 - od34); data[4*x + i]= lrintf(os34 + od34); }else if(type==2){ dest[0*stride + i]= av_clip_uint8(((int)dest[0*stride + i]) + lrintf(os07 + od07)); dest[7*stride + i]= av_clip_uint8(((int)dest[7*stride + i]) + lrintf(os07 - od07)); dest[1*stride + i]= av_clip_uint8(((int)dest[1*stride + i]) + lrintf(os16 + od16)); dest[6*stride + i]= av_clip_uint8(((int)dest[6*stride + i]) + lrintf(os16 - od16)); dest[2*stride + i]= av_clip_uint8(((int)dest[2*stride + i]) + lrintf(os25 + od25)); dest[5*stride + i]= av_clip_uint8(((int)dest[5*stride + i]) + lrintf(os25 - od25)); dest[3*stride + i]= av_clip_uint8(((int)dest[3*stride + i]) + lrintf(os34 - od34)); dest[4*stride + i]= av_clip_uint8(((int)dest[4*stride + i]) + lrintf(os34 + od34)); }else{ dest[0*stride + i]= av_clip_uint8(lrintf(os07 + od07)); dest[7*stride + i]= av_clip_uint8(lrintf(os07 - od07)); dest[1*stride + i]= av_clip_uint8(lrintf(os16 + od16)); dest[6*stride + i]= av_clip_uint8(lrintf(os16 - od16)); dest[2*stride + i]= av_clip_uint8(lrintf(os25 + od25)); dest[5*stride + i]= av_clip_uint8(lrintf(os25 - od25)); dest[3*stride + i]= av_clip_uint8(lrintf(os34 - od34)); dest[4*stride + i]= av_clip_uint8(lrintf(os34 + od34)); } } } void ff_faanidct(int16_t block[64]){ FLOAT temp[64]; int i; emms_c(); for(i=0; i<64; i++) temp[i] = block[i] * prescale[i]; p8idct(block, temp, NULL, 0, 1, 8, 0); p8idct(block, temp, NULL, 0, 8, 1, 1); } void ff_faanidct_add(uint8_t *dest, int line_size, int16_t block[64]){ FLOAT temp[64]; int i; emms_c(); for(i=0; i<64; i++) temp[i] = block[i] * prescale[i]; p8idct(block, temp, NULL, 0, 1, 8, 0); p8idct(NULL , temp, dest, line_size, 8, 1, 2); } void ff_faanidct_put(uint8_t *dest, int line_size, int16_t block[64]){ FLOAT temp[64]; int i; emms_c(); for(i=0; i<64; i++) temp[i] = block[i] * prescale[i]; p8idct(block, temp, NULL, 0, 1, 8, 0); p8idct(NULL , temp, dest, line_size, 8, 1, 3); }
24853.c
// ganjiang-jian.c 干将剑 // Last Modified by winder on Sep. 7 2001 #include <weapon.h> #include <ansi.h> inherit SWORD; inherit F_UNIQUE; void create() { set_name(HIC "干将剑" NOR, ({"ganjiang jian", "jian", "sword"})); set_weight(8000); if (clonep()) set_default_object(__FILE__); else { set("unit", "柄"); set("long", "这就是赫赫有名的干将剑,剑锋上隐隐透出一股清气,仔细凝望,只觉一股肃杀之气森然外散。\n"); set("value", 20000); set("material", "steel"); set("weapon_prop/personality", 8); set("wield_msg", "$N「唰」的一声抽出一柄$n握在手中,顿时风沙飞扬,黑云罩日,漫天神鬼惊惧。\n"); set("unwield_msg", "$N将手中的$n插回剑鞘,一下子风平浪静,晴空万里。\n"); } init_sword(130); setup(); }
654488.c
/****************************************************************************** * * Module Name: nsxfname - Public interfaces to the ACPI subsystem * ACPI Namespace oriented interfaces * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2019, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #define EXPORT_ACPI_INTERFACES #include "acpi.h" #include "accommon.h" #include "acnamesp.h" #include "acparser.h" #include "amlcode.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nsxfname") /* Local prototypes */ static char * AcpiNsCopyDeviceId ( ACPI_PNP_DEVICE_ID *Dest, ACPI_PNP_DEVICE_ID *Source, char *StringArea); /****************************************************************************** * * FUNCTION: AcpiGetHandle * * PARAMETERS: Parent - Object to search under (search scope). * Pathname - Pointer to an asciiz string containing the * name * RetHandle - Where the return handle is returned * * RETURN: Status * * DESCRIPTION: This routine will search for a caller specified name in the * name space. The caller can restrict the search region by * specifying a non NULL parent. The parent value is itself a * namespace handle. * ******************************************************************************/ ACPI_STATUS AcpiGetHandle ( ACPI_HANDLE Parent, ACPI_STRING Pathname, ACPI_HANDLE *RetHandle) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node = NULL; ACPI_NAMESPACE_NODE *PrefixNode = NULL; ACPI_FUNCTION_ENTRY (); /* Parameter Validation */ if (!RetHandle || !Pathname) { return (AE_BAD_PARAMETER); } /* Convert a parent handle to a prefix node */ if (Parent) { PrefixNode = AcpiNsValidateHandle (Parent); if (!PrefixNode) { return (AE_BAD_PARAMETER); } } /* * Valid cases are: * 1) Fully qualified pathname * 2) Parent + Relative pathname * * Error for <null Parent + relative path> */ if (ACPI_IS_ROOT_PREFIX (Pathname[0])) { /* Pathname is fully qualified (starts with '\') */ /* Special case for root-only, since we can't search for it */ if (!strcmp (Pathname, ACPI_NS_ROOT_PATH)) { *RetHandle = ACPI_CAST_PTR (ACPI_HANDLE, AcpiGbl_RootNode); return (AE_OK); } } else if (!PrefixNode) { /* Relative path with null prefix is disallowed */ return (AE_BAD_PARAMETER); } /* Find the Node and convert to a handle */ Status = AcpiNsGetNode (PrefixNode, Pathname, ACPI_NS_NO_UPSEARCH, &Node); if (ACPI_SUCCESS (Status)) { *RetHandle = ACPI_CAST_PTR (ACPI_HANDLE, Node); } return (Status); } ACPI_EXPORT_SYMBOL (AcpiGetHandle) /****************************************************************************** * * FUNCTION: AcpiGetName * * PARAMETERS: Handle - Handle to be converted to a pathname * NameType - Full pathname or single segment * Buffer - Buffer for returned path * * RETURN: Pointer to a string containing the fully qualified Name. * * DESCRIPTION: This routine returns the fully qualified name associated with * the Handle parameter. This and the AcpiPathnameToHandle are * complementary functions. * ******************************************************************************/ ACPI_STATUS AcpiGetName ( ACPI_HANDLE Handle, UINT32 NameType, ACPI_BUFFER *Buffer) { ACPI_STATUS Status; /* Parameter validation */ if (NameType > ACPI_NAME_TYPE_MAX) { return (AE_BAD_PARAMETER); } Status = AcpiUtValidateBuffer (Buffer); if (ACPI_FAILURE (Status)) { return (Status); } /* * Wants the single segment ACPI name. * Validate handle and convert to a namespace Node */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (Status); } if (NameType == ACPI_FULL_PATHNAME || NameType == ACPI_FULL_PATHNAME_NO_TRAILING) { /* Get the full pathname (From the namespace root) */ Status = AcpiNsHandleToPathname (Handle, Buffer, NameType == ACPI_FULL_PATHNAME ? FALSE : TRUE); } else { /* Get the single name */ Status = AcpiNsHandleToName (Handle, Buffer); } (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return (Status); } ACPI_EXPORT_SYMBOL (AcpiGetName) /****************************************************************************** * * FUNCTION: AcpiNsCopyDeviceId * * PARAMETERS: Dest - Pointer to the destination PNP_DEVICE_ID * Source - Pointer to the source PNP_DEVICE_ID * StringArea - Pointer to where to copy the dest string * * RETURN: Pointer to the next string area * * DESCRIPTION: Copy a single PNP_DEVICE_ID, including the string data. * ******************************************************************************/ static char * AcpiNsCopyDeviceId ( ACPI_PNP_DEVICE_ID *Dest, ACPI_PNP_DEVICE_ID *Source, char *StringArea) { /* Create the destination PNP_DEVICE_ID */ Dest->String = StringArea; Dest->Length = Source->Length; /* Copy actual string and return a pointer to the next string area */ memcpy (StringArea, Source->String, Source->Length); return (StringArea + Source->Length); } /****************************************************************************** * * FUNCTION: AcpiGetObjectInfo * * PARAMETERS: Handle - Object Handle * ReturnBuffer - Where the info is returned * * RETURN: Status * * DESCRIPTION: Returns information about an object as gleaned from the * namespace node and possibly by running several standard * control methods (Such as in the case of a device.) * * For Device and Processor objects, run the Device _HID, _UID, _CID, * _CLS, _ADR, _SxW, and _SxD methods. * * Note: Allocates the return buffer, must be freed by the caller. * * Note: This interface is intended to be used during the initial device * discovery namespace traversal. Therefore, no complex methods can be * executed, especially those that access operation regions. Therefore, do * not add any additional methods that could cause problems in this area. * Because of this reason support for the following methods has been removed: * 1) _SUB method was removed (11/2015) * 2) _STA method was removed (02/2018) * ******************************************************************************/ ACPI_STATUS AcpiGetObjectInfo ( ACPI_HANDLE Handle, ACPI_DEVICE_INFO **ReturnBuffer) { ACPI_NAMESPACE_NODE *Node; ACPI_DEVICE_INFO *Info; ACPI_PNP_DEVICE_ID_LIST *CidList = NULL; ACPI_PNP_DEVICE_ID *Hid = NULL; ACPI_PNP_DEVICE_ID *Uid = NULL; ACPI_PNP_DEVICE_ID *Cls = NULL; char *NextIdString; ACPI_OBJECT_TYPE Type; ACPI_NAME Name; UINT8 ParamCount= 0; UINT16 Valid = 0; UINT32 InfoSize; UINT32 i; ACPI_STATUS Status; /* Parameter validation */ if (!Handle || !ReturnBuffer) { return (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (Status); } Node = AcpiNsValidateHandle (Handle); if (!Node) { (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return (AE_BAD_PARAMETER); } /* Get the namespace node data while the namespace is locked */ InfoSize = sizeof (ACPI_DEVICE_INFO); Type = Node->Type; Name = Node->Name.Integer; if (Node->Type == ACPI_TYPE_METHOD) { ParamCount = Node->Object->Method.ParamCount; } Status = AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return (Status); } if ((Type == ACPI_TYPE_DEVICE) || (Type == ACPI_TYPE_PROCESSOR)) { /* * Get extra info for ACPI Device/Processor objects only: * Run the Device _HID, _UID, _CLS, and _CID methods. * * Note: none of these methods are required, so they may or may * not be present for this device. The Info->Valid bitfield is used * to indicate which methods were found and run successfully. */ /* Execute the Device._HID method */ Status = AcpiUtExecute_HID (Node, &Hid); if (ACPI_SUCCESS (Status)) { InfoSize += Hid->Length; Valid |= ACPI_VALID_HID; } /* Execute the Device._UID method */ Status = AcpiUtExecute_UID (Node, &Uid); if (ACPI_SUCCESS (Status)) { InfoSize += Uid->Length; Valid |= ACPI_VALID_UID; } /* Execute the Device._CID method */ Status = AcpiUtExecute_CID (Node, &CidList); if (ACPI_SUCCESS (Status)) { /* Add size of CID strings and CID pointer array */ InfoSize += (CidList->ListSize - sizeof (ACPI_PNP_DEVICE_ID_LIST)); Valid |= ACPI_VALID_CID; } /* Execute the Device._CLS method */ Status = AcpiUtExecute_CLS (Node, &Cls); if (ACPI_SUCCESS (Status)) { InfoSize += Cls->Length; Valid |= ACPI_VALID_CLS; } } /* * Now that we have the variable-length data, we can allocate the * return buffer */ Info = ACPI_ALLOCATE_ZEROED (InfoSize); if (!Info) { Status = AE_NO_MEMORY; goto Cleanup; } /* Get the fixed-length data */ if ((Type == ACPI_TYPE_DEVICE) || (Type == ACPI_TYPE_PROCESSOR)) { /* * Get extra info for ACPI Device/Processor objects only: * Run the _ADR and, SxW, and _SxD methods. * * Notes: none of these methods are required, so they may or may * not be present for this device. The Info->Valid bitfield is used * to indicate which methods were found and run successfully. */ /* Execute the Device._ADR method */ Status = AcpiUtEvaluateNumericObject (METHOD_NAME__ADR, Node, &Info->Address); if (ACPI_SUCCESS (Status)) { Valid |= ACPI_VALID_ADR; } /* Execute the Device._SxW methods */ Status = AcpiUtExecutePowerMethods (Node, AcpiGbl_LowestDstateNames, ACPI_NUM_SxW_METHODS, Info->LowestDstates); if (ACPI_SUCCESS (Status)) { Valid |= ACPI_VALID_SXWS; } /* Execute the Device._SxD methods */ Status = AcpiUtExecutePowerMethods (Node, AcpiGbl_HighestDstateNames, ACPI_NUM_SxD_METHODS, Info->HighestDstates); if (ACPI_SUCCESS (Status)) { Valid |= ACPI_VALID_SXDS; } } /* * Create a pointer to the string area of the return buffer. * Point to the end of the base ACPI_DEVICE_INFO structure. */ NextIdString = ACPI_CAST_PTR (char, Info->CompatibleIdList.Ids); if (CidList) { /* Point past the CID PNP_DEVICE_ID array */ NextIdString += ((ACPI_SIZE) CidList->Count * sizeof (ACPI_PNP_DEVICE_ID)); } /* * Copy the HID, UID, and CIDs to the return buffer. The variable-length * strings are copied to the reserved area at the end of the buffer. * * For HID and CID, check if the ID is a PCI Root Bridge. */ if (Hid) { NextIdString = AcpiNsCopyDeviceId (&Info->HardwareId, Hid, NextIdString); if (AcpiUtIsPciRootBridge (Hid->String)) { Info->Flags |= ACPI_PCI_ROOT_BRIDGE; } } if (Uid) { NextIdString = AcpiNsCopyDeviceId (&Info->UniqueId, Uid, NextIdString); } if (CidList) { Info->CompatibleIdList.Count = CidList->Count; Info->CompatibleIdList.ListSize = CidList->ListSize; /* Copy each CID */ for (i = 0; i < CidList->Count; i++) { NextIdString = AcpiNsCopyDeviceId (&Info->CompatibleIdList.Ids[i], &CidList->Ids[i], NextIdString); if (AcpiUtIsPciRootBridge (CidList->Ids[i].String)) { Info->Flags |= ACPI_PCI_ROOT_BRIDGE; } } } if (Cls) { (void) AcpiNsCopyDeviceId (&Info->ClassCode, Cls, NextIdString); } /* Copy the fixed-length data */ Info->InfoSize = InfoSize; Info->Type = Type; Info->Name = Name; Info->ParamCount = ParamCount; Info->Valid = Valid; *ReturnBuffer = Info; Status = AE_OK; Cleanup: if (Hid) { ACPI_FREE (Hid); } if (Uid) { ACPI_FREE (Uid); } if (CidList) { ACPI_FREE (CidList); } if (Cls) { ACPI_FREE (Cls); } return (Status); } ACPI_EXPORT_SYMBOL (AcpiGetObjectInfo) /****************************************************************************** * * FUNCTION: AcpiInstallMethod * * PARAMETERS: Buffer - An ACPI table containing one control method * * RETURN: Status * * DESCRIPTION: Install a control method into the namespace. If the method * name already exists in the namespace, it is overwritten. The * input buffer must contain a valid DSDT or SSDT containing a * single control method. * ******************************************************************************/ ACPI_STATUS AcpiInstallMethod ( UINT8 *Buffer) { ACPI_TABLE_HEADER *Table = ACPI_CAST_PTR (ACPI_TABLE_HEADER, Buffer); UINT8 *AmlBuffer; UINT8 *AmlStart; char *Path; ACPI_NAMESPACE_NODE *Node; ACPI_OPERAND_OBJECT *MethodObj; ACPI_PARSE_STATE ParserState; UINT32 AmlLength; UINT16 Opcode; UINT8 MethodFlags; ACPI_STATUS Status; /* Parameter validation */ if (!Buffer) { return (AE_BAD_PARAMETER); } /* Table must be a DSDT or SSDT */ if (!ACPI_COMPARE_NAMESEG (Table->Signature, ACPI_SIG_DSDT) && !ACPI_COMPARE_NAMESEG (Table->Signature, ACPI_SIG_SSDT)) { return (AE_BAD_HEADER); } /* First AML opcode in the table must be a control method */ ParserState.Aml = Buffer + sizeof (ACPI_TABLE_HEADER); Opcode = AcpiPsPeekOpcode (&ParserState); if (Opcode != AML_METHOD_OP) { return (AE_BAD_PARAMETER); } /* Extract method information from the raw AML */ ParserState.Aml += AcpiPsGetOpcodeSize (Opcode); ParserState.PkgEnd = AcpiPsGetNextPackageEnd (&ParserState); Path = AcpiPsGetNextNamestring (&ParserState); MethodFlags = *ParserState.Aml++; AmlStart = ParserState.Aml; AmlLength = ACPI_PTR_DIFF (ParserState.PkgEnd, AmlStart); /* * Allocate resources up-front. We don't want to have to delete a new * node from the namespace if we cannot allocate memory. */ AmlBuffer = ACPI_ALLOCATE (AmlLength); if (!AmlBuffer) { return (AE_NO_MEMORY); } MethodObj = AcpiUtCreateInternalObject (ACPI_TYPE_METHOD); if (!MethodObj) { ACPI_FREE (AmlBuffer); return (AE_NO_MEMORY); } /* Lock namespace for AcpiNsLookup, we may be creating a new node */ Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { goto ErrorExit; } /* The lookup either returns an existing node or creates a new one */ Status = AcpiNsLookup (NULL, Path, ACPI_TYPE_METHOD, ACPI_IMODE_LOAD_PASS1, ACPI_NS_DONT_OPEN_SCOPE | ACPI_NS_ERROR_IF_FOUND, NULL, &Node); (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) /* NsLookup */ { if (Status != AE_ALREADY_EXISTS) { goto ErrorExit; } /* Node existed previously, make sure it is a method node */ if (Node->Type != ACPI_TYPE_METHOD) { Status = AE_TYPE; goto ErrorExit; } } /* Copy the method AML to the local buffer */ memcpy (AmlBuffer, AmlStart, AmlLength); /* Initialize the method object with the new method's information */ MethodObj->Method.AmlStart = AmlBuffer; MethodObj->Method.AmlLength = AmlLength; MethodObj->Method.ParamCount = (UINT8) (MethodFlags & AML_METHOD_ARG_COUNT); if (MethodFlags & AML_METHOD_SERIALIZED) { MethodObj->Method.InfoFlags = ACPI_METHOD_SERIALIZED; MethodObj->Method.SyncLevel = (UINT8) ((MethodFlags & AML_METHOD_SYNC_LEVEL) >> 4); } /* * Now that it is complete, we can attach the new method object to * the method Node (detaches/deletes any existing object) */ Status = AcpiNsAttachObject (Node, MethodObj, ACPI_TYPE_METHOD); /* * Flag indicates AML buffer is dynamic, must be deleted later. * Must be set only after attach above. */ Node->Flags |= ANOBJ_ALLOCATED_BUFFER; /* Remove local reference to the method object */ AcpiUtRemoveReference (MethodObj); return (Status); ErrorExit: ACPI_FREE (AmlBuffer); ACPI_FREE (MethodObj); return (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallMethod)
692500.c
#include <stdio.h> void scilab_rt_plot3d_i2i2i2i0_(int in00, int in01, int matrixin0[in00][in01], int in10, int in11, int matrixin1[in10][in11], int in20, int in21, int matrixin2[in20][in21], int scalarin0) { int i; int j; int val0 = 0; int val1 = 0; int val2 = 0; for (i = 0; i < in00; ++i) { for (j = 0; j < in01; ++j) { val0 += matrixin0[i][j]; } } printf("%d", val0); for (i = 0; i < in10; ++i) { for (j = 0; j < in11; ++j) { val1 += matrixin1[i][j]; } } printf("%d", val1); for (i = 0; i < in20; ++i) { for (j = 0; j < in21; ++j) { val2 += matrixin2[i][j]; } } printf("%d", val2); printf("%d", scalarin0); }
868791.c
/* // Copyright (c) 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include "oc_config.h" #ifdef OC_SECURITY #ifndef OC_DYNAMIC_ALLOCATION #error "ERROR: Please rebuild with OC_DYNAMIC_ALLOCATION" #endif /* !OC_DYNAMIC_ALLOCATION */ #ifndef OC_STORAGE #error Preprocessor macro OC_SECURITY is defined but OC_STORAGE is not defined \ check oc_config.h and make sure OC_STORAGE is defined if OC_SECURITY is defined. #endif #include "oc_obt.h" #include "oc_core_res.h" #include "security/oc_acl_internal.h" #include "security/oc_certs.h" #include "security/oc_cred_internal.h" #include "security/oc_doxm.h" #include "security/oc_keypair.h" #include "security/oc_obt_internal.h" #include "security/oc_pstat.h" #include "security/oc_store.h" #include "security/oc_tls.h" #include "security/oc_sdi.h" #include <stdlib.h> OC_MEMB(oc_discovery_s, oc_discovery_cb_t, 1); OC_LIST(oc_discovery_cbs); OC_MEMB(oc_otm_ctx_m, oc_otm_ctx_t, 1); OC_LIST(oc_otm_ctx_l); OC_MEMB(oc_switch_dos_ctx_m, oc_switch_dos_ctx_t, 1); OC_LIST(oc_switch_dos_ctx_l); OC_MEMB(oc_hard_reset_ctx_m, oc_hard_reset_ctx_t, 1); OC_LIST(oc_hard_reset_ctx_l); OC_MEMB(oc_credprov_ctx_m, oc_credprov_ctx_t, 1); OC_LIST(oc_credprov_ctx_l); OC_MEMB(oc_credret_ctx_m, oc_credret_ctx_t, 1); OC_LIST(oc_credret_ctx_l); OC_MEMB(oc_creddel_ctx_m, oc_creddel_ctx_t, 1); OC_LIST(oc_creddel_ctx_l); OC_MEMB(oc_cred_m, oc_sec_cred_t, 1); OC_MEMB(oc_creds_m, oc_sec_creds_t, 1); OC_MEMB(oc_acl2prov_ctx_m, oc_acl2prov_ctx_t, 1); OC_LIST(oc_acl2prov_ctx_l); OC_MEMB(oc_aclret_ctx_m, oc_aclret_ctx_t, 1); OC_LIST(oc_aclret_ctx_l); OC_MEMB(oc_acedel_ctx_m, oc_acedel_ctx_t, 1); OC_LIST(oc_acedel_ctx_l); OC_MEMB(oc_aces_m, oc_sec_ace_t, 1); OC_MEMB(oc_res_m, oc_ace_res_t, 1); OC_MEMB(oc_acl_m, oc_sec_acl_t, 1); #ifdef OC_PKI OC_MEMB(oc_roles, oc_role_t, 1); #endif /* OC_PKI */ /* Owned/unowned device caches */ OC_MEMB(oc_devices_s, oc_device_t, 1); OC_LIST(oc_devices); OC_LIST(oc_cache); /* Public/Private key-pair for the local domain's root of trust */ #ifdef OC_PKI const char *root_subject = "C=US, O=OCF, CN=IoTivity-Lite OBT Root"; uint8_t private_key[OC_ECDSA_PRIVKEY_SIZE]; size_t private_key_size; int root_cert_credid; #endif /* OC_PKI */ /* Internal utility functions */ oc_endpoint_t * oc_obt_get_unsecure_endpoint(oc_endpoint_t *endpoint) { while (endpoint && endpoint->next != NULL && endpoint->flags & SECURED) { endpoint = endpoint->next; } return endpoint; } oc_endpoint_t * oc_obt_get_secure_endpoint(oc_endpoint_t *endpoint) { while (endpoint && endpoint->next != NULL && !(endpoint->flags & SECURED)) { endpoint = endpoint->next; } return endpoint; } static oc_device_t * get_device_handle(oc_uuid_t *uuid, oc_list_t list) { oc_device_t *device = (oc_device_t *)oc_list_head(list); while (device) { if (memcmp(uuid->id, device->uuid.id, 16) == 0) { return device; } device = device->next; } return NULL; } oc_device_t * oc_obt_get_cached_device_handle(oc_uuid_t *uuid) { return get_device_handle(uuid, oc_cache); } oc_device_t * oc_obt_get_owned_device_handle(oc_uuid_t *uuid) { return get_device_handle(uuid, oc_devices); } bool oc_obt_is_owned_device(oc_uuid_t *uuid) { /* Check if we already own this device by querying our creds */ oc_sec_creds_t *creds = oc_sec_get_creds(0); oc_sec_cred_t *c = (oc_sec_cred_t *)oc_list_head(creds->creds); while (c != NULL) { if (memcmp(c->subjectuuid.id, uuid->id, 16) == 0 && c->owner_cred) { return true; } c = c->next; } return false; } oc_dostype_t oc_obt_parse_dos(oc_rep_t *rep) { oc_dostype_t s = 0; while (rep != NULL) { switch (rep->type) { case OC_REP_OBJECT: { if (oc_string_len(rep->name) == 3 && memcmp(oc_string(rep->name), "dos", 3) == 0) { oc_rep_t *dos = rep->value.object; while (dos != NULL) { switch (dos->type) { case OC_REP_INT: { if (oc_string_len(dos->name) == 1 && oc_string(dos->name)[0] == 's') { s = dos->value.integer; } } break; default: break; } dos = dos->next; } } } break; default: break; } rep = rep->next; } return s; } static oc_device_t * cache_new_device(oc_list_t list, oc_uuid_t *uuid, oc_endpoint_t *endpoint) { oc_device_t *device = (oc_device_t *)oc_list_head(list); while (device != NULL) { if (memcmp(device->uuid.id, uuid->id, sizeof(oc_uuid_t)) == 0) { break; } device = device->next; } if (!device) { device = oc_memb_alloc(&oc_devices_s); if (!device) { return NULL; } memcpy(device->uuid.id, uuid->id, sizeof(oc_uuid_t)); oc_list_add(list, device); } if (device->endpoint) { oc_free_server_endpoints(device->endpoint); } oc_endpoint_t *ep = oc_new_endpoint(); if (!ep) { oc_list_remove(list, device); oc_memb_free(&oc_devices_s, device); return NULL; } memcpy(ep, endpoint, sizeof(oc_endpoint_t)); device->endpoint = ep; ep->next = NULL; return device; } static oc_event_callback_retval_t free_device(void *data) { oc_device_t *device = (oc_device_t *)data; oc_free_server_endpoints(device->endpoint); oc_list_remove(oc_cache, device); oc_list_remove(oc_devices, device); oc_memb_free(&oc_devices_s, device); return OC_EVENT_DONE; } #ifdef OC_PKI static void oc_obt_dump_state(void) { uint8_t *buf = oc_alloc(OC_MAX_APP_DATA_SIZE); if (!buf) return; oc_rep_new(buf, OC_MAX_APP_DATA_SIZE); oc_rep_start_root_object(); oc_rep_set_byte_string(root, private_key, private_key, private_key_size); oc_rep_set_int(root, credid, root_cert_credid); oc_rep_end_root_object(); int size = oc_rep_get_encoded_payload_size(); if (size > 0) { OC_DBG("oc_obt: dumped current state: size %d", size); oc_storage_write("obt_state", buf, size); } oc_free(buf); } static void oc_obt_load_state(void) { long ret = 0; oc_rep_t *rep, *head; uint8_t *buf = oc_alloc(OC_MAX_APP_DATA_SIZE); if (!buf) { return; } ret = oc_storage_read("obt_state", buf, OC_MAX_APP_DATA_SIZE); if (ret > 0) { struct oc_memb rep_objects = { sizeof(oc_rep_t), 0, 0, 0, 0 }; oc_rep_set_pool(&rep_objects); int err = oc_parse_rep(buf, ret, &rep); head = rep; if (err == 0) { while (rep != NULL) { switch (rep->type) { case OC_REP_INT: if (oc_string_len(rep->name) == 6 && memcmp(oc_string(rep->name), "credid", 6) == 0) { root_cert_credid = (int)rep->value.integer; } break; case OC_REP_BYTE_STRING: if (oc_string_len(rep->name) == 11 && memcmp(oc_string(rep->name), "private_key", 11) == 0) { private_key_size = oc_string_len(rep->value.string); memcpy(private_key, oc_string(rep->value.string), private_key_size); } break; default: break; } rep = rep->next; } } oc_free_rep(head); } oc_free(buf); } #endif /* OC_PKI */ struct list { struct list *next; }; bool is_item_in_list(oc_list_t list, void *item) { struct list *h = oc_list_head(list); while (h != NULL) { if (h == item) { return true; } h = h->next; } return false; } bool oc_obt_is_otm_ctx_valid(oc_otm_ctx_t *ctx) { return is_item_in_list(oc_otm_ctx_l, ctx); } oc_otm_ctx_t * oc_obt_alloc_otm_ctx(void) { oc_otm_ctx_t *o = (oc_otm_ctx_t *)oc_memb_alloc(&oc_otm_ctx_m); if (o) { oc_list_add(oc_otm_ctx_l, o); } return o; } /* End of utility functions */ /* Ownership Transfer */ static void free_otm_state(oc_otm_ctx_t *o, int status, oc_obt_otm_t otm) { if (!is_item_in_list(oc_otm_ctx_l, o)) { return; } oc_list_remove(oc_otm_ctx_l, o); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(o->device->endpoint); oc_tls_close_connection(ep); if (status == -1) { char suuid[OC_UUID_LEN]; oc_uuid_to_str(&o->device->uuid, suuid, OC_UUID_LEN); oc_cred_remove_subject(suuid, 0); o->cb.cb(&o->device->uuid, status, o->cb.data); free_device(o->device); } else { if (otm != OC_OBT_RDP) { oc_list_remove(oc_cache, o->device); oc_list_add(oc_devices, o->device); } o->cb.cb(&o->device->uuid, status, o->cb.data); } oc_memb_free(&oc_otm_ctx_m, o); } void oc_obt_free_otm_ctx(oc_otm_ctx_t *ctx, int status, oc_obt_otm_t otm) { free_otm_state(ctx, status, otm); } /* Device discovery */ /* Owned/Unowned discovery timeout */ static oc_event_callback_retval_t free_discovery_cb(void *data) { oc_discovery_cb_t *c = (oc_discovery_cb_t *)data; if (is_item_in_list(oc_discovery_cbs, c)) { oc_list_remove(oc_discovery_cbs, c); oc_memb_free(&oc_discovery_s, c); } return OC_EVENT_DONE; } static void get_endpoints(oc_client_response_t *data) { if (data->code >= OC_STATUS_BAD_REQUEST) { return; } oc_rep_t *links = data->payload; oc_uuid_t di; oc_rep_t *link = (links) ? links->value.object : NULL; while (link != NULL) { switch (link->type) { case OC_REP_STRING: { if (oc_string_len(link->name) == 6 && memcmp(oc_string(link->name), "anchor", 6) == 0) { oc_str_to_uuid(oc_string(link->value.string) + 6, &di); break; } } break; default: break; } link = link->next; } oc_uuid_t *my_uuid = oc_core_get_device_id(0); if (memcmp(my_uuid->id, di.id, 16) == 0) { return; } oc_discovery_cb_t *cb = NULL; oc_device_t *device = NULL; oc_client_cb_t *ccb = (oc_client_cb_t *)data->client_cb; if (ccb->multicast) { cb = (oc_discovery_cb_t *)data->user_data; if (links && oc_obt_is_owned_device(&di)) { device = cache_new_device(oc_devices, &di, data->endpoint); } } else { device = (oc_device_t *)data->user_data; cb = (oc_discovery_cb_t *)device->ctx; } if (!device) { return; } oc_free_server_endpoints(device->endpoint); device->endpoint = NULL; oc_endpoint_t *eps_cur = NULL; link = links->value.object; oc_endpoint_t temp_ep; while (link != NULL) { switch (link->type) { case OC_REP_OBJECT_ARRAY: { oc_rep_t *eps = link->value.object_array; while (eps != NULL) { oc_rep_t *ep = eps->value.object; while (ep != NULL) { switch (ep->type) { case OC_REP_STRING: { if (oc_string_len(ep->name) == 2 && memcmp(oc_string(ep->name), "ep", 2) == 0) { if (oc_string_to_endpoint(&ep->value.string, &temp_ep, NULL) == 0) { if (((data->endpoint->flags & IPV4) && (temp_ep.flags & IPV6)) || ((data->endpoint->flags & IPV6) && (temp_ep.flags & IPV4))) { goto next_ep; } if (eps_cur) { eps_cur->next = oc_new_endpoint(); eps_cur = eps_cur->next; } else { eps_cur = device->endpoint = oc_new_endpoint(); } if (eps_cur) { memcpy(eps_cur, &temp_ep, sizeof(oc_endpoint_t)); eps_cur->next = NULL; eps_cur->device = data->endpoint->device; memcpy(eps_cur->di.id, di.id, 16); eps_cur->interface_index = data->endpoint->interface_index; oc_endpoint_set_local_address( eps_cur, data->endpoint->interface_index); if (oc_ipv6_endpoint_is_link_local(eps_cur) == 0 && oc_ipv6_endpoint_is_link_local(data->endpoint) == 0) { eps_cur->addr.ipv6.scope = data->endpoint->addr.ipv6.scope; } } } } } break; default: break; } ep = ep->next; } next_ep: eps = eps->next; } } break; default: break; } link = link->next; } if (!is_item_in_list(oc_discovery_cbs, cb) || !device->endpoint) { return; } cb->cb(&device->uuid, device->endpoint, cb->data); } static void obt_check_owned(oc_client_response_t *data) { if (data->code >= OC_STATUS_BAD_REQUEST) { return; } oc_uuid_t uuid; int owned = -1; oc_rep_t *rep = data->payload; while (rep != NULL) { switch (rep->type) { case OC_REP_STRING: if (oc_string_len(rep->name) == 10 && memcmp(oc_string(rep->name), "deviceuuid", 10) == 0) { oc_str_to_uuid(oc_string(rep->value.string), &uuid); } break; case OC_REP_BOOL: if (oc_string_len(rep->name) == 5 && memcmp(oc_string(rep->name), "owned", 5) == 0) { owned = (int)rep->value.boolean; } break; default: break; } rep = rep->next; } if (owned == -1) { return; } oc_uuid_t *my_uuid = oc_core_get_device_id(0); if (memcmp(my_uuid->id, uuid.id, 16) == 0) { return; } oc_device_t *device = NULL; if (owned == 0) { device = cache_new_device(oc_cache, &uuid, data->endpoint); } if (device) { device->ctx = data->user_data; oc_do_get("/oic/res", device->endpoint, "rt=oic.r.doxm", &get_endpoints, HIGH_QOS, device); } } /* Unowned device discovery */ static int discover_unowned_devices(uint8_t scope, oc_obt_discovery_cb_t cb, void *data) { oc_discovery_cb_t *c = (oc_discovery_cb_t *)oc_memb_alloc(&oc_discovery_s); if (!c) { return -1; } c->cb = cb; c->data = data; if (scope == 0x02) { if (oc_do_ip_multicast("/oic/sec/doxm", "owned=FALSE", &obt_check_owned, c)) { oc_list_add(oc_discovery_cbs, c); oc_set_delayed_callback(c, free_discovery_cb, DISCOVERY_CB_PERIOD); return 0; } } else if (scope == 0x03) { if (oc_do_realm_local_ipv6_multicast("/oic/sec/doxm", "owned=FALSE", &obt_check_owned, c)) { oc_list_add(oc_discovery_cbs, c); oc_set_delayed_callback(c, free_discovery_cb, DISCOVERY_CB_PERIOD); return 0; } } else if (scope == 0x05) { if (oc_do_site_local_ipv6_multicast("/oic/sec/doxm", "owned=FALSE", &obt_check_owned, c)) { oc_list_add(oc_discovery_cbs, c); oc_set_delayed_callback(c, free_discovery_cb, DISCOVERY_CB_PERIOD); return 0; } } oc_memb_free(&oc_discovery_s, c); return -1; } int oc_obt_discover_unowned_devices_realm_local_ipv6(oc_obt_discovery_cb_t cb, void *data) { return discover_unowned_devices(0x03, cb, data); } int oc_obt_discover_unowned_devices_site_local_ipv6(oc_obt_discovery_cb_t cb, void *data) { return discover_unowned_devices(0x05, cb, data); } int oc_obt_discover_unowned_devices(oc_obt_discovery_cb_t cb, void *data) { return discover_unowned_devices(0x02, cb, data); } /* Owned device disvoery */ static int discover_owned_devices(uint8_t scope, oc_obt_discovery_cb_t cb, void *data) { oc_discovery_cb_t *c = (oc_discovery_cb_t *)oc_memb_alloc(&oc_discovery_s); if (!c) { return -1; } c->cb = cb; c->data = data; if (scope == 0x02) { if (oc_do_ip_multicast("/oic/res", "rt=oic.r.doxm", &get_endpoints, c)) { oc_list_add(oc_discovery_cbs, c); oc_set_delayed_callback(c, free_discovery_cb, DISCOVERY_CB_PERIOD); return 0; } } else if (scope == 0x03) { if (oc_do_realm_local_ipv6_multicast("/oic/res", "rt=oic.r.doxm", &get_endpoints, c)) { oc_list_add(oc_discovery_cbs, c); oc_set_delayed_callback(c, free_discovery_cb, DISCOVERY_CB_PERIOD); return 0; } } else if (scope == 0x05) { if (oc_do_site_local_ipv6_multicast("/oic/res", "rt=oic.r.doxm", &get_endpoints, c)) { oc_list_add(oc_discovery_cbs, c); oc_set_delayed_callback(c, free_discovery_cb, DISCOVERY_CB_PERIOD); return 0; } } oc_memb_free(&oc_discovery_s, c); return -1; } int oc_obt_discover_owned_devices_realm_local_ipv6(oc_obt_discovery_cb_t cb, void *data) { return discover_owned_devices(0x03, cb, data); } int oc_obt_discover_owned_devices_site_local_ipv6(oc_obt_discovery_cb_t cb, void *data) { return discover_owned_devices(0x05, cb, data); } int oc_obt_discover_owned_devices(oc_obt_discovery_cb_t cb, void *data) { return discover_owned_devices(0x02, cb, data); } /* End of device discovery */ /* Resource discovery */ int oc_obt_discover_all_resources(oc_uuid_t *uuid, oc_discovery_all_handler_t handler, void *data) { oc_endpoint_t *ep = NULL; oc_device_t *device = get_device_handle(uuid, oc_devices); if (device) { ep = oc_obt_get_secure_endpoint(device->endpoint); } else { device = get_device_handle(uuid, oc_cache); if (device) { ep = oc_obt_get_unsecure_endpoint(device->endpoint); } } if (!device || !ep) { return -1; } if (oc_do_ip_discovery_all_at_endpoint(handler, ep, data)) { return 0; } return -1; } /* End of resource discovery */ /* Helper sequence to switch between pstat device states */ static void free_switch_dos_state(oc_switch_dos_ctx_t *d) { if (!is_item_in_list(oc_switch_dos_ctx_l, d)) { return; } oc_list_remove(oc_switch_dos_ctx_l, d); oc_memb_free(&oc_switch_dos_ctx_m, d); } static void free_switch_dos_ctx(oc_switch_dos_ctx_t *d, int status) { oc_status_cb_t cb = d->cb; free_switch_dos_state(d); cb.cb(status, cb.data); } static void pstat_POST_dos1_to_dos2(oc_client_response_t *data) { if (!is_item_in_list(oc_switch_dos_ctx_l, data->user_data)) { return; } oc_switch_dos_ctx_t *d = (oc_switch_dos_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST && data->code != OC_STATUS_SERVICE_UNAVAILABLE) { free_switch_dos_ctx(d, -1); return; } free_switch_dos_ctx(d, 0); } static oc_switch_dos_ctx_t * switch_dos(oc_device_t *device, oc_dostype_t dos, oc_obt_status_cb_t cb, void *data) { oc_endpoint_t *ep = oc_obt_get_secure_endpoint(device->endpoint); if (!ep) { return NULL; } oc_switch_dos_ctx_t *d = (oc_switch_dos_ctx_t *)oc_memb_alloc(&oc_switch_dos_ctx_m); if (!d) { return NULL; } /* oc_switch_dos_ctx_t */ d->device = device; d->dos = dos; /* oc_status_cb_t */ d->cb.cb = cb; d->cb.data = data; if (oc_init_post("/oic/sec/pstat", ep, NULL, &pstat_POST_dos1_to_dos2, HIGH_QOS, d)) { oc_rep_start_root_object(); oc_rep_set_object(root, dos); oc_rep_set_int(dos, s, dos); oc_rep_close_object(root, dos); oc_rep_end_root_object(); if (oc_do_post()) { oc_list_add(oc_switch_dos_ctx_l, d); return d; } } oc_memb_free(&oc_switch_dos_ctx_m, d); return NULL; } /* End of switch dos sequence */ /* Hard RESET sequence */ static void free_hard_reset_ctx(oc_hard_reset_ctx_t *ctx, int status) { if (!is_item_in_list(oc_hard_reset_ctx_l, ctx)) { return; } oc_list_remove(oc_hard_reset_ctx_l, ctx); oc_device_status_cb_t cb = ctx->cb; oc_endpoint_t *ep = oc_obt_get_secure_endpoint(ctx->device->endpoint); oc_tls_close_connection(ep); if (status == 0) { /* Remove device's credential from OBT's credential store */ char subjectuuid[OC_UUID_LEN]; oc_uuid_to_str(&ctx->device->uuid, subjectuuid, OC_UUID_LEN); oc_cred_remove_subject(subjectuuid, 0); cb.cb(&ctx->device->uuid, 0, cb.data); } else { cb.cb(&ctx->device->uuid, -1, cb.data); } free_device(ctx->device); if (ctx->switch_dos) { free_switch_dos_state(ctx->switch_dos); } oc_memb_free(&oc_hard_reset_ctx_m, ctx); } static void hard_reset_cb(int status, void *data) { oc_hard_reset_ctx_t *d = (oc_hard_reset_ctx_t *)data; if (!is_item_in_list(oc_hard_reset_ctx_l, d)) { return; } d->switch_dos = NULL; free_hard_reset_ctx(data, status); } int oc_obt_device_hard_reset(oc_uuid_t *uuid, oc_obt_device_status_cb_t cb, void *data) { oc_hard_reset_ctx_t *d = (oc_hard_reset_ctx_t *)oc_memb_alloc(&oc_hard_reset_ctx_m); if (!d) { return -1; } if (!oc_obt_is_owned_device(uuid)) { return -1; } oc_device_t *device = oc_obt_get_owned_device_handle(uuid); if (!device) { return -1; } d->cb.cb = cb; d->cb.data = data; d->device = device; d->switch_dos = switch_dos(device, OC_DOS_RESET, hard_reset_cb, d); if (!d->switch_dos) { oc_memb_free(&oc_hard_reset_ctx_m, d); return -1; } oc_list_add(oc_hard_reset_ctx_l, d); return 0; } /* End of hard RESET sequence */ /* Provision pairwise credentials sequence */ static void free_credprov_state(oc_credprov_ctx_t *p, int status) { if (!is_item_in_list(oc_credprov_ctx_l, p)) { return; } oc_list_remove(oc_credprov_ctx_l, p); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device1->endpoint); oc_tls_close_connection(ep); if (p->device2) { ep = oc_obt_get_secure_endpoint(p->device2->endpoint); oc_tls_close_connection(ep); } p->cb.cb(status, p->cb.data); #ifdef OC_PKI if (p->roles) { oc_obt_free_roleid(p->roles); p->roles = NULL; } #endif /* OC_PKI */ if (p->switch_dos) { free_switch_dos_state(p->switch_dos); p->switch_dos = NULL; } oc_memb_free(&oc_credprov_ctx_m, p); } static void free_credprov_ctx(oc_credprov_ctx_t *ctx, int status) { free_credprov_state(ctx, status); } static void device2_RFNOP(int status, void *data) { if (!is_item_in_list(oc_credprov_ctx_l, data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { free_credprov_ctx(p, 0); } else { free_credprov_ctx(p, -1); } } static void device1_RFNOP(int status, void *data) { if (!is_item_in_list(oc_credprov_ctx_l, data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { p->switch_dos = switch_dos(p->device2, OC_DOS_RFNOP, device2_RFNOP, p); if (p->switch_dos) { return; } } free_credprov_ctx(p, -1); } static void device2_cred(oc_client_response_t *data) { if (!is_item_in_list(oc_credprov_ctx_l, data->user_data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { free_credprov_ctx(p, -1); return; } p->switch_dos = switch_dos(p->device1, OC_DOS_RFNOP, device1_RFNOP, p); if (!p->switch_dos) { free_credprov_ctx(p, -1); } } static void device1_cred(oc_client_response_t *data) { if (!is_item_in_list(oc_credprov_ctx_l, data->user_data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { free_credprov_ctx(p, -1); return; } char d1uuid[OC_UUID_LEN]; oc_uuid_to_str(&p->device1->uuid, d1uuid, OC_UUID_LEN); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device2->endpoint); if (oc_init_post("/oic/sec/cred", ep, NULL, &device2_cred, HIGH_QOS, p)) { oc_rep_start_root_object(); oc_rep_set_array(root, creds); oc_rep_object_array_start_item(creds); oc_rep_set_int(creds, credtype, 1); oc_rep_set_text_string(creds, subjectuuid, d1uuid); oc_rep_set_object(creds, privatedata); oc_rep_set_byte_string(privatedata, data, p->key, 16); oc_rep_set_text_string(privatedata, encoding, "oic.sec.encoding.raw"); oc_rep_close_object(creds, privatedata); oc_rep_object_array_end_item(creds); oc_rep_close_array(root, creds); oc_rep_end_root_object(); if (oc_do_post()) { return; } } free_credprov_ctx(p, -1); } static void device2_RFPRO(int status, void *data) { if (!is_item_in_list(oc_credprov_ctx_l, data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { int i; for (i = 0; i < 4; i++) { unsigned int r = oc_random_value(); memcpy(&p->key[i * 4], &r, sizeof(r)); i += 4; } char d2uuid[OC_UUID_LEN]; oc_uuid_to_str(&p->device2->uuid, d2uuid, OC_UUID_LEN); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device1->endpoint); if (oc_init_post("/oic/sec/cred", ep, NULL, &device1_cred, HIGH_QOS, p)) { oc_rep_start_root_object(); oc_rep_set_array(root, creds); oc_rep_object_array_start_item(creds); oc_rep_set_int(creds, credtype, 1); oc_rep_set_text_string(creds, subjectuuid, d2uuid); oc_rep_set_object(creds, privatedata); oc_rep_set_byte_string(privatedata, data, p->key, 16); oc_rep_set_text_string(privatedata, encoding, "oic.sec.encoding.raw"); oc_rep_close_object(creds, privatedata); oc_rep_object_array_end_item(creds); oc_rep_close_array(root, creds); oc_rep_end_root_object(); if (oc_do_post()) { return; } } } free_credprov_state(p, -1); } static void device1_RFPRO(int status, void *data) { if (!is_item_in_list(oc_credprov_ctx_l, data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { p->switch_dos = switch_dos(p->device2, OC_DOS_RFPRO, device2_RFPRO, p); if (!p->switch_dos) { free_credprov_ctx(p, -1); } } else { free_credprov_ctx(p, -1); } } int oc_obt_provision_pairwise_credentials(oc_uuid_t *uuid1, oc_uuid_t *uuid2, oc_obt_status_cb_t cb, void *data) { oc_credprov_ctx_t *p = oc_memb_alloc(&oc_credprov_ctx_m); if (!p) { return -1; } if (!oc_obt_is_owned_device(uuid1)) { return -1; } if (!oc_obt_is_owned_device(uuid2)) { return -1; } oc_device_t *device1 = oc_obt_get_owned_device_handle(uuid1); if (!device1) { return -1; } oc_device_t *device2 = oc_obt_get_owned_device_handle(uuid2); if (!device2) { return -1; } p->cb.cb = cb; p->cb.data = data; p->device1 = device1; p->device2 = device2; oc_tls_select_psk_ciphersuite(); p->switch_dos = switch_dos(device1, OC_DOS_RFPRO, device1_RFPRO, p); if (!p->switch_dos) { oc_memb_free(&oc_credprov_ctx_m, p); return -1; } oc_list_add(oc_credprov_ctx_l, p); return 0; } /* End of provision pair-wise credentials sequence */ #ifdef OC_PKI /* Construct list of role ids to encode into a role certificate */ oc_role_t * oc_obt_add_roleid(oc_role_t *roles, const char *role, const char *authority) { oc_role_t *roleid = (oc_role_t *)oc_memb_alloc(&oc_roles); if (roleid) { oc_new_string(&roleid->role, role, strlen(role)); if (authority) { oc_new_string(&roleid->authority, authority, strlen(authority)); } roleid->next = roles; } return roleid; } void oc_obt_free_roleid(oc_role_t *roles) { oc_role_t *r = roles, *next; while (r) { next = r->next; oc_free_string(&r->role); if (oc_string_len(r->authority) > 0) { oc_free_string(&r->authority); } oc_memb_free(&oc_roles, r); r = next; } } /* Provision identity/role certificates */ static void device_RFNOP(int status, void *data) { if (!is_item_in_list(oc_credprov_ctx_l, data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { free_credprov_ctx(p, 0); } else { free_credprov_ctx(p, -1); } } static void device_authcrypt_roles(oc_client_response_t *data) { if (!is_item_in_list(oc_credprov_ctx_l, data->user_data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { goto err_device_authcrypt_roles; } /** 7) switch dos to RFNOP */ p->switch_dos = switch_dos(p->device1, OC_DOS_RFNOP, device_RFNOP, p); if (p->switch_dos) { return; } err_device_authcrypt_roles: free_credprov_ctx(p, -1); } static void device_cred(oc_client_response_t *data) { if (!is_item_in_list(oc_credprov_ctx_l, data->user_data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { goto err_device_cred; } /** 6) post acl2 with auth-crypt RW ACE for /oic/sec/roles */ oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device1->endpoint); if (oc_init_post("/oic/sec/acl2", ep, NULL, &device_authcrypt_roles, HIGH_QOS, p)) { oc_rep_start_root_object(); oc_rep_set_array(root, aclist2); oc_rep_object_array_start_item(aclist2); oc_rep_set_object(aclist2, subject); oc_rep_set_text_string(subject, conntype, "auth-crypt"); oc_rep_close_object(aclist2, subject); oc_rep_set_array(aclist2, resources); oc_rep_object_array_start_item(resources); oc_rep_set_text_string(resources, href, "/oic/sec/roles"); oc_rep_object_array_end_item(resources); oc_rep_close_array(aclist2, resources); oc_rep_set_uint(aclist2, permission, OC_PERM_RETRIEVE | OC_PERM_UPDATE); oc_rep_object_array_end_item(aclist2); oc_rep_close_array(root, aclist2); oc_rep_end_root_object(); if (oc_do_post()) { return; } } err_device_cred: free_credprov_ctx(p, -1); } static void device_CSR(oc_client_response_t *data) { if (!is_item_in_list(oc_credprov_ctx_l, data->user_data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data->user_data; oc_string_t subject, cert; memset(&subject, 0, sizeof(oc_string_t)); memset(&cert, 0, sizeof(oc_string_t)); uint8_t pub_key[OC_ECDSA_PUBKEY_SIZE]; if (data->code >= OC_STATUS_BAD_REQUEST) { goto err_device_CSR; } size_t csr_len = 0; char *csr = NULL; size_t encoding_len = 0; char *encoding = NULL; if (!oc_rep_get_string(data->payload, "encoding", &encoding, &encoding_len)) { goto err_device_CSR; } if (encoding_len == 20 && memcmp(encoding, "oic.sec.encoding.pem", 20) == 0) { if (!oc_rep_get_string(data->payload, "csr", &csr, &csr_len)) { goto err_device_CSR; } csr_len++; } else { goto err_device_CSR; } /** 5) validate csr */ int ret = oc_certs_validate_csr((const unsigned char *)csr, csr_len, &subject, pub_key); if (ret < 0) { goto err_device_CSR; } if (!p->roles) { /** 5) generate identity cert */ ret = oc_obt_generate_identity_cert(oc_string(subject), pub_key, OC_ECDSA_PUBKEY_SIZE, root_subject, private_key, private_key_size, &cert); } else { /** 5) generate role cert */ ret = oc_obt_generate_role_cert(p->roles, oc_string(subject), pub_key, OC_ECDSA_PUBKEY_SIZE, root_subject, private_key, private_key_size, &cert); } if (ret < 0) { goto err_device_CSR; } /** 5) post cred with identity/role cert */ oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device1->endpoint); if (oc_init_post("/oic/sec/cred", ep, NULL, &device_cred, HIGH_QOS, p)) { oc_rep_start_root_object(); oc_rep_set_array(root, creds); oc_rep_object_array_start_item(creds); oc_rep_set_int(creds, credtype, OC_CREDTYPE_CERT); oc_rep_set_text_string(creds, subjectuuid, "*"); oc_rep_set_object(creds, publicdata); oc_rep_set_text_string(publicdata, data, oc_string(cert)); oc_rep_set_text_string(publicdata, encoding, "oic.sec.encoding.pem"); oc_rep_close_object(creds, publicdata); if (p->roles) { oc_rep_set_text_string(creds, credusage, "oic.sec.cred.rolecert"); } else { oc_rep_set_text_string(creds, credusage, "oic.sec.cred.cert"); } oc_rep_object_array_end_item(creds); oc_rep_close_array(root, creds); oc_rep_end_root_object(); if (oc_do_post()) { oc_free_string(&subject); oc_free_string(&cert); return; } } err_device_CSR: if (oc_string_len(subject) > 0) { oc_free_string(&subject); } if (oc_string_len(cert) > 0) { oc_free_string(&cert); } free_credprov_state(p, -1); } static void device_root(oc_client_response_t *data) { if (!is_item_in_list(oc_credprov_ctx_l, data->user_data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { goto err_device_root; } /** 4) get csr */ oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device1->endpoint); if (oc_do_get("/oic/sec/csr", ep, NULL, &device_CSR, HIGH_QOS, p)) { return; } err_device_root: free_credprov_ctx(p, -1); } static void device_RFPRO(int status, void *data) { if (!is_item_in_list(oc_credprov_ctx_l, data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { oc_sec_cred_t *root = oc_sec_get_cred_by_credid(root_cert_credid, 0); if (!root) { goto err_device_RFPRO; } /** 3) post cred with trustca */ oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device1->endpoint); if (oc_init_post("/oic/sec/cred", ep, NULL, &device_root, HIGH_QOS, p)) { oc_rep_start_root_object(); oc_rep_set_array(root, creds); oc_rep_object_array_start_item(creds); oc_rep_set_int(creds, credtype, OC_CREDTYPE_CERT); oc_rep_set_text_string(creds, subjectuuid, "*"); oc_rep_set_object(creds, publicdata); oc_rep_set_text_string(publicdata, data, oc_string(root->publicdata.data)); oc_rep_set_text_string(publicdata, encoding, "oic.sec.encoding.pem"); oc_rep_close_object(creds, publicdata); oc_rep_set_text_string(creds, credusage, "oic.sec.cred.trustca"); oc_rep_object_array_end_item(creds); oc_rep_close_array(root, creds); oc_rep_end_root_object(); if (oc_do_post()) { return; } } } err_device_RFPRO: free_credprov_state(p, -1); } static void supports_cert_creds(oc_client_response_t *data) { if (!is_item_in_list(oc_credprov_ctx_l, data->user_data)) { return; } oc_credprov_ctx_t *p = (oc_credprov_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { goto err_supports_cert_creds; } int64_t sct = 0; if (oc_rep_get_int(data->payload, "sct", &sct)) { /* Confirm that the device handles certificate credentials */ if (sct & 0x0000000000000008) { /** 2) switch dos to RFPRO */ p->switch_dos = switch_dos(p->device1, OC_DOS_RFPRO, device_RFPRO, p); if (p->switch_dos) { return; } } } err_supports_cert_creds: free_credprov_state(p, -1); } /* Provision role certificate: 1) get doxm 2) switch dos to RFPRO 3) post cred with trustca 4) get csr 5) validate csr, generate role cert, post cred with role cert 6) post acl2 with auth-crypt RW ACE for /oic/sec/roles 7) switch dos to RFNOP */ int oc_obt_provision_role_certificate(oc_role_t *roles, oc_uuid_t *uuid, oc_obt_status_cb_t cb, void *data) { oc_credprov_ctx_t *p = oc_memb_alloc(&oc_credprov_ctx_m); if (!p) { OC_ERR("could not allocate API context"); return -1; } if (!oc_obt_is_owned_device(uuid)) { OC_ERR("device is not owned"); return -1; } oc_device_t *device = oc_obt_get_owned_device_handle(uuid); if (!device) { OC_ERR("could not obtain device handle"); return -1; } p->cb.cb = cb; p->cb.data = data; p->device1 = device; p->device2 = NULL; p->roles = roles; oc_tls_select_psk_ciphersuite(); /** 1) get doxm */ oc_endpoint_t *ep = oc_obt_get_secure_endpoint(device->endpoint); if (oc_do_get("/oic/sec/doxm", ep, NULL, &supports_cert_creds, HIGH_QOS, p)) { oc_list_add(oc_credprov_ctx_l, p); return 0; } oc_memb_free(&oc_credprov_ctx_m, p); return -1; } /* Provision identity certificate: 1) switch dos to RFPRO 2) post cred with trustca 3) get csr 4) validate csr, generate identity cert, post cred with identity cert 5) post acl2 with auth-crypt RW ACE for /oic/sec/roles 6) switch dos to RFNOP */ int oc_obt_provision_identity_certificate(oc_uuid_t *uuid, oc_obt_status_cb_t cb, void *data) { oc_credprov_ctx_t *p = oc_memb_alloc(&oc_credprov_ctx_m); if (!p) { return -1; } if (!oc_obt_is_owned_device(uuid)) { return -1; } oc_device_t *device = oc_obt_get_owned_device_handle(uuid); if (!device) { return -1; } p->cb.cb = cb; p->cb.data = data; p->device1 = device; p->device2 = NULL; oc_tls_select_psk_ciphersuite(); /** 1) get doxm */ oc_endpoint_t *ep = oc_obt_get_secure_endpoint(device->endpoint); if (oc_do_get("/oic/sec/doxm", ep, NULL, &supports_cert_creds, HIGH_QOS, p)) { oc_list_add(oc_credprov_ctx_l, p); return 0; } oc_memb_free(&oc_credprov_ctx_m, p); return -1; } #endif /* OC_PKI */ /* Provision role ACE for wildcard "*" resource with RW permissions */ int oc_obt_provision_role_wildcard_ace(oc_uuid_t *subject, const char *role, const char *authority, oc_obt_device_status_cb_t cb, void *data) { oc_sec_ace_t *ace = NULL; oc_ace_res_t *res = NULL; int ret = -1; ace = oc_obt_new_ace_for_role(role, authority); if (!ace) { goto exit_aceprov_role_wc; } res = oc_obt_ace_new_resource(ace); if (!res) { oc_obt_free_ace(ace); goto exit_aceprov_role_wc; } oc_obt_ace_resource_set_wc(res, OC_ACE_WC_ALL); oc_obt_ace_add_permission(ace, OC_PERM_RETRIEVE | OC_PERM_UPDATE); if (oc_obt_provision_ace(subject, ace, cb, data) >= 0) { ret = 0; return ret; } exit_aceprov_role_wc: return ret; } /* Provision auth-crypt ACE for the wildcard "*" resource with RW permissions */ int oc_obt_provision_auth_wildcard_ace(oc_uuid_t *subject, oc_obt_device_status_cb_t cb, void *data) { oc_sec_ace_t *ace = NULL; oc_ace_res_t *res = NULL; int ret = -1; ace = oc_obt_new_ace_for_connection(OC_CONN_AUTH_CRYPT); if (!ace) { goto exit_aceprov_ac_wc; } res = oc_obt_ace_new_resource(ace); if (!res) { oc_obt_free_ace(ace); goto exit_aceprov_ac_wc; } oc_obt_ace_resource_set_wc(res, OC_ACE_WC_ALL); oc_obt_ace_add_permission(ace, OC_PERM_RETRIEVE | OC_PERM_UPDATE); if (oc_obt_provision_ace(subject, ace, cb, data) >= 0) { ret = 0; return ret; } exit_aceprov_ac_wc: return ret; } /* Provision access-control entries */ static oc_sec_ace_t * oc_obt_new_ace(void) { oc_sec_ace_t *ace = (oc_sec_ace_t *)oc_memb_alloc(&oc_aces_m); if (ace) { OC_LIST_STRUCT_INIT(ace, resources); } return ace; } oc_sec_ace_t * oc_obt_new_ace_for_subject(oc_uuid_t *uuid) { oc_sec_ace_t *ace = oc_obt_new_ace(); if (ace) { ace->subject_type = OC_SUBJECT_UUID; memcpy(ace->subject.uuid.id, uuid->id, 16); } return ace; } oc_sec_ace_t * oc_obt_new_ace_for_role(const char *role, const char *authority) { if (!role) { return NULL; } oc_sec_ace_t *ace = oc_obt_new_ace(); if (ace) { ace->subject_type = OC_SUBJECT_ROLE; oc_new_string(&ace->subject.role.role, role, strlen(role)); if (authority) { oc_new_string(&ace->subject.role.authority, authority, strlen(authority)); } } return ace; } oc_sec_ace_t * oc_obt_new_ace_for_connection(oc_ace_connection_type_t conn) { oc_sec_ace_t *ace = oc_obt_new_ace(); if (ace) { ace->subject_type = OC_SUBJECT_CONN; ace->subject.conn = conn; } return ace; } oc_ace_res_t * oc_obt_ace_new_resource(oc_sec_ace_t *ace) { oc_ace_res_t *res = (oc_ace_res_t *)oc_memb_alloc(&oc_res_m); if (res) { oc_list_add(ace->resources, res); } return res; } void oc_obt_ace_resource_set_href(oc_ace_res_t *resource, const char *href) { if (resource) { if (oc_string_len(resource->href) > 0) { oc_free_string(&resource->href); } oc_new_string(&resource->href, href, strlen(href)); } } void oc_obt_ace_resource_set_wc(oc_ace_res_t *resource, oc_ace_wildcard_t wc) { if (resource) { resource->wildcard = wc; } } void oc_obt_ace_add_permission(oc_sec_ace_t *ace, oc_ace_permissions_t permission) { if (ace) { ace->permission |= permission; } } static void free_ace(oc_sec_ace_t *ace) { if (ace) { oc_ace_res_t *res = (oc_ace_res_t *)oc_list_pop(ace->resources); while (res != NULL) { if (oc_string_len(res->href) > 0) { oc_free_string(&res->href); } oc_memb_free(&oc_res_m, res); res = (oc_ace_res_t *)oc_list_pop(ace->resources); } if (ace->subject_type == OC_SUBJECT_ROLE) { if (oc_string_len(ace->subject.role.role) > 0) { oc_free_string(&ace->subject.role.role); } if (oc_string_len(ace->subject.role.authority) > 0) { oc_free_string(&ace->subject.role.authority); } } oc_memb_free(&oc_aces_m, ace); } } void oc_obt_free_ace(oc_sec_ace_t *ace) { free_ace(ace); } static void free_acl2prov_state(oc_acl2prov_ctx_t *request, int status) { if (!is_item_in_list(oc_acl2prov_ctx_l, request)) { return; } oc_list_remove(oc_acl2prov_ctx_l, request); free_ace(request->ace); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(request->device->endpoint); oc_tls_close_connection(ep); if (request->switch_dos) { free_switch_dos_state(request->switch_dos); } request->cb.cb(&request->device->uuid, status, request->cb.data); oc_memb_free(&oc_acl2prov_ctx_m, request); } static void free_acl2prov_ctx(oc_acl2prov_ctx_t *r, int status) { free_acl2prov_state(r, status); } static void provision_ace_complete(int status, void *data) { if (!is_item_in_list(oc_acl2prov_ctx_l, data)) { return; } oc_acl2prov_ctx_t *r = (oc_acl2prov_ctx_t *)data; r->switch_dos = NULL; if (status >= 0) { free_acl2prov_ctx(r, 0); } else { free_acl2prov_ctx(r, -1); } } static void acl2_response(oc_client_response_t *data) { if (!is_item_in_list(oc_acl2prov_ctx_l, data->user_data)) { return; } oc_acl2prov_ctx_t *r = (oc_acl2prov_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { free_acl2prov_ctx(r, -1); return; } oc_device_t *device = r->device; r->switch_dos = switch_dos(device, OC_DOS_RFNOP, provision_ace_complete, r); if (!r->switch_dos) { free_acl2prov_ctx(r, -1); } } static void provision_ace(int status, void *data) { if (!is_item_in_list(oc_acl2prov_ctx_l, data)) { return; } oc_acl2prov_ctx_t *r = (oc_acl2prov_ctx_t *)data; r->switch_dos = NULL; if (status >= 0) { oc_device_t *device = r->device; oc_sec_ace_t *ace = r->ace; oc_endpoint_t *ep = oc_obt_get_secure_endpoint(device->endpoint); if (oc_init_post("/oic/sec/acl2", ep, NULL, &acl2_response, HIGH_QOS, r)) { oc_rep_start_root_object(); oc_rep_set_array(root, aclist2); oc_rep_object_array_start_item(aclist2); oc_rep_set_object(aclist2, subject); switch (ace->subject_type) { case OC_SUBJECT_UUID: { char uuid[OC_UUID_LEN]; oc_uuid_to_str(&ace->subject.uuid, uuid, OC_UUID_LEN); oc_rep_set_text_string(subject, uuid, uuid); } break; case OC_SUBJECT_CONN: { switch (ace->subject.conn) { case OC_CONN_AUTH_CRYPT: oc_rep_set_text_string(subject, conntype, "auth-crypt"); break; case OC_CONN_ANON_CLEAR: oc_rep_set_text_string(subject, conntype, "anon-clear"); break; } } break; case OC_SUBJECT_ROLE: { oc_rep_set_text_string(subject, role, oc_string(ace->subject.role.role)); if (oc_string_len(ace->subject.role.authority) > 0) { oc_rep_set_text_string(subject, authority, oc_string(ace->subject.role.authority)); } } break; default: break; } oc_rep_close_object(aclist2, subject); oc_ace_res_t *res = (oc_ace_res_t *)oc_list_head(ace->resources); oc_rep_set_array(aclist2, resources); while (res != NULL) { oc_rep_object_array_start_item(resources); if (oc_string_len(res->href) > 0) { oc_rep_set_text_string(resources, href, oc_string(res->href)); } else { switch (res->wildcard) { case OC_ACE_WC_ALL_SECURED: oc_rep_set_text_string(resources, wc, "+"); break; case OC_ACE_WC_ALL_PUBLIC: oc_rep_set_text_string(resources, wc, "-"); break; case OC_ACE_WC_ALL: oc_rep_set_text_string(resources, wc, "*"); break; default: break; } } oc_rep_object_array_end_item(resources); res = res->next; } oc_rep_close_array(aclist2, resources); oc_rep_set_uint(aclist2, permission, ace->permission); oc_rep_object_array_end_item(aclist2); oc_rep_close_array(root, aclist2); oc_rep_end_root_object(); if (oc_do_post()) { return; } } } free_acl2prov_ctx(r, -1); } int oc_obt_provision_ace(oc_uuid_t *uuid, oc_sec_ace_t *ace, oc_obt_device_status_cb_t cb, void *data) { oc_acl2prov_ctx_t *r = (oc_acl2prov_ctx_t *)oc_memb_alloc(&oc_acl2prov_ctx_m); if (!r) { return -1; } if (!oc_obt_is_owned_device(uuid)) { return -1; } oc_device_t *device = oc_obt_get_owned_device_handle(uuid); if (!device) { return -1; } r->cb.cb = cb; r->cb.data = data; r->ace = ace; r->device = device; oc_tls_select_psk_ciphersuite(); r->switch_dos = switch_dos(device, OC_DOS_RFPRO, provision_ace, r); if (!r->switch_dos) { free_ace(ace); oc_memb_free(&oc_acl2prov_ctx_m, r); return -1; } oc_list_add(oc_acl2prov_ctx_l, r); return 0; } /* End of provision ACE sequence */ /* Retrieving credentials */ void oc_obt_free_creds(oc_sec_creds_t *creds) { oc_sec_cred_t *cred = oc_list_head(creds->creds), *next; while (cred != NULL) { next = cred->next; if (oc_string_len(cred->role.role) > 0) { oc_free_string(&cred->role.role); if (oc_string_len(cred->role.authority) > 0) { oc_free_string(&cred->role.authority); } } if (oc_string_len(cred->privatedata.data) > 0) { oc_free_string(&cred->privatedata.data); } #ifdef OC_PKI if (oc_string_len(cred->publicdata.data) > 0) { oc_free_string(&cred->publicdata.data); } #endif /* OC_PKI */ oc_memb_free(&oc_cred_m, cred); cred = next; } oc_memb_free(&oc_creds_m, creds); } static bool decode_cred(oc_rep_t *rep, oc_sec_creds_t *creds) { size_t len = 0; while (rep != NULL) { len = oc_string_len(rep->name); switch (rep->type) { /* rowneruuid */ case OC_REP_STRING: if (len == 10 && memcmp(oc_string(rep->name), "rowneruuid", 10) == 0) { oc_str_to_uuid(oc_string(rep->value.string), &creds->rowneruuid); } break; /* creds */ case OC_REP_OBJECT_ARRAY: { if (len == 5 && (memcmp(oc_string(rep->name), "creds", 5) == 0 || memcmp(oc_string(rep->name), "roles", 5) == 0)) { oc_rep_t *creds_array = rep->value.object_array; /* array of oic.sec.cred */ while (creds_array != NULL) { oc_sec_cred_t *cr = (oc_sec_cred_t *)oc_memb_alloc(&oc_cred_m); if (!cr) { goto error_decode_cred; } oc_list_add(creds->creds, cr); oc_rep_t *cred = creds_array->value.object; while (cred != NULL) { len = oc_string_len(cred->name); switch (cred->type) { /* credid and credtype */ case OC_REP_INT: if (len == 6 && memcmp(oc_string(cred->name), "credid", 6) == 0) { cr->credid = (int)cred->value.integer; } else if (len == 8 && memcmp(oc_string(cred->name), "credtype", 8) == 0) { cr->credtype = cred->value.integer; } break; /* subjectuuid and credusage */ case OC_REP_STRING: if (len == 11 && memcmp(oc_string(cred->name), "subjectuuid", 11) == 0) { oc_str_to_uuid(oc_string(cred->value.string), &cr->subjectuuid); } #ifdef OC_PKI else if (len == 9 && memcmp(oc_string(cred->name), "credusage", 9) == 0) { cr->credusage = oc_cred_parse_credusage(&cred->value.string); } #endif /* OC_PKI */ break; /* publicdata, privatedata and roleid */ case OC_REP_OBJECT: { oc_rep_t *data = cred->value.object; if ((len == 11 && memcmp(oc_string(cred->name), "privatedata", 11) == 0) #ifdef OC_PKI || (len == 10 && memcmp(oc_string(cred->name), "publicdata", 10) == 0) #endif /* OC_PKI */ ) { while (data != NULL) { switch (data->type) { case OC_REP_STRING: { if (oc_string_len(data->name) == 8 && memcmp("encoding", oc_string(data->name), 8) == 0) { oc_sec_encoding_t encoding = oc_cred_parse_encoding(&data->value.string); if (len == 11) { cr->privatedata.encoding = encoding; } #ifdef OC_PKI else { cr->publicdata.encoding = encoding; } #endif /* OC_PKI */ } else if (oc_string_len(data->name) == 4 && memcmp(oc_string(data->name), "data", 4) == 0) { if (oc_string_len(data->value.string) == 0) { goto next_item; } if (len == 11) { oc_new_string(&cr->privatedata.data, oc_string(data->value.string), oc_string_len(data->value.string)); } #ifdef OC_PKI else { oc_new_string(&cr->publicdata.data, oc_string(data->value.string), oc_string_len(data->value.string)); } #endif /* OC_PKI */ } } break; case OC_REP_BYTE_STRING: { if (oc_string_len(data->name) == 4 && memcmp(oc_string(data->name), "data", 4) == 0) { if (oc_string_len(data->value.string) == 0) { goto next_item; } if (len == 11) { oc_new_string(&cr->privatedata.data, oc_string(data->value.string), oc_string_len(data->value.string)); } #ifdef OC_PKI else { oc_new_string(&cr->publicdata.data, oc_string(data->value.string), oc_string_len(data->value.string)); } #endif /* OC_PKI */ } } break; default: break; } next_item: data = data->next; } } else if (len == 6 && memcmp(oc_string(cred->name), "roleid", 6) == 0) { while (data != NULL) { len = oc_string_len(data->name); if (len == 4 && memcmp(oc_string(data->name), "role", 4) == 0) { oc_new_string(&cr->role.role, oc_string(data->value.string), oc_string_len(data->value.string)); } else if (len == 9 && memcmp(oc_string(data->name), "authority", 9) == 0) { oc_new_string(&cr->role.role, oc_string(data->value.string), oc_string_len(data->value.string)); } data = data->next; } } } break; case OC_REP_BOOL: if (len == 10 && memcmp(oc_string(cred->name), "owner_cred", 10) == 0) { cr->owner_cred = cred->value.boolean; } break; default: break; } cred = cred->next; } creds_array = creds_array->next; } } } break; default: break; } rep = rep->next; } return true; error_decode_cred: return false; } static void cred_rsrc(oc_client_response_t *data) { oc_credret_ctx_t *ctx = (oc_credret_ctx_t *)data->user_data; if (!is_item_in_list(oc_credret_ctx_l, ctx)) { return; } oc_list_remove(oc_credret_ctx_l, ctx); oc_sec_creds_t *creds = NULL; if (data->code < OC_STATUS_BAD_REQUEST) { creds = (oc_sec_creds_t *)oc_memb_alloc(&oc_creds_m); if (creds) { OC_LIST_STRUCT_INIT(creds, creds); if (decode_cred(data->payload, creds)) { OC_DBG("oc_obt:decoded /oic/sec/cred payload"); } else { OC_DBG("oc_obt:error decoding /oic/sec/cred payload"); } if (oc_list_length(creds->creds) > 0) { ctx->cb(creds, ctx->data); } else { oc_memb_free(&oc_creds_m, creds); creds = NULL; } } } if (!creds) { ctx->cb(NULL, ctx->data); } oc_memb_free(&oc_credret_ctx_m, ctx); } int oc_obt_retrieve_creds(oc_uuid_t *uuid, oc_obt_creds_cb_t cb, void *data) { if (!oc_obt_is_owned_device(uuid)) { return -1; } oc_device_t *device = oc_obt_get_owned_device_handle(uuid); if (!device) { return -1; } oc_credret_ctx_t *r = (oc_credret_ctx_t *)oc_memb_alloc(&oc_credret_ctx_m); if (!r) { return -1; } r->cb = cb; r->data = data; oc_tls_select_psk_ciphersuite(); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(device->endpoint); if (oc_do_get("/oic/sec/cred", ep, NULL, &cred_rsrc, HIGH_QOS, r)) { oc_list_add(oc_credret_ctx_l, r); return 0; } oc_memb_free(&oc_credret_ctx_m, r); return 0; } /* Deleting Credentials */ static void free_creddel_state(oc_creddel_ctx_t *p, int status) { if (!is_item_in_list(oc_creddel_ctx_l, p)) { return; } oc_list_remove(oc_creddel_ctx_l, p); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device->endpoint); oc_tls_close_connection(ep); p->cb.cb(status, p->cb.data); if (p->switch_dos) { free_switch_dos_state(p->switch_dos); p->switch_dos = NULL; } oc_memb_free(&oc_creddel_ctx_m, p); } static void free_creddel_ctx(oc_creddel_ctx_t *ctx, int status) { free_creddel_state(ctx, status); } static void creddel_RFNOP(int status, void *data) { if (!is_item_in_list(oc_creddel_ctx_l, data)) { return; } oc_creddel_ctx_t *p = (oc_creddel_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { free_creddel_ctx(p, 0); } else { free_creddel_ctx(p, -1); } } static void cred_del(oc_client_response_t *data) { if (!is_item_in_list(oc_creddel_ctx_l, data->user_data)) { return; } oc_creddel_ctx_t *p = (oc_creddel_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { free_creddel_ctx(p, -1); return; } p->switch_dos = switch_dos(p->device, OC_DOS_RFNOP, creddel_RFNOP, p); if (!p->switch_dos) { free_creddel_state(p, -1); } } static void creddel_RFPRO(int status, void *data) { if (!is_item_in_list(oc_creddel_ctx_l, data)) { return; } oc_creddel_ctx_t *p = (oc_creddel_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { char query[64]; snprintf(query, 64, "credid=%d", p->credid); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device->endpoint); if (oc_do_delete("/oic/sec/cred", ep, query, &cred_del, HIGH_QOS, p)) { return; } } free_creddel_ctx(p, -1); } int oc_obt_delete_cred_by_credid(oc_uuid_t *uuid, int credid, oc_obt_status_cb_t cb, void *data) { if (!oc_obt_is_owned_device(uuid)) { return -1; } oc_device_t *device = oc_obt_get_owned_device_handle(uuid); if (!device) { return -1; } oc_creddel_ctx_t *p = oc_memb_alloc(&oc_creddel_ctx_m); if (!p) { return -1; } p->cb.cb = cb; p->cb.data = data; p->device = device; p->credid = credid; oc_tls_select_psk_ciphersuite(); p->switch_dos = switch_dos(device, OC_DOS_RFPRO, creddel_RFPRO, p); if (!p->switch_dos) { oc_memb_free(&oc_creddel_ctx_m, p); return -1; } oc_list_add(oc_creddel_ctx_l, p); return 0; } /* Retrieve ACL */ bool decode_acl(oc_rep_t *rep, oc_sec_acl_t *acl) { size_t len = 0; while (rep != NULL) { len = oc_string_len(rep->name); switch (rep->type) { case OC_REP_STRING: if (len == 10 && memcmp(oc_string(rep->name), "rowneruuid", 10) == 0) { oc_str_to_uuid(oc_string(rep->value.string), &acl->rowneruuid); } break; case OC_REP_OBJECT_ARRAY: { oc_rep_t *aclist2 = rep->value.object_array; OC_LIST_STRUCT_INIT(acl, subjects); while (aclist2 != NULL) { oc_sec_ace_t *ac = (oc_sec_ace_t *)oc_memb_alloc(&oc_aces_m); if (!ac) { goto error_decode_acl; } OC_LIST_STRUCT_INIT(ac, resources); oc_list_add(acl->subjects, ac); oc_rep_t *resources = NULL; oc_rep_t *ace = aclist2->value.object; while (ace != NULL) { len = oc_string_len(ace->name); switch (ace->type) { case OC_REP_INT: if (len == 10 && memcmp(oc_string(ace->name), "permission", 10) == 0) { ac->permission = (uint16_t)ace->value.integer; } else if (len == 5 && memcmp(oc_string(ace->name), "aceid", 5) == 0) { ac->aceid = (int)ace->value.integer; } break; case OC_REP_OBJECT_ARRAY: if (len == 9 && memcmp(oc_string(ace->name), "resources", 9) == 0) resources = ace->value.object_array; break; case OC_REP_OBJECT: { oc_rep_t *sub = ace->value.object; while (sub != NULL) { len = oc_string_len(sub->name); if (len == 4 && memcmp(oc_string(sub->name), "uuid", 4) == 0) { oc_str_to_uuid(oc_string(sub->value.string), &ac->subject.uuid); ac->subject_type = OC_SUBJECT_UUID; } else if (len == 4 && memcmp(oc_string(sub->name), "role", 4) == 0) { oc_new_string(&ac->subject.role.role, oc_string(sub->value.string), oc_string_len(sub->value.string)); ac->subject_type = OC_SUBJECT_ROLE; } else if (len == 9 && memcmp(oc_string(sub->name), "authority", 9) == 0) { oc_new_string(&ac->subject.role.authority, oc_string(sub->value.string), oc_string_len(sub->value.string)); ac->subject_type = OC_SUBJECT_ROLE; } else if (len == 8 && memcmp(oc_string(sub->name), "conntype", 8) == 0) { if (oc_string_len(sub->value.string) == 10 && memcmp(oc_string(sub->value.string), "auth-crypt", 10) == 0) { ac->subject.conn = OC_CONN_AUTH_CRYPT; } else if (oc_string_len(sub->value.string) == 10 && memcmp(oc_string(sub->value.string), "anon-clear", 10) == 0) { ac->subject.conn = OC_CONN_ANON_CLEAR; } ac->subject_type = OC_SUBJECT_CONN; } sub = sub->next; } } break; default: break; } ace = ace->next; } while (resources != NULL) { oc_ace_res_t *res = (oc_ace_res_t *)oc_memb_alloc(&oc_res_m); if (!res) { goto error_decode_acl; } oc_list_add(ac->resources, res); oc_rep_t *resource = resources->value.object; while (resource != NULL) { switch (resource->type) { case OC_REP_STRING: if (oc_string_len(resource->name) == 4 && memcmp(oc_string(resource->name), "href", 4) == 0) { oc_new_string(&res->href, oc_string(resource->value.string), oc_string_len(resource->value.string)); } else if (oc_string_len(resource->name) == 2 && memcmp(oc_string(resource->name), "wc", 2) == 0) { if (oc_string(resource->value.string)[0] == '*') { res->wildcard = OC_ACE_WC_ALL; } if (oc_string(resource->value.string)[0] == '+') { res->wildcard = OC_ACE_WC_ALL_SECURED; } if (oc_string(resource->value.string)[0] == '-') { res->wildcard = OC_ACE_WC_ALL_PUBLIC; } } break; default: break; } resource = resource->next; } resources = resources->next; } aclist2 = aclist2->next; } } break; default: break; } rep = rep->next; } return true; error_decode_acl: return false; } void oc_obt_free_acl(oc_sec_acl_t *acl) { oc_sec_ace_t *ace = (oc_sec_ace_t *)oc_list_pop(acl->subjects), *next; while (ace) { next = ace->next; oc_obt_free_ace(ace); ace = next; } oc_memb_free(&oc_acl_m, acl); } static void acl2_rsrc(oc_client_response_t *data) { oc_aclret_ctx_t *ctx = (oc_aclret_ctx_t *)data->user_data; if (!is_item_in_list(oc_aclret_ctx_l, ctx)) { return; } oc_list_remove(oc_aclret_ctx_l, ctx); oc_sec_acl_t *acl = NULL; if (data->code < OC_STATUS_BAD_REQUEST) { acl = (oc_sec_acl_t *)oc_memb_alloc(&oc_acl_m); if (acl) { if (decode_acl(data->payload, acl)) { OC_DBG("oc_obt:decoded /oic/sec/acl2 payload"); } else { OC_DBG("oc_obt:error decoding /oic/sec/acl2 payload"); } if (oc_list_length(acl->subjects) > 0) { ctx->cb(acl, ctx->data); } else { oc_memb_free(&oc_acl_m, acl); acl = NULL; } } } if (!acl) { ctx->cb(NULL, ctx->data); } oc_memb_free(&oc_aclret_ctx_m, ctx); } int oc_obt_retrieve_acl(oc_uuid_t *uuid, oc_obt_acl_cb_t cb, void *data) { if (!oc_obt_is_owned_device(uuid)) { return -1; } oc_device_t *device = oc_obt_get_owned_device_handle(uuid); if (!device) { return -1; } oc_aclret_ctx_t *r = (oc_aclret_ctx_t *)oc_memb_alloc(&oc_aclret_ctx_m); if (!r) { return -1; } r->cb = cb; r->data = data; oc_tls_select_psk_ciphersuite(); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(device->endpoint); if (oc_do_get("/oic/sec/acl2", ep, NULL, &acl2_rsrc, HIGH_QOS, r)) { oc_list_add(oc_aclret_ctx_l, r); return 0; } oc_memb_free(&oc_aclret_ctx_m, r); return 0; } /* Deleting ACEs */ static void free_acedel_state(oc_acedel_ctx_t *p, int status) { if (!is_item_in_list(oc_acedel_ctx_l, p)) { return; } oc_list_remove(oc_acedel_ctx_l, p); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device->endpoint); oc_tls_close_connection(ep); p->cb.cb(status, p->cb.data); if (p->switch_dos) { free_switch_dos_state(p->switch_dos); p->switch_dos = NULL; } oc_memb_free(&oc_acedel_ctx_m, p); } static void free_acedel_ctx(oc_acedel_ctx_t *ctx, int status) { free_acedel_state(ctx, status); } static void acedel_RFNOP(int status, void *data) { if (!is_item_in_list(oc_acedel_ctx_l, data)) { return; } oc_acedel_ctx_t *p = (oc_acedel_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { free_acedel_ctx(p, 0); } else { free_acedel_ctx(p, -1); } } static void ace_del(oc_client_response_t *data) { if (!is_item_in_list(oc_acedel_ctx_l, data->user_data)) { return; } oc_acedel_ctx_t *p = (oc_acedel_ctx_t *)data->user_data; if (data->code >= OC_STATUS_BAD_REQUEST) { free_acedel_ctx(p, -1); return; } p->switch_dos = switch_dos(p->device, OC_DOS_RFNOP, acedel_RFNOP, p); if (!p->switch_dos) { free_acedel_state(p, -1); } } static void acedel_RFPRO(int status, void *data) { if (!is_item_in_list(oc_acedel_ctx_l, data)) { return; } oc_acedel_ctx_t *p = (oc_acedel_ctx_t *)data; p->switch_dos = NULL; if (status >= 0) { char query[64]; snprintf(query, 64, "aceid=%d", p->aceid); oc_endpoint_t *ep = oc_obt_get_secure_endpoint(p->device->endpoint); if (oc_do_delete("/oic/sec/acl2", ep, query, &ace_del, HIGH_QOS, p)) { return; } } free_acedel_ctx(p, -1); } int oc_obt_delete_ace_by_aceid(oc_uuid_t *uuid, int aceid, oc_obt_status_cb_t cb, void *data) { if (!oc_obt_is_owned_device(uuid)) { return -1; } oc_device_t *device = oc_obt_get_owned_device_handle(uuid); if (!device) { return -1; } oc_acedel_ctx_t *p = oc_memb_alloc(&oc_acedel_ctx_m); if (!p) { return -1; } p->cb.cb = cb; p->cb.data = data; p->device = device; p->aceid = aceid; oc_tls_select_psk_ciphersuite(); p->switch_dos = switch_dos(device, OC_DOS_RFPRO, acedel_RFPRO, p); if (!p->switch_dos) { oc_memb_free(&oc_acedel_ctx_m, p); return -1; } oc_list_add(oc_acedel_ctx_l, p); return 0; } oc_sec_creds_t * oc_obt_retrieve_own_creds(void) { return oc_sec_get_creds(0); } int oc_obt_delete_own_cred_by_credid(int credid) { oc_sec_cred_t *cred = oc_sec_get_cred_by_credid(credid, 0); if (cred) { oc_sec_remove_cred(cred, 0); return 0; } return -1; } void oc_obt_set_sd_info(char *name, bool priv) { oc_sec_sdi_t *sdi = oc_sec_get_sdi(0); oc_free_string(&sdi->name); oc_new_string(&sdi->name, name, strlen(name)); sdi->priv = priv; oc_sec_dump_sdi(0); } /* OBT initialization and shutdown */ int oc_obt_init(void) { OC_DBG("oc_obt:OBT init"); if (!oc_sec_is_operational(0)) { OC_DBG("oc_obt: performing self-onboarding"); oc_device_info_t *self = oc_core_get_device_info(0); oc_uuid_t *uuid = oc_core_get_device_id(0); oc_sec_acl_t *acl = oc_sec_get_acl(0); oc_sec_doxm_t *doxm = oc_sec_get_doxm(0); oc_sec_creds_t *creds = oc_sec_get_creds(0); oc_sec_pstat_t *ps = oc_sec_get_pstat(0); oc_sec_sdi_t *sdi = oc_sec_get_sdi(0); memcpy(acl->rowneruuid.id, uuid->id, 16); memcpy(doxm->devowneruuid.id, uuid->id, 16); memcpy(doxm->deviceuuid.id, uuid->id, 16); memcpy(doxm->rowneruuid.id, uuid->id, 16); doxm->owned = true; doxm->oxmsel = 0; memcpy(creds->rowneruuid.id, uuid->id, 16); memcpy(ps->rowneruuid.id, uuid->id, 16); ps->tm = ps->cm = 0; ps->isop = true; ps->s = OC_DOS_RFNOP; oc_sec_ace_clear_bootstrap_aces(0); oc_gen_uuid(&sdi->uuid); oc_new_string(&sdi->name, oc_string(self->name), oc_string_len(self->name)); sdi->priv = false; oc_sec_dump_pstat(0); oc_sec_dump_doxm(0); oc_sec_dump_cred(0); oc_sec_dump_acl(0); oc_sec_dump_ael(0); oc_sec_dump_sdi(0); #ifdef OC_PKI uint8_t public_key[OC_ECDSA_PUBKEY_SIZE]; size_t public_key_size = 0; if (oc_generate_ecdsa_keypair( public_key, OC_ECDSA_PUBKEY_SIZE, &public_key_size, private_key, OC_ECDSA_PRIVKEY_SIZE, &private_key_size) < 0) { OC_ERR("oc_obt: could not generate ECDSA keypair for local domain root " "certificate"); } else if (public_key_size != OC_ECDSA_PUBKEY_SIZE) { OC_ERR("oc_obt: invalid ECDSA keypair for local domain root certificate"); } else { root_cert_credid = oc_obt_generate_self_signed_root_cert( root_subject, public_key, OC_ECDSA_PUBKEY_SIZE, private_key, private_key_size); if (root_cert_credid > 0) { oc_obt_dump_state(); OC_DBG("oc_obt: successfully returning from obt_init()"); return 0; } } OC_DBG("oc_obt: returning from oc_obt() with errors"); return -1; #endif /* OC_PKI */ } else { #ifdef OC_PKI oc_obt_load_state(); #endif /* OC_PKI */ } OC_DBG("oc_obt: successfully returning from obt_init()"); return 0; } void oc_obt_shutdown(void) { oc_device_t *device = (oc_device_t *)oc_list_pop(oc_cache); while (device) { oc_free_server_endpoints(device->endpoint); oc_memb_free(&oc_devices_s, device); device = (oc_device_t *)oc_list_pop(oc_cache); } device = (oc_device_t *)oc_list_pop(oc_devices); while (device) { oc_free_server_endpoints(device->endpoint); oc_memb_free(&oc_devices_s, device); device = (oc_device_t *)oc_list_pop(oc_devices); } oc_discovery_cb_t *cb = (oc_discovery_cb_t *)oc_list_head(oc_discovery_cbs); while (cb) { free_discovery_cb(cb); cb = (oc_discovery_cb_t *)oc_list_head(oc_discovery_cbs); } } #endif /* OC_SECURITY */
415552.c
#include <stdint.h> #include <string.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "FreeRTOS_IO.h" #include "FreeRTOS_CLI.h" #define MAX_INPUT_LENGTH 50 #define MAX_OUTPUT_LENGTH 100 static const char * const pcWelcomeMessage = "FreeRTOS command server.\nType Help to view a list of registered commands.\n> "; void vCommandConsoleTask( void *pvParameters ) { Peripheral_Descriptor_t xConsole; char cRxedChar = 0; int8_t cInputIndex = 0; BaseType_t xMoreDataToFollow; /* The input and output buffers are declared static to keep them off the stack. */ static char pcOutputString[ MAX_OUTPUT_LENGTH ], pcInputString[ MAX_INPUT_LENGTH ]; /* This code assumes the peripheral being used as the console has already been opened and configured, and is passed into the task as the task parameter. Cast the task parameter to the correct type. */ xConsole = ( Peripheral_Descriptor_t ) pvParameters; /* Send a welcome message to the user knows they are connected. */ FreeRTOS_write( xConsole, pcWelcomeMessage, strlen( pcWelcomeMessage ) ); for( ;; ) { /* This implementation reads a single character at a time. Wait in the Blocked state until a character is received. */ FreeRTOS_read( xConsole, &cRxedChar, sizeof( cRxedChar ) ); if( cRxedChar == '\n' || cRxedChar == '\r' ) { /* A newline character was received, so the input command string is complete and can be processed. Transmit a line separator, just to make the output easier to read. */ FreeRTOS_write( xConsole, "\n", strlen( "\n" ) ); /* The command interpreter is called repeatedly until it returns pdFALSE. See the "Implementing a command" documentation for an exaplanation of why this is. */ do { /* Send the command string to the command interpreter. Any output generated by the command interpreter will be placed in the pcOutputString buffer. */ xMoreDataToFollow = FreeRTOS_CLIProcessCommand ( pcInputString, /* The command string.*/ pcOutputString, /* The output buffer. */ MAX_OUTPUT_LENGTH/* The size of the output buffer. */ ); /* Write the output generated by the command interpreter to the console. */ FreeRTOS_write( xConsole, pcOutputString, strlen( pcOutputString ) ); } while( xMoreDataToFollow != pdFALSE ); /* All the strings generated by the input command have been sent. Processing of the command is complete. Clear the input string ready to receive the next command. */ cInputIndex = 0; memset( pcInputString, 0x00, MAX_INPUT_LENGTH ); FreeRTOS_write( xConsole, "> ", strlen( "> " ) ); } else { /* The if() clause performs the processing after a newline character is received. This else clause performs the processing if any other character is received. */ if( cRxedChar == '\r' ) { /* Ignore carriage returns. */ } else if( cRxedChar == 127 ) /* Used to be `\b`. */ { /* Backspace was pressed. Erase the last character in the input buffer - if there are any. */ if( cInputIndex > 0 ) { cInputIndex--; pcInputString[ cInputIndex ] = '\0'; /* Hacky solution to backspaces */ FreeRTOS_write( xConsole, "\b", strlen( "\b" ) ); cRxedChar = 127; FreeRTOS_write( xConsole, &cRxedChar, strlen( &cRxedChar ) ); FreeRTOS_write( xConsole, "\b", strlen( "\b" ) ); } } else { /* A character was entered. It was not a new line, backspace or carriage return, so it is accepted as part of the input and placed into the input buffer. When a n is entered the complete string will be passed to the command interpreter. */ if( cInputIndex < MAX_INPUT_LENGTH ) { pcInputString[ cInputIndex ] = cRxedChar; cInputIndex++; FreeRTOS_write( xConsole, &cRxedChar, sizeof( cRxedChar ) ); } } } } }
693688.c
/* MDIO Bus interface * * Author: Andy Fleming * * Copyright (c) 2004 Freescale Semiconductor, Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/unistd.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/of_device.h> #include <linux/of_mdio.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/mii.h> #include <linux/ethtool.h> #include <linux/phy.h> #include <linux/io.h> #include <linux/uaccess.h> #include <asm/irq.h> /** * mdiobus_alloc_size - allocate a mii_bus structure * @size: extra amount of memory to allocate for private storage. * If non-zero, then bus->priv is points to that memory. * * Description: called by a bus driver to allocate an mii_bus * structure to fill in. */ struct mii_bus *mdiobus_alloc_size(size_t size) { struct mii_bus *bus; size_t aligned_size = ALIGN(sizeof(*bus), NETDEV_ALIGN); size_t alloc_size; /* If we alloc extra space, it should be aligned */ if (size) alloc_size = aligned_size + size; else alloc_size = sizeof(*bus); bus = kzalloc(alloc_size, GFP_KERNEL); if (bus) { bus->state = MDIOBUS_ALLOCATED; if (size) bus->priv = (void *)bus + aligned_size; } return bus; } EXPORT_SYMBOL(mdiobus_alloc_size); static void _devm_mdiobus_free(struct device *dev, void *res) { mdiobus_free(*(struct mii_bus **)res); } static int devm_mdiobus_match(struct device *dev, void *res, void *data) { struct mii_bus **r = res; if (WARN_ON(!r || !*r)) return 0; return *r == data; } /** * devm_mdiobus_alloc_size - Resource-managed mdiobus_alloc_size() * @dev: Device to allocate mii_bus for * @sizeof_priv: Space to allocate for private structure. * * Managed mdiobus_alloc_size. mii_bus allocated with this function is * automatically freed on driver detach. * * If an mii_bus allocated with this function needs to be freed separately, * devm_mdiobus_free() must be used. * * RETURNS: * Pointer to allocated mii_bus on success, NULL on failure. */ struct mii_bus *devm_mdiobus_alloc_size(struct device *dev, int sizeof_priv) { struct mii_bus **ptr, *bus; ptr = devres_alloc(_devm_mdiobus_free, sizeof(*ptr), GFP_KERNEL); if (!ptr) return NULL; /* use raw alloc_dr for kmalloc caller tracing */ bus = mdiobus_alloc_size(sizeof_priv); if (bus) { *ptr = bus; devres_add(dev, ptr); } else { devres_free(ptr); } return bus; } EXPORT_SYMBOL_GPL(devm_mdiobus_alloc_size); /** * devm_mdiobus_free - Resource-managed mdiobus_free() * @dev: Device this mii_bus belongs to * @bus: the mii_bus associated with the device * * Free mii_bus allocated with devm_mdiobus_alloc_size(). */ void devm_mdiobus_free(struct device *dev, struct mii_bus *bus) { int rc; rc = devres_release(dev, _devm_mdiobus_free, devm_mdiobus_match, bus); WARN_ON(rc); } EXPORT_SYMBOL_GPL(devm_mdiobus_free); /** * mdiobus_release - mii_bus device release callback * @d: the target struct device that contains the mii_bus * * Description: called when the last reference to an mii_bus is * dropped, to free the underlying memory. */ static void mdiobus_release(struct device *d) { struct mii_bus *bus = to_mii_bus(d); BUG_ON(bus->state != MDIOBUS_RELEASED && /* for compatibility with error handling in drivers */ bus->state != MDIOBUS_ALLOCATED); kfree(bus); } static struct class mdio_bus_class = { .name = "mdio_bus", .dev_release = mdiobus_release, }; #if IS_ENABLED(CONFIG_OF_MDIO) /* Helper function for of_mdio_find_bus */ static int of_mdio_bus_match(struct device *dev, const void *mdio_bus_np) { return dev->of_node == mdio_bus_np; } /** * of_mdio_find_bus - Given an mii_bus node, find the mii_bus. * @mdio_bus_np: Pointer to the mii_bus. * * Returns a pointer to the mii_bus, or NULL if none found. * * Because the association of a device_node and mii_bus is made via * of_mdiobus_register(), the mii_bus cannot be found before it is * registered with of_mdiobus_register(). * */ struct mii_bus *of_mdio_find_bus(struct device_node *mdio_bus_np) { struct device *d; if (!mdio_bus_np) return NULL; d = class_find_device(&mdio_bus_class, NULL, mdio_bus_np, of_mdio_bus_match); return d ? to_mii_bus(d) : NULL; } EXPORT_SYMBOL(of_mdio_find_bus); /* Walk the list of subnodes of a mdio bus and look for a node that matches the * phy's address with its 'reg' property. If found, set the of_node pointer for * the phy. This allows auto-probed pyh devices to be supplied with information * passed in via DT. */ static void of_mdiobus_link_phydev(struct mii_bus *mdio, struct phy_device *phydev) { struct device *dev = &phydev->dev; struct device_node *child; if (dev->of_node || !mdio->dev.of_node) return; for_each_available_child_of_node(mdio->dev.of_node, child) { int addr; int ret; ret = of_property_read_u32(child, "reg", &addr); if (ret < 0) { dev_err(dev, "%s has invalid PHY address\n", child->full_name); continue; } /* A PHY must have a reg property in the range [0-31] */ if (addr >= PHY_MAX_ADDR) { dev_err(dev, "%s PHY address %i is too large\n", child->full_name, addr); continue; } if (addr == phydev->addr) { dev->of_node = child; return; } } } #else /* !IS_ENABLED(CONFIG_OF_MDIO) */ static inline void of_mdiobus_link_phydev(struct mii_bus *mdio, struct phy_device *phydev) { } #endif /** * mdiobus_register - bring up all the PHYs on a given bus and attach them to bus * @bus: target mii_bus * * Description: Called by a bus driver to bring up all the PHYs * on a given bus, and attach them to the bus. * * Returns 0 on success or < 0 on error. */ int mdiobus_register(struct mii_bus *bus) { int i, err; if (NULL == bus || NULL == bus->name || NULL == bus->read || NULL == bus->write) return -EINVAL; BUG_ON(bus->state != MDIOBUS_ALLOCATED && bus->state != MDIOBUS_UNREGISTERED); bus->dev.parent = bus->parent; bus->dev.class = &mdio_bus_class; bus->dev.groups = NULL; dev_set_name(&bus->dev, "%s", bus->id); err = device_register(&bus->dev); if (err) { pr_err("mii_bus %s failed to register\n", bus->id); put_device(&bus->dev); return -EINVAL; } mutex_init(&bus->mdio_lock); if (bus->reset) bus->reset(bus); for (i = 0; i < PHY_MAX_ADDR; i++) { if ((bus->phy_mask & (1 << i)) == 0) { struct phy_device *phydev; phydev = mdiobus_scan(bus, i); if (IS_ERR(phydev)) { err = PTR_ERR(phydev); goto error; } } } bus->state = MDIOBUS_REGISTERED; pr_info("%s: probed\n", bus->name); return 0; error: while (--i >= 0) { if (bus->phy_map[i]) device_unregister(&bus->phy_map[i]->dev); } device_del(&bus->dev); return err; } EXPORT_SYMBOL(mdiobus_register); void mdiobus_unregister(struct mii_bus *bus) { int i; BUG_ON(bus->state != MDIOBUS_REGISTERED); bus->state = MDIOBUS_UNREGISTERED; device_del(&bus->dev); for (i = 0; i < PHY_MAX_ADDR; i++) { if (bus->phy_map[i]) device_unregister(&bus->phy_map[i]->dev); bus->phy_map[i] = NULL; } } EXPORT_SYMBOL(mdiobus_unregister); /** * mdiobus_free - free a struct mii_bus * @bus: mii_bus to free * * This function releases the reference to the underlying device * object in the mii_bus. If this is the last reference, the mii_bus * will be freed. */ void mdiobus_free(struct mii_bus *bus) { /* For compatibility with error handling in drivers. */ if (bus->state == MDIOBUS_ALLOCATED) { kfree(bus); return; } BUG_ON(bus->state != MDIOBUS_UNREGISTERED); bus->state = MDIOBUS_RELEASED; put_device(&bus->dev); } EXPORT_SYMBOL(mdiobus_free); struct phy_device *mdiobus_scan(struct mii_bus *bus, int addr) { struct phy_device *phydev; int err; phydev = get_phy_device(bus, addr, false); if (IS_ERR(phydev) || phydev == NULL) return phydev; /* * For DT, see if the auto-probed phy has a correspoding child * in the bus node, and set the of_node pointer in this case. */ of_mdiobus_link_phydev(bus, phydev); err = phy_device_register(phydev); if (err) { phy_device_free(phydev); return NULL; } return phydev; } EXPORT_SYMBOL(mdiobus_scan); /** * mdiobus_read - Convenience function for reading a given MII mgmt register * @bus: the mii_bus struct * @addr: the phy address * @regnum: register number to read * * NOTE: MUST NOT be called from interrupt context, * because the bus read/write functions may wait for an interrupt * to conclude the operation. */ int mdiobus_read(struct mii_bus *bus, int addr, u32 regnum) { int retval; BUG_ON(in_interrupt()); mutex_lock(&bus->mdio_lock); retval = bus->read(bus, addr, regnum); mutex_unlock(&bus->mdio_lock); return retval; } EXPORT_SYMBOL(mdiobus_read); /** * mdiobus_write - Convenience function for writing a given MII mgmt register * @bus: the mii_bus struct * @addr: the phy address * @regnum: register number to write * @val: value to write to @regnum * * NOTE: MUST NOT be called from interrupt context, * because the bus read/write functions may wait for an interrupt * to conclude the operation. */ int mdiobus_write(struct mii_bus *bus, int addr, u32 regnum, u16 val) { int err; BUG_ON(in_interrupt()); mutex_lock(&bus->mdio_lock); err = bus->write(bus, addr, regnum, val); mutex_unlock(&bus->mdio_lock); return err; } EXPORT_SYMBOL(mdiobus_write); /** * mdio_bus_match - determine if given PHY driver supports the given PHY device * @dev: target PHY device * @drv: given PHY driver * * Description: Given a PHY device, and a PHY driver, return 1 if * the driver supports the device. Otherwise, return 0. */ static int mdio_bus_match(struct device *dev, struct device_driver *drv) { struct phy_device *phydev = to_phy_device(dev); struct phy_driver *phydrv = to_phy_driver(drv); if (of_driver_match_device(dev, drv)) return 1; if (phydrv->match_phy_device) return phydrv->match_phy_device(phydev); return (phydrv->phy_id & phydrv->phy_id_mask) == (phydev->phy_id & phydrv->phy_id_mask); } #ifdef CONFIG_PM static bool mdio_bus_phy_may_suspend(struct phy_device *phydev) { struct device_driver *drv = phydev->dev.driver; struct phy_driver *phydrv = to_phy_driver(drv); struct net_device *netdev = phydev->attached_dev; if (!drv || !phydrv->suspend) return false; /* PHY not attached? May suspend. */ if (!netdev) return true; /* Don't suspend PHY if the attched netdev parent may wakeup. * The parent may point to a PCI device, as in tg3 driver. */ if (netdev->dev.parent && device_may_wakeup(netdev->dev.parent)) return false; /* Also don't suspend PHY if the netdev itself may wakeup. This * is the case for devices w/o underlaying pwr. mgmt. aware bus, * e.g. SoC devices. */ if (device_may_wakeup(&netdev->dev)) return false; return true; } static int mdio_bus_suspend(struct device *dev) { struct phy_driver *phydrv = to_phy_driver(dev->driver); struct phy_device *phydev = to_phy_device(dev); /* We must stop the state machine manually, otherwise it stops out of * control, possibly with the phydev->lock held. Upon resume, netdev * may call phy routines that try to grab the same lock, and that may * lead to a deadlock. */ if (phydev->attached_dev && phydev->adjust_link) phy_stop_machine(phydev); if (!mdio_bus_phy_may_suspend(phydev)) return 0; return phydrv->suspend(phydev); } static int mdio_bus_resume(struct device *dev) { struct phy_driver *phydrv = to_phy_driver(dev->driver); struct phy_device *phydev = to_phy_device(dev); int ret; if (!mdio_bus_phy_may_suspend(phydev)) goto no_resume; ret = phydrv->resume(phydev); if (ret < 0) return ret; no_resume: if (phydev->attached_dev && phydev->adjust_link) phy_start_machine(phydev); return 0; } static int mdio_bus_restore(struct device *dev) { struct phy_device *phydev = to_phy_device(dev); struct net_device *netdev = phydev->attached_dev; int ret; if (!netdev) return 0; ret = phy_init_hw(phydev); if (ret < 0) return ret; /* The PHY needs to renegotiate. */ phydev->link = 0; phydev->state = PHY_UP; phy_start_machine(phydev); return 0; } static const struct dev_pm_ops mdio_bus_pm_ops = { .suspend = mdio_bus_suspend, .resume = mdio_bus_resume, .freeze = mdio_bus_suspend, .thaw = mdio_bus_resume, .restore = mdio_bus_restore, }; #define MDIO_BUS_PM_OPS (&mdio_bus_pm_ops) #else #define MDIO_BUS_PM_OPS NULL #endif /* CONFIG_PM */ static ssize_t phy_id_show(struct device *dev, struct device_attribute *attr, char *buf) { struct phy_device *phydev = to_phy_device(dev); return sprintf(buf, "0x%.8lx\n", (unsigned long)phydev->phy_id); } static DEVICE_ATTR_RO(phy_id); static ssize_t phy_interface_show(struct device *dev, struct device_attribute *attr, char *buf) { struct phy_device *phydev = to_phy_device(dev); const char *mode = NULL; if (phy_is_internal(phydev)) mode = "internal"; else mode = phy_modes(phydev->interface); return sprintf(buf, "%s\n", mode); } static DEVICE_ATTR_RO(phy_interface); static ssize_t phy_has_fixups_show(struct device *dev, struct device_attribute *attr, char *buf) { struct phy_device *phydev = to_phy_device(dev); return sprintf(buf, "%d\n", phydev->has_fixups); } static DEVICE_ATTR_RO(phy_has_fixups); static struct attribute *mdio_dev_attrs[] = { &dev_attr_phy_id.attr, &dev_attr_phy_interface.attr, &dev_attr_phy_has_fixups.attr, NULL, }; ATTRIBUTE_GROUPS(mdio_dev); struct bus_type mdio_bus_type = { .name = "mdio_bus", .match = mdio_bus_match, .pm = MDIO_BUS_PM_OPS, .dev_groups = mdio_dev_groups, }; EXPORT_SYMBOL(mdio_bus_type); int __init mdio_bus_init(void) { int ret; ret = class_register(&mdio_bus_class); if (!ret) { ret = bus_register(&mdio_bus_type); if (ret) class_unregister(&mdio_bus_class); } return ret; } void mdio_bus_exit(void) { class_unregister(&mdio_bus_class); bus_unregister(&mdio_bus_type); }
432214.c
/* * Metafile functions * * Copyright David W. Metcalfe, 1994 * Copyright Niels de Carpentier, 1996 * Copyright Albrecht Kleine, 1996 * Copyright Huw Davies, 1996 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include "config.h" #include <string.h> #include <fcntl.h> #include "wine/winbase16.h" #include "wine/wingdi16.h" #include "wownt32.h" #include "winreg.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(metafile); #define METAFILE_MEMORY 1 #define METAFILE_DISK 2 #define MFHEADERSIZE (sizeof(METAHEADER)) #define MFVERSION 0x300 /****************************************************************** * MF_GetMetaHeader16 * * Returns ptr to METAHEADER associated with HMETAFILE16 * Should be followed by call to MF_ReleaseMetaHeader16 */ static METAHEADER *MF_GetMetaHeader16( HMETAFILE16 hmf ) { return GlobalLock16(hmf); } /****************************************************************** * MF_ReleaseMetaHeader16 * * Releases METAHEADER associated with HMETAFILE16 */ static BOOL16 MF_ReleaseMetaHeader16( HMETAFILE16 hmf ) { return GlobalUnlock16( hmf ); } /****************************************************************** * create_metafile16 * * Create a 16-bit metafile from a 32-bit one. The 32-bit one is deleted. */ static HMETAFILE16 create_metafile16( HMETAFILE hmf ) { UINT size; HMETAFILE16 hmf16; if (!hmf) return 0; size = GetMetaFileBitsEx( hmf, 0, NULL ); hmf16 = GlobalAlloc16( GMEM_MOVEABLE, size ); if (hmf16) { void *buffer = GlobalLock16( hmf16 ); GetMetaFileBitsEx( hmf, size, buffer ); GlobalUnlock16( hmf16 ); } DeleteMetaFile( hmf ); return hmf16; } /****************************************************************** * create_metafile32 * * Create a 32-bit metafile from a 16-bit one. */ static HMETAFILE create_metafile32( HMETAFILE16 hmf16 ) { METAHEADER *mh = MF_GetMetaHeader16( hmf16 ); if (!mh) return 0; return SetMetaFileBitsEx( mh->mtSize * 2, (BYTE *)mh ); } /********************************************************************** * CreateMetaFile (GDI.125) */ HDC16 WINAPI CreateMetaFile16( LPCSTR filename ) { return HDC_16( CreateMetaFileA( filename ) ); } /****************************************************************** * CloseMetaFile (GDI.126) */ HMETAFILE16 WINAPI CloseMetaFile16(HDC16 hdc) { return create_metafile16( CloseMetaFile( HDC_32(hdc) )); } /****************************************************************** * DeleteMetaFile (GDI.127) */ BOOL16 WINAPI DeleteMetaFile16( HMETAFILE16 hmf ) { return !GlobalFree16( hmf ); } /****************************************************************** * GetMetaFile (GDI.124) */ HMETAFILE16 WINAPI GetMetaFile16( LPCSTR lpFilename ) { return create_metafile16( GetMetaFileA( lpFilename )); } /****************************************************************** * CopyMetaFile (GDI.151) */ HMETAFILE16 WINAPI CopyMetaFile16( HMETAFILE16 hSrcMetaFile, LPCSTR lpFilename) { HMETAFILE hmf = create_metafile32( hSrcMetaFile ); HMETAFILE hmf2 = CopyMetaFileA( hmf, lpFilename ); DeleteMetaFile( hmf ); return create_metafile16( hmf2 ); } /****************************************************************** * IsValidMetaFile (GDI.410) * * Attempts to check if a given metafile is correctly formatted. * Currently, the only things verified are several properties of the * header. * * RETURNS * TRUE if hmf passes some tests for being a valid metafile, FALSE otherwise. * * BUGS * This is not exactly what windows does, see _Undocumented_Windows_ * for details. */ BOOL16 WINAPI IsValidMetaFile16(HMETAFILE16 hmf) { BOOL16 res=FALSE; METAHEADER *mh = MF_GetMetaHeader16(hmf); if (mh) { if (mh->mtType == METAFILE_MEMORY || mh->mtType == METAFILE_DISK) if (mh->mtHeaderSize == MFHEADERSIZE/sizeof(INT16)) if (mh->mtVersion == MFVERSION) res=TRUE; MF_ReleaseMetaHeader16(hmf); } TRACE("IsValidMetaFile %x => %d\n",hmf,res); return res; } /****************************************************************** * PlayMetaFile (GDI.123) * */ BOOL16 WINAPI PlayMetaFile16( HDC16 hdc, HMETAFILE16 hmf16 ) { HMETAFILE hmf = create_metafile32( hmf16 ); BOOL ret = PlayMetaFile( HDC_32(hdc), hmf ); DeleteMetaFile( hmf ); return ret; } /****************************************************************** * EnumMetaFile (GDI.175) * */ BOOL16 WINAPI EnumMetaFile16( HDC16 hdc16, HMETAFILE16 hmf, MFENUMPROC16 lpEnumFunc, LPARAM lpData ) { METAHEADER *mh = MF_GetMetaHeader16(hmf); METARECORD *mr; HANDLETABLE16 *ht; HDC hdc = HDC_32(hdc16); HGLOBAL16 hHT; SEGPTR spht; unsigned int offset = 0; WORD i, seg; HPEN hPen; HBRUSH hBrush; HFONT hFont; WORD args[8]; BOOL16 result = TRUE; TRACE("(%p, %04x, %p, %08lx)\n", hdc, hmf, lpEnumFunc, lpData); if(!mh) return FALSE; /* save the current pen, brush and font */ hPen = GetCurrentObject(hdc, OBJ_PEN); hBrush = GetCurrentObject(hdc, OBJ_BRUSH); hFont = GetCurrentObject(hdc, OBJ_FONT); /* create the handle table */ hHT = GlobalAlloc16(GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof(HANDLETABLE16) * mh->mtNoObjects); spht = WOWGlobalLock16(hHT); seg = hmf | 7; offset = mh->mtHeaderSize * 2; /* loop through metafile records */ args[7] = hdc16; args[6] = SELECTOROF(spht); args[5] = OFFSETOF(spht); args[4] = seg + (HIWORD(offset) << __AHSHIFT); args[3] = LOWORD(offset); args[2] = mh->mtNoObjects; args[1] = HIWORD(lpData); args[0] = LOWORD(lpData); while (offset < (mh->mtSize * 2)) { DWORD ret; mr = (METARECORD *)((char *)mh + offset); WOWCallback16Ex( (DWORD)lpEnumFunc, WCB16_PASCAL, sizeof(args), args, &ret ); if (!LOWORD(ret)) { result = FALSE; break; } offset += (mr->rdSize * 2); args[4] = seg + (HIWORD(offset) << __AHSHIFT); args[3] = LOWORD(offset); } SelectObject(hdc, hBrush); SelectObject(hdc, hPen); SelectObject(hdc, hFont); ht = GlobalLock16(hHT); /* free objects in handle table */ for(i = 0; i < mh->mtNoObjects; i++) if(*(ht->objectHandle + i) != 0) DeleteObject( (HGDIOBJ)(ULONG_PTR)(*(ht->objectHandle + i) )); /* free handle table */ GlobalFree16(hHT); MF_ReleaseMetaHeader16(hmf); return result; } /****************************************************************** * GetMetaFileBits (GDI.159) * * Trade in a metafile object handle for a handle to the metafile memory. * * PARAMS * hmf [I] metafile handle */ HGLOBAL16 WINAPI GetMetaFileBits16( HMETAFILE16 hmf ) { TRACE("hMem out: %04x\n", hmf); return hmf; } /****************************************************************** * SetMetaFileBits (GDI.160) * * Trade in a metafile memory handle for a handle to a metafile object. * The memory region should hold a proper metafile, otherwise * problems will occur when it is used. Validity of the memory is not * checked. The function is essentially just the identity function. * * PARAMS * hMem [I] handle to a memory region holding a metafile * * RETURNS * Handle to a metafile on success, NULL on failure.. */ HMETAFILE16 WINAPI SetMetaFileBits16( HGLOBAL16 hMem ) { TRACE("hmf out: %04x\n", hMem); return hMem; } /****************************************************************** * SetMetaFileBitsBetter (GDI.196) * * Trade in a metafile memory handle for a handle to a metafile object, * making a cursory check (using IsValidMetaFile()) that the memory * handle points to a valid metafile. * * RETURNS * Handle to a metafile on success, NULL on failure.. */ HMETAFILE16 WINAPI SetMetaFileBitsBetter16( HMETAFILE16 hMeta ) { if( IsValidMetaFile16( hMeta ) ) return GlobalReAlloc16( hMeta, 0, GMEM_SHARE | GMEM_NODISCARD | GMEM_MODIFY); return 0; }
672046.c
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2005 Blender Foundation. * All rights reserved. */ /** \file * \ingroup gpu */ #include "MEM_guardedalloc.h" #include "BLI_blenlib.h" #include "BLI_utildefines.h" #include "BLI_math_base.h" #include "GPU_batch.h" #include "GPU_draw.h" #include "GPU_extensions.h" #include "GPU_framebuffer.h" #include "GPU_matrix.h" #include "GPU_shader.h" #include "GPU_texture.h" #include "gpu_private.h" #include "gpu_context_private.h" typedef enum { GPU_FB_DEPTH_ATTACHMENT = 0, GPU_FB_DEPTH_STENCIL_ATTACHMENT, GPU_FB_COLOR_ATTACHMENT0, GPU_FB_COLOR_ATTACHMENT1, GPU_FB_COLOR_ATTACHMENT2, GPU_FB_COLOR_ATTACHMENT3, GPU_FB_COLOR_ATTACHMENT4, GPU_FB_COLOR_ATTACHMENT5, /* Number of maximum output slots. * We support 6 outputs for now (usually we wouldn't need more to preserve fill rate). */ /* Keep in mind that GL max is GL_MAX_DRAW_BUFFERS and is at least 8, corresponding to * the maximum number of COLOR attachments specified by glDrawBuffers. */ GPU_FB_MAX_ATTACHEMENT, } GPUAttachmentType; #define GPU_FB_MAX_COLOR_ATTACHMENT (GPU_FB_MAX_ATTACHEMENT - GPU_FB_COLOR_ATTACHMENT0) #define GPU_FB_DIRTY_DRAWBUFFER (1 << 15) #define GPU_FB_ATTACHEMENT_IS_DIRTY(flag, type) ((flag & (1 << type)) != 0) #define GPU_FB_ATTACHEMENT_SET_DIRTY(flag, type) (flag |= (1 << type)) struct GPUFrameBuffer { GPUContext *ctx; GLuint object; GPUAttachment attachments[GPU_FB_MAX_ATTACHEMENT]; uint16_t dirty_flag; int width, height; bool multisample; /* TODO Check that we always use the right context when binding * (FBOs are not shared across ogl contexts). */ // void *ctx; }; static GLenum convert_attachment_type_to_gl(GPUAttachmentType type) { static const GLenum table[] = { [GPU_FB_DEPTH_ATTACHMENT] = GL_DEPTH_ATTACHMENT, [GPU_FB_DEPTH_STENCIL_ATTACHMENT] = GL_DEPTH_STENCIL_ATTACHMENT, [GPU_FB_COLOR_ATTACHMENT0] = GL_COLOR_ATTACHMENT0, [GPU_FB_COLOR_ATTACHMENT1] = GL_COLOR_ATTACHMENT1, [GPU_FB_COLOR_ATTACHMENT2] = GL_COLOR_ATTACHMENT2, [GPU_FB_COLOR_ATTACHMENT3] = GL_COLOR_ATTACHMENT3, [GPU_FB_COLOR_ATTACHMENT4] = GL_COLOR_ATTACHMENT4, [GPU_FB_COLOR_ATTACHMENT5] = GL_COLOR_ATTACHMENT5, }; return table[type]; } static GPUAttachmentType attachment_type_from_tex(GPUTexture *tex, int slot) { switch (GPU_texture_format(tex)) { case GPU_DEPTH_COMPONENT32F: case GPU_DEPTH_COMPONENT24: case GPU_DEPTH_COMPONENT16: return GPU_FB_DEPTH_ATTACHMENT; case GPU_DEPTH24_STENCIL8: case GPU_DEPTH32F_STENCIL8: return GPU_FB_DEPTH_STENCIL_ATTACHMENT; default: return GPU_FB_COLOR_ATTACHMENT0 + slot; } } static GLenum convert_buffer_bits_to_gl(eGPUFrameBufferBits bits) { GLbitfield mask = 0; mask |= (bits & GPU_DEPTH_BIT) ? GL_DEPTH_BUFFER_BIT : 0; mask |= (bits & GPU_STENCIL_BIT) ? GL_STENCIL_BUFFER_BIT : 0; mask |= (bits & GPU_COLOR_BIT) ? GL_COLOR_BUFFER_BIT : 0; return mask; } static GPUTexture *framebuffer_get_depth_tex(GPUFrameBuffer *fb) { if (fb->attachments[GPU_FB_DEPTH_ATTACHMENT].tex) { return fb->attachments[GPU_FB_DEPTH_ATTACHMENT].tex; } else { return fb->attachments[GPU_FB_DEPTH_STENCIL_ATTACHMENT].tex; } } static GPUTexture *framebuffer_get_color_tex(GPUFrameBuffer *fb, int slot) { return fb->attachments[GPU_FB_COLOR_ATTACHMENT0 + slot].tex; } static void gpu_print_framebuffer_error(GLenum status, char err_out[256]) { const char *format = "GPUFrameBuffer: framebuffer status %s\n"; const char *err = "unknown"; #define FORMAT_STATUS(X) \ case GL_FRAMEBUFFER_##X: \ err = "GL_FRAMEBUFFER_" #X; \ break; switch (status) { /* success */ FORMAT_STATUS(COMPLETE); /* errors shared by OpenGL desktop & ES */ FORMAT_STATUS(INCOMPLETE_ATTACHMENT); FORMAT_STATUS(INCOMPLETE_MISSING_ATTACHMENT); FORMAT_STATUS(UNSUPPORTED); #if 0 /* for OpenGL ES only */ FORMAT_STATUS(INCOMPLETE_DIMENSIONS); #else /* for desktop GL only */ FORMAT_STATUS(INCOMPLETE_DRAW_BUFFER); FORMAT_STATUS(INCOMPLETE_READ_BUFFER); FORMAT_STATUS(INCOMPLETE_MULTISAMPLE); FORMAT_STATUS(UNDEFINED); #endif } #undef FORMAT_STATUS if (err_out) { BLI_snprintf(err_out, 256, format, err); } else { fprintf(stderr, format, err); } } void gpu_framebuffer_module_init(void) { } void gpu_framebuffer_module_exit(void) { } GPUFrameBuffer *GPU_framebuffer_active_get(void) { GPUContext *ctx = GPU_context_active_get(); if (ctx) { return gpu_context_active_framebuffer_get(ctx); } else { return 0; } } static void gpu_framebuffer_current_set(GPUFrameBuffer *fb) { GPUContext *ctx = GPU_context_active_get(); if (ctx) { gpu_context_active_framebuffer_set(ctx, fb); } } /* GPUFrameBuffer */ GPUFrameBuffer *GPU_framebuffer_create(void) { /* We generate the FB object later at first use in order to * create the framebuffer in the right opengl context. */ return MEM_callocN(sizeof(GPUFrameBuffer), "GPUFrameBuffer"); } static void gpu_framebuffer_init(GPUFrameBuffer *fb) { fb->object = GPU_fbo_alloc(); fb->ctx = GPU_context_active_get(); gpu_context_add_framebuffer(fb->ctx, fb); } void GPU_framebuffer_free(GPUFrameBuffer *fb) { for (GPUAttachmentType type = 0; type < GPU_FB_MAX_ATTACHEMENT; type++) { if (fb->attachments[type].tex != NULL) { GPU_framebuffer_texture_detach(fb, fb->attachments[type].tex); } } if (fb->object != 0) { /* This restores the framebuffer if it was bound */ GPU_fbo_free(fb->object, fb->ctx); gpu_context_remove_framebuffer(fb->ctx, fb); } if (GPU_framebuffer_active_get() == fb) { gpu_framebuffer_current_set(NULL); } MEM_freeN(fb); } /* ---------- Attach ----------- */ static void gpu_framebuffer_texture_attach_ex( GPUFrameBuffer *fb, GPUTexture *tex, int slot, int layer, int mip) { if (slot >= GPU_FB_MAX_COLOR_ATTACHMENT) { fprintf(stderr, "Attaching to index %d framebuffer slot unsupported. " "Use at most %d\n", slot, GPU_FB_MAX_COLOR_ATTACHMENT); return; } GPUAttachmentType type = attachment_type_from_tex(tex, slot); GPUAttachment *attachment = &fb->attachments[type]; if ((attachment->tex == tex) && (attachment->mip == mip) && (attachment->layer == layer)) { return; /* Exact same texture already bound here. */ } else if (attachment->tex != NULL) { GPU_framebuffer_texture_detach(fb, attachment->tex); } if (attachment->tex == NULL) { GPU_texture_attach_framebuffer(tex, fb, type); } attachment->tex = tex; attachment->mip = mip; attachment->layer = layer; GPU_FB_ATTACHEMENT_SET_DIRTY(fb->dirty_flag, type); } void GPU_framebuffer_texture_attach(GPUFrameBuffer *fb, GPUTexture *tex, int slot, int mip) { gpu_framebuffer_texture_attach_ex(fb, tex, slot, -1, mip); } void GPU_framebuffer_texture_layer_attach( GPUFrameBuffer *fb, GPUTexture *tex, int slot, int layer, int mip) { /* NOTE: We could support 1D ARRAY texture. */ BLI_assert(GPU_texture_target(tex) == GL_TEXTURE_2D_ARRAY); gpu_framebuffer_texture_attach_ex(fb, tex, slot, layer, mip); } void GPU_framebuffer_texture_cubeface_attach( GPUFrameBuffer *fb, GPUTexture *tex, int slot, int face, int mip) { BLI_assert(GPU_texture_cube(tex)); gpu_framebuffer_texture_attach_ex(fb, tex, slot, face, mip); } /* ---------- Detach ----------- */ void GPU_framebuffer_texture_detach_slot(GPUFrameBuffer *fb, GPUTexture *tex, int type) { GPUAttachment *attachment = &fb->attachments[type]; if (attachment->tex != tex) { fprintf(stderr, "Warning, attempting to detach Texture %p from framebuffer %p " "but texture is not attached.\n", tex, fb); return; } attachment->tex = NULL; GPU_FB_ATTACHEMENT_SET_DIRTY(fb->dirty_flag, type); } void GPU_framebuffer_texture_detach(GPUFrameBuffer *fb, GPUTexture *tex) { GPUAttachmentType type = GPU_texture_detach_framebuffer(tex, fb); GPU_framebuffer_texture_detach_slot(fb, tex, type); } /* ---------- Config (Attach & Detach) ----------- */ /** * First GPUAttachment in *config is always the depth/depth_stencil buffer. * Following GPUAttachments are color buffers. * Setting GPUAttachment.mip to -1 will leave the texture in this slot. * Setting GPUAttachment.tex to NULL will detach the texture in this slot. */ void GPU_framebuffer_config_array(GPUFrameBuffer *fb, const GPUAttachment *config, int config_len) { if (config[0].tex) { BLI_assert(GPU_texture_depth(config[0].tex)); gpu_framebuffer_texture_attach_ex(fb, config[0].tex, 0, config[0].layer, config[0].mip); } else if (config[0].mip == -1) { /* Leave texture attached */ } else if (fb->attachments[GPU_FB_DEPTH_ATTACHMENT].tex != NULL) { GPU_framebuffer_texture_detach(fb, fb->attachments[GPU_FB_DEPTH_ATTACHMENT].tex); } else if (fb->attachments[GPU_FB_DEPTH_STENCIL_ATTACHMENT].tex != NULL) { GPU_framebuffer_texture_detach(fb, fb->attachments[GPU_FB_DEPTH_STENCIL_ATTACHMENT].tex); } int slot = 0; for (int i = 1; i < config_len; i++, slot++) { if (config[i].tex != NULL) { BLI_assert(GPU_texture_depth(config[i].tex) == false); gpu_framebuffer_texture_attach_ex(fb, config[i].tex, slot, config[i].layer, config[i].mip); } else if (config[i].mip != -1) { GPUTexture *tex = framebuffer_get_color_tex(fb, slot); if (tex != NULL) { GPU_framebuffer_texture_detach(fb, tex); } } } } /* ---------- Bind / Restore ----------- */ static void gpu_framebuffer_attachment_attach(GPUAttachment *attach, GPUAttachmentType attach_type) { int tex_bind = GPU_texture_opengl_bindcode(attach->tex); GLenum gl_attachment = convert_attachment_type_to_gl(attach_type); if (attach->layer > -1) { if (GPU_texture_cube(attach->tex)) { glFramebufferTexture2D(GL_FRAMEBUFFER, gl_attachment, GL_TEXTURE_CUBE_MAP_POSITIVE_X + attach->layer, tex_bind, attach->mip); } else { glFramebufferTextureLayer( GL_FRAMEBUFFER, gl_attachment, tex_bind, attach->mip, attach->layer); } } else { glFramebufferTexture(GL_FRAMEBUFFER, gl_attachment, tex_bind, attach->mip); } } static void gpu_framebuffer_attachment_detach(GPUAttachment *UNUSED(attachment), GPUAttachmentType attach_type) { GLenum gl_attachment = convert_attachment_type_to_gl(attach_type); glFramebufferTexture(GL_FRAMEBUFFER, gl_attachment, 0, 0); } static void gpu_framebuffer_update_attachments(GPUFrameBuffer *fb) { GLenum gl_attachments[GPU_FB_MAX_COLOR_ATTACHMENT]; int numslots = 0; BLI_assert(GPU_framebuffer_active_get() == fb); /* Update attachments */ for (GPUAttachmentType type = 0; type < GPU_FB_MAX_ATTACHEMENT; type++) { if (type >= GPU_FB_COLOR_ATTACHMENT0) { if (fb->attachments[type].tex) { gl_attachments[numslots] = convert_attachment_type_to_gl(type); } else { gl_attachments[numslots] = GL_NONE; } numslots++; } if (GPU_FB_ATTACHEMENT_IS_DIRTY(fb->dirty_flag, type) == false) { continue; } else if (fb->attachments[type].tex != NULL) { gpu_framebuffer_attachment_attach(&fb->attachments[type], type); fb->multisample = (GPU_texture_samples(fb->attachments[type].tex) > 0); fb->width = GPU_texture_width(fb->attachments[type].tex); fb->height = GPU_texture_height(fb->attachments[type].tex); } else { gpu_framebuffer_attachment_detach(&fb->attachments[type], type); } } fb->dirty_flag = 0; /* Update draw buffers (color targets) * This state is saved in the FBO */ if (numslots) { glDrawBuffers(numslots, gl_attachments); } else { glDrawBuffer(GL_NONE); } } /** * Hack to solve the problem of some bugged AMD GPUs (see `GPU_unused_fb_slot_workaround`). * If there is an empty color slot between the color slots, * all textures after this slot are apparently skipped/discarded. */ static void gpu_framebuffer_update_attachments_and_fill_empty_slots(GPUFrameBuffer *fb) { GLenum gl_attachments[GPU_FB_MAX_COLOR_ATTACHMENT]; int dummy_tex = 0; BLI_assert(GPU_framebuffer_active_get() == fb); /* Update attachments */ for (GPUAttachmentType type = GPU_FB_MAX_ATTACHEMENT; type--;) { GPUTexture *tex = fb->attachments[type].tex; if (type >= GPU_FB_COLOR_ATTACHMENT0) { int slot = type - GPU_FB_COLOR_ATTACHMENT0; if (tex != NULL || (dummy_tex != 0)) { gl_attachments[slot] = convert_attachment_type_to_gl(type); if (dummy_tex == 0) { dummy_tex = GPU_texture_opengl_bindcode(tex); } } else { gl_attachments[slot] = GL_NONE; } } else { dummy_tex = 0; } if ((dummy_tex != 0) && tex == NULL) { /* Fill empty slot */ glFramebufferTexture(GL_FRAMEBUFFER, convert_attachment_type_to_gl(type), dummy_tex, 0); } else if (GPU_FB_ATTACHEMENT_IS_DIRTY(fb->dirty_flag, type)) { if (tex != NULL) { gpu_framebuffer_attachment_attach(&fb->attachments[type], type); fb->multisample = (GPU_texture_samples(tex) > 0); fb->width = GPU_texture_width(tex); fb->height = GPU_texture_height(tex); } else { gpu_framebuffer_attachment_detach(&fb->attachments[type], type); } } } fb->dirty_flag = 0; /* Update draw buffers (color targets) * This state is saved in the FBO */ glDrawBuffers(GPU_FB_MAX_COLOR_ATTACHMENT, gl_attachments); } #define FRAMEBUFFER_STACK_DEPTH 16 static struct { GPUFrameBuffer *framebuffers[FRAMEBUFFER_STACK_DEPTH]; uint top; } FrameBufferStack = {{0}}; static void gpuPushFrameBuffer(GPUFrameBuffer *fbo) { BLI_assert(FrameBufferStack.top < FRAMEBUFFER_STACK_DEPTH); FrameBufferStack.framebuffers[FrameBufferStack.top] = fbo; FrameBufferStack.top++; } static GPUFrameBuffer *gpuPopFrameBuffer(void) { BLI_assert(FrameBufferStack.top > 0); FrameBufferStack.top--; return FrameBufferStack.framebuffers[FrameBufferStack.top]; } #undef FRAMEBUFFER_STACK_DEPTH void GPU_framebuffer_bind(GPUFrameBuffer *fb) { if (fb->object == 0) { gpu_framebuffer_init(fb); } if (GPU_framebuffer_active_get() != fb) { glBindFramebuffer(GL_FRAMEBUFFER, fb->object); } gpu_framebuffer_current_set(fb); if (fb->dirty_flag != 0) { if (GPU_unused_fb_slot_workaround()) { /* XXX: Please AMD, fix this. */ gpu_framebuffer_update_attachments_and_fill_empty_slots(fb); } else { gpu_framebuffer_update_attachments(fb); } } /* TODO manually check for errors? */ #if 0 char err_out[256]; if (!GPU_framebuffer_check_valid(fb, err_out)) { printf("Invalid %s\n", err_out); } #endif if (fb->multisample) { glEnable(GL_MULTISAMPLE); } glViewport(0, 0, fb->width, fb->height); } void GPU_framebuffer_restore(void) { if (GPU_framebuffer_active_get() != NULL) { glBindFramebuffer(GL_FRAMEBUFFER, GPU_framebuffer_default()); gpu_framebuffer_current_set(NULL); } } bool GPU_framebuffer_bound(GPUFrameBuffer *fb) { return (fb == GPU_framebuffer_active_get()) && (fb->object != 0); } bool GPU_framebuffer_check_valid(GPUFrameBuffer *fb, char err_out[256]) { if (!GPU_framebuffer_bound(fb)) { GPU_framebuffer_bind(fb); } GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { GPU_framebuffer_restore(); gpu_print_framebuffer_error(status, err_out); return false; } return true; } /* ---------- Framebuffer Operations ----------- */ #define CHECK_FRAMEBUFFER_IS_BOUND(_fb) \ BLI_assert(GPU_framebuffer_bound(_fb)); \ UNUSED_VARS_NDEBUG(_fb); \ ((void)0) /* Needs to be done after binding. */ void GPU_framebuffer_viewport_set(GPUFrameBuffer *fb, int x, int y, int w, int h) { CHECK_FRAMEBUFFER_IS_BOUND(fb); glViewport(x, y, w, h); } void GPU_framebuffer_clear(GPUFrameBuffer *fb, eGPUFrameBufferBits buffers, const float clear_col[4], float clear_depth, uint clear_stencil) { CHECK_FRAMEBUFFER_IS_BOUND(fb); if (buffers & GPU_COLOR_BIT) { glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClearColor(clear_col[0], clear_col[1], clear_col[2], clear_col[3]); } if (buffers & GPU_DEPTH_BIT) { glDepthMask(GL_TRUE); glClearDepth(clear_depth); } if (buffers & GPU_STENCIL_BIT) { glStencilMask(0xFF); glClearStencil(clear_stencil); } GLbitfield mask = convert_buffer_bits_to_gl(buffers); glClear(mask); } void GPU_framebuffer_read_depth(GPUFrameBuffer *fb, int x, int y, int w, int h, float *data) { CHECK_FRAMEBUFFER_IS_BOUND(fb); GLenum type = GL_DEPTH_COMPONENT; glReadBuffer(GL_COLOR_ATTACHMENT0); /* This is OK! */ glReadPixels(x, y, w, h, type, GL_FLOAT, data); } void GPU_framebuffer_read_color( GPUFrameBuffer *fb, int x, int y, int w, int h, int channels, int slot, float *data) { CHECK_FRAMEBUFFER_IS_BOUND(fb); GLenum type; switch (channels) { case 1: type = GL_RED; break; case 2: type = GL_RG; break; case 3: type = GL_RGB; break; case 4: type = GL_RGBA; break; default: BLI_assert(false && "wrong number of read channels"); return; } glReadBuffer(GL_COLOR_ATTACHMENT0 + slot); glReadPixels(x, y, w, h, type, GL_FLOAT, data); } /* read_slot and write_slot are only used for color buffers. */ void GPU_framebuffer_blit(GPUFrameBuffer *fb_read, int read_slot, GPUFrameBuffer *fb_write, int write_slot, eGPUFrameBufferBits blit_buffers) { BLI_assert(blit_buffers != 0); GPUFrameBuffer *prev_fb = GPU_framebuffer_active_get(); /* Framebuffers must be up to date. This simplify this function. */ if (fb_read->dirty_flag != 0 || fb_read->object == 0) { GPU_framebuffer_bind(fb_read); } if (fb_write->dirty_flag != 0 || fb_write->object == 0) { GPU_framebuffer_bind(fb_write); } const bool do_color = (blit_buffers & GPU_COLOR_BIT); const bool do_depth = (blit_buffers & GPU_DEPTH_BIT); const bool do_stencil = (blit_buffers & GPU_STENCIL_BIT); GPUTexture *read_tex = ((do_depth || do_stencil) ? framebuffer_get_depth_tex(fb_read) : framebuffer_get_color_tex(fb_read, read_slot)); GPUTexture *write_tex = ((do_depth || do_stencil) ? framebuffer_get_depth_tex(fb_write) : framebuffer_get_color_tex(fb_write, read_slot)); if (do_depth) { BLI_assert(GPU_texture_depth(read_tex) && GPU_texture_depth(write_tex)); BLI_assert(GPU_texture_format(read_tex) == GPU_texture_format(write_tex)); } if (do_stencil) { BLI_assert(GPU_texture_stencil(read_tex) && GPU_texture_stencil(write_tex)); BLI_assert(GPU_texture_format(read_tex) == GPU_texture_format(write_tex)); } if (GPU_texture_samples(write_tex) != 0 || GPU_texture_samples(read_tex) != 0) { /* Can only blit multisample textures to another texture of the same size. */ BLI_assert((fb_read->width == fb_write->width) && (fb_read->height == fb_write->height)); } glBindFramebuffer(GL_READ_FRAMEBUFFER, fb_read->object); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb_write->object); if (do_color) { glReadBuffer(GL_COLOR_ATTACHMENT0 + read_slot); glDrawBuffer(GL_COLOR_ATTACHMENT0 + write_slot); /* XXX we messed with the glDrawBuffer, this will reset the * glDrawBuffers the next time we bind fb_write. */ fb_write->dirty_flag = GPU_FB_DIRTY_DRAWBUFFER; } GLbitfield mask = convert_buffer_bits_to_gl(blit_buffers); glBlitFramebuffer(0, 0, fb_read->width, fb_read->height, 0, 0, fb_write->width, fb_write->height, mask, GL_NEAREST); /* Restore previous framebuffer */ if (fb_write == prev_fb) { GPU_framebuffer_bind(fb_write); /* To update drawbuffers */ } else if (prev_fb) { glBindFramebuffer(GL_FRAMEBUFFER, prev_fb->object); gpu_framebuffer_current_set(prev_fb); } else { glBindFramebuffer(GL_FRAMEBUFFER, GPU_framebuffer_default()); gpu_framebuffer_current_set(NULL); } } /** * Use this if you need to custom down-sample your texture and use the previous mip level as input. * This function only takes care of the correct texture handling. * It execute the callback for each texture level. */ void GPU_framebuffer_recursive_downsample(GPUFrameBuffer *fb, int max_lvl, void (*callback)(void *userData, int level), void *userData) { /* Framebuffer must be up to date and bound. This simplify this function. */ if (GPU_framebuffer_active_get() != fb || fb->dirty_flag != 0 || fb->object == 0) { GPU_framebuffer_bind(fb); } /* HACK: We make the framebuffer appear not bound in order to * not trigger any error in GPU_texture_bind(). */ GPUFrameBuffer *prev_fb = GPU_framebuffer_active_get(); gpu_framebuffer_current_set(NULL); int levels = floor(log2(max_ii(fb->width, fb->height))); max_lvl = min_ii(max_lvl, levels); int i; int current_dim[2] = {fb->width, fb->height}; for (i = 1; i < max_lvl + 1; i++) { /* calculate next viewport size */ current_dim[0] = max_ii(current_dim[0] / 2, 1); current_dim[1] = max_ii(current_dim[1] / 2, 1); for (GPUAttachmentType type = 0; type < GPU_FB_MAX_ATTACHEMENT; type++) { if (fb->attachments[type].tex != NULL) { /* Some Intel HDXXX have issue with rendering to a mipmap that is below * the texture GL_TEXTURE_MAX_LEVEL. So even if it not correct, in this case * we allow GL_TEXTURE_MAX_LEVEL to be one level lower. In practice it does work! */ int next_lvl = (GPU_mip_render_workaround()) ? i : i - 1; /* bind next level for rendering but first restrict fetches only to previous level */ GPUTexture *tex = fb->attachments[type].tex; GPU_texture_bind(tex, 0); glTexParameteri(GPU_texture_target(tex), GL_TEXTURE_BASE_LEVEL, i - 1); glTexParameteri(GPU_texture_target(tex), GL_TEXTURE_MAX_LEVEL, next_lvl); GPU_texture_unbind(tex); /* copy attachment and replace miplevel. */ GPUAttachment attachment = fb->attachments[type]; attachment.mip = i; gpu_framebuffer_attachment_attach(&attachment, type); } } BLI_assert(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)); glViewport(0, 0, current_dim[0], current_dim[1]); callback(userData, i); if (current_dim[0] == 1 && current_dim[1] == 1) { break; } } for (GPUAttachmentType type = 0; type < GPU_FB_MAX_ATTACHEMENT; type++) { if (fb->attachments[type].tex != NULL) { /* reset mipmap level range */ GPUTexture *tex = fb->attachments[type].tex; GPU_texture_bind(tex, 0); glTexParameteri(GPU_texture_target(tex), GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GPU_texture_target(tex), GL_TEXTURE_MAX_LEVEL, i - 1); GPU_texture_unbind(tex); /* Reattach original level */ /* NOTE: This is not necessary but this makes the FBO config * remain in sync with the GPUFrameBuffer config. */ gpu_framebuffer_attachment_attach(&fb->attachments[type], type); } } gpu_framebuffer_current_set(prev_fb); } /* GPUOffScreen */ #define MAX_CTX_FB_LEN 3 struct GPUOffScreen { struct { GPUContext *ctx; GPUFrameBuffer *fb; } framebuffers[MAX_CTX_FB_LEN]; GPUTexture *color; GPUTexture *depth; }; /* Returns the correct framebuffer for the current context. */ static GPUFrameBuffer *gpu_offscreen_fb_get(GPUOffScreen *ofs) { GPUContext *ctx = GPU_context_active_get(); BLI_assert(ctx); for (int i = 0; i < MAX_CTX_FB_LEN; i++) { if (ofs->framebuffers[i].fb == NULL) { ofs->framebuffers[i].ctx = ctx; GPU_framebuffer_ensure_config( &ofs->framebuffers[i].fb, {GPU_ATTACHMENT_TEXTURE(ofs->depth), GPU_ATTACHMENT_TEXTURE(ofs->color)}); } if (ofs->framebuffers[i].ctx == ctx) { return ofs->framebuffers[i].fb; } } /* List is full, this should never happen or * it might just slow things down if it happens * regularly. In this case we just empty the list * and start over. This is most likely never going * to happen under normal usage. */ BLI_assert(0); printf( "Warning: GPUOffscreen used in more than 3 GPUContext. " "This may create performance drop.\n"); for (int i = 0; i < MAX_CTX_FB_LEN; i++) { GPU_framebuffer_free(ofs->framebuffers[i].fb); ofs->framebuffers[i].fb = NULL; } return gpu_offscreen_fb_get(ofs); } GPUOffScreen *GPU_offscreen_create( int width, int height, int samples, bool depth, bool high_bitdepth, char err_out[256]) { GPUOffScreen *ofs; ofs = MEM_callocN(sizeof(GPUOffScreen), "GPUOffScreen"); /* Sometimes areas can have 0 height or width and this will * create a 1D texture which we don't want. */ height = max_ii(1, height); width = max_ii(1, width); ofs->color = GPU_texture_create_2d_multisample( width, height, (high_bitdepth) ? GPU_RGBA16F : GPU_RGBA8, NULL, samples, err_out); if (depth) { ofs->depth = GPU_texture_create_2d_multisample( width, height, GPU_DEPTH24_STENCIL8, NULL, samples, err_out); } if ((depth && !ofs->depth) || !ofs->color) { GPU_offscreen_free(ofs); return NULL; } gpuPushAttr(GPU_VIEWPORT_BIT); GPUFrameBuffer *fb = gpu_offscreen_fb_get(ofs); /* check validity at the very end! */ if (!GPU_framebuffer_check_valid(fb, err_out)) { GPU_offscreen_free(ofs); gpuPopAttr(); return NULL; } GPU_framebuffer_restore(); gpuPopAttr(); return ofs; } void GPU_offscreen_free(GPUOffScreen *ofs) { for (int i = 0; i < MAX_CTX_FB_LEN; i++) { if (ofs->framebuffers[i].fb) { GPU_framebuffer_free(ofs->framebuffers[i].fb); } } if (ofs->color) { GPU_texture_free(ofs->color); } if (ofs->depth) { GPU_texture_free(ofs->depth); } MEM_freeN(ofs); } void GPU_offscreen_bind(GPUOffScreen *ofs, bool save) { if (save) { gpuPushAttr(GPU_SCISSOR_BIT | GPU_VIEWPORT_BIT); GPUFrameBuffer *fb = GPU_framebuffer_active_get(); gpuPushFrameBuffer(fb); } glDisable(GL_SCISSOR_TEST); GPUFrameBuffer *ofs_fb = gpu_offscreen_fb_get(ofs); GPU_framebuffer_bind(ofs_fb); } void GPU_offscreen_unbind(GPUOffScreen *UNUSED(ofs), bool restore) { GPUFrameBuffer *fb = NULL; if (restore) { gpuPopAttr(); fb = gpuPopFrameBuffer(); } if (fb) { GPU_framebuffer_bind(fb); } else { GPU_framebuffer_restore(); } } void GPU_offscreen_draw_to_screen(GPUOffScreen *ofs, int x, int y) { const int w = GPU_texture_width(ofs->color); const int h = GPU_texture_height(ofs->color); GPUFrameBuffer *ofs_fb = gpu_offscreen_fb_get(ofs); glBindFramebuffer(GL_READ_FRAMEBUFFER, ofs_fb->object); GLenum status = glCheckFramebufferStatus(GL_READ_FRAMEBUFFER); if (status == GL_FRAMEBUFFER_COMPLETE) { glBlitFramebuffer(0, 0, w, h, x, y, x + w, y + h, GL_COLOR_BUFFER_BIT, GL_NEAREST); } else { gpu_print_framebuffer_error(status, NULL); } glBindFramebuffer(GL_READ_FRAMEBUFFER, GPU_framebuffer_default()); } void GPU_offscreen_read_pixels(GPUOffScreen *ofs, int type, void *pixels) { const int w = GPU_texture_width(ofs->color); const int h = GPU_texture_height(ofs->color); BLI_assert(type == GL_UNSIGNED_BYTE || type == GL_FLOAT); if (GPU_texture_target(ofs->color) == GL_TEXTURE_2D_MULTISAMPLE) { /* For a multi-sample texture, * we need to create an intermediate buffer to blit to, * before its copied using 'glReadPixels' */ GLuint fbo_blit = 0; GLuint tex_blit = 0; /* create texture for new 'fbo_blit' */ glGenTextures(1, &tex_blit); glBindTexture(GL_TEXTURE_2D, tex_blit); glTexImage2D( GL_TEXTURE_2D, 0, (type == GL_FLOAT) ? GL_RGBA16F : GL_RGBA8, w, h, 0, GL_RGBA, type, 0); /* write into new single-sample buffer */ glGenFramebuffers(1, &fbo_blit); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_blit); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_blit, 0); GLenum status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { goto finally; } /* perform the copy */ glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST); /* read the results */ glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo_blit); glReadPixels(0, 0, w, h, GL_RGBA, type, pixels); /* restore the original frame-bufer */ GPUFrameBuffer *ofs_fb = gpu_offscreen_fb_get(ofs); glBindFramebuffer(GL_FRAMEBUFFER, ofs_fb->object); finally: /* cleanup */ glDeleteTextures(1, &tex_blit); glDeleteFramebuffers(1, &fbo_blit); } else { glReadPixels(0, 0, w, h, GL_RGBA, type, pixels); } } int GPU_offscreen_width(const GPUOffScreen *ofs) { return GPU_texture_width(ofs->color); } int GPU_offscreen_height(const GPUOffScreen *ofs) { return GPU_texture_height(ofs->color); } GPUTexture *GPU_offscreen_color_texture(const GPUOffScreen *ofs) { return ofs->color; } /* only to be used by viewport code! */ void GPU_offscreen_viewport_data_get(GPUOffScreen *ofs, GPUFrameBuffer **r_fb, GPUTexture **r_color, GPUTexture **r_depth) { *r_fb = gpu_offscreen_fb_get(ofs); *r_color = ofs->color; *r_depth = ofs->depth; } void GPU_clear_color(float red, float green, float blue, float alpha) { glClearColor(red, green, blue, alpha); } void GPU_clear_depth(float depth) { glClearDepth(depth); } void GPU_clear(eGPUFrameBufferBits flags) { glClear(convert_buffer_bits_to_gl(flags)); }
655700.c
#include <stdio.h> #include <stdlib.h> #include "items.h" #include "util.h" Item *newItem(ItemList *list) { Item *item; if (list->len == list->cap) { list->cap += BUFSIZ; if (!(list->item = realloc(list->item, sizeof(Item) * list->cap))) { return NULL; } } item = list->item + list->len; (list->len)++; item->text = NULL; item->sel = FALSE; return item; } void ItemListFilter(ItemList *dest, ItemList src, CFStringRef substr) { bool alwaysAdd = CFStringGetLength(substr) == 0; for (size_t i = 0; i < src.len; i++) { Item *cur = src.item + i; if (!alwaysAdd) { CFRange r = CFStringFind(cur->text, substr, kCFCompareCaseInsensitive | kCFCompareDiacriticInsensitive); if (r.location == kCFNotFound || r.length == 0) { continue; } } newItem(dest)->text = cur->text; } } void ItemListReset(ItemList *l) { l->len = 0; } void ItemListFrom(ItemList *dest, ItemList src) { dest->cap = src.len; dest->len = src.len; dest->item = ecalloc(sizeof(Item), src.len); memcpy(dest->item, src.item, sizeof(Item) * src.len); } Item *ItemListSetSelected(ItemList *l, Item *cur, Item *next) { if (cur != NULL && l->item <= cur && cur < l->item + l->len) { cur->sel = FALSE; } if (next != NULL && l->item <= next && next < l->item + l->len) { next->sel = TRUE; } return next; } ItemList ReadStdin(void) { ItemList list; list.item = NULL; list.len = 0; list.cap = 0; char *buf = NULL; size_t cap = 0; size_t len; while ((len = getline(&buf, &cap, stdin)) != (size_t)(-1)) { if (len && buf[len - 1] == '\n') buf[len - 1] = '\0'; Item *item = newItem(&list); if (item == NULL) { goto end; } item->sel = false; item->text = CFStringCreateWithCString(NULL, buf, kCFStringEncodingUTF8); } end: free(buf); return list; }
43207.c
/******************************************************************************* * Project: * "Audioprocessor" * * Version / Date: * 2.3 / Jan 2018 * * Authors: * Markus Hufschmid * * File Name: * controls.c * * Description: * Updates and processes controls (buttons, encoders) *******************************************************************************/ #include <xc.h> #include "controls.h" #include "GUI.h" #include "DOGS.h" #include "globals.h" #include "GenericTypeDefs.h" #include "menu.h" #include "hardware.h" #include "filterdesign.h" /* states */ #define ARMED 0 #define PRESSED 1 #define RELEASED 2 enum buttonStates { BTN_STATE_ARMED, BTN_STATE_DEBOUNCE, BTN_STATE_PRESSED, BTN_STATE_RELEASED }; /* time constants for debouncing */ #define DEBOUNCE_5MS 50 #define DEBOUNCE_10MS 100 #define WAIT_250MS 2500 CONTROLSTATUS updateControls(void) { static unsigned char REncState = 0, LEncState = 0; //update states of buttons buttonStateMachine(&topButton, TOPBUTTON); buttonStateMachine(&middleButton, MIDDLEBUTTON); buttonStateMachine(&bottomButton, BOTTOMBUTTON); buttonStateMachine(&leftEncoderButton, LEFTENCODERBUTTON); buttonStateMachine(&rightEncoderButton, RIGHTENCODERBUTTON); switch (REncState) { case ARMED: if (RIGHTENCODER_A == 0) { REncState = PRESSED; if (RIGHTENCODER_B == 1) { REncValue += 1; } else { REncValue -= 1; } controls.flags.REnc = 1; } break; case PRESSED: if (RIGHTENCODER_A == 1) { REncState = RELEASED; } REncTimer = DEBOUNCE_5MS; break; case RELEASED: if (RIGHTENCODER_A == 0) { REncState = PRESSED; } else if (REncTimer == 0) { REncState = ARMED; } break; } switch (LEncState) { case ARMED: if (LEFTENCODER_A == 0) { LEncState = PRESSED; if (LEFTENCODER_B == 1) { LEncValue += 1; } else { LEncValue -= 1; } controls.flags.LEnc = 1; } break; case PRESSED: if (LEFTENCODER_A == 1) { LEncState = RELEASED; } LEncTimer = DEBOUNCE_5MS; break; case RELEASED: if (LEFTENCODER_A == 0) { LEncState = PRESSED; } else if (LEncTimer == 0) { LEncState = ARMED; } break; } return controls; } void processControls(void) { if (topButton.counter) { filterOn = 1 - filterOn; topButton.counter = 0; } if (middleButton.counter) { autonotchOn = 1 - autonotchOn; middleButton.counter = 0; } if (bottomButton.counter) { clearPartScreen(1, 0, 4, 66); dispFFT = 1 - dispFFT; bottomButton.counter = 0; } if (rightEncoderButton.counter) { rightEncoderButton.counter = 0; filter_type = 1 - filter_type; if (filter_type == BPFILTER) { build_filter(BANDPASS); } else { build_filter(LOWPASS); build_filter(HIGHPASS); } } if (leftEncoderButton.counter > 4) { //if left encoder button is pressed longer than 4*250ms menu(); build_menu(); build_GUI(); update_GUI(); leftEncoderButton.counter = 0; } if (controls.flags.REnc || controls.flags.LEnc) { controls.flags.REnc = 0; controls.flags.LEnc = 0; if (filter_type == BPFILTER) { iBPFilter += LEncValue; if (iBPFilter < 0) { iBPFilter = 0; } if (iBPFilter > N_BP_FILTERS - 1) { iBPFilter = N_BP_FILTERS - 1; } LEncValue = 0; fc += FC_STEP*REncValue; if (fc < FC_MIN) { fc = FC_MIN; } if (fc > FC_MAX) { fc = FC_MAX; } REncValue = 0; build_filter(BANDPASS); } else { iHPFilter += LEncValue; if (iHPFilter < 0) { iHPFilter = 0; } if (iHPFilter > N_HP_FILTERS - 1) { iHPFilter = N_HP_FILTERS - 1; } LEncValue = 0; iLPFilter += REncValue; if (iLPFilter < 0) { iLPFilter = 0; } if (iLPFilter > N_LP_FILTERS - 1) { iLPFilter = N_LP_FILTERS - 1; } REncValue = 0; build_filter(LOWPASS); build_filter(HIGHPASS); } } } void buttonStateMachine(buttonStruct* button, int port) { // update state of button, increment counter if necessary switch (button->state) { case BTN_STATE_ARMED: if (port == 0) { button->state = BTN_STATE_DEBOUNCE; button->counter++; controls.flags.anyButton = 1; button->timer = DEBOUNCE_10MS; } break; case BTN_STATE_DEBOUNCE: if (button->timer == 0) { button->state = BTN_STATE_PRESSED; button->timer = WAIT_250MS; } break; case BTN_STATE_PRESSED: if (port == 1) { button->state = BTN_STATE_RELEASED; button->timer = DEBOUNCE_10MS; } else { if (button->timer == 0) { button->timer = WAIT_250MS; button->counter++; } } break; case BTN_STATE_RELEASED: if (button->timer == 0) { button->state = BTN_STATE_ARMED; } break; } }
534277.c
/* Copyright (c) 2019, Ameer Haj Ali (UC Berkeley), and Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "header.h" short sa[8192]; short sb[8192]; int ia[8192] ALIGNED16; int ib[8192] ALIGNED16; __attribute__((noinline)) void example10b(short *__restrict__ sa, short *__restrict__ sb, int* __restrict__ ia, int* __restrict__ ib) { int i; for (i = 0; i < 8192; i+=2) { ia[i] = (int) sa[i]; ib[i] = (int) sb[i]; } } int main(int argc,char* argv[]){ init_memory(&ia[0], &ia[8192]); init_memory(&ib[0], &ib[8192]); init_memory(&sa[0], &sa[8192]); init_memory(&sb[0], &sb[8192]); BENCH("Example10b", example10b(sa,sb,ia,ib), Mi*4/8192*512, digest_memory(&ia[0], &ia[8192])+digest_memory(&ib[0], &ib[8192])); return 0; }
513531.c
/* * Copyright(c) 2019 Intel Corporation * SPDX - License - Identifier: BSD - 2 - Clause - Patent */ /* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <stdlib.h> #include "EbEncHandle.h" #include "EbUtility.h" #include "EbPictureControlSet.h" #include "EbModeDecisionConfigurationProcess.h" #include "EbRateControlResults.h" #include "EbEncDecTasks.h" #include "EbModeDecisionConfiguration.h" #include "EbReferenceObject.h" #include "EbModeDecisionProcess.h" #include "av1me.h" #include "EbQMatrices.h" #include "EbLog.h" #include "EbCoefficients.h" #include "EbCommonUtils.h" int32_t get_qzbin_factor(int32_t q, AomBitDepth bit_depth); void invert_quant(int16_t *quant, int16_t *shift, int32_t d); int16_t eb_av1_dc_quant_q3(int32_t qindex, int32_t delta, AomBitDepth bit_depth); int16_t eb_av1_ac_quant_q3(int32_t qindex, int32_t delta, AomBitDepth bit_depth); int16_t eb_av1_dc_quant_qtx(int32_t qindex, int32_t delta, AomBitDepth bit_depth); #define MAX_MESH_SPEED 5 // Max speed setting for mesh motion method static MeshPattern good_quality_mesh_patterns[MAX_MESH_SPEED + 1][MAX_MESH_STEP] = { {{64, 8}, {28, 4}, {15, 1}, {7, 1}}, {{64, 8}, {28, 4}, {15, 1}, {7, 1}}, {{64, 8}, {14, 2}, {7, 1}, {7, 1}}, {{64, 16}, {24, 8}, {12, 4}, {7, 1}}, {{64, 16}, {24, 8}, {12, 4}, {7, 1}}, {{64, 16}, {24, 8}, {12, 4}, {7, 1}}, }; static unsigned char good_quality_max_mesh_pct[MAX_MESH_SPEED + 1] = {50, 50, 25, 15, 5, 1}; // TODO: These settings are pretty relaxed, tune them for // each speed setting static MeshPattern intrabc_mesh_patterns[MAX_MESH_SPEED + 1][MAX_MESH_STEP] = { {{256, 1}, {256, 1}, {0, 0}, {0, 0}}, {{256, 1}, {256, 1}, {0, 0}, {0, 0}}, {{64, 1}, {64, 1}, {0, 0}, {0, 0}}, {{64, 1}, {64, 1}, {0, 0}, {0, 0}}, {{64, 4}, {16, 1}, {0, 0}, {0, 0}}, {{64, 4}, {16, 1}, {0, 0}, {0, 0}}, }; static uint8_t intrabc_max_mesh_pct[MAX_MESH_SPEED + 1] = {100, 100, 100, 25, 25, 10}; // Adaptive Depth Partitioning // Shooting states #define UNDER_SHOOTING 0 #define OVER_SHOOTING 1 #define TBD_SHOOTING 2 #define SB_PRED_OPEN_LOOP_COST 100 // Let's assume PRED_OPEN_LOOP_COST costs ~100 U #define U_101 101 #define U_102 102 #define U_103 103 #define U_104 104 #define U_105 105 #define U_107 107 #define SB_FAST_OPEN_LOOP_COST 108 #define U_109 109 #define SB_OPEN_LOOP_COST 110 // F_MDC is ~10% slower than PRED_OPEN_LOOP_COST #define U_111 111 #define U_112 112 #define U_113 113 #define U_114 114 #define U_115 115 #define U_116 116 #define U_117 117 #define U_118 118 #define U_119 119 #define U_120 120 #define U_121 121 #define U_122 122 #define U_125 125 #define U_127 127 #define U_130 130 #define U_132 132 #define U_133 133 #define U_134 134 #define U_140 140 #define U_145 145 #define U_150 150 #define U_152 152 #define SQ_NON4_BLOCKS_SEARCH_COST 155 #define SQ_BLOCKS_SEARCH_COST 190 #define HIGH_SB_SCORE 60000 #define MEDIUM_SB_SCORE 16000 #define LOW_SB_SCORE 6000 #define MAX_LUMINOSITY_BOOST 10 int32_t budget_per_sb_boost[MAX_SUPPORTED_MODES] = {55, 55, 55, 55, 55, 55, 5, 5, 0, 0, 0, 0, 0}; static INLINE int32_t aom_get_qmlevel(int32_t qindex, int32_t first, int32_t last) { return first + (qindex * (last + 1 - first)) / QINDEX_RANGE; } void set_global_motion_field(PictureControlSet *pcs_ptr) { // Init Global Motion Vector uint8_t frame_index; for (frame_index = INTRA_FRAME; frame_index <= ALTREF_FRAME; ++frame_index) { pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmtype = IDENTITY; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].alpha = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].beta = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].delta = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].gamma = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].invalid = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmmat[0] = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmmat[1] = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmmat[2] = (1 << WARPEDMODEL_PREC_BITS); pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmmat[3] = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmmat[4] = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmmat[5] = (1 << WARPEDMODEL_PREC_BITS); pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmmat[6] = 0; pcs_ptr->parent_pcs_ptr->global_motion[frame_index].wmmat[7] = 0; } //Update MV #if GLOBAL_WARPED_MOTION PictureParentControlSet *parent_pcs_ptr = pcs_ptr->parent_pcs_ptr; #if GLOBAL_WARPED_MOTION if (parent_pcs_ptr->gm_level <= GM_DOWN) { #endif if (parent_pcs_ptr ->is_global_motion[get_list_idx(LAST_FRAME)][get_ref_frame_idx(LAST_FRAME)]) parent_pcs_ptr->global_motion[LAST_FRAME] = parent_pcs_ptr->global_motion_estimation[get_list_idx(LAST_FRAME)] [get_ref_frame_idx(LAST_FRAME)]; if (parent_pcs_ptr ->is_global_motion[get_list_idx(BWDREF_FRAME)][get_ref_frame_idx(BWDREF_FRAME)]) parent_pcs_ptr->global_motion[BWDREF_FRAME] = parent_pcs_ptr->global_motion_estimation[get_list_idx(BWDREF_FRAME)] [get_ref_frame_idx(BWDREF_FRAME)]; #if GLOBAL_WARPED_MOTION // Upscale the translation parameters by 2, because the search is done on a down-sampled // version of the source picture (with a down-sampling factor of 2 in each dimension). if (parent_pcs_ptr->gm_level == GM_DOWN) { parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[0] *= 2; parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[1] *= 2; parent_pcs_ptr->global_motion[BWDREF_FRAME].wmmat[0] *= 2; parent_pcs_ptr->global_motion[BWDREF_FRAME].wmmat[1] *= 2; } #endif #endif #if GLOBAL_WARPED_MOTION } else { if (pcs_ptr->parent_pcs_ptr->is_pan && pcs_ptr->parent_pcs_ptr->is_tilt) { pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmtype = TRANSLATION; pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[1] = ((pcs_ptr->parent_pcs_ptr->pan_mvx + pcs_ptr->parent_pcs_ptr->tilt_mvx) / 2) << 1 << GM_TRANS_ONLY_PREC_DIFF; pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[0] = ((pcs_ptr->parent_pcs_ptr->pan_mvy + pcs_ptr->parent_pcs_ptr->tilt_mvy) / 2) << 1 << GM_TRANS_ONLY_PREC_DIFF; } else if (pcs_ptr->parent_pcs_ptr->is_pan) { pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmtype = TRANSLATION; pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[1] = pcs_ptr->parent_pcs_ptr->pan_mvx << 1 << GM_TRANS_ONLY_PREC_DIFF; pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[0] = pcs_ptr->parent_pcs_ptr->pan_mvy << 1 << GM_TRANS_ONLY_PREC_DIFF; } else if (pcs_ptr->parent_pcs_ptr->is_tilt) { pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmtype = TRANSLATION; pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[1] = pcs_ptr->parent_pcs_ptr->tilt_mvx << 1 << GM_TRANS_ONLY_PREC_DIFF; pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[0] = pcs_ptr->parent_pcs_ptr->tilt_mvy << 1 << GM_TRANS_ONLY_PREC_DIFF; } pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[1] = (int32_t)clamp(pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[1], GM_TRANS_MIN * GM_TRANS_DECODE_FACTOR, GM_TRANS_MAX * GM_TRANS_DECODE_FACTOR); pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[0] = (int32_t)clamp(pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[0], GM_TRANS_MIN * GM_TRANS_DECODE_FACTOR, GM_TRANS_MAX * GM_TRANS_DECODE_FACTOR); pcs_ptr->parent_pcs_ptr->global_motion[BWDREF_FRAME].wmtype = TRANSLATION; pcs_ptr->parent_pcs_ptr->global_motion[BWDREF_FRAME].wmmat[1] = 0 - pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[1]; pcs_ptr->parent_pcs_ptr->global_motion[BWDREF_FRAME].wmmat[0] = 0 - pcs_ptr->parent_pcs_ptr->global_motion[LAST_FRAME].wmmat[0]; pcs_ptr->parent_pcs_ptr->global_motion[BWDREF_FRAME].wmmat[1] = (int32_t)clamp(pcs_ptr->parent_pcs_ptr->global_motion[BWDREF_FRAME].wmmat[1], GM_TRANS_MIN * GM_TRANS_DECODE_FACTOR, GM_TRANS_MAX * GM_TRANS_DECODE_FACTOR); pcs_ptr->parent_pcs_ptr->global_motion[BWDREF_FRAME].wmmat[0] = (int32_t)clamp(pcs_ptr->parent_pcs_ptr->global_motion[BWDREF_FRAME].wmmat[0], GM_TRANS_MIN * GM_TRANS_DECODE_FACTOR, GM_TRANS_MAX * GM_TRANS_DECODE_FACTOR); } #endif } void eb_av1_set_quantizer(PictureParentControlSet *pcs_ptr, int32_t q) { // quantizer has to be reinitialized with av1_init_quantizer() if any // delta_q changes. FrameHeader *frm_hdr = &pcs_ptr->frm_hdr; frm_hdr->quantization_params.using_qmatrix = 0; pcs_ptr->min_qmlevel = 5; pcs_ptr->max_qmlevel = 9; frm_hdr->quantization_params.base_q_idx = AOMMAX(frm_hdr->delta_q_params.delta_q_present, q); frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_Y] = 0; frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_Y] = 0; frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_U] = 0; frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_U] = 0; frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_V] = 0; frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_V] = 0; frm_hdr->quantization_params.qm[AOM_PLANE_Y] = aom_get_qmlevel( frm_hdr->quantization_params.base_q_idx, pcs_ptr->min_qmlevel, pcs_ptr->max_qmlevel); frm_hdr->quantization_params.qm[AOM_PLANE_U] = aom_get_qmlevel(frm_hdr->quantization_params.base_q_idx + frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_U], pcs_ptr->min_qmlevel, pcs_ptr->max_qmlevel); if (!pcs_ptr->separate_uv_delta_q) frm_hdr->quantization_params.qm[AOM_PLANE_V] = frm_hdr->quantization_params.qm[AOM_PLANE_U]; else frm_hdr->quantization_params.qm[AOM_PLANE_V] = aom_get_qmlevel(frm_hdr->quantization_params.base_q_idx + frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_V], pcs_ptr->min_qmlevel, pcs_ptr->max_qmlevel); } void eb_av1_build_quantizer(AomBitDepth bit_depth, int32_t y_dc_delta_q, int32_t u_dc_delta_q, int32_t u_ac_delta_q, int32_t v_dc_delta_q, int32_t v_ac_delta_q, Quants *const quants, Dequants *const deq) { int32_t i, q, quant_q3, quant_qtx; for (q = 0; q < QINDEX_RANGE; q++) { const int32_t qzbin_factor = get_qzbin_factor(q, bit_depth); const int32_t qrounding_factor = q == 0 ? 64 : 48; for (i = 0; i < 2; ++i) { int32_t qrounding_factor_fp = 64; // y quantizer setup with original coeff shift of Q3 quant_q3 = i == 0 ? eb_av1_dc_quant_q3(q, y_dc_delta_q, bit_depth) : eb_av1_ac_quant_q3(q, 0, bit_depth); // y quantizer with TX scale quant_qtx = i == 0 ? eb_av1_dc_quant_qtx(q, y_dc_delta_q, bit_depth) : eb_av1_ac_quant_qtx(q, 0, bit_depth); invert_quant(&quants->y_quant[q][i], &quants->y_quant_shift[q][i], quant_qtx); quants->y_quant_fp[q][i] = (int16_t)((1 << 16) / quant_qtx); quants->y_round_fp[q][i] = (int16_t)((qrounding_factor_fp * quant_qtx) >> 7); quants->y_zbin[q][i] = (int16_t)ROUND_POWER_OF_TWO(qzbin_factor * quant_qtx, 7); quants->y_round[q][i] = (int16_t)((qrounding_factor * quant_qtx) >> 7); deq->y_dequant_qtx[q][i] = (int16_t)quant_qtx; deq->y_dequant_q3[q][i] = (int16_t)quant_q3; // u quantizer setup with original coeff shift of Q3 quant_q3 = i == 0 ? eb_av1_dc_quant_q3(q, u_dc_delta_q, bit_depth) : eb_av1_ac_quant_q3(q, u_ac_delta_q, bit_depth); // u quantizer with TX scale quant_qtx = i == 0 ? eb_av1_dc_quant_qtx(q, u_dc_delta_q, bit_depth) : eb_av1_ac_quant_qtx(q, u_ac_delta_q, bit_depth); invert_quant(&quants->u_quant[q][i], &quants->u_quant_shift[q][i], quant_qtx); quants->u_quant_fp[q][i] = (int16_t)((1 << 16) / quant_qtx); quants->u_round_fp[q][i] = (int16_t)((qrounding_factor_fp * quant_qtx) >> 7); quants->u_zbin[q][i] = (int16_t)ROUND_POWER_OF_TWO(qzbin_factor * quant_qtx, 7); quants->u_round[q][i] = (int16_t)((qrounding_factor * quant_qtx) >> 7); deq->u_dequant_qtx[q][i] = (int16_t)quant_qtx; deq->u_dequant_q3[q][i] = (int16_t)quant_q3; // v quantizer setup with original coeff shift of Q3 quant_q3 = i == 0 ? eb_av1_dc_quant_q3(q, v_dc_delta_q, bit_depth) : eb_av1_ac_quant_q3(q, v_ac_delta_q, bit_depth); // v quantizer with TX scale quant_qtx = i == 0 ? eb_av1_dc_quant_qtx(q, v_dc_delta_q, bit_depth) : eb_av1_ac_quant_qtx(q, v_ac_delta_q, bit_depth); invert_quant(&quants->v_quant[q][i], &quants->v_quant_shift[q][i], quant_qtx); quants->v_quant_fp[q][i] = (int16_t)((1 << 16) / quant_qtx); quants->v_round_fp[q][i] = (int16_t)((qrounding_factor_fp * quant_qtx) >> 7); quants->v_zbin[q][i] = (int16_t)ROUND_POWER_OF_TWO(qzbin_factor * quant_qtx, 7); quants->v_round[q][i] = (int16_t)((qrounding_factor * quant_qtx) >> 7); deq->v_dequant_qtx[q][i] = (int16_t)quant_qtx; deq->v_dequant_q3[q][i] = (int16_t)quant_q3; } for (i = 2; i < 8; i++) { // 8: SIMD width quants->y_quant[q][i] = quants->y_quant[q][1]; quants->y_quant_fp[q][i] = quants->y_quant_fp[q][1]; quants->y_round_fp[q][i] = quants->y_round_fp[q][1]; quants->y_quant_shift[q][i] = quants->y_quant_shift[q][1]; quants->y_zbin[q][i] = quants->y_zbin[q][1]; quants->y_round[q][i] = quants->y_round[q][1]; deq->y_dequant_qtx[q][i] = deq->y_dequant_qtx[q][1]; deq->y_dequant_q3[q][i] = deq->y_dequant_q3[q][1]; quants->u_quant[q][i] = quants->u_quant[q][1]; quants->u_quant_fp[q][i] = quants->u_quant_fp[q][1]; quants->u_round_fp[q][i] = quants->u_round_fp[q][1]; quants->u_quant_shift[q][i] = quants->u_quant_shift[q][1]; quants->u_zbin[q][i] = quants->u_zbin[q][1]; quants->u_round[q][i] = quants->u_round[q][1]; deq->u_dequant_qtx[q][i] = deq->u_dequant_qtx[q][1]; deq->u_dequant_q3[q][i] = deq->u_dequant_q3[q][1]; quants->v_quant[q][i] = quants->u_quant[q][1]; quants->v_quant_fp[q][i] = quants->v_quant_fp[q][1]; quants->v_round_fp[q][i] = quants->v_round_fp[q][1]; quants->v_quant_shift[q][i] = quants->v_quant_shift[q][1]; quants->v_zbin[q][i] = quants->v_zbin[q][1]; quants->v_round[q][i] = quants->v_round[q][1]; deq->v_dequant_qtx[q][i] = deq->v_dequant_qtx[q][1]; deq->v_dequant_q3[q][i] = deq->v_dequant_q3[q][1]; } } } void eb_av1_qm_init(PictureParentControlSet *pcs_ptr) { const uint8_t num_planes = 3; // MAX_MB_PLANE;// NM- No monochroma uint8_t q, c, t; int32_t current; for (q = 0; q < NUM_QM_LEVELS; ++q) { for (c = 0; c < num_planes; ++c) { current = 0; for (t = 0; t < TX_SIZES_ALL; ++t) { const int32_t size = tx_size_2d[t]; const TxSize qm_tx_size = av1_get_adjusted_tx_size(t); if (q == NUM_QM_LEVELS - 1) { pcs_ptr->gqmatrix[q][c][t] = NULL; pcs_ptr->giqmatrix[q][c][t] = NULL; } else if (t != qm_tx_size) { // Reuse matrices for 'qm_tx_size' pcs_ptr->gqmatrix[q][c][t] = pcs_ptr->gqmatrix[q][c][qm_tx_size]; pcs_ptr->giqmatrix[q][c][t] = pcs_ptr->giqmatrix[q][c][qm_tx_size]; } else { assert(current + size <= QM_TOTAL_SIZE); pcs_ptr->gqmatrix[q][c][t] = &wt_matrix_ref[q][c >= 1][current]; pcs_ptr->giqmatrix[q][c][t] = &iwt_matrix_ref[q][c >= 1][current]; current += size; } } } } } /****************************************************** * Compute picture and slice level chroma QP offsets ******************************************************/ void set_slice_and_picture_chroma_qp_offsets(PictureControlSet *pcs_ptr) { // This is a picture level chroma QP offset and is sent in the PPS pcs_ptr->cb_qp_offset = 0; pcs_ptr->cr_qp_offset = 0; //In order to have QP offsets for chroma at a slice level set slice_level_chroma_qp_flag flag in pcs_ptr (can be done in the PCS Ctor) // The below are slice level chroma QP offsets and is sent for each slice when slice_level_chroma_qp_flag is set // IMPORTANT: Lambda tables assume that the cb and cr have the same QP offsets. // However the offsets for each component can be very different for ENC DEC and we are conformant. pcs_ptr->slice_cb_qp_offset = 0; pcs_ptr->slice_cr_qp_offset = 0; if (pcs_ptr->parent_pcs_ptr->pic_noise_class >= PIC_NOISE_CLASS_6) { pcs_ptr->slice_cb_qp_offset = 10; pcs_ptr->slice_cr_qp_offset = 10; } else if (pcs_ptr->parent_pcs_ptr->pic_noise_class >= PIC_NOISE_CLASS_4) { pcs_ptr->slice_cb_qp_offset = 8; pcs_ptr->slice_cr_qp_offset = 8; } else { if (pcs_ptr->temporal_layer_index == 1) { pcs_ptr->slice_cb_qp_offset = 2; pcs_ptr->slice_cr_qp_offset = 2; } else { pcs_ptr->slice_cb_qp_offset = 0; pcs_ptr->slice_cr_qp_offset = 0; } } } /****************************************************** * Set the reference sg ep for a given picture ******************************************************/ void set_reference_sg_ep(PictureControlSet *pcs_ptr) { Av1Common * cm = pcs_ptr->parent_pcs_ptr->av1_cm; EbReferenceObject *ref_obj_l0, *ref_obj_l1; memset(cm->sg_frame_ep_cnt, 0, SGRPROJ_PARAMS * sizeof(int32_t)); cm->sg_frame_ep = 0; // NADER: set cm->sg_ref_frame_ep[0] = cm->sg_ref_frame_ep[1] = -1 to perform all iterations switch (pcs_ptr->slice_type) { case I_SLICE: cm->sg_ref_frame_ep[0] = -1; cm->sg_ref_frame_ep[1] = -1; break; case B_SLICE: ref_obj_l0 = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[REF_LIST_0][0]->object_ptr; ref_obj_l1 = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[REF_LIST_1][0]->object_ptr; cm->sg_ref_frame_ep[0] = ref_obj_l0->sg_frame_ep; cm->sg_ref_frame_ep[1] = ref_obj_l1->sg_frame_ep; break; case P_SLICE: ref_obj_l0 = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[REF_LIST_0][0]->object_ptr; cm->sg_ref_frame_ep[0] = ref_obj_l0->sg_frame_ep; cm->sg_ref_frame_ep[1] = 0; break; default: SVT_LOG("SG: Not supported picture type"); break; } } /****************************************************** * Set the reference cdef strength for a given picture ******************************************************/ void set_reference_cdef_strength(PictureControlSet *pcs_ptr) { EbReferenceObject *ref_obj_l0, *ref_obj_l1; int32_t strength; // NADER: set pcs_ptr->parent_pcs_ptr->use_ref_frame_cdef_strength 0 to test all strengths switch (pcs_ptr->slice_type) { case I_SLICE: pcs_ptr->parent_pcs_ptr->use_ref_frame_cdef_strength = 0; pcs_ptr->parent_pcs_ptr->cdf_ref_frame_strenght = 0; break; case B_SLICE: ref_obj_l0 = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[REF_LIST_0][0]->object_ptr; ref_obj_l1 = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[REF_LIST_1][0]->object_ptr; strength = (ref_obj_l0->cdef_frame_strength + ref_obj_l1->cdef_frame_strength) / 2; pcs_ptr->parent_pcs_ptr->use_ref_frame_cdef_strength = 1; pcs_ptr->parent_pcs_ptr->cdf_ref_frame_strenght = strength; break; case P_SLICE: ref_obj_l0 = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[REF_LIST_0][0]->object_ptr; strength = ref_obj_l0->cdef_frame_strength; pcs_ptr->parent_pcs_ptr->use_ref_frame_cdef_strength = 1; pcs_ptr->parent_pcs_ptr->cdf_ref_frame_strenght = strength; break; default: SVT_LOG("CDEF: Not supported picture type"); break; } } /****************************************************** * Compute Tc, and Beta offsets for a given picture ******************************************************/ static void mode_decision_configuration_context_dctor(EbPtr p) { EbThreadContext * thread_context_ptr = (EbThreadContext *)p; ModeDecisionConfigurationContext *obj = (ModeDecisionConfigurationContext *)thread_context_ptr->priv; if (obj->is_md_rate_estimation_ptr_owner) EB_FREE_ARRAY(obj->md_rate_estimation_ptr); EB_FREE_ARRAY(obj->sb_score_array); EB_FREE_ARRAY(obj->sb_cost_array); EB_FREE_ARRAY(obj->mdc_candidate_ptr); EB_FREE_ARRAY(obj->mdc_ref_mv_stack); EB_FREE_ARRAY(obj->mdc_blk_ptr->av1xd); EB_FREE_ARRAY(obj->mdc_blk_ptr); EB_FREE_ARRAY(obj); } /****************************************************** * Mode Decision Configuration Context Constructor ******************************************************/ EbErrorType mode_decision_configuration_context_ctor(EbThreadContext * thread_context_ptr, const EbEncHandle *enc_handle_ptr, int input_index, int output_index) { const SequenceControlSet *scs_ptr = enc_handle_ptr->scs_instance_array[0]->scs_ptr; uint32_t sb_total_count = ((scs_ptr->max_input_luma_width + BLOCK_SIZE_64 - 1) / BLOCK_SIZE_64) * ((scs_ptr->max_input_luma_height + BLOCK_SIZE_64 - 1) / BLOCK_SIZE_64); ModeDecisionConfigurationContext *context_ptr; EB_CALLOC_ARRAY(context_ptr, 1); thread_context_ptr->priv = context_ptr; thread_context_ptr->dctor = mode_decision_configuration_context_dctor; // Input/Output System Resource Manager FIFOs context_ptr->rate_control_input_fifo_ptr = eb_system_resource_get_consumer_fifo( enc_handle_ptr->rate_control_results_resource_ptr, input_index); context_ptr->mode_decision_configuration_output_fifo_ptr = eb_system_resource_get_producer_fifo( enc_handle_ptr->enc_dec_tasks_resource_ptr, output_index); // Rate estimation EB_MALLOC_ARRAY(context_ptr->md_rate_estimation_ptr, 1); context_ptr->is_md_rate_estimation_ptr_owner = EB_TRUE; // Adaptive Depth Partitioning EB_MALLOC_ARRAY(context_ptr->sb_score_array, sb_total_count); EB_MALLOC_ARRAY(context_ptr->sb_cost_array, sb_total_count); // Open Loop Partitioning EB_MALLOC_ARRAY(context_ptr->mdc_candidate_ptr, 1); EB_MALLOC_ARRAY(context_ptr->mdc_ref_mv_stack, 1); EB_MALLOC_ARRAY(context_ptr->mdc_blk_ptr, 1); context_ptr->mdc_blk_ptr->av1xd = NULL; EB_MALLOC_ARRAY(context_ptr->mdc_blk_ptr->av1xd, 1); return EB_ErrorNone; } /****************************************************** * Predict the SB partitionning ******************************************************/ void perform_early_sb_partitionning(ModeDecisionConfigurationContext *context_ptr, SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr) { SuperBlock *sb_ptr; uint32_t sb_index; pcs_ptr->parent_pcs_ptr->average_qp = (uint8_t)pcs_ptr->parent_pcs_ptr->picture_qp; // SB Loop : Partitionnig Decision for (sb_index = 0; sb_index < pcs_ptr->sb_total_count; ++sb_index) { sb_ptr = pcs_ptr->sb_ptr_array[sb_index]; early_mode_decision_sb(scs_ptr, pcs_ptr, sb_ptr, sb_index, context_ptr); } // End of SB Loop } void perform_early_sb_partitionning_sb(ModeDecisionConfigurationContext *context_ptr, SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr, uint32_t sb_index) { SuperBlock *sb_ptr; // SB Loop : Partitionnig Decision sb_ptr = pcs_ptr->sb_ptr_array[sb_index]; early_mode_decision_sb(scs_ptr, pcs_ptr, sb_ptr, sb_index, context_ptr); } void forward_all_blocks_to_md(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr) { uint32_t sb_index; EbBool split_flag; UNUSED(split_flag); for (sb_index = 0; sb_index < pcs_ptr->sb_total_count_pix; ++sb_index) { MdcSbData *results_ptr = &pcs_ptr->mdc_sb_array[sb_index]; results_ptr->leaf_count = 0; uint32_t blk_index = 0; while (blk_index < scs_ptr->max_block_cnt) { split_flag = EB_TRUE; const BlockGeom *blk_geom = get_blk_geom_mds(blk_index); //if the parentSq is inside inject this block uint8_t is_blk_allowed = pcs_ptr->slice_type != I_SLICE ? 1 : (blk_geom->sq_size < 128) ? 1 : 0; if (pcs_ptr->parent_pcs_ptr->sb_geom[sb_index].block_is_inside_md_scan[blk_index] && is_blk_allowed) { results_ptr->leaf_data_array[results_ptr->leaf_count].tot_d1_blocks = blk_geom->sq_size == 128 ? 17 : blk_geom->sq_size > 8 ? 25 : blk_geom->sq_size == 8 ? 5 : 1; results_ptr->leaf_data_array[results_ptr->leaf_count].leaf_index = 0; //valid only for square 85 world. will be removed. results_ptr->leaf_data_array[results_ptr->leaf_count].mds_idx = blk_index; if (blk_geom->sq_size > 4) { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_TRUE; split_flag = EB_TRUE; } else { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_FALSE; split_flag = EB_FALSE; } } blk_index++; } } pcs_ptr->parent_pcs_ptr->average_qp = (uint8_t)pcs_ptr->parent_pcs_ptr->picture_qp; } void forward_sq_blocks_to_md(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr) { uint32_t sb_index; EbBool split_flag; for (sb_index = 0; sb_index < pcs_ptr->sb_total_count_pix; ++sb_index) { MdcSbData *results_ptr = &pcs_ptr->mdc_sb_array[sb_index]; results_ptr->leaf_count = 0; uint32_t blk_index = pcs_ptr->slice_type == I_SLICE && scs_ptr->seq_header.sb_size == BLOCK_128X128 ? 17 : 0; while (blk_index < scs_ptr->max_block_cnt) { split_flag = EB_TRUE; const BlockGeom *blk_geom = get_blk_geom_mds(blk_index); //if the parentSq is inside inject this block if (pcs_ptr->parent_pcs_ptr->sb_geom[sb_index].block_is_inside_md_scan[blk_index]) { //int32_t offset_d1 = ns_blk_offset[(int32_t)from_shape_to_part[blk_geom->shape]]; //blk_ptr->best_d1_blk; // TOCKECK //int32_t num_d1_block = ns_blk_num[(int32_t)from_shape_to_part[blk_geom->shape]]; // context_ptr->blk_geom->totns; // TOCKECK // // // for (int32_t d1_itr = blk_it; d1_itr < blk_it + num_d1_block; d1_itr++) { // for (int32_t d1_itr = (int32_t)blk_index ; d1_itr < (int32_t)blk_index + num_d1_block ; d1_itr++) { results_ptr->leaf_data_array[results_ptr->leaf_count].tot_d1_blocks = 1; results_ptr->leaf_data_array[results_ptr->leaf_count].leaf_index = 0; //valid only for square 85 world. will be removed. results_ptr->leaf_data_array[results_ptr->leaf_count].mds_idx = blk_index; if (blk_geom->sq_size > 4) { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_TRUE; split_flag = EB_TRUE; } else { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_FALSE; split_flag = EB_FALSE; } } blk_index += split_flag ? d1_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128][blk_geom->depth] : ns_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128] [blk_geom->depth]; } } pcs_ptr->parent_pcs_ptr->average_qp = (uint8_t)pcs_ptr->parent_pcs_ptr->picture_qp; } void sb_forward_sq_blocks_to_md(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr, uint32_t sb_index) { EbBool split_flag; MdcSbData *results_ptr = &pcs_ptr->mdc_sb_array[sb_index]; results_ptr->leaf_count = 0; uint32_t blk_index = pcs_ptr->slice_type == I_SLICE && scs_ptr->seq_header.sb_size == BLOCK_128X128 ? 17 : 0; while (blk_index < scs_ptr->max_block_cnt) { split_flag = EB_TRUE; const BlockGeom *blk_geom = get_blk_geom_mds(blk_index); if (pcs_ptr->parent_pcs_ptr->sb_geom[sb_index].block_is_inside_md_scan[blk_index]) { results_ptr->leaf_data_array[results_ptr->leaf_count].tot_d1_blocks = 1; results_ptr->leaf_data_array[results_ptr->leaf_count].leaf_index = 0; //valid only for square 85 world. will be removed. results_ptr->leaf_data_array[results_ptr->leaf_count].mds_idx = blk_index; if (blk_geom->sq_size > 4) { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_TRUE; split_flag = EB_TRUE; } else { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_FALSE; split_flag = EB_FALSE; } } blk_index += split_flag ? d1_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128][blk_geom->depth] : ns_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128][blk_geom->depth]; } pcs_ptr->parent_pcs_ptr->average_qp = (uint8_t)pcs_ptr->parent_pcs_ptr->picture_qp; } /****************************************************** * Load the cost of the different partitioning method into a local array and derive sensitive picture flag Input : the offline derived cost per search method, detection signals Output : valid cost_depth_mode and valid sensitivePicture ******************************************************/ void configure_adp(PictureControlSet *pcs_ptr, ModeDecisionConfigurationContext *context_ptr) { UNUSED(pcs_ptr); context_ptr->cost_depth_mode[SB_SQ_BLOCKS_DEPTH_MODE - 1] = SQ_BLOCKS_SEARCH_COST; context_ptr->cost_depth_mode[SB_SQ_NON4_BLOCKS_DEPTH_MODE - 1] = SQ_NON4_BLOCKS_SEARCH_COST; context_ptr->cost_depth_mode[SB_OPEN_LOOP_DEPTH_MODE - 1] = SB_OPEN_LOOP_COST; context_ptr->cost_depth_mode[SB_FAST_OPEN_LOOP_DEPTH_MODE - 1] = SB_FAST_OPEN_LOOP_COST; context_ptr->cost_depth_mode[SB_PRED_OPEN_LOOP_DEPTH_MODE - 1] = SB_PRED_OPEN_LOOP_COST; // Initialize the score based TH context_ptr->score_th[0] = ~0; context_ptr->score_th[1] = ~0; context_ptr->score_th[2] = ~0; context_ptr->score_th[3] = ~0; context_ptr->score_th[4] = ~0; context_ptr->score_th[5] = ~0; context_ptr->score_th[6] = ~0; // Initialize the predicted budget context_ptr->predicted_cost = (uint32_t)~0; } /****************************************************** * Assign a search method based on the allocated cost Input : allocated budget per SB Output : search method per SB ******************************************************/ void derive_search_method(PictureControlSet * pcs_ptr, ModeDecisionConfigurationContext *context_ptr) { uint32_t sb_index; for (sb_index = 0; sb_index < pcs_ptr->sb_total_count_pix; sb_index++) { if (context_ptr->sb_cost_array[sb_index] == context_ptr->cost_depth_mode[SB_PRED_OPEN_LOOP_DEPTH_MODE - 1]) pcs_ptr->parent_pcs_ptr->sb_depth_mode_array[sb_index] = SB_PRED_OPEN_LOOP_DEPTH_MODE; else if (context_ptr->sb_cost_array[sb_index] == context_ptr->cost_depth_mode[SB_FAST_OPEN_LOOP_DEPTH_MODE - 1]) pcs_ptr->parent_pcs_ptr->sb_depth_mode_array[sb_index] = SB_FAST_OPEN_LOOP_DEPTH_MODE; else if (context_ptr->sb_cost_array[sb_index] == context_ptr->cost_depth_mode[SB_OPEN_LOOP_DEPTH_MODE - 1]) pcs_ptr->parent_pcs_ptr->sb_depth_mode_array[sb_index] = SB_OPEN_LOOP_DEPTH_MODE; else if (context_ptr->sb_cost_array[sb_index] == context_ptr->cost_depth_mode[SB_SQ_NON4_BLOCKS_DEPTH_MODE - 1]) pcs_ptr->parent_pcs_ptr->sb_depth_mode_array[sb_index] = SB_SQ_NON4_BLOCKS_DEPTH_MODE; else pcs_ptr->parent_pcs_ptr->sb_depth_mode_array[sb_index] = SB_SQ_BLOCKS_DEPTH_MODE; } } /****************************************************** * Set SB budget Input : SB score, detection signals, iteration Output : predicted budget for the SB ******************************************************/ void set_sb_budget(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr, SuperBlock *sb_ptr, ModeDecisionConfigurationContext *context_ptr) { const uint32_t sb_index = sb_ptr->index; uint32_t max_to_min_score, score_to_min; UNUSED(scs_ptr); UNUSED(pcs_ptr); { context_ptr->sb_score_array[sb_index] = CLIP3(context_ptr->sb_min_score, context_ptr->sb_max_score, context_ptr->sb_score_array[sb_index]); score_to_min = context_ptr->sb_score_array[sb_index] - context_ptr->sb_min_score; max_to_min_score = context_ptr->sb_max_score - context_ptr->sb_min_score; if ((score_to_min <= (max_to_min_score * context_ptr->score_th[0]) / 100 && context_ptr->score_th[0] != 0) || context_ptr->number_of_segments == 1 || context_ptr->score_th[1] == 100) { context_ptr->sb_cost_array[sb_index] = context_ptr->interval_cost[0]; context_ptr->predicted_cost += context_ptr->interval_cost[0]; } else if ((score_to_min <= (max_to_min_score * context_ptr->score_th[1]) / 100 && context_ptr->score_th[1] != 0) || context_ptr->number_of_segments == 2 || context_ptr->score_th[2] == 100) { context_ptr->sb_cost_array[sb_index] = context_ptr->interval_cost[1]; context_ptr->predicted_cost += context_ptr->interval_cost[1]; } else if ((score_to_min <= (max_to_min_score * context_ptr->score_th[2]) / 100 && context_ptr->score_th[2] != 0) || context_ptr->number_of_segments == 3 || context_ptr->score_th[3] == 100) { context_ptr->sb_cost_array[sb_index] = context_ptr->interval_cost[2]; context_ptr->predicted_cost += context_ptr->interval_cost[2]; } else if ((score_to_min <= (max_to_min_score * context_ptr->score_th[3]) / 100 && context_ptr->score_th[3] != 0) || context_ptr->number_of_segments == 4 || context_ptr->score_th[4] == 100) { context_ptr->sb_cost_array[sb_index] = context_ptr->interval_cost[3]; context_ptr->predicted_cost += context_ptr->interval_cost[3]; } else if ((score_to_min <= (max_to_min_score * context_ptr->score_th[4]) / 100 && context_ptr->score_th[4] != 0) || context_ptr->number_of_segments == 5 || context_ptr->score_th[5] == 100) { context_ptr->sb_cost_array[sb_index] = context_ptr->interval_cost[4]; context_ptr->predicted_cost += context_ptr->interval_cost[4]; } else if ((score_to_min <= (max_to_min_score * context_ptr->score_th[5]) / 100 && context_ptr->score_th[5] != 0) || context_ptr->number_of_segments == 6 || context_ptr->score_th[6] == 100) { context_ptr->sb_cost_array[sb_index] = context_ptr->interval_cost[5]; context_ptr->predicted_cost += context_ptr->interval_cost[5]; } else { context_ptr->sb_cost_array[sb_index] = context_ptr->interval_cost[6]; context_ptr->predicted_cost += context_ptr->interval_cost[6]; } } } /****************************************************** * Loop multiple times over the SBs in order to derive the optimal budget per SB Input : budget per picture, ditortion, detection signals, iteration Output : optimal budget for each SB ******************************************************/ void derive_optimal_budget_per_sb(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr, ModeDecisionConfigurationContext *context_ptr) { uint32_t sb_index; // Initialize the deviation between the picture predicted cost & the target budget to 100, uint32_t deviation_to_target = 1000; // Set the adjustment step to 1 (could be increased for faster convergence), int8_t adjustement_step = 1; // Set the initial shooting state & the final shooting state to TBD uint32_t initial_shooting = TBD_SHOOTING; uint32_t final_shooting = TBD_SHOOTING; uint8_t max_adjustement_iteration = 100; uint8_t adjustement_iteration = 0; while (deviation_to_target != 0 && (initial_shooting == final_shooting) && adjustement_iteration <= max_adjustement_iteration) { if (context_ptr->predicted_cost < context_ptr->budget) initial_shooting = UNDER_SHOOTING; else initial_shooting = OVER_SHOOTING; // reset running cost context_ptr->predicted_cost = 0; for (sb_index = 0; sb_index < pcs_ptr->sb_total_count_pix; sb_index++) { SuperBlock *sb_ptr = pcs_ptr->sb_ptr_array[sb_index]; set_sb_budget(scs_ptr, pcs_ptr, sb_ptr, context_ptr); } // Compute the deviation between the predicted budget & the target budget deviation_to_target = (ABS((int32_t)(context_ptr->predicted_cost - context_ptr->budget)) * 1000) / context_ptr->budget; // Derive shooting status if (context_ptr->predicted_cost < context_ptr->budget) { context_ptr->score_th[0] = MAX((context_ptr->score_th[0] - adjustement_step), 0); context_ptr->score_th[1] = MAX((context_ptr->score_th[1] - adjustement_step), 0); context_ptr->score_th[2] = MAX((context_ptr->score_th[2] - adjustement_step), 0); context_ptr->score_th[3] = MAX((context_ptr->score_th[3] - adjustement_step), 0); context_ptr->score_th[4] = MAX((context_ptr->score_th[4] - adjustement_step), 0); final_shooting = UNDER_SHOOTING; } else { context_ptr->score_th[0] = (context_ptr->score_th[0] == 0) ? 0 : MIN(context_ptr->score_th[0] + adjustement_step, 100); context_ptr->score_th[1] = (context_ptr->score_th[1] == 0) ? 0 : MIN(context_ptr->score_th[1] + adjustement_step, 100); context_ptr->score_th[2] = (context_ptr->score_th[2] == 0) ? 0 : MIN(context_ptr->score_th[2] + adjustement_step, 100); context_ptr->score_th[3] = (context_ptr->score_th[3] == 0) ? 0 : MIN(context_ptr->score_th[3] + adjustement_step, 100); context_ptr->score_th[4] = (context_ptr->score_th[4] == 0) ? 0 : MIN(context_ptr->score_th[4] + adjustement_step, 100); final_shooting = OVER_SHOOTING; } if (adjustement_iteration == 0) initial_shooting = final_shooting; adjustement_iteration++; } } EbErrorType derive_default_segments(SequenceControlSet * scs_ptr, ModeDecisionConfigurationContext *context_ptr) { EbErrorType return_error = EB_ErrorNone; if (context_ptr->budget > (uint16_t)(scs_ptr->sb_tot_cnt * U_140)) { context_ptr->number_of_segments = 2; context_ptr->score_th[0] = (int8_t)((1 * 100) / context_ptr->number_of_segments); context_ptr->score_th[1] = (int8_t)((2 * 100) / context_ptr->number_of_segments); context_ptr->score_th[2] = (int8_t)((3 * 100) / context_ptr->number_of_segments); context_ptr->score_th[3] = (int8_t)((4 * 100) / context_ptr->number_of_segments); context_ptr->interval_cost[0] = context_ptr->cost_depth_mode[SB_OPEN_LOOP_DEPTH_MODE - 1]; context_ptr->interval_cost[1] = context_ptr->cost_depth_mode[SB_SQ_NON4_BLOCKS_DEPTH_MODE - 1]; } else if (context_ptr->budget > (uint16_t)(scs_ptr->sb_tot_cnt * U_115)) { context_ptr->number_of_segments = 3; context_ptr->score_th[0] = (int8_t)((1 * 100) / context_ptr->number_of_segments); context_ptr->score_th[1] = (int8_t)((2 * 100) / context_ptr->number_of_segments); context_ptr->score_th[2] = (int8_t)((3 * 100) / context_ptr->number_of_segments); context_ptr->score_th[3] = (int8_t)((4 * 100) / context_ptr->number_of_segments); context_ptr->interval_cost[0] = context_ptr->cost_depth_mode[SB_FAST_OPEN_LOOP_DEPTH_MODE - 1]; context_ptr->interval_cost[1] = context_ptr->cost_depth_mode[SB_OPEN_LOOP_DEPTH_MODE - 1]; context_ptr->interval_cost[2] = context_ptr->cost_depth_mode[SB_SQ_NON4_BLOCKS_DEPTH_MODE - 1]; } else { context_ptr->number_of_segments = 4; context_ptr->score_th[0] = (int8_t)((1 * 100) / context_ptr->number_of_segments); context_ptr->score_th[1] = (int8_t)((2 * 100) / context_ptr->number_of_segments); context_ptr->score_th[2] = (int8_t)((3 * 100) / context_ptr->number_of_segments); context_ptr->score_th[3] = (int8_t)((4 * 100) / context_ptr->number_of_segments); context_ptr->interval_cost[0] = context_ptr->cost_depth_mode[SB_PRED_OPEN_LOOP_DEPTH_MODE - 1]; context_ptr->interval_cost[1] = context_ptr->cost_depth_mode[SB_FAST_OPEN_LOOP_DEPTH_MODE - 1]; context_ptr->interval_cost[2] = context_ptr->cost_depth_mode[SB_OPEN_LOOP_DEPTH_MODE - 1]; context_ptr->interval_cost[3] = context_ptr->cost_depth_mode[SB_SQ_NON4_BLOCKS_DEPTH_MODE - 1]; } return return_error; } /****************************************************** * Compute the score of each SB Input : distortion, detection signals Output : SB score ******************************************************/ void derive_sb_score(PictureControlSet *pcs_ptr, ModeDecisionConfigurationContext *context_ptr) { uint32_t sb_index; uint32_t sb_score = 0; uint32_t distortion; uint64_t sb_tot_score = 0; context_ptr->sb_min_score = ~0u; context_ptr->sb_max_score = 0u; for (sb_index = 0; sb_index < pcs_ptr->sb_total_count_pix; sb_index++) { SbParams *sb_params = &pcs_ptr->parent_pcs_ptr->sb_params_array[sb_index]; if (pcs_ptr->slice_type == I_SLICE) assert(0); else { if (sb_params->raster_scan_blk_validity[RASTER_SCAN_CU_INDEX_64x64] == EB_FALSE) { uint8_t blk8x8_index; uint8_t valid_blk_8x8_count = 0; distortion = 0; for (blk8x8_index = RASTER_SCAN_CU_INDEX_8x8_0; blk8x8_index <= RASTER_SCAN_CU_INDEX_8x8_63; blk8x8_index++) { if (sb_params->raster_scan_blk_validity[blk8x8_index]) { distortion = pcs_ptr->parent_pcs_ptr->me_results[sb_index] ->me_candidate[blk8x8_index][0] .distortion; valid_blk_8x8_count++; } } if (valid_blk_8x8_count > 0) distortion = (distortion / valid_blk_8x8_count) * 64; // Do not perform SB score manipulation for incomplete SBs as not valid signals sb_score = distortion; } else { distortion = pcs_ptr->parent_pcs_ptr->me_results[sb_index] ->me_candidate[RASTER_SCAN_CU_INDEX_64x64][0] .distortion; // Perform SB score manipulation for incomplete SBs for SQ mode sb_score = distortion; } } context_ptr->sb_score_array[sb_index] = sb_score; // Track MIN and MAX SB scores context_ptr->sb_min_score = MIN(sb_score, context_ptr->sb_min_score); context_ptr->sb_max_score = MAX(sb_score, context_ptr->sb_max_score); sb_tot_score += sb_score; } context_ptr->sb_average_score = (uint32_t)(sb_tot_score / pcs_ptr->sb_total_count_pix); } /****************************************************** * Set the target budget Input : cost per depth Output : budget per picture ******************************************************/ void set_target_budget_oq(PictureControlSet *pcs_ptr, ModeDecisionConfigurationContext *context_ptr) { uint32_t budget; // Luminosity-based budget boost - if P or b only; add 1 U for each 1 current-to-ref diff uint32_t luminosity_change_boost = 0; if (pcs_ptr->slice_type != I_SLICE) { if (pcs_ptr->parent_pcs_ptr->is_used_as_reference_flag) { EbReferenceObject *ref_obj__l0, *ref_obj__l1; ref_obj__l0 = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[REF_LIST_0][0]->object_ptr; ref_obj__l1 = (pcs_ptr->parent_pcs_ptr->slice_type == B_SLICE) ? (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[REF_LIST_1][0]->object_ptr : (EbReferenceObject *)EB_NULL; luminosity_change_boost = ABS(pcs_ptr->parent_pcs_ptr->average_intensity[0] - ref_obj__l0->average_intensity); luminosity_change_boost += (ref_obj__l1 != EB_NULL) ? ABS(pcs_ptr->parent_pcs_ptr->average_intensity[0] - ref_obj__l1->average_intensity) : 0; luminosity_change_boost = MAX(MAX_LUMINOSITY_BOOST, luminosity_change_boost); } } // Hsan: cross multiplication to derive budget_per_sb from sb_average_score; budget_per_sb range is [SB_PRED_OPEN_LOOP_COST,U_150], and sb_average_score range [0,HIGH_SB_SCORE] // Hsan: 3 segments [0,LOW_SB_SCORE], [LOW_SB_SCORE,MEDIUM_SB_SCORE] and [MEDIUM_SB_SCORE,U_150] uint32_t budget_per_sb; if (context_ptr->sb_average_score <= LOW_SB_SCORE) budget_per_sb = ((context_ptr->sb_average_score * (SB_OPEN_LOOP_COST - SB_PRED_OPEN_LOOP_COST)) / LOW_SB_SCORE) + SB_PRED_OPEN_LOOP_COST; else if (context_ptr->sb_average_score <= MEDIUM_SB_SCORE) budget_per_sb = (((context_ptr->sb_average_score - LOW_SB_SCORE) * (U_125 - SB_OPEN_LOOP_COST)) / (MEDIUM_SB_SCORE - LOW_SB_SCORE)) + SB_OPEN_LOOP_COST; else budget_per_sb = (((context_ptr->sb_average_score - MEDIUM_SB_SCORE) * (U_150 - U_125)) / (HIGH_SB_SCORE - MEDIUM_SB_SCORE)) + U_125; budget_per_sb = CLIP3( SB_PRED_OPEN_LOOP_COST, U_150, budget_per_sb + budget_per_sb_boost[context_ptr->adp_level] + luminosity_change_boost); //SVT_LOG("picture_number = %d\tsb_average_score = %d\n", pcs_ptr->picture_number, budget_per_sb); budget = pcs_ptr->sb_total_count_pix * budget_per_sb; context_ptr->budget = budget; } /****************************************************** * Assign a search method for each SB Input : SB score, detection signals Output : search method for each SB ******************************************************/ void derive_sb_md_mode(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr, ModeDecisionConfigurationContext *context_ptr) { // Configure ADP configure_adp(pcs_ptr, context_ptr); // Derive SB score derive_sb_score(pcs_ptr, context_ptr); // Set the target budget set_target_budget_oq(pcs_ptr, context_ptr); // Set the percentage based thresholds derive_default_segments(scs_ptr, context_ptr); // Perform Budgetting derive_optimal_budget_per_sb(scs_ptr, pcs_ptr, context_ptr); // Set the search method using the SB cost (mapping) derive_search_method(pcs_ptr, context_ptr); } /****************************************************** * Derive Mode Decision Config Settings for OQ Input : encoder mode and tune Output : EncDec Kernel signal(s) ******************************************************/ EbErrorType signal_derivation_mode_decision_config_kernel_oq( SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr, ModeDecisionConfigurationContext *context_ptr) { UNUSED(scs_ptr); EbErrorType return_error = EB_ErrorNone; context_ptr->adp_level = pcs_ptr->parent_pcs_ptr->enc_mode; if (pcs_ptr->parent_pcs_ptr->sc_content_detected) if (pcs_ptr->enc_mode <= ENC_M6) pcs_ptr->update_cdf = 1; else pcs_ptr->update_cdf = 0; else pcs_ptr->update_cdf = (pcs_ptr->parent_pcs_ptr->enc_mode <= ENC_M5) ? 1 : 0; if (pcs_ptr->update_cdf) assert(scs_ptr->cdf_mode == 0 && "use cdf_mode 0"); //Filter Intra Mode : 0: OFF 1: ON if (scs_ptr->seq_header.enable_filter_intra) pcs_ptr->pic_filter_intra_mode = pcs_ptr->parent_pcs_ptr->sc_content_detected == 0 && pcs_ptr->temporal_layer_index == 0 ? 1 : 0; else pcs_ptr->pic_filter_intra_mode = 0; FrameHeader *frm_hdr = &pcs_ptr->parent_pcs_ptr->frm_hdr; frm_hdr->allow_high_precision_mv = pcs_ptr->enc_mode <= ENC_M7 && frm_hdr->quantization_params.base_q_idx < HIGH_PRECISION_MV_QTHRESH && (scs_ptr->input_resolution == INPUT_SIZE_576p_RANGE_OR_LOWER) ? 1 : 0; EbBool enable_wm; if (pcs_ptr->parent_pcs_ptr->sc_content_detected) enable_wm = EB_FALSE; else #if WARP_IMPROVEMENT enable_wm = (pcs_ptr->parent_pcs_ptr->enc_mode <= ENC_M2 || #else enable_wm = (pcs_ptr->parent_pcs_ptr->enc_mode == ENC_M0 || #endif (pcs_ptr->parent_pcs_ptr->enc_mode <= ENC_M5 && pcs_ptr->parent_pcs_ptr->temporal_layer_index == 0)) ? EB_TRUE : EB_FALSE; frm_hdr->allow_warped_motion = enable_wm && !(frm_hdr->frame_type == KEY_FRAME || frm_hdr->frame_type == INTRA_ONLY_FRAME) && !frm_hdr->error_resilient_mode; frm_hdr->is_motion_mode_switchable = frm_hdr->allow_warped_motion; // OBMC Level Settings // 0 OFF // 1 OBMC @(MVP, PME and ME) + 16 NICs // 2 OBMC @(MVP, PME and ME) + Opt NICs // 3 OBMC @(MVP, PME ) + Opt NICs // 4 OBMC @(MVP, PME ) + Opt2 NICs if (scs_ptr->static_config.enable_obmc) { if (pcs_ptr->parent_pcs_ptr->enc_mode == ENC_M0) pcs_ptr->parent_pcs_ptr->pic_obmc_mode = pcs_ptr->slice_type != I_SLICE ? 2 : 0; else if (pcs_ptr->parent_pcs_ptr->enc_mode <= ENC_M2) pcs_ptr->parent_pcs_ptr->pic_obmc_mode = pcs_ptr->parent_pcs_ptr->sc_content_detected == 0 && pcs_ptr->slice_type != I_SLICE ? 2 : 0; else pcs_ptr->parent_pcs_ptr->pic_obmc_mode = 0; #if MR_MODE pcs_ptr->parent_pcs_ptr->pic_obmc_mode = pcs_ptr->parent_pcs_ptr->sc_content_detected == 0 && pcs_ptr->slice_type != I_SLICE ? 1 : 0; #endif } else pcs_ptr->parent_pcs_ptr->pic_obmc_mode = 0; frm_hdr->is_motion_mode_switchable = frm_hdr->is_motion_mode_switchable || pcs_ptr->parent_pcs_ptr->pic_obmc_mode; return return_error; } void forward_sq_non4_blocks_to_md(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr) { uint32_t sb_index; EbBool split_flag; for (sb_index = 0; sb_index < pcs_ptr->sb_total_count_pix; ++sb_index) { MdcSbData *results_ptr = &pcs_ptr->mdc_sb_array[sb_index]; results_ptr->leaf_count = 0; uint32_t blk_index = pcs_ptr->slice_type == I_SLICE && scs_ptr->seq_header.sb_size == BLOCK_128X128 ? 17 : 0; while (blk_index < scs_ptr->max_block_cnt) { split_flag = EB_TRUE; const BlockGeom *blk_geom = get_blk_geom_mds(blk_index); //if the parentSq is inside inject this block if (pcs_ptr->parent_pcs_ptr->sb_geom[sb_index].block_is_inside_md_scan[blk_index]) { //int32_t offset_d1 = ns_blk_offset[(int32_t)from_shape_to_part[blk_geom->shape]]; //blk_ptr->best_d1_blk; // TOCKECK //int32_t num_d1_block = ns_blk_num[(int32_t)from_shape_to_part[blk_geom->shape]]; // context_ptr->blk_geom->totns; // TOCKECK // // // for (int32_t d1_itr = blk_it; d1_itr < blk_it + num_d1_block; d1_itr++) { // for (int32_t d1_itr = (int32_t)blk_index ; d1_itr < (int32_t)blk_index + num_d1_block ; d1_itr++) { results_ptr->leaf_data_array[results_ptr->leaf_count].tot_d1_blocks = 1; results_ptr->leaf_data_array[results_ptr->leaf_count].leaf_index = 0; //valid only for square 85 world. will be removed. results_ptr->leaf_data_array[results_ptr->leaf_count].mds_idx = blk_index; if (blk_geom->sq_size > 8) { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_TRUE; split_flag = EB_TRUE; } else { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_FALSE; split_flag = EB_FALSE; } } blk_index += split_flag ? d1_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128][blk_geom->depth] : ns_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128] [blk_geom->depth]; } } pcs_ptr->parent_pcs_ptr->average_qp = (uint8_t)pcs_ptr->parent_pcs_ptr->picture_qp; } void sb_forward_sq_non4_blocks_to_md(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr, uint32_t sb_index) { EbBool split_flag; MdcSbData *results_ptr = &pcs_ptr->mdc_sb_array[sb_index]; results_ptr->leaf_count = 0; uint32_t blk_index = pcs_ptr->slice_type == I_SLICE && scs_ptr->seq_header.sb_size == BLOCK_128X128 ? 17 : 0; while (blk_index < scs_ptr->max_block_cnt) { split_flag = EB_TRUE; const BlockGeom *blk_geom = get_blk_geom_mds(blk_index); if (pcs_ptr->parent_pcs_ptr->sb_geom[sb_index].block_is_inside_md_scan[blk_index]) { results_ptr->leaf_data_array[results_ptr->leaf_count].tot_d1_blocks = 1; results_ptr->leaf_data_array[results_ptr->leaf_count].leaf_index = 0; //valid only for square 85 world. will be removed. results_ptr->leaf_data_array[results_ptr->leaf_count].mds_idx = blk_index; if (blk_geom->sq_size > 8) { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_TRUE; split_flag = EB_TRUE; } else { results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_FALSE; split_flag = EB_FALSE; } } blk_index += split_flag ? d1_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128][blk_geom->depth] : ns_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128][blk_geom->depth]; } pcs_ptr->parent_pcs_ptr->average_qp = (uint8_t)pcs_ptr->parent_pcs_ptr->picture_qp; } void forward_all_c_blocks_to_md(SequenceControlSet *scs_ptr, PictureControlSet *pcs_ptr) { uint32_t sb_index; for (sb_index = 0; sb_index < pcs_ptr->sb_total_count_pix; ++sb_index) { MdcSbData *results_ptr = &pcs_ptr->mdc_sb_array[sb_index]; results_ptr->leaf_count = 0; uint32_t blk_index = 0; uint32_t tot_d1_blocks; while (blk_index < scs_ptr->max_block_cnt) { tot_d1_blocks = 0; const BlockGeom *blk_geom = get_blk_geom_mds(blk_index); //if the parentSq is inside inject this block uint8_t is_blk_allowed = pcs_ptr->slice_type != I_SLICE ? 1 : (blk_geom->sq_size < 128) ? 1 : 0; if (pcs_ptr->parent_pcs_ptr->sb_geom[sb_index].block_is_inside_md_scan[blk_index] && is_blk_allowed) { tot_d1_blocks = results_ptr->leaf_data_array[results_ptr->leaf_count].tot_d1_blocks = blk_geom->sq_size == 128 ? 17 : blk_geom->sq_size > 16 ? 25 : blk_geom->sq_size == 16 ? 17 : blk_geom->sq_size == 8 ? 1 : 1; for (uint32_t idx = 0; idx < tot_d1_blocks; ++idx) { blk_geom = get_blk_geom_mds(blk_index); //if the parentSq is inside inject this block if (pcs_ptr->parent_pcs_ptr->sb_geom[sb_index].block_is_inside_md_scan[blk_index]) { results_ptr->leaf_data_array[results_ptr->leaf_count].leaf_index = 0; //valid only for square 85 world. will be removed. results_ptr->leaf_data_array[results_ptr->leaf_count].mds_idx = blk_index; if (blk_geom->sq_size > 4) results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_TRUE; else results_ptr->leaf_data_array[results_ptr->leaf_count++].split_flag = EB_FALSE; } blk_index++; } } blk_index += (d1_depth_offset[scs_ptr->seq_header.sb_size == BLOCK_128X128][blk_geom->depth] - tot_d1_blocks); } } pcs_ptr->parent_pcs_ptr->average_qp = (uint8_t)pcs_ptr->parent_pcs_ptr->picture_qp; } void av1_set_ref_frame(MvReferenceFrame *rf, int8_t ref_frame_type); static INLINE int get_relative_dist(const OrderHintInfo *oh, int a, int b) { if (!oh->enable_order_hint) return 0; const int bits = oh->order_hint_bits; assert(bits >= 1); assert(a >= 0 && a < (1 << bits)); assert(b >= 0 && b < (1 << bits)); int diff = a - b; const int m = 1 << (bits - 1); diff = (diff & (m - 1)) - (diff & m); return diff; } static int get_block_position(Av1Common *cm, int *mi_r, int *mi_c, int blk_row, int blk_col, MV mv, int sign_bias) { const int base_blk_row = (blk_row >> 3) << 3; const int base_blk_col = (blk_col >> 3) << 3; const int row_offset = (mv.row >= 0) ? (mv.row >> (4 + MI_SIZE_LOG2)) : -((-mv.row) >> (4 + MI_SIZE_LOG2)); const int col_offset = (mv.col >= 0) ? (mv.col >> (4 + MI_SIZE_LOG2)) : -((-mv.col) >> (4 + MI_SIZE_LOG2)); const int row = (sign_bias == 1) ? blk_row - row_offset : blk_row + row_offset; const int col = (sign_bias == 1) ? blk_col - col_offset : blk_col + col_offset; if (row < 0 || row >= (cm->mi_rows >> 1) || col < 0 || col >= (cm->mi_cols >> 1)) return 0; if (row < base_blk_row - (MAX_OFFSET_HEIGHT >> 3) || row >= base_blk_row + 8 + (MAX_OFFSET_HEIGHT >> 3) || col < base_blk_col - (MAX_OFFSET_WIDTH >> 3) || col >= base_blk_col + 8 + (MAX_OFFSET_WIDTH >> 3)) return 0; *mi_r = row; *mi_c = col; return 1; } #define MFMV_STACK_SIZE 3 // Note: motion_filed_projection finds motion vectors of current frame's // reference frame, and projects them to current frame. To make it clear, // let's call current frame's reference frame as start frame. // Call Start frame's reference frames as reference frames. // Call ref_offset as frame distances between start frame and its reference // frames. static int motion_field_projection(Av1Common *cm, PictureControlSet *pcs_ptr, MvReferenceFrame start_frame, int dir) { TPL_MV_REF *tpl_mvs_base = pcs_ptr->tpl_mvs; int ref_offset[REF_FRAMES] = {0}; MvReferenceFrame rf[2]; av1_set_ref_frame(rf, start_frame); uint8_t list_idx0, ref_idx_l0; list_idx0 = get_list_idx(start_frame); ref_idx_l0 = get_ref_frame_idx(start_frame); EbReferenceObject *start_frame_buf = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[list_idx0][ref_idx_l0]->object_ptr; if (start_frame_buf == NULL) return 0; if (start_frame_buf->frame_type == KEY_FRAME || start_frame_buf->frame_type == INTRA_ONLY_FRAME) return 0; const int start_frame_order_hint = start_frame_buf->order_hint; const unsigned int *const ref_order_hints = &start_frame_buf->ref_order_hint[0]; const int cur_order_hint = pcs_ptr->parent_pcs_ptr->cur_order_hint; int start_to_current_frame_offset = get_relative_dist(&pcs_ptr->parent_pcs_ptr->scs_ptr->seq_header.order_hint_info, start_frame_order_hint, cur_order_hint); for (MvReferenceFrame rf = LAST_FRAME; rf <= INTER_REFS_PER_FRAME; ++rf) { ref_offset[rf] = get_relative_dist(&pcs_ptr->parent_pcs_ptr->scs_ptr->seq_header.order_hint_info, start_frame_order_hint, ref_order_hints[rf - LAST_FRAME]); } if (dir == 2) start_to_current_frame_offset = -start_to_current_frame_offset; MV_REF * mv_ref_base = start_frame_buf->mvs; const int mvs_rows = (cm->mi_rows + 1) >> 1; const int mvs_cols = (cm->mi_cols + 1) >> 1; for (int blk_row = 0; blk_row < mvs_rows; ++blk_row) { for (int blk_col = 0; blk_col < mvs_cols; ++blk_col) { MV_REF *mv_ref = &mv_ref_base[blk_row * mvs_cols + blk_col]; MV fwd_mv = mv_ref->mv.as_mv; if (mv_ref->ref_frame > INTRA_FRAME) { IntMv this_mv; int mi_r, mi_c; const int ref_frame_offset = ref_offset[mv_ref->ref_frame]; int pos_valid = abs(ref_frame_offset) <= MAX_FRAME_DISTANCE && ref_frame_offset > 0 && abs(start_to_current_frame_offset) <= MAX_FRAME_DISTANCE; if (pos_valid) { get_mv_projection( &this_mv.as_mv, fwd_mv, start_to_current_frame_offset, ref_frame_offset); pos_valid = get_block_position( cm, &mi_r, &mi_c, blk_row, blk_col, this_mv.as_mv, dir >> 1); } if (pos_valid) { const int mi_offset = mi_r * (cm->mi_stride >> 1) + mi_c; tpl_mvs_base[mi_offset].mfmv0.as_mv.row = fwd_mv.row; tpl_mvs_base[mi_offset].mfmv0.as_mv.col = fwd_mv.col; tpl_mvs_base[mi_offset].ref_frame_offset = ref_frame_offset; } } } } return 1; } void av1_setup_motion_field(Av1Common *cm, PictureControlSet *pcs_ptr) { const OrderHintInfo *const order_hint_info = &pcs_ptr->parent_pcs_ptr->scs_ptr->seq_header.order_hint_info; memset(pcs_ptr->ref_frame_side, 0, sizeof(pcs_ptr->ref_frame_side)); if (!order_hint_info->enable_order_hint) return; TPL_MV_REF *tpl_mvs_base = pcs_ptr->tpl_mvs; int size = ((cm->mi_rows + MAX_MIB_SIZE) >> 1) * (cm->mi_stride >> 1); for (int idx = 0; idx < size; ++idx) { tpl_mvs_base[idx].mfmv0.as_int = INVALID_MV; tpl_mvs_base[idx].ref_frame_offset = 0; } const int cur_order_hint = pcs_ptr->parent_pcs_ptr->cur_order_hint; const EbReferenceObject *ref_buf[INTER_REFS_PER_FRAME]; int ref_order_hint[INTER_REFS_PER_FRAME]; for (int ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) { const int ref_idx = ref_frame - LAST_FRAME; int order_hint = 0; uint8_t list_idx0, ref_idx_l0; list_idx0 = get_list_idx(ref_frame); ref_idx_l0 = get_ref_frame_idx(ref_frame); EbReferenceObject *buf = (EbReferenceObject *)pcs_ptr->ref_pic_ptr_array[list_idx0][ref_idx_l0]->object_ptr; if (buf != NULL) order_hint = buf->order_hint; ref_buf[ref_idx] = buf; ref_order_hint[ref_idx] = order_hint; if (get_relative_dist(order_hint_info, order_hint, cur_order_hint) > 0) pcs_ptr->ref_frame_side[ref_frame] = 1; else if (order_hint == cur_order_hint) pcs_ptr->ref_frame_side[ref_frame] = -1; } int ref_stamp = MFMV_STACK_SIZE - 1; if (ref_buf[LAST_FRAME - LAST_FRAME] != NULL) { const int alt_of_lst_order_hint = ref_buf[LAST_FRAME - LAST_FRAME]->ref_order_hint[ALTREF_FRAME - LAST_FRAME]; const int is_lst_overlay = (alt_of_lst_order_hint == ref_order_hint[GOLDEN_FRAME - LAST_FRAME]); if (!is_lst_overlay) motion_field_projection(cm, pcs_ptr, LAST_FRAME, 2); --ref_stamp; } if (get_relative_dist( order_hint_info, ref_order_hint[BWDREF_FRAME - LAST_FRAME], cur_order_hint) > 0) { if (motion_field_projection(cm, pcs_ptr, BWDREF_FRAME, 0)) --ref_stamp; } if (get_relative_dist( order_hint_info, ref_order_hint[ALTREF2_FRAME - LAST_FRAME], cur_order_hint) > 0) { if (motion_field_projection(cm, pcs_ptr, ALTREF2_FRAME, 0)) --ref_stamp; } if (get_relative_dist( order_hint_info, ref_order_hint[ALTREF_FRAME - LAST_FRAME], cur_order_hint) > 0 && ref_stamp >= 0) if (motion_field_projection(cm, pcs_ptr, ALTREF_FRAME, 0)) --ref_stamp; if (ref_stamp >= 0) motion_field_projection(cm, pcs_ptr, LAST2_FRAME, 2); } /* Mode Decision Configuration Kernel */ /********************************************************************************* * * @brief * The Mode Decision Configuration Process involves a number of initialization steps, * setting flags for a number of features, and determining the blocks to be considered * in subsequent MD stages. * * @par Description: * The Mode Decision Configuration Process involves a number of initialization steps, * setting flags for a number of features, and determining the blocks to be considered * in subsequent MD stages. Examples of flags that are set are the flags for filter intra, * eighth-pel, OBMC and warped motion and flags for updating the cumulative density functions * Examples of initializations include initializations for picture chroma QP offsets, * CDEF strength, self-guided restoration filter parameters, quantization parameters, * lambda arrays, mv and coefficient rate estimation arrays. * * The set of blocks to be processed in subsequent MD stages is decided in this process as a * function of the picture depth mode (pic_depth_mode). * * @param[in] Configurations * Configuration flags that are to be set * * @param[out] Initializations * Initializations for various flags and variables * ********************************************************************************/ void *mode_decision_configuration_kernel(void *input_ptr) { // Context & SCS & PCS EbThreadContext * thread_context_ptr = (EbThreadContext *)input_ptr; ModeDecisionConfigurationContext *context_ptr = (ModeDecisionConfigurationContext *)thread_context_ptr->priv; PictureControlSet * pcs_ptr; SequenceControlSet *scs_ptr; FrameHeader * frm_hdr; // Input EbObjectWrapper * rate_control_results_wrapper_ptr; RateControlResults *rate_control_results_ptr; // Output EbObjectWrapper *enc_dec_tasks_wrapper_ptr; EncDecTasks * enc_dec_tasks_ptr; for (;;) { // Get RateControl Results eb_get_full_object(context_ptr->rate_control_input_fifo_ptr, &rate_control_results_wrapper_ptr); rate_control_results_ptr = (RateControlResults *)rate_control_results_wrapper_ptr->object_ptr; pcs_ptr = (PictureControlSet *)rate_control_results_ptr->pcs_wrapper_ptr->object_ptr; scs_ptr = (SequenceControlSet *)pcs_ptr->scs_wrapper_ptr->object_ptr; if (pcs_ptr->parent_pcs_ptr->frm_hdr.use_ref_frame_mvs) av1_setup_motion_field(pcs_ptr->parent_pcs_ptr->av1_cm, pcs_ptr); frm_hdr = &pcs_ptr->parent_pcs_ptr->frm_hdr; // Mode Decision Configuration Kernel Signal(s) derivation signal_derivation_mode_decision_config_kernel_oq(scs_ptr, pcs_ptr, context_ptr); context_ptr->qp = pcs_ptr->picture_qp; pcs_ptr->parent_pcs_ptr->average_qp = 0; pcs_ptr->intra_coded_area = 0; // Compute picture and slice level chroma QP offsets set_slice_and_picture_chroma_qp_offsets( // HT done pcs_ptr); // Compute Tc, and Beta offsets for a given picture // Set reference cdef strength set_reference_cdef_strength(pcs_ptr); // Set reference sg ep set_reference_sg_ep(pcs_ptr); set_global_motion_field(pcs_ptr); eb_av1_qm_init(pcs_ptr->parent_pcs_ptr); Quants *const quants = &pcs_ptr->parent_pcs_ptr->quants; Dequants *const dequants = &pcs_ptr->parent_pcs_ptr->deq; eb_av1_set_quantizer(pcs_ptr->parent_pcs_ptr, frm_hdr->quantization_params.base_q_idx); eb_av1_build_quantizer((AomBitDepth)scs_ptr->static_config.encoder_bit_depth, frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_Y], frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_U], frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_U], frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_V], frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_V], quants, dequants); Quants *const quants_md = &pcs_ptr->parent_pcs_ptr->quants_md; Dequants *const dequants_md = &pcs_ptr->parent_pcs_ptr->deq_md; eb_av1_build_quantizer(pcs_ptr->hbd_mode_decision ? AOM_BITS_10 : AOM_BITS_8, frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_Y], frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_U], frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_U], frm_hdr->quantization_params.delta_q_dc[AOM_PLANE_V], frm_hdr->quantization_params.delta_q_ac[AOM_PLANE_V], quants_md, dequants_md); // Hsan: collapse spare code MdRateEstimationContext *md_rate_estimation_array; uint32_t entropy_coding_qp; // QP context_ptr->qp = pcs_ptr->picture_qp; // QP Index context_ptr->qp_index = (uint8_t)frm_hdr->quantization_params.base_q_idx; // Lambda Assignement uint32_t lambda_sse; uint32_t lambdasad_; (*av1_lambda_assignment_function_table[pcs_ptr->parent_pcs_ptr->pred_structure])( &lambdasad_, &lambda_sse, &lambdasad_, &lambda_sse, (uint8_t)pcs_ptr->parent_pcs_ptr->enhanced_picture_ptr->bit_depth, context_ptr->qp_index, pcs_ptr->hbd_mode_decision); context_ptr->lambda = (uint64_t)lambdasad_; md_rate_estimation_array = pcs_ptr->md_rate_estimation_array; // Reset MD rate Estimation table to initial values by copying from md_rate_estimation_array if (context_ptr->is_md_rate_estimation_ptr_owner) { EB_FREE_ARRAY(context_ptr->md_rate_estimation_ptr); context_ptr->is_md_rate_estimation_ptr_owner = EB_FALSE; } context_ptr->md_rate_estimation_ptr = md_rate_estimation_array; entropy_coding_qp = frm_hdr->quantization_params.base_q_idx; if (pcs_ptr->parent_pcs_ptr->frm_hdr.primary_ref_frame != PRIMARY_REF_NONE) memcpy(pcs_ptr->coeff_est_entropy_coder_ptr->fc, &pcs_ptr->ref_frame_context[pcs_ptr->parent_pcs_ptr->frm_hdr.primary_ref_frame], sizeof(FRAME_CONTEXT)); else reset_entropy_coder(scs_ptr->encode_context_ptr, pcs_ptr->coeff_est_entropy_coder_ptr, entropy_coding_qp, pcs_ptr->slice_type); // Initial Rate Estimation of the syntax elements av1_estimate_syntax_rate(md_rate_estimation_array, pcs_ptr->slice_type == I_SLICE ? EB_TRUE : EB_FALSE, pcs_ptr->coeff_est_entropy_coder_ptr->fc); // Initial Rate Estimation of the Motion vectors av1_estimate_mv_rate( pcs_ptr, md_rate_estimation_array, pcs_ptr->coeff_est_entropy_coder_ptr->fc); // Initial Rate Estimation of the quantized coefficients av1_estimate_coefficients_rate(md_rate_estimation_array, pcs_ptr->coeff_est_entropy_coder_ptr->fc); if (pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_SB_SWITCH_DEPTH_MODE) { derive_sb_md_mode(scs_ptr, pcs_ptr, context_ptr); for (int sb_index = 0; sb_index < pcs_ptr->sb_total_count; ++sb_index) { if (pcs_ptr->parent_pcs_ptr->sb_depth_mode_array[sb_index] == SB_SQ_BLOCKS_DEPTH_MODE) { sb_forward_sq_blocks_to_md(scs_ptr, pcs_ptr, sb_index); } else if (pcs_ptr->parent_pcs_ptr->sb_depth_mode_array[sb_index] == SB_SQ_NON4_BLOCKS_DEPTH_MODE) { sb_forward_sq_non4_blocks_to_md(scs_ptr, pcs_ptr, sb_index); } else { perform_early_sb_partitionning_sb(context_ptr, scs_ptr, pcs_ptr, sb_index); } } } else if (pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_ALL_DEPTH_MODE || pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_MULTI_PASS_PD_MODE_0 || pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_MULTI_PASS_PD_MODE_1 || pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_MULTI_PASS_PD_MODE_2 || pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_MULTI_PASS_PD_MODE_3) { forward_all_blocks_to_md(scs_ptr, pcs_ptr); } else if (pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_ALL_C_DEPTH_MODE) { forward_all_c_blocks_to_md(scs_ptr, pcs_ptr); } else if (pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_SQ_DEPTH_MODE) { forward_sq_blocks_to_md(scs_ptr, pcs_ptr); } else if (pcs_ptr->parent_pcs_ptr->pic_depth_mode == PIC_SQ_NON4_DEPTH_MODE) { forward_sq_non4_blocks_to_md(scs_ptr, pcs_ptr); } else if (pcs_ptr->parent_pcs_ptr->pic_depth_mode >= PIC_OPEN_LOOP_DEPTH_MODE) { // Predict the SB partitionning perform_early_sb_partitionning( // HT done context_ptr, scs_ptr, pcs_ptr); } else { // (pcs_ptr->parent_pcs_ptr->mdMode == PICT_BDP_DEPTH_MODE || pcs_ptr->parent_pcs_ptr->mdMode == PICT_LIGHT_BDP_DEPTH_MODE ) pcs_ptr->parent_pcs_ptr->average_qp = (uint8_t)pcs_ptr->parent_pcs_ptr->picture_qp; } if (frm_hdr->allow_intrabc) { int i; int speed = 1; SpeedFeatures *sf = &pcs_ptr->sf; sf->allow_exhaustive_searches = 1; const int mesh_speed = AOMMIN(speed, MAX_MESH_SPEED); //if (cpi->twopass.fr_content_type == FC_GRAPHICS_ANIMATION) // sf->exhaustive_searches_thresh = (1 << 24); //else sf->exhaustive_searches_thresh = (1 << 25); sf->max_exaustive_pct = good_quality_max_mesh_pct[mesh_speed]; if (mesh_speed > 0) sf->exhaustive_searches_thresh = sf->exhaustive_searches_thresh << 1; for (i = 0; i < MAX_MESH_STEP; ++i) { sf->mesh_patterns[i].range = good_quality_mesh_patterns[mesh_speed][i].range; sf->mesh_patterns[i].interval = good_quality_mesh_patterns[mesh_speed][i].interval; } if (pcs_ptr->slice_type == I_SLICE) { for (i = 0; i < MAX_MESH_STEP; ++i) { sf->mesh_patterns[i].range = intrabc_mesh_patterns[mesh_speed][i].range; sf->mesh_patterns[i].interval = intrabc_mesh_patterns[mesh_speed][i].interval; } sf->max_exaustive_pct = intrabc_max_mesh_pct[mesh_speed]; } { // add to hash table const int pic_width = pcs_ptr->parent_pcs_ptr->aligned_width; const int pic_height = pcs_ptr->parent_pcs_ptr->aligned_height; uint32_t *block_hash_values[2][2]; int8_t * is_block_same[2][3]; int k, j; for (k = 0; k < 2; k++) { for (j = 0; j < 2; j++) block_hash_values[k][j] = malloc(sizeof(uint32_t) * pic_width * pic_height); for (j = 0; j < 3; j++) is_block_same[k][j] = malloc(sizeof(int8_t) * pic_width * pic_height); } //pcs_ptr->hash_table.p_lookup_table = NULL; //av1_hash_table_create(&pcs_ptr->hash_table); Yv12BufferConfig cpi_source; link_eb_to_aom_buffer_desc_8bit(pcs_ptr->parent_pcs_ptr->enhanced_picture_ptr, &cpi_source); av1_crc_calculator_init(&pcs_ptr->crc_calculator1, 24, 0x5D6DCB); av1_crc_calculator_init(&pcs_ptr->crc_calculator2, 24, 0x864CFB); av1_generate_block_2x2_hash_value( &cpi_source, block_hash_values[0], is_block_same[0], pcs_ptr); av1_generate_block_hash_value(&cpi_source, 4, block_hash_values[0], block_hash_values[1], is_block_same[0], is_block_same[1], pcs_ptr); av1_add_to_hash_map_by_row_with_precal_data(&pcs_ptr->hash_table, block_hash_values[1], is_block_same[1][2], pic_width, pic_height, 4); av1_generate_block_hash_value(&cpi_source, 8, block_hash_values[1], block_hash_values[0], is_block_same[1], is_block_same[0], pcs_ptr); av1_add_to_hash_map_by_row_with_precal_data(&pcs_ptr->hash_table, block_hash_values[0], is_block_same[0][2], pic_width, pic_height, 8); av1_generate_block_hash_value(&cpi_source, 16, block_hash_values[0], block_hash_values[1], is_block_same[0], is_block_same[1], pcs_ptr); av1_add_to_hash_map_by_row_with_precal_data(&pcs_ptr->hash_table, block_hash_values[1], is_block_same[1][2], pic_width, pic_height, 16); av1_generate_block_hash_value(&cpi_source, 32, block_hash_values[1], block_hash_values[0], is_block_same[1], is_block_same[0], pcs_ptr); av1_add_to_hash_map_by_row_with_precal_data(&pcs_ptr->hash_table, block_hash_values[0], is_block_same[0][2], pic_width, pic_height, 32); av1_generate_block_hash_value(&cpi_source, 64, block_hash_values[0], block_hash_values[1], is_block_same[0], is_block_same[1], pcs_ptr); av1_add_to_hash_map_by_row_with_precal_data(&pcs_ptr->hash_table, block_hash_values[1], is_block_same[1][2], pic_width, pic_height, 64); av1_generate_block_hash_value(&cpi_source, 128, block_hash_values[1], block_hash_values[0], is_block_same[1], is_block_same[0], pcs_ptr); av1_add_to_hash_map_by_row_with_precal_data(&pcs_ptr->hash_table, block_hash_values[0], is_block_same[0][2], pic_width, pic_height, 128); for (k = 0; k < 2; k++) { for (j = 0; j < 2; j++) free(block_hash_values[k][j]); for (j = 0; j < 3; j++) free(is_block_same[k][j]); } } eb_av1_init3smotion_compensation( &pcs_ptr->ss_cfg, pcs_ptr->parent_pcs_ptr->enhanced_picture_ptr->stride_y); } // Post the results to the MD processes #if TILES_PARALLEL uint16_t tg_count = pcs_ptr->parent_pcs_ptr->tile_group_cols * pcs_ptr->parent_pcs_ptr->tile_group_rows; for (uint16_t tile_group_idx = 0; tile_group_idx < tg_count; tile_group_idx++) { eb_get_empty_object(context_ptr->mode_decision_configuration_output_fifo_ptr, &enc_dec_tasks_wrapper_ptr); enc_dec_tasks_ptr = (EncDecTasks *)enc_dec_tasks_wrapper_ptr->object_ptr; enc_dec_tasks_ptr->pcs_wrapper_ptr = rate_control_results_ptr->pcs_wrapper_ptr; enc_dec_tasks_ptr->input_type = ENCDEC_TASKS_MDC_INPUT; enc_dec_tasks_ptr->tile_group_index = tile_group_idx; // Post the Full Results Object eb_post_full_object(enc_dec_tasks_wrapper_ptr); } #else eb_get_empty_object(context_ptr->mode_decision_configuration_output_fifo_ptr, &enc_dec_tasks_wrapper_ptr); enc_dec_tasks_ptr = (EncDecTasks *)enc_dec_tasks_wrapper_ptr->object_ptr; enc_dec_tasks_ptr->pcs_wrapper_ptr = rate_control_results_ptr->pcs_wrapper_ptr; enc_dec_tasks_ptr->input_type = ENCDEC_TASKS_MDC_INPUT; // Post the Full Results Object eb_post_full_object(enc_dec_tasks_wrapper_ptr); #endif // Release Rate Control Results eb_release_object(rate_control_results_wrapper_ptr); } return EB_NULL; }
886149.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_portable.h" #include "apr_strings.h" #include "apr_thread_proc.h" #include "apr_signal.h" #define APR_WANT_STDIO #define APR_WANT_STRFUNC #include "apr_want.h" #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #include "ap_config.h" #include "httpd.h" #include "mpm_default.h" #include "http_main.h" #include "http_log.h" #include "http_config.h" #include "http_core.h" /* for get_remote_host */ #include "http_connection.h" #include "scoreboard.h" #include "ap_mpm.h" #include "util_mutex.h" #include "unixd.h" #include "mpm_common.h" #include "ap_listen.h" #include "ap_mmn.h" #include "apr_poll.h" #include "util_time.h" #include <stdlib.h> #ifdef HAVE_TIME_H #include <time.h> #endif #ifdef HAVE_SYS_PROCESSOR_H #include <sys/processor.h> /* for bindprocessor() */ #endif #include <signal.h> #include <sys/times.h> /* Limit on the total --- clients will be locked out if more servers than * this are needed. It is intended solely to keep the server from crashing * when things get out of hand. * * We keep a hard maximum number of servers, for two reasons --- first off, * in case something goes seriously wrong, we want to stop the fork bomb * short of actually crashing the machine we're running on by filling some * kernel table. Secondly, it keeps the size of the scoreboard file small * enough that we can read the whole thing without worrying too much about * the overhead. */ #ifndef DEFAULT_SERVER_LIMIT #define DEFAULT_SERVER_LIMIT 256 #endif /* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT. We want * some sort of compile-time limit to help catch typos. */ #ifndef MAX_SERVER_LIMIT #define MAX_SERVER_LIMIT 200000 #endif #ifndef HARD_THREAD_LIMIT #define HARD_THREAD_LIMIT 1 #endif /* config globals */ static int ap_daemons_to_start=0; static int ap_daemons_min_free=0; static int ap_daemons_max_free=0; static int ap_daemons_limit=0; /* MaxRequestWorkers */ static int server_limit = 0; typedef struct prefork_child_bucket { ap_pod_t *pod; ap_listen_rec *listeners; apr_proc_mutex_t *mutex; } prefork_child_bucket; static prefork_child_bucket *my_bucket; /* Current child bucket */ /* data retained by prefork across load/unload of the module * allocated on first call to pre-config hook; located on * subsequent calls to pre-config hook */ typedef struct prefork_retained_data { ap_unixd_mpm_retained_data *mpm; apr_pool_t *gen_pool; /* generation pool (children start->stop lifetime) */ prefork_child_bucket *buckets; /* children buckets (reset per generation) */ int first_server_limit; int maxclients_reported; /* * The max child slot ever assigned, preserved across restarts. Necessary * to deal with MaxRequestWorkers changes across AP_SIG_GRACEFUL restarts. We * use this value to optimize routines that have to scan the entire scoreboard. */ int max_daemons_limit; /* * idle_spawn_rate is the number of children that will be spawned on the * next maintenance cycle if there aren't enough idle servers. It is * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by * without the need to spawn. */ int idle_spawn_rate; #ifndef MAX_SPAWN_RATE #define MAX_SPAWN_RATE (32) #endif int hold_off_on_exponential_spawning; } prefork_retained_data; static prefork_retained_data *retained; #define MPM_CHILD_PID(i) (ap_scoreboard_image->parent[i].pid) /* one_process --- debugging mode variable; can be set from the command line * with the -X flag. If set, this gets you the child_main loop running * in the process which originally started up (no detach, no make_child), * which is a pretty nice debugging environment. (You'll get a SIGHUP * early in standalone_main; just continue through. This is the server * trying to kill off any child processes which it might have lying * around --- Apache doesn't keep track of their pids, it just sends * SIGHUP to the process group, ignoring it in the root process. * Continue through and you'll be fine.). */ static int one_process = 0; static apr_pool_t *pconf; /* Pool for config stuff */ static apr_pool_t *pchild; /* Pool for httpd child stuff */ static pid_t ap_my_pid; /* it seems silly to call getpid all the time */ static pid_t parent_pid; static int my_child_num; #ifdef GPROF /* * change directory for gprof to plop the gmon.out file * configure in httpd.conf: * GprofDir $RuntimeDir/ -> $ServerRoot/$RuntimeDir/gmon.out * GprofDir $RuntimeDir/% -> $ServerRoot/$RuntimeDir/gprof.$pid/gmon.out */ static void chdir_for_gprof(void) { core_server_config *sconf = ap_get_core_module_config(ap_server_conf->module_config); char *dir = sconf->gprof_dir; const char *use_dir; if(dir) { apr_status_t res; char *buf = NULL ; int len = strlen(sconf->gprof_dir) - 1; if(*(dir + len) == '%') { dir[len] = '\0'; buf = ap_append_pid(pconf, dir, "gprof."); } use_dir = ap_server_root_relative(pconf, buf ? buf : dir); res = apr_dir_make(use_dir, APR_UREAD | APR_UWRITE | APR_UEXECUTE | APR_GREAD | APR_GEXECUTE | APR_WREAD | APR_WEXECUTE, pconf); if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) { ap_log_error(APLOG_MARK, APLOG_ERR, res, ap_server_conf, APLOGNO(00142) "gprof: error creating directory %s", dir); } } else { use_dir = ap_runtime_dir_relative(pconf, ""); } chdir(use_dir); } #else #define chdir_for_gprof() #endif static void prefork_note_child_killed(int childnum, pid_t pid, ap_generation_t gen) { AP_DEBUG_ASSERT(childnum != -1); /* no scoreboard squatting with this MPM */ ap_run_child_status(ap_server_conf, ap_scoreboard_image->parent[childnum].pid, ap_scoreboard_image->parent[childnum].generation, childnum, MPM_CHILD_EXITED); ap_scoreboard_image->parent[childnum].pid = 0; } static void prefork_note_child_started(int slot, pid_t pid) { ap_generation_t gen = retained->mpm->my_generation; ap_scoreboard_image->parent[slot].pid = pid; ap_scoreboard_image->parent[slot].generation = gen; ap_run_child_status(ap_server_conf, pid, gen, slot, MPM_CHILD_STARTED); } /* a clean exit from a child with proper cleanup */ static void clean_child_exit(int code) __attribute__ ((noreturn)); static void clean_child_exit(int code) { apr_signal(SIGHUP, SIG_IGN); apr_signal(SIGTERM, SIG_IGN); retained->mpm->mpm_state = AP_MPMQ_STOPPING; if (code == 0) { ap_run_child_stopping(pchild, 0); } if (pchild) { apr_pool_destroy(pchild); /* * Be safe in case someone still uses afterwards or we get here again. * Should not happen. */ pchild = NULL; } if (one_process) { prefork_note_child_killed(/* slot */ 0, 0, 0); } ap_mpm_pod_close(my_bucket->pod); chdir_for_gprof(); exit(code); } static apr_status_t accept_mutex_on(void) { apr_status_t rv = apr_proc_mutex_lock(my_bucket->mutex); if (rv != APR_SUCCESS) { const char *msg = "couldn't grab the accept mutex"; if (retained->mpm->my_generation != ap_scoreboard_image->global->running_generation) { ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(00143) "%s", msg); clean_child_exit(0); } else { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(00144) "%s", msg); exit(APEXIT_CHILDFATAL); } } return APR_SUCCESS; } static apr_status_t accept_mutex_off(void) { apr_status_t rv = apr_proc_mutex_unlock(my_bucket->mutex); if (rv != APR_SUCCESS) { const char *msg = "couldn't release the accept mutex"; if (retained->mpm->my_generation != ap_scoreboard_image->global->running_generation) { ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(00145) "%s", msg); /* don't exit here... we have a connection to * process, after which point we'll see that the * generation changed and we'll exit cleanly */ } else { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(00146) "%s", msg); exit(APEXIT_CHILDFATAL); } } return APR_SUCCESS; } /* On some architectures it's safe to do unserialized accept()s in the single * Listen case. But it's never safe to do it in the case where there's * multiple Listen statements. Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT * when it's safe in the single Listen case. */ #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT #define SAFE_ACCEPT(stmt) (ap_listeners->next ? (stmt) : APR_SUCCESS) #else #define SAFE_ACCEPT(stmt) (stmt) #endif static int prefork_query(int query_code, int *result, apr_status_t *rv) { *rv = APR_SUCCESS; switch(query_code){ case AP_MPMQ_MAX_DAEMON_USED: *result = ap_daemons_limit; break; case AP_MPMQ_IS_THREADED: *result = AP_MPMQ_NOT_SUPPORTED; break; case AP_MPMQ_IS_FORKED: *result = AP_MPMQ_DYNAMIC; break; case AP_MPMQ_HARD_LIMIT_DAEMONS: *result = server_limit; break; case AP_MPMQ_HARD_LIMIT_THREADS: *result = HARD_THREAD_LIMIT; break; case AP_MPMQ_MAX_THREADS: *result = 1; break; case AP_MPMQ_MIN_SPARE_DAEMONS: *result = ap_daemons_min_free; break; case AP_MPMQ_MIN_SPARE_THREADS: *result = 0; break; case AP_MPMQ_MAX_SPARE_DAEMONS: *result = ap_daemons_max_free; break; case AP_MPMQ_MAX_SPARE_THREADS: *result = 0; break; case AP_MPMQ_MAX_REQUESTS_DAEMON: *result = ap_max_requests_per_child; break; case AP_MPMQ_MAX_DAEMONS: *result = ap_daemons_limit; break; case AP_MPMQ_MPM_STATE: *result = retained->mpm->mpm_state; break; case AP_MPMQ_GENERATION: *result = retained->mpm->my_generation; break; default: *rv = APR_ENOTIMPL; break; } return OK; } static const char *prefork_get_name(void) { return "prefork"; } /***************************************************************** * Connection structures and accounting... */ static void just_die(int sig) { clean_child_exit(0); } /* volatile because it's updated from a signal handler */ static int volatile die_now = 0; static void stop_listening(int sig) { retained->mpm->mpm_state = AP_MPMQ_STOPPING; ap_close_listeners_ex(my_bucket->listeners); /* For a graceful stop, we want the child to exit when done */ die_now = 1; } /***************************************************************** * Child process main loop. * The following vars are static to avoid getting clobbered by longjmp(); * they are really private to child_main. */ static int requests_this_child; static int num_listensocks = 0; #if APR_HAS_THREADS static void child_sigmask(sigset_t *new_mask, sigset_t *old_mask) { #if defined(SIGPROCMASK_SETS_THREAD_MASK) sigprocmask(SIG_SETMASK, new_mask, old_mask); #else pthread_sigmask(SIG_SETMASK, new_mask, old_mask); #endif } #endif static void child_main(int child_num_arg, int child_bucket) { #if APR_HAS_THREADS apr_thread_t *thd = NULL; apr_os_thread_t osthd; sigset_t sig_mask; #endif apr_pool_t *ptrans; apr_allocator_t *allocator; apr_status_t status; int i; ap_listen_rec *lr; apr_pollset_t *pollset; ap_sb_handle_t *sbh; apr_bucket_alloc_t *bucket_alloc; int last_poll_idx = 0; const char *lockfile; /* for benefit of any hooks that run as this child initializes */ retained->mpm->mpm_state = AP_MPMQ_STARTING; my_child_num = child_num_arg; ap_my_pid = getpid(); requests_this_child = 0; ap_fatal_signal_child_setup(ap_server_conf); /* Get a sub context for global allocations in this child, so that * we can have cleanups occur when the child exits. */ apr_allocator_create(&allocator); apr_allocator_max_free_set(allocator, ap_max_mem_free); apr_pool_create_ex(&pchild, pconf, NULL, allocator); apr_allocator_owner_set(allocator, pchild); apr_pool_tag(pchild, "pchild"); #if APR_HAS_THREADS osthd = apr_os_thread_current(); apr_os_thread_put(&thd, &osthd, pchild); #endif apr_pool_create(&ptrans, pchild); apr_pool_tag(ptrans, "transaction"); /* close unused listeners and pods */ for (i = 0; i < retained->mpm->num_buckets; i++) { if (i != child_bucket) { ap_close_listeners_ex(retained->buckets[i].listeners); ap_mpm_pod_close(retained->buckets[i].pod); } } /* needs to be done before we switch UIDs so we have permissions */ ap_reopen_scoreboard(pchild, NULL, 0); status = SAFE_ACCEPT(apr_proc_mutex_child_init(&my_bucket->mutex, apr_proc_mutex_lockfile(my_bucket->mutex), pchild)); if (status != APR_SUCCESS) { lockfile = apr_proc_mutex_lockfile(my_bucket->mutex); ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(00155) "Couldn't initialize cross-process lock in child " "(%s) (%s)", lockfile ? lockfile : "none", apr_proc_mutex_name(my_bucket->mutex)); clean_child_exit(APEXIT_CHILDFATAL); } if (ap_run_drop_privileges(pchild, ap_server_conf)) { clean_child_exit(APEXIT_CHILDFATAL); } #if APR_HAS_THREADS /* Save the signal mask and block all the signals from being received by * threads potentially created in child_init() hooks (e.g. mod_watchdog). */ child_sigmask(NULL, &sig_mask); { apr_status_t rv; rv = apr_setup_signal_thread(); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(10271) "Couldn't initialize signal thread"); clean_child_exit(APEXIT_CHILDFATAL); } } #endif /* APR_HAS_THREADS */ ap_run_child_init(pchild, ap_server_conf); #if APR_HAS_THREADS /* Restore the original signal mask for this main thread, the only one * that should possibly get interrupted by signals. */ child_sigmask(&sig_mask, NULL); #endif ap_create_sb_handle(&sbh, pchild, my_child_num, 0); (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL); /* Set up the pollfd array */ status = apr_pollset_create(&pollset, num_listensocks, pchild, APR_POLLSET_NOCOPY); if (status != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(00156) "Couldn't create pollset in child; check system or user limits"); clean_child_exit(APEXIT_CHILDSICK); /* assume temporary resource issue */ } for (lr = my_bucket->listeners, i = num_listensocks; i--; lr = lr->next) { apr_pollfd_t *pfd = apr_pcalloc(pchild, sizeof *pfd); pfd->desc_type = APR_POLL_SOCKET; pfd->desc.s = lr->sd; pfd->reqevents = APR_POLLIN; pfd->client_data = lr; status = apr_pollset_add(pollset, pfd); if (status != APR_SUCCESS) { /* If the child processed a SIGWINCH before setting up the * pollset, this error path is expected and harmless, * since the listener fd was already closed; so don't * pollute the logs in that case. */ if (!die_now) { ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(00157) "Couldn't add listener to pollset; check system or user limits"); clean_child_exit(APEXIT_CHILDSICK); } clean_child_exit(0); } lr->accept_func = ap_unixd_accept; } retained->mpm->mpm_state = AP_MPMQ_RUNNING; bucket_alloc = apr_bucket_alloc_create(pchild); /* die_now is set when AP_SIG_GRACEFUL is received in the child; * {shutdown,restart}_pending are set when a signal is received while * running in single process mode. */ while (!die_now && !retained->mpm->shutdown_pending && !retained->mpm->restart_pending) { conn_rec *current_conn; void *csd; /* * (Re)initialize this child to a pre-connection state. */ apr_pool_clear(ptrans); if ((ap_max_requests_per_child > 0 && requests_this_child++ >= ap_max_requests_per_child)) { clean_child_exit(0); } (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL); /* * Wait for an acceptable connection to arrive. */ /* Lock around "accept", if necessary */ SAFE_ACCEPT(accept_mutex_on()); if (num_listensocks == 1) { /* There is only one listener record, so refer to that one. */ lr = my_bucket->listeners; } else { /* multiple listening sockets - need to poll */ for (;;) { apr_int32_t numdesc; const apr_pollfd_t *pdesc; /* check for termination first so we don't sleep for a while in * poll if already signalled */ if (die_now /* in graceful stop/restart */ || retained->mpm->shutdown_pending || retained->mpm->restart_pending) { SAFE_ACCEPT(accept_mutex_off()); clean_child_exit(0); } /* timeout == 10 seconds to avoid a hang at graceful restart/stop * caused by the closing of sockets by the signal handler */ status = apr_pollset_poll(pollset, apr_time_from_sec(10), &numdesc, &pdesc); if (status != APR_SUCCESS) { if (APR_STATUS_IS_TIMEUP(status) || APR_STATUS_IS_EINTR(status)) { continue; } /* Single Unix documents select as returning errnos * EBADF, EINTR, and EINVAL... and in none of those * cases does it make sense to continue. In fact * on Linux 2.0.x we seem to end up with EFAULT * occasionally, and we'd loop forever due to it. */ ap_log_error(APLOG_MARK, APLOG_ERR, status, ap_server_conf, APLOGNO(00158) "apr_pollset_poll: (listen)"); SAFE_ACCEPT(accept_mutex_off()); clean_child_exit(APEXIT_CHILDSICK); } /* We can always use pdesc[0], but sockets at position N * could end up completely starved of attention in a very * busy server. Therefore, we round-robin across the * returned set of descriptors. While it is possible that * the returned set of descriptors might flip around and * continue to starve some sockets, we happen to know the * internal pollset implementation retains ordering * stability of the sockets. Thus, the round-robin should * ensure that a socket will eventually be serviced. */ if (last_poll_idx >= numdesc) last_poll_idx = 0; /* Grab a listener record from the client_data of the poll * descriptor, and advance our saved index to round-robin * the next fetch. * * ### hmm... this descriptor might have POLLERR rather * ### than POLLIN */ lr = pdesc[last_poll_idx++].client_data; goto got_fd; } } got_fd: /* if we accept() something we don't want to die, so we have to * defer the exit */ status = lr->accept_func(&csd, lr, ptrans); SAFE_ACCEPT(accept_mutex_off()); /* unlock after "accept" */ if (status == APR_EGENERAL) { /* resource shortage or should-not-occur occurred */ clean_child_exit(APEXIT_CHILDSICK); } if (ap_accept_error_is_nonfatal(status)) { ap_log_error(APLOG_MARK, APLOG_DEBUG, status, ap_server_conf, "accept() on client socket failed"); } if (status != APR_SUCCESS) { continue; } /* * We now have a connection, so set it up with the appropriate * socket options, file descriptors, and read/write buffers. */ current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh, bucket_alloc); if (current_conn) { #if APR_HAS_THREADS current_conn->current_thread = thd; #endif ap_process_connection(current_conn, csd); ap_lingering_close(current_conn); } /* Check the pod and the generation number after processing a * connection so that we'll go away if a graceful restart occurred * while we were processing the connection or we are the lucky * idle server process that gets to die. */ if (ap_mpm_pod_check(my_bucket->pod) == APR_SUCCESS) { /* selected as idle? */ die_now = 1; } else if (retained->mpm->my_generation != ap_scoreboard_image->global->running_generation) { /* restart? */ /* yeah, this could be non-graceful restart, in which case the * parent will kill us soon enough, but why bother checking? */ die_now = 1; } } apr_pool_clear(ptrans); /* kludge to avoid crash in APR reslist cleanup code */ clean_child_exit(0); } static int make_child(server_rec *s, int slot) { int bucket = slot % retained->mpm->num_buckets; int pid; if (slot + 1 > retained->max_daemons_limit) { retained->max_daemons_limit = slot + 1; } if (one_process) { my_bucket = &retained->buckets[0]; prefork_note_child_started(slot, getpid()); child_main(slot, 0); /* NOTREACHED */ ap_assert(0); return -1; } (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING, (request_rec *) NULL); #ifdef _OSD_POSIX /* BS2000 requires a "special" version of fork() before a setuid() call */ if ((pid = os_fork(ap_unixd_config.user_name)) == -1) { #else if ((pid = fork()) == -1) { #endif ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, APLOGNO(00159) "fork: Unable to fork new process"); /* fork didn't succeed. Fix the scoreboard or else * it will say SERVER_STARTING forever and ever */ (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD, (request_rec *) NULL); /* In case system resources are maxxed out, we don't want * Apache running away with the CPU trying to fork over and * over and over again. */ sleep(10); return -1; } if (!pid) { my_bucket = &retained->buckets[bucket]; #ifdef HAVE_BINDPROCESSOR /* by default AIX binds to a single processor * this bit unbinds children which will then bind to another cpu */ int status = bindprocessor(BINDPROCESS, (int)getpid(), PROCESSOR_CLASS_ANY); if (status != OK) { ap_log_error(APLOG_MARK, APLOG_DEBUG, errno, ap_server_conf, APLOGNO(00160) "processor unbind failed"); } #endif RAISE_SIGSTOP(MAKE_CHILD); AP_MONCONTROL(1); /* Disable the parent's signal handlers and set up proper handling in * the child. */ apr_signal(SIGHUP, just_die); apr_signal(SIGTERM, just_die); /* Ignore SIGINT in child. This fixes race-conditions in signals * handling when httpd is running on foreground and user hits ctrl+c. * In this case, SIGINT is sent to all children followed by SIGTERM * from the main process, which interrupts the SIGINT handler and * leads to inconsistency. */ apr_signal(SIGINT, SIG_IGN); /* The child process just closes listeners on AP_SIG_GRACEFUL. * The pod is used for signalling the graceful restart. */ apr_signal(AP_SIG_GRACEFUL, stop_listening); child_main(slot, bucket); } prefork_note_child_started(slot, pid); return 0; } /* start up a bunch of children */ static void startup_children(int number_to_start) { int i; for (i = 0; number_to_start && i < ap_daemons_limit; ++i) { if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) { continue; } if (make_child(ap_server_conf, i) < 0) { break; } --number_to_start; } } static void perform_idle_server_maintenance(apr_pool_t *p) { int i; int idle_count; worker_score *ws; int free_length; int free_slots[MAX_SPAWN_RATE]; int last_non_dead; int total_non_dead; /* initialize the free_list */ free_length = 0; idle_count = 0; last_non_dead = -1; total_non_dead = 0; for (i = 0; i < ap_daemons_limit; ++i) { int status; if (i >= retained->max_daemons_limit && free_length == retained->idle_spawn_rate) break; ws = &ap_scoreboard_image->servers[i][0]; status = ws->status; if (status == SERVER_DEAD) { /* try to keep children numbers as low as possible */ if (free_length < retained->idle_spawn_rate) { free_slots[free_length] = i; ++free_length; } } else { /* We consider a starting server as idle because we started it * at least a cycle ago, and if it still hasn't finished starting * then we're just going to swamp things worse by forking more. * So we hopefully won't need to fork more if we count it. * This depends on the ordering of SERVER_READY and SERVER_STARTING. */ if (status <= SERVER_READY) { ++ idle_count; } ++total_non_dead; last_non_dead = i; } } retained->max_daemons_limit = last_non_dead + 1; if (idle_count > ap_daemons_max_free) { static int bucket_kill_child_record = -1; /* kill off one child... we use the pod because that'll cause it to * shut down gracefully, in case it happened to pick up a request * while we were counting */ bucket_kill_child_record = (bucket_kill_child_record + 1) % retained->mpm->num_buckets; ap_mpm_pod_signal(retained->buckets[bucket_kill_child_record].pod); retained->idle_spawn_rate = 1; } else if (idle_count < ap_daemons_min_free) { /* terminate the free list */ if (free_length == 0) { /* only report this condition once */ if (!retained->maxclients_reported) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00161) "server reached MaxRequestWorkers setting, consider" " raising the MaxRequestWorkers setting"); retained->maxclients_reported = 1; } retained->idle_spawn_rate = 1; } else { if (retained->idle_spawn_rate >= 8) { ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00162) "server seems busy, (you may need " "to increase StartServers, or Min/MaxSpareServers), " "spawning %d children, there are %d idle, and " "%d total children", retained->idle_spawn_rate, idle_count, total_non_dead); } for (i = 0; i < free_length; ++i) { make_child(ap_server_conf, free_slots[i]); } /* the next time around we want to spawn twice as many if this * wasn't good enough, but not if we've just done a graceful */ if (retained->hold_off_on_exponential_spawning) { --retained->hold_off_on_exponential_spawning; } else if (retained->idle_spawn_rate < MAX_SPAWN_RATE) { retained->idle_spawn_rate *= 2; } } } else { retained->idle_spawn_rate = 1; } } /***************************************************************** * Executive routines. */ static int prefork_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s) { ap_listen_rec **listen_buckets = NULL; int num_buckets = retained->mpm->num_buckets; int remaining_children_to_start; apr_status_t rv; char id[16]; int i; ap_log_pid(pconf, ap_pid_fname); /* On first startup create gen_pool to satisfy the lifetime of the * parent's PODs and listeners; on restart stop the children from the * previous generation and clear gen_pool for the next one. */ if (!retained->gen_pool) { apr_pool_create(&retained->gen_pool, ap_pglobal); } else { if (retained->mpm->was_graceful) { /* kill off the idle ones */ for (i = 0; i < num_buckets; i++) { ap_mpm_pod_killpg(retained->buckets[i].pod, retained->max_daemons_limit); } /* This is mostly for debugging... so that we know what is still * gracefully dealing with existing request. This will break * in a very nasty way if we ever have the scoreboard totally * file-based (no shared memory) */ for (i = 0; i < ap_daemons_limit; ++i) { if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) { ap_scoreboard_image->servers[i][0].status = SERVER_GRACEFUL; /* Ask each child to close its listeners. * * NOTE: we use the scoreboard, because if we send SIGUSR1 * to every process in the group, this may include CGI's, * piped loggers, etc. They almost certainly won't handle * it gracefully. */ ap_mpm_safe_kill(ap_scoreboard_image->parent[i].pid, AP_SIG_GRACEFUL); } } } else { /* Kill 'em off */ if (ap_unixd_killpg(getpgrp(), SIGHUP) < 0) { ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00172) "killpg SIGHUP"); } ap_reclaim_child_processes(0, /* Not when just starting up */ prefork_note_child_killed); } apr_pool_clear(retained->gen_pool); retained->buckets = NULL; /* advance to the next generation */ /* XXX: we really need to make sure this new generation number isn't in * use by any of the children. */ ++retained->mpm->my_generation; } if (!retained->mpm->was_graceful) { if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) { retained->mpm->mpm_state = AP_MPMQ_STOPPING; return !OK; } num_buckets = (one_process) ? 1 : 0; /* one_process => one bucket */ retained->idle_spawn_rate = 1; /* reset idle_spawn_rate */ } /* Now on for the new generation. */ ap_scoreboard_image->global->running_generation = retained->mpm->my_generation; ap_unixd_mpm_set_signals(pconf, one_process); if ((rv = ap_duplicate_listeners(retained->gen_pool, ap_server_conf, &listen_buckets, &num_buckets))) { ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(03280) "could not duplicate listeners"); return !OK; } retained->buckets = apr_pcalloc(retained->gen_pool, num_buckets * sizeof(*retained->buckets)); for (i = 0; i < num_buckets; i++) { if (!one_process /* no POD in one_process mode */ && (rv = ap_mpm_pod_open(retained->gen_pool, &retained->buckets[i].pod))) { ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(03281) "could not open pipe-of-death"); return !OK; } /* Initialize cross-process accept lock (safe accept needed only) */ if ((rv = SAFE_ACCEPT((apr_snprintf(id, sizeof id, "%i", i), ap_proc_mutex_create(&retained->buckets[i].mutex, NULL, AP_ACCEPT_MUTEX_TYPE, id, s, retained->gen_pool, 0))))) { ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(03282) "could not create accept mutex"); return !OK; } retained->buckets[i].listeners = listen_buckets[i]; } retained->mpm->num_buckets = num_buckets; /* Don't thrash since num_buckets depends on the * system and the number of online CPU cores... */ if (ap_daemons_limit < num_buckets) ap_daemons_limit = num_buckets; if (ap_daemons_to_start < num_buckets) ap_daemons_to_start = num_buckets; if (ap_daemons_min_free < num_buckets) ap_daemons_min_free = num_buckets; if (ap_daemons_max_free < ap_daemons_min_free + num_buckets) ap_daemons_max_free = ap_daemons_min_free + num_buckets; /* If we're doing a graceful_restart then we're going to see a lot * of children exiting immediately when we get into the main loop * below (because we just sent them AP_SIG_GRACEFUL). This happens pretty * rapidly... and for each one that exits we'll start a new one until * we reach at least daemons_min_free. But we may be permitted to * start more than that, so we'll just keep track of how many we're * supposed to start up without the 1 second penalty between each fork. */ remaining_children_to_start = ap_daemons_to_start; if (remaining_children_to_start > ap_daemons_limit) { remaining_children_to_start = ap_daemons_limit; } if (!retained->mpm->was_graceful) { startup_children(remaining_children_to_start); remaining_children_to_start = 0; } else { /* give the system some time to recover before kicking into * exponential mode */ retained->hold_off_on_exponential_spawning = 10; } ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00163) "%s configured -- resuming normal operations", ap_get_server_description()); ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00164) "Server built: %s", ap_get_server_built()); ap_log_command_line(plog, s); ap_log_mpm_common(s); ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00165) "Accept mutex: %s (default: %s)", (retained->buckets[0].mutex) ? apr_proc_mutex_name(retained->buckets[0].mutex) : "none", apr_proc_mutex_defname()); retained->mpm->mpm_state = AP_MPMQ_RUNNING; if (one_process) { AP_MONCONTROL(1); make_child(ap_server_conf, 0); /* NOTREACHED */ ap_assert(0); return !OK; } while (!retained->mpm->restart_pending && !retained->mpm->shutdown_pending) { int child_slot; apr_exit_why_e exitwhy; int status, processed_status; /* this is a memory leak, but I'll fix it later. */ apr_proc_t pid; ap_wait_or_timeout(&exitwhy, &status, &pid, pconf, ap_server_conf); /* XXX: if it takes longer than 1 second for all our children * to start up and get into IDLE state then we may spawn an * extra child */ if (pid.pid != -1) { processed_status = ap_process_child_status(&pid, exitwhy, status); child_slot = ap_find_child_by_pid(&pid); if (processed_status == APEXIT_CHILDFATAL) { /* fix race condition found in PR 39311 * A child created at the same time as a graceful happens * can find the lock missing and create a fatal error. * It is not fatal for the last generation to be in this state. */ if (child_slot < 0 || ap_get_scoreboard_process(child_slot)->generation == retained->mpm->my_generation) { retained->mpm->mpm_state = AP_MPMQ_STOPPING; return !OK; } else { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(00166) "Ignoring fatal error in child of previous " "generation (pid %ld).", (long)pid.pid); } } /* non-fatal death... note that it's gone in the scoreboard. */ if (child_slot >= 0) { (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD, (request_rec *) NULL); prefork_note_child_killed(child_slot, 0, 0); if (processed_status == APEXIT_CHILDSICK) { /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc) * cut the fork rate to the minimum */ retained->idle_spawn_rate = 1; } else if (remaining_children_to_start && child_slot < ap_daemons_limit) { /* we're still doing a 1-for-1 replacement of dead * children with new children */ make_child(ap_server_conf, child_slot); --remaining_children_to_start; } #if APR_HAS_OTHER_CHILD } else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH, status) == APR_SUCCESS) { /* handled */ #endif } else if (retained->mpm->was_graceful) { /* Great, we've probably just lost a slot in the * scoreboard. Somehow we don't know about this * child. */ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(00167) "long lost child came home! (pid %ld)", (long)pid.pid); } /* Don't perform idle maintenance when a child dies, * only do it when there's a timeout. Remember only a * finite number of children can die, and it's pretty * pathological for a lot to die suddenly. */ continue; } else if (remaining_children_to_start) { /* we hit a 1 second timeout in which none of the previous * generation of children needed to be reaped... so assume * they're all done, and pick up the slack if any is left. */ startup_children(remaining_children_to_start); remaining_children_to_start = 0; /* In any event we really shouldn't do the code below because * few of the servers we just started are in the IDLE state * yet, so we'd mistakenly create an extra server. */ continue; } perform_idle_server_maintenance(pconf); } retained->mpm->mpm_state = AP_MPMQ_STOPPING; if (retained->mpm->shutdown_pending && retained->mpm->is_ungraceful) { /* Time to shut down: * Kill child processes, tell them to call child_exit, etc... */ if (ap_unixd_killpg(getpgrp(), SIGTERM) < 0) { ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(00168) "killpg SIGTERM"); } ap_reclaim_child_processes(1, /* Start with SIGTERM */ prefork_note_child_killed); /* cleanup pid file on normal shutdown */ ap_remove_pid(pconf, ap_pid_fname); ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00169) "caught SIGTERM, shutting down"); return DONE; } if (retained->mpm->shutdown_pending) { /* Time to perform a graceful shut down: * Reap the inactive children, and ask the active ones * to close their listeners, then wait until they are * all done to exit. */ int active_children; apr_time_t cutoff = 0; /* Stop listening */ ap_close_listeners(); /* kill off the idle ones */ for (i = 0; i < num_buckets; i++) { ap_mpm_pod_killpg(retained->buckets[i].pod, retained->max_daemons_limit); } /* Send SIGUSR1 to the active children */ active_children = 0; for (i = 0; i < ap_daemons_limit; ++i) { if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) { /* Ask each child to close its listeners. */ ap_mpm_safe_kill(MPM_CHILD_PID(i), AP_SIG_GRACEFUL); active_children++; } } /* Allow each child which actually finished to exit */ ap_relieve_child_processes(prefork_note_child_killed); /* cleanup pid file */ ap_remove_pid(pconf, ap_pid_fname); ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00170) "caught " AP_SIG_GRACEFUL_STOP_STRING ", shutting down gracefully"); if (ap_graceful_shutdown_timeout) { cutoff = apr_time_now() + apr_time_from_sec(ap_graceful_shutdown_timeout); } /* Don't really exit until each child has finished */ retained->mpm->shutdown_pending = 0; do { /* Pause for a second */ sleep(1); /* Relieve any children which have now exited */ ap_relieve_child_processes(prefork_note_child_killed); active_children = 0; for (i = 0; i < ap_daemons_limit; ++i) { if (ap_mpm_safe_kill(MPM_CHILD_PID(i), 0) == APR_SUCCESS) { active_children = 1; /* Having just one child is enough to stay around */ break; } } } while (!retained->mpm->shutdown_pending && active_children && (!ap_graceful_shutdown_timeout || apr_time_now() < cutoff)); /* We might be here because we received SIGTERM, either * way, try and make sure that all of our processes are * really dead. */ ap_unixd_killpg(getpgrp(), SIGTERM); return DONE; } /* we've been told to restart */ if (one_process) { /* not worth thinking about */ return DONE; } if (!retained->mpm->is_ungraceful) { ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00171) "Graceful restart requested, doing restart"); } else { ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00173) "SIGHUP received. Attempting to restart"); } return OK; } /* This really should be a post_config hook, but the error log is already * redirected by that point, so we need to do this in the open_logs phase. */ static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { int startup = 0; int level_flags = 0; pconf = p; /* the reverse of pre_config, we want this only the first time around */ if (retained->mpm->module_loads == 1) { startup = 1; level_flags |= APLOG_STARTUP; } if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) { ap_log_error(APLOG_MARK, APLOG_ALERT | level_flags, 0, (startup ? NULL : s), APLOGNO(03279) "no listening sockets available, shutting down"); return !OK; } return OK; } static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp) { int no_detach, debug, foreground; apr_status_t rv; const char *userdata_key = "mpm_prefork_module"; debug = ap_exists_config_define("DEBUG"); if (debug) { foreground = one_process = 1; no_detach = 0; } else { no_detach = ap_exists_config_define("NO_DETACH"); one_process = ap_exists_config_define("ONE_PROCESS"); foreground = ap_exists_config_define("FOREGROUND"); } ap_mutex_register(p, AP_ACCEPT_MUTEX_TYPE, NULL, APR_LOCK_DEFAULT, 0); retained = ap_retained_data_get(userdata_key); if (!retained) { retained = ap_retained_data_create(userdata_key, sizeof(*retained)); retained->mpm = ap_unixd_mpm_get_retained_data(); retained->mpm->baton = retained; retained->max_daemons_limit = -1; retained->idle_spawn_rate = 1; } else if (retained->mpm->baton != retained) { /* If the MPM changes on restart, be ungraceful */ retained->mpm->baton = retained; retained->mpm->was_graceful = 0; } retained->mpm->mpm_state = AP_MPMQ_STARTING; ++retained->mpm->module_loads; /* sigh, want this only the second time around */ if (retained->mpm->module_loads == 2) { if (!one_process && !foreground) { /* before we detach, setup crash handlers to log to errorlog */ ap_fatal_signal_setup(ap_server_conf, p /* == pconf */); rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND : APR_PROC_DETACH_DAEMONIZE); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00174) "apr_proc_detach failed"); return HTTP_INTERNAL_SERVER_ERROR; } } } parent_pid = ap_my_pid = getpid(); ap_listen_pre_config(); ap_daemons_to_start = DEFAULT_START_DAEMON; ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON; ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON; server_limit = DEFAULT_SERVER_LIMIT; ap_daemons_limit = server_limit; ap_extended_status = 0; return OK; } static int prefork_check_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { int startup = 0; /* the reverse of pre_config, we want this only the first time around */ if (retained->mpm->module_loads == 1) { startup = 1; } if (server_limit > MAX_SERVER_LIMIT) { if (startup) { ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00175) "WARNING: ServerLimit of %d exceeds compile-time " "limit of %d servers, decreasing to %d.", server_limit, MAX_SERVER_LIMIT, MAX_SERVER_LIMIT); } else { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00176) "ServerLimit of %d exceeds compile-time limit " "of %d, decreasing to match", server_limit, MAX_SERVER_LIMIT); } server_limit = MAX_SERVER_LIMIT; } else if (server_limit < 1) { if (startup) { ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00177) "WARNING: ServerLimit of %d not allowed, " "increasing to 1.", server_limit); } else { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00178) "ServerLimit of %d not allowed, increasing to 1", server_limit); } server_limit = 1; } /* you cannot change ServerLimit across a restart; ignore * any such attempts */ if (!retained->first_server_limit) { retained->first_server_limit = server_limit; } else if (server_limit != retained->first_server_limit) { /* don't need a startup console version here */ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00179) "changing ServerLimit to %d from original value of %d " "not allowed during restart", server_limit, retained->first_server_limit); server_limit = retained->first_server_limit; } if (ap_daemons_limit > server_limit) { if (startup) { ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00180) "WARNING: MaxRequestWorkers of %d exceeds ServerLimit " "value of %d servers, decreasing MaxRequestWorkers to %d. " "To increase, please see the ServerLimit directive.", ap_daemons_limit, server_limit, server_limit); } else { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00181) "MaxRequestWorkers of %d exceeds ServerLimit value " "of %d, decreasing to match", ap_daemons_limit, server_limit); } ap_daemons_limit = server_limit; } else if (ap_daemons_limit < 1) { if (startup) { ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00182) "WARNING: MaxRequestWorkers of %d not allowed, " "increasing to 1.", ap_daemons_limit); } else { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00183) "MaxRequestWorkers of %d not allowed, increasing to 1", ap_daemons_limit); } ap_daemons_limit = 1; } /* ap_daemons_to_start > ap_daemons_limit checked in prefork_run() */ if (ap_daemons_to_start < 1) { if (startup) { ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00184) "WARNING: StartServers of %d not allowed, " "increasing to 1.", ap_daemons_to_start); } else { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00185) "StartServers of %d not allowed, increasing to 1", ap_daemons_to_start); } ap_daemons_to_start = 1; } if (ap_daemons_min_free < 1) { if (startup) { ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00186) "WARNING: MinSpareServers of %d not allowed, " "increasing to 1 to avoid almost certain server failure. " "Please read the documentation.", ap_daemons_min_free); } else { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00187) "MinSpareServers of %d not allowed, increasing to 1", ap_daemons_min_free); } ap_daemons_min_free = 1; } /* ap_daemons_max_free < ap_daemons_min_free + 1 checked in prefork_run() */ return OK; } static void prefork_hooks(apr_pool_t *p) { /* Our open_logs hook function must run before the core's, or stderr * will be redirected to a file, and the messages won't print to the * console. */ static const char *const aszSucc[] = {"core.c", NULL}; ap_force_set_tz(p); ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST); /* we need to set the MPM state before other pre-config hooks use MPM query * to retrieve it, so register as REALLY_FIRST */ ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST); ap_hook_check_config(prefork_check_config, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_mpm(prefork_run, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_mpm_query(prefork_query, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_mpm_get_name(prefork_get_name, NULL, NULL, APR_HOOK_MIDDLE); } static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg) { const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); if (err != NULL) { return err; } ap_daemons_to_start = atoi(arg); return NULL; } static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg) { const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); if (err != NULL) { return err; } ap_daemons_min_free = atoi(arg); return NULL; } static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg) { const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); if (err != NULL) { return err; } ap_daemons_max_free = atoi(arg); return NULL; } static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg) { const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); if (err != NULL) { return err; } if (!strcasecmp(cmd->cmd->name, "MaxClients")) { ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, APLOGNO(00188) "MaxClients is deprecated, use MaxRequestWorkers " "instead."); } ap_daemons_limit = atoi(arg); return NULL; } static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg) { const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); if (err != NULL) { return err; } server_limit = atoi(arg); return NULL; } static const command_rec prefork_cmds[] = { LISTEN_COMMANDS, AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF, "Number of child processes launched at server startup"), AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF, "Minimum number of idle children, to handle request spikes"), AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF, "Maximum number of idle children"), AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF, "Deprecated name of MaxRequestWorkers"), AP_INIT_TAKE1("MaxRequestWorkers", set_max_clients, NULL, RSRC_CONF, "Maximum number of children alive at the same time"), AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF, "Maximum value of MaxRequestWorkers for this run of Apache"), AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND, { NULL } }; AP_DECLARE_MODULE(mpm_prefork) = { MPM20_MODULE_STUFF, NULL, /* hook to run before apache parses args */ NULL, /* create per-directory config structure */ NULL, /* merge per-directory config structures */ NULL, /* create per-server config structure */ NULL, /* merge per-server config structures */ prefork_cmds, /* command apr_table_t */ prefork_hooks, /* register hooks */ };
64541.c
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2009 Blender Foundation, Joshua Leung * All rights reserved. */ /** \file * \ingroup edanimation */ #include <float.h> #include <math.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include "MEM_guardedalloc.h" #include "BLI_blenlib.h" #include "BLI_math.h" #include "BLI_utildefines.h" #include "BLT_translation.h" #include "DNA_anim_types.h" #include "DNA_armature_types.h" #include "DNA_constraint_types.h" #include "DNA_key_types.h" #include "DNA_material_types.h" #include "DNA_object_types.h" #include "DNA_rigidbody_types.h" #include "DNA_scene_types.h" #include "BKE_action.h" #include "BKE_anim_data.h" #include "BKE_animsys.h" #include "BKE_armature.h" #include "BKE_context.h" #include "BKE_fcurve.h" #include "BKE_fcurve_driver.h" #include "BKE_global.h" #include "BKE_idtype.h" #include "BKE_key.h" #include "BKE_main.h" #include "BKE_material.h" #include "BKE_nla.h" #include "BKE_report.h" #include "DEG_depsgraph.h" #include "DEG_depsgraph_build.h" #include "DEG_depsgraph_query.h" #include "ED_anim_api.h" #include "ED_keyframes_edit.h" #include "ED_keyframing.h" #include "ED_object.h" #include "ED_screen.h" #include "UI_interface.h" #include "UI_resources.h" #include "WM_api.h" #include "WM_types.h" #include "RNA_access.h" #include "RNA_define.h" #include "RNA_enum_types.h" #include "anim_intern.h" static KeyingSet *keyingset_get_from_op_with_error(wmOperator *op, PropertyRNA *prop, Scene *scene); /* ************************************************** */ /* Keyframing Setting Wrangling */ /* Get the active settings for keyframing settings from context (specifically the given scene) */ eInsertKeyFlags ANIM_get_keyframing_flags(Scene *scene, const bool use_autokey_mode) { eInsertKeyFlags flag = INSERTKEY_NOFLAGS; /* standard flags */ { /* visual keying */ if (IS_AUTOKEY_FLAG(scene, AUTOMATKEY)) { flag |= INSERTKEY_MATRIX; } /* only needed */ if (IS_AUTOKEY_FLAG(scene, INSERTNEEDED)) { flag |= INSERTKEY_NEEDED; } /* default F-Curve color mode - RGB from XYZ indices */ if (IS_AUTOKEY_FLAG(scene, XYZ2RGB)) { flag |= INSERTKEY_XYZ2RGB; } } /* only if including settings from the autokeying mode... */ if (use_autokey_mode) { /* keyframing mode - only replace existing keyframes */ if (IS_AUTOKEY_MODE(scene, EDITKEYS)) { flag |= INSERTKEY_REPLACE; } /* cycle-aware keyframe insertion - preserve cycle period and flow */ if (IS_AUTOKEY_FLAG(scene, CYCLEAWARE)) { flag |= INSERTKEY_CYCLE_AWARE; } } return flag; } /* ******************************************* */ /* Animation Data Validation */ /* Get (or add relevant data to be able to do so) the Active Action for the given * Animation Data block, given an ID block where the Animation Data should reside. */ bAction *ED_id_action_ensure(Main *bmain, ID *id) { AnimData *adt; /* init animdata if none available yet */ adt = BKE_animdata_from_id(id); if (adt == NULL) { adt = BKE_animdata_add_id(id); } if (adt == NULL) { /* if still none (as not allowed to add, or ID doesn't have animdata for some reason) */ printf("ERROR: Couldn't add AnimData (ID = %s)\n", (id) ? (id->name) : "<None>"); return NULL; } /* init action if none available yet */ /* TODO: need some wizardry to handle NLA stuff correct */ if (adt->action == NULL) { /* init action name from name of ID block */ char actname[sizeof(id->name) - 2]; BLI_snprintf(actname, sizeof(actname), "%sAction", id->name + 2); /* create action */ adt->action = BKE_action_add(bmain, actname); /* set ID-type from ID-block that this is going to be assigned to * so that users can't accidentally break actions by assigning them * to the wrong places */ adt->action->idroot = GS(id->name); /* Tag depsgraph to be rebuilt to include time dependency. */ DEG_relations_tag_update(bmain); } DEG_id_tag_update(&adt->action->id, ID_RECALC_ANIMATION_NO_FLUSH); /* return the action */ return adt->action; } /** * Find the F-Curve from the Active Action, * for the given Animation Data block. This assumes that all the destinations are valid. */ FCurve *ED_action_fcurve_find(struct bAction *act, const char rna_path[], const int array_index) { /* Sanity checks. */ if (ELEM(NULL, act, rna_path)) { return NULL; } return list_find_fcurve(&act->curves, rna_path, array_index); } /** * Get (or add relevant data to be able to do so) F-Curve from the Active Action, * for the given Animation Data block. This assumes that all the destinations are valid. */ FCurve *ED_action_fcurve_ensure(struct Main *bmain, struct bAction *act, const char group[], struct PointerRNA *ptr, const char rna_path[], const int array_index) { bActionGroup *agrp; FCurve *fcu; /* Sanity checks. */ if (ELEM(NULL, act, rna_path)) { return NULL; } /* try to find f-curve matching for this setting * - add if not found and allowed to add one * TODO: add auto-grouping support? how this works will need to be resolved */ fcu = list_find_fcurve(&act->curves, rna_path, array_index); if (fcu == NULL) { /* use default settings to make a F-Curve */ fcu = MEM_callocN(sizeof(FCurve), "FCurve"); fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED); fcu->auto_smoothing = U.auto_smoothing_new; if (BLI_listbase_is_empty(&act->curves)) { fcu->flag |= FCURVE_ACTIVE; /* first one added active */ } /* store path - make copy, and store that */ fcu->rna_path = BLI_strdup(rna_path); fcu->array_index = array_index; /* if a group name has been provided, try to add or find a group, then add F-Curve to it */ if (group) { /* try to find group */ agrp = BKE_action_group_find_name(act, group); /* no matching groups, so add one */ if (agrp == NULL) { agrp = action_groups_add_new(act, group); /* sync bone group colors if applicable */ if (ptr && (ptr->type == &RNA_PoseBone)) { Object *ob = (Object *)ptr->owner_id; bPoseChannel *pchan = ptr->data; bPose *pose = ob->pose; bActionGroup *grp; /* find bone group (if present), and use the color from that */ grp = (bActionGroup *)BLI_findlink(&pose->agroups, (pchan->agrp_index - 1)); if (grp) { agrp->customCol = grp->customCol; action_group_colors_sync(agrp, grp); } } } /* add F-Curve to group */ action_groups_add_channel(act, agrp, fcu); } else { /* just add F-Curve to end of Action's list */ BLI_addtail(&act->curves, fcu); } /* New f-curve was added, meaning it's possible that it affects * dependency graph component which wasn't previously animated. */ DEG_relations_tag_update(bmain); } /* return the F-Curve */ return fcu; } /* Helper for update_autoflags_fcurve() */ static void update_autoflags_fcurve_direct(FCurve *fcu, PropertyRNA *prop) { /* set additional flags for the F-Curve (i.e. only integer values) */ fcu->flag &= ~(FCURVE_INT_VALUES | FCURVE_DISCRETE_VALUES); switch (RNA_property_type(prop)) { case PROP_FLOAT: /* do nothing */ break; case PROP_INT: /* do integer (only 'whole' numbers) interpolation between all points */ fcu->flag |= FCURVE_INT_VALUES; break; default: /* do 'discrete' (i.e. enum, boolean values which cannot take any intermediate * values at all) interpolation between all points * - however, we must also ensure that evaluated values are only integers still */ fcu->flag |= (FCURVE_DISCRETE_VALUES | FCURVE_INT_VALUES); break; } } /* Update integer/discrete flags of the FCurve (used when creating/inserting keyframes, * but also through RNA when editing an ID prop, see T37103). */ void update_autoflags_fcurve(FCurve *fcu, bContext *C, ReportList *reports, PointerRNA *ptr) { PointerRNA tmp_ptr; PropertyRNA *prop; int old_flag = fcu->flag; if ((ptr->owner_id == NULL) && (ptr->data == NULL)) { BKE_report(reports, RPT_ERROR, "No RNA pointer available to retrieve values for this fcurve"); return; } /* try to get property we should be affecting */ if (RNA_path_resolve_property(ptr, fcu->rna_path, &tmp_ptr, &prop) == false) { /* property not found... */ const char *idname = (ptr->owner_id) ? ptr->owner_id->name : TIP_("<No ID pointer>"); BKE_reportf(reports, RPT_ERROR, "Could not update flags for this fcurve, as RNA path is invalid for the given ID " "(ID = %s, path = %s)", idname, fcu->rna_path); return; } /* update F-Curve flags */ update_autoflags_fcurve_direct(fcu, prop); if (old_flag != fcu->flag) { /* Same as if keyframes had been changed */ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL); } } /* ************************************************** */ /* KEYFRAME INSERTION */ /* Move the point where a key is about to be inserted to be inside the main cycle range. * Returns the type of the cycle if it is enabled and valid. */ static eFCU_Cycle_Type remap_cyclic_keyframe_location(FCurve *fcu, float *px, float *py) { if (fcu->totvert < 2 || !fcu->bezt) { return FCU_CYCLE_NONE; } eFCU_Cycle_Type type = BKE_fcurve_get_cycle_type(fcu); if (type == FCU_CYCLE_NONE) { return FCU_CYCLE_NONE; } BezTriple *first = &fcu->bezt[0], *last = &fcu->bezt[fcu->totvert - 1]; float start = first->vec[1][0], end = last->vec[1][0]; if (start >= end) { return FCU_CYCLE_NONE; } if (*px < start || *px > end) { float period = end - start; float step = floorf((*px - start) / period); *px -= step * period; if (type == FCU_CYCLE_OFFSET) { /* Nasty check to handle the case when the modes are different better. */ FMod_Cycles *data = ((FModifier *)fcu->modifiers.first)->data; short mode = (step >= 0) ? data->after_mode : data->before_mode; if (mode == FCM_EXTRAPOLATE_CYCLIC_OFFSET) { *py -= step * (last->vec[1][1] - first->vec[1][1]); } } } return type; } /* -------------- BezTriple Insertion -------------------- */ /* Change the Y position of a keyframe to match the input, adjusting handles. */ static void replace_bezt_keyframe_ypos(BezTriple *dst, const BezTriple *bezt) { /* just change the values when replacing, so as to not overwrite handles */ float dy = bezt->vec[1][1] - dst->vec[1][1]; /* just apply delta value change to the handle values */ dst->vec[0][1] += dy; dst->vec[1][1] += dy; dst->vec[2][1] += dy; dst->f1 = bezt->f1; dst->f2 = bezt->f2; dst->f3 = bezt->f3; /* TODO: perform some other operations? */ } /* This function adds a given BezTriple to an F-Curve. It will allocate * memory for the array if needed, and will insert the BezTriple into a * suitable place in chronological order. * * NOTE: any recalculate of the F-Curve that needs to be done will need to * be done by the caller. */ int insert_bezt_fcurve(FCurve *fcu, const BezTriple *bezt, eInsertKeyFlags flag) { int i = 0; /* are there already keyframes? */ if (fcu->bezt) { bool replace; i = binarysearch_bezt_index(fcu->bezt, bezt->vec[1][0], fcu->totvert, &replace); /* replace an existing keyframe? */ if (replace) { /* sanity check: 'i' may in rare cases exceed arraylen */ if ((i >= 0) && (i < fcu->totvert)) { if (flag & INSERTKEY_OVERWRITE_FULL) { fcu->bezt[i] = *bezt; } else { replace_bezt_keyframe_ypos(&fcu->bezt[i], bezt); } if (flag & INSERTKEY_CYCLE_AWARE) { /* If replacing an end point of a cyclic curve without offset, * modify the other end too. */ if ((i == 0 || i == fcu->totvert - 1) && BKE_fcurve_get_cycle_type(fcu) == FCU_CYCLE_PERFECT) { replace_bezt_keyframe_ypos(&fcu->bezt[i == 0 ? fcu->totvert - 1 : 0], bezt); } } } } /* keyframing modes allow to not replace keyframe */ else if ((flag & INSERTKEY_REPLACE) == 0) { /* insert new - if we're not restricted to replacing keyframes only */ BezTriple *newb = MEM_callocN((fcu->totvert + 1) * sizeof(BezTriple), "beztriple"); /* Add the beztriples that should occur before the beztriple to be pasted * (originally in fcu). */ if (i > 0) { memcpy(newb, fcu->bezt, i * sizeof(BezTriple)); } /* add beztriple to paste at index i */ *(newb + i) = *bezt; /* add the beztriples that occur after the beztriple to be pasted (originally in fcu) */ if (i < fcu->totvert) { memcpy(newb + i + 1, fcu->bezt + i, (fcu->totvert - i) * sizeof(BezTriple)); } /* replace (+ free) old with new, only if necessary to do so */ MEM_freeN(fcu->bezt); fcu->bezt = newb; fcu->totvert++; } else { return -1; } } /* no keyframes already, but can only add if... * 1) keyframing modes say that keyframes can only be replaced, so adding new ones won't know * 2) there are no samples on the curve * // NOTE: maybe we may want to allow this later when doing samples -> bezt conversions, * // but for now, having both is asking for trouble */ else if ((flag & INSERTKEY_REPLACE) == 0 && (fcu->fpt == NULL)) { /* create new keyframes array */ fcu->bezt = MEM_callocN(sizeof(BezTriple), "beztriple"); *(fcu->bezt) = *bezt; fcu->totvert = 1; } /* cannot add anything */ else { /* return error code -1 to prevent any misunderstandings */ return -1; } /* we need to return the index, so that some tools which do post-processing can * detect where we added the BezTriple in the array */ return i; } /** * This function is a wrapper for #insert_bezt_fcurve(), and should be used when * adding a new keyframe to a curve, when the keyframe doesn't exist anywhere else yet. * It returns the index at which the keyframe was added. * * \param keyframe_type: The type of keyframe (#eBezTriple_KeyframeType). * \param flag: Optional flags (eInsertKeyFlags) for controlling how keys get added * and/or whether updates get done. */ int insert_vert_fcurve( FCurve *fcu, float x, float y, eBezTriple_KeyframeType keyframe_type, eInsertKeyFlags flag) { BezTriple beztr = {{{0}}}; uint oldTot = fcu->totvert; int a; /* set all three points, for nicer start position * NOTE: +/- 1 on vec.x for left and right handles is so that 'free' handles work ok... */ beztr.vec[0][0] = x - 1.0f; beztr.vec[0][1] = y; beztr.vec[1][0] = x; beztr.vec[1][1] = y; beztr.vec[2][0] = x + 1.0f; beztr.vec[2][1] = y; beztr.f1 = beztr.f2 = beztr.f3 = SELECT; /* set default handle types and interpolation mode */ if (flag & INSERTKEY_NO_USERPREF) { /* for Py-API, we want scripts to have predictable behavior, * hence the option to not depend on the userpref defaults */ beztr.h1 = beztr.h2 = HD_AUTO_ANIM; beztr.ipo = BEZT_IPO_BEZ; } else { /* for UI usage - defaults should come from the userprefs and/or toolsettings */ beztr.h1 = beztr.h2 = U.keyhandles_new; /* use default handle type here */ /* use default interpolation mode, with exceptions for int/discrete values */ beztr.ipo = U.ipo_new; } /* interpolation type used is constrained by the type of values the curve can take */ if (fcu->flag & FCURVE_DISCRETE_VALUES) { beztr.ipo = BEZT_IPO_CONST; } else if ((beztr.ipo == BEZT_IPO_BEZ) && (fcu->flag & FCURVE_INT_VALUES)) { beztr.ipo = BEZT_IPO_LIN; } /* set keyframe type value (supplied), which should come from the scene settings in most cases */ BEZKEYTYPE(&beztr) = keyframe_type; /* set default values for "easing" interpolation mode settings * NOTE: Even if these modes aren't currently used, if users switch * to these later, we want these to work in a sane way out of * the box. */ /* "back" easing - this value used to be used when overshoot=0, but that * introduced discontinuities in how the param worked. */ beztr.back = 1.70158f; /* "elastic" easing - values here were hand-optimized for a default duration of * ~10 frames (typical mograph motion length) */ beztr.amplitude = 0.8f; beztr.period = 4.1f; /* add temp beztriple to keyframes */ a = insert_bezt_fcurve(fcu, &beztr, flag); /* what if 'a' is a negative index? * for now, just exit to prevent any segfaults */ if (a < 0) { return -1; } /* don't recalculate handles if fast is set * - this is a hack to make importers faster * - we may calculate twice (due to autohandle needing to be calculated twice) */ if ((flag & INSERTKEY_FAST) == 0) { calchandles_fcurve(fcu); } /* set handletype and interpolation */ if ((fcu->totvert > 2) && (flag & INSERTKEY_REPLACE) == 0) { BezTriple *bezt = (fcu->bezt + a); /* Set interpolation from previous (if available), * but only if we didn't just replace some keyframe: * - Replacement is indicated by no-change in number of verts. * - When replacing, the user may have specified some interpolation that should be kept. */ if (fcu->totvert > oldTot) { if (a > 0) { bezt->ipo = (bezt - 1)->ipo; } else if (a < fcu->totvert - 1) { bezt->ipo = (bezt + 1)->ipo; } } /* don't recalculate handles if fast is set * - this is a hack to make importers faster * - we may calculate twice (due to autohandle needing to be calculated twice) */ if ((flag & INSERTKEY_FAST) == 0) { calchandles_fcurve(fcu); } } /* return the index at which the keyframe was added */ return a; } /* -------------- 'Smarter' Keyframing Functions -------------------- */ /* return codes for new_key_needed */ enum { KEYNEEDED_DONTADD = 0, KEYNEEDED_JUSTADD, KEYNEEDED_DELPREV, KEYNEEDED_DELNEXT, } /*eKeyNeededStatus*/; /* This helper function determines whether a new keyframe is needed */ /* Cases where keyframes should not be added: * 1. Keyframe to be added between two keyframes with similar values * 2. Keyframe to be added on frame where two keyframes are already situated * 3. Keyframe lies at point that intersects the linear line between two keyframes */ static short new_key_needed(FCurve *fcu, float cFrame, float nValue) { BezTriple *bezt = NULL, *prev = NULL; int totCount, i; float valA = 0.0f, valB = 0.0f; /* safety checking */ if (fcu == NULL) { return KEYNEEDED_JUSTADD; } totCount = fcu->totvert; if (totCount == 0) { return KEYNEEDED_JUSTADD; } /* loop through checking if any are the same */ bezt = fcu->bezt; for (i = 0; i < totCount; i++) { float prevPosi = 0.0f, prevVal = 0.0f; float beztPosi = 0.0f, beztVal = 0.0f; /* get current time+value */ beztPosi = bezt->vec[1][0]; beztVal = bezt->vec[1][1]; if (prev) { /* there is a keyframe before the one currently being examined */ /* get previous time+value */ prevPosi = prev->vec[1][0]; prevVal = prev->vec[1][1]; /* keyframe to be added at point where there are already two similar points? */ if (IS_EQF(prevPosi, cFrame) && IS_EQF(beztPosi, cFrame) && IS_EQF(beztPosi, prevPosi)) { return KEYNEEDED_DONTADD; } /* keyframe between prev+current points ? */ if ((prevPosi <= cFrame) && (cFrame <= beztPosi)) { /* is the value of keyframe to be added the same as keyframes on either side ? */ if (IS_EQF(prevVal, nValue) && IS_EQF(beztVal, nValue) && IS_EQF(prevVal, beztVal)) { return KEYNEEDED_DONTADD; } else { float realVal; /* get real value of curve at that point */ realVal = evaluate_fcurve(fcu, cFrame); /* compare whether it's the same as proposed */ if (IS_EQF(realVal, nValue)) { return KEYNEEDED_DONTADD; } else { return KEYNEEDED_JUSTADD; } } } /* new keyframe before prev beztriple? */ if (cFrame < prevPosi) { /* A new keyframe will be added. However, whether the previous beztriple * stays around or not depends on whether the values of previous/current * beztriples and new keyframe are the same. */ if (IS_EQF(prevVal, nValue) && IS_EQF(beztVal, nValue) && IS_EQF(prevVal, beztVal)) { return KEYNEEDED_DELNEXT; } else { return KEYNEEDED_JUSTADD; } } } else { /* just add a keyframe if there's only one keyframe * and the new one occurs before the existing one does. */ if ((cFrame < beztPosi) && (totCount == 1)) { return KEYNEEDED_JUSTADD; } } /* continue. frame to do not yet passed (or other conditions not met) */ if (i < (totCount - 1)) { prev = bezt; bezt++; } else { break; } } /* Frame in which to add a new-keyframe occurs after all other keys * -> If there are at least two existing keyframes, then if the values of the * last two keyframes and the new-keyframe match, the last existing keyframe * gets deleted as it is no longer required. * -> Otherwise, a keyframe is just added. 1.0 is added so that fake-2nd-to-last * keyframe is not equal to last keyframe. */ bezt = (fcu->bezt + (fcu->totvert - 1)); valA = bezt->vec[1][1]; if (prev) { valB = prev->vec[1][1]; } else { valB = bezt->vec[1][1] + 1.0f; } if (IS_EQF(valA, nValue) && IS_EQF(valA, valB)) { return KEYNEEDED_DELPREV; } else { return KEYNEEDED_JUSTADD; } } /* ------------------ RNA Data-Access Functions ------------------ */ /* Try to read value using RNA-properties obtained already */ static float *setting_get_rna_values( PointerRNA *ptr, PropertyRNA *prop, float *buffer, int buffer_size, int *r_count) { BLI_assert(buffer_size >= 1); float *values = buffer; if (RNA_property_array_check(prop)) { int length = *r_count = RNA_property_array_length(ptr, prop); bool *tmp_bool; int *tmp_int; if (length > buffer_size) { values = MEM_malloc_arrayN(sizeof(float), length, __func__); } switch (RNA_property_type(prop)) { case PROP_BOOLEAN: tmp_bool = MEM_malloc_arrayN(sizeof(*tmp_bool), length, __func__); RNA_property_boolean_get_array(ptr, prop, tmp_bool); for (int i = 0; i < length; i++) { values[i] = (float)tmp_bool[i]; } MEM_freeN(tmp_bool); break; case PROP_INT: tmp_int = MEM_malloc_arrayN(sizeof(*tmp_int), length, __func__); RNA_property_int_get_array(ptr, prop, tmp_int); for (int i = 0; i < length; i++) { values[i] = (float)tmp_int[i]; } MEM_freeN(tmp_int); break; case PROP_FLOAT: RNA_property_float_get_array(ptr, prop, values); break; default: memset(values, 0, sizeof(float) * length); } } else { *r_count = 1; switch (RNA_property_type(prop)) { case PROP_BOOLEAN: *values = (float)RNA_property_boolean_get(ptr, prop); break; case PROP_INT: *values = (float)RNA_property_int_get(ptr, prop); break; case PROP_FLOAT: *values = RNA_property_float_get(ptr, prop); break; case PROP_ENUM: *values = (float)RNA_property_enum_get(ptr, prop); break; default: *values = 0.0f; } } return values; } /* ------------------ 'Visual' Keyframing Functions ------------------ */ /* internal status codes for visualkey_can_use */ enum { VISUALKEY_NONE = 0, VISUALKEY_LOC, VISUALKEY_ROT, VISUALKEY_SCA, }; /* This helper function determines if visual-keyframing should be used when * inserting keyframes for the given channel. As visual-keyframing only works * on Object and Pose-Channel blocks, this should only get called for those * blocktypes, when using "standard" keying but 'Visual Keying' option in Auto-Keying * settings is on. */ static bool visualkey_can_use(PointerRNA *ptr, PropertyRNA *prop) { bConstraint *con = NULL; short searchtype = VISUALKEY_NONE; bool has_rigidbody = false; bool has_parent = false; const char *identifier = NULL; /* validate data */ if (ELEM(NULL, ptr, ptr->data, prop)) { return false; } /* get first constraint and determine type of keyframe constraints to check for * - constraints can be on either Objects or PoseChannels, so we only check if the * ptr->type is RNA_Object or RNA_PoseBone, which are the RNA wrapping-info for * those structs, allowing us to identify the owner of the data */ if (ptr->type == &RNA_Object) { /* Object */ Object *ob = ptr->data; RigidBodyOb *rbo = ob->rigidbody_object; con = ob->constraints.first; identifier = RNA_property_identifier(prop); has_parent = (ob->parent != NULL); /* active rigidbody objects only, as only those are affected by sim */ has_rigidbody = ((rbo) && (rbo->type == RBO_TYPE_ACTIVE)); } else if (ptr->type == &RNA_PoseBone) { /* Pose Channel */ bPoseChannel *pchan = ptr->data; con = pchan->constraints.first; identifier = RNA_property_identifier(prop); has_parent = (pchan->parent != NULL); } /* check if any data to search using */ if (ELEM(NULL, con, identifier) && (has_parent == false) && (has_rigidbody == false)) { return false; } /* location or rotation identifiers only... */ if (identifier == NULL) { printf("%s failed: NULL identifier\n", __func__); return false; } else if (strstr(identifier, "location")) { searchtype = VISUALKEY_LOC; } else if (strstr(identifier, "rotation")) { searchtype = VISUALKEY_ROT; } else if (strstr(identifier, "scale")) { searchtype = VISUALKEY_SCA; } else { printf("%s failed: identifier - '%s'\n", __func__, identifier); return false; } /* only search if a searchtype and initial constraint are available */ if (searchtype) { /* parent or rigidbody are always matching */ if (has_parent || has_rigidbody) { return true; } /* constraints */ for (; con; con = con->next) { /* only consider constraint if it is not disabled, and has influence */ if (con->flag & CONSTRAINT_DISABLE) { continue; } if (con->enforce == 0.0f) { continue; } /* some constraints may alter these transforms */ switch (con->type) { /* multi-transform constraints */ case CONSTRAINT_TYPE_CHILDOF: case CONSTRAINT_TYPE_ARMATURE: return true; case CONSTRAINT_TYPE_TRANSFORM: case CONSTRAINT_TYPE_TRANSLIKE: return true; case CONSTRAINT_TYPE_FOLLOWPATH: return true; case CONSTRAINT_TYPE_KINEMATIC: return true; /* single-transform constraints */ case CONSTRAINT_TYPE_TRACKTO: if (searchtype == VISUALKEY_ROT) { return true; } break; case CONSTRAINT_TYPE_DAMPTRACK: if (searchtype == VISUALKEY_ROT) { return true; } break; case CONSTRAINT_TYPE_ROTLIMIT: if (searchtype == VISUALKEY_ROT) { return true; } break; case CONSTRAINT_TYPE_LOCLIMIT: if (searchtype == VISUALKEY_LOC) { return true; } break; case CONSTRAINT_TYPE_SIZELIMIT: if (searchtype == VISUALKEY_SCA) { return true; } break; case CONSTRAINT_TYPE_DISTLIMIT: if (searchtype == VISUALKEY_LOC) { return true; } break; case CONSTRAINT_TYPE_ROTLIKE: if (searchtype == VISUALKEY_ROT) { return true; } break; case CONSTRAINT_TYPE_LOCLIKE: if (searchtype == VISUALKEY_LOC) { return true; } break; case CONSTRAINT_TYPE_SIZELIKE: if (searchtype == VISUALKEY_SCA) { return true; } break; case CONSTRAINT_TYPE_LOCKTRACK: if (searchtype == VISUALKEY_ROT) { return true; } break; case CONSTRAINT_TYPE_MINMAX: if (searchtype == VISUALKEY_LOC) { return true; } break; default: break; } } } /* when some condition is met, this function returns, so that means we've got nothing */ return false; } /* This helper function extracts the value to use for visual-keyframing * In the event that it is not possible to perform visual keying, try to fall-back * to using the default method. Assumes that all data it has been passed is valid. */ static float *visualkey_get_values( PointerRNA *ptr, PropertyRNA *prop, float *buffer, int buffer_size, int *r_count) { BLI_assert(buffer_size >= 4); const char *identifier = RNA_property_identifier(prop); float tmat[4][4]; int rotmode; /* handle for Objects or PoseChannels only * - only Location, Rotation or Scale keyframes are supported currently * - constraints can be on either Objects or PoseChannels, so we only check if the * ptr->type is RNA_Object or RNA_PoseBone, which are the RNA wrapping-info for * those structs, allowing us to identify the owner of the data * - assume that array_index will be sane */ if (ptr->type == &RNA_Object) { Object *ob = ptr->data; /* Loc code is specific... */ if (strstr(identifier, "location")) { copy_v3_v3(buffer, ob->obmat[3]); *r_count = 3; return buffer; } copy_m4_m4(tmat, ob->obmat); rotmode = ob->rotmode; } else if (ptr->type == &RNA_PoseBone) { bPoseChannel *pchan = ptr->data; BKE_armature_mat_pose_to_bone(pchan, pchan->pose_mat, tmat); rotmode = pchan->rotmode; /* Loc code is specific... */ if (strstr(identifier, "location")) { /* only use for non-connected bones */ if ((pchan->bone->parent == NULL) || !(pchan->bone->flag & BONE_CONNECTED)) { copy_v3_v3(buffer, tmat[3]); *r_count = 3; return buffer; } } } else { return setting_get_rna_values(ptr, prop, buffer, buffer_size, r_count); } /* Rot/Scale code are common! */ if (strstr(identifier, "rotation_euler")) { mat4_to_eulO(buffer, rotmode, tmat); *r_count = 3; return buffer; } else if (strstr(identifier, "rotation_quaternion")) { float mat3[3][3]; copy_m3_m4(mat3, tmat); mat3_to_quat_is_ok(buffer, mat3); *r_count = 4; return buffer; } else if (strstr(identifier, "rotation_axis_angle")) { /* w = 0, x,y,z = 1,2,3 */ mat4_to_axis_angle(buffer + 1, buffer, tmat); *r_count = 4; return buffer; } else if (strstr(identifier, "scale")) { mat4_to_size(buffer, tmat); *r_count = 3; return buffer; } /* as the function hasn't returned yet, read value from system in the default way */ return setting_get_rna_values(ptr, prop, buffer, buffer_size, r_count); } /* ------------------------- Insert Key API ------------------------- */ /** * Retrieve current property values to keyframe, * possibly applying NLA correction when necessary. */ static float *get_keyframe_values(ReportList *reports, PointerRNA ptr, PropertyRNA *prop, int index, struct NlaKeyframingContext *nla_context, eInsertKeyFlags flag, float *buffer, int buffer_size, int *r_count, bool *r_force_all) { float *values; if ((flag & INSERTKEY_MATRIX) && (visualkey_can_use(&ptr, prop))) { /* visual-keying is only available for object and pchan datablocks, as * it works by keyframing using a value extracted from the final matrix * instead of using the kt system to extract a value. */ values = visualkey_get_values(&ptr, prop, buffer, buffer_size, r_count); } else { /* read value from system */ values = setting_get_rna_values(&ptr, prop, buffer, buffer_size, r_count); } /* adjust the value for NLA factors */ if (!BKE_animsys_nla_remap_keyframe_values( nla_context, &ptr, prop, values, *r_count, index, r_force_all)) { BKE_report( reports, RPT_ERROR, "Could not insert keyframe due to zero NLA influence or base value"); if (values != buffer) { MEM_freeN(values); } return NULL; } return values; } /* Insert the specified keyframe value into a single F-Curve. */ static bool insert_keyframe_value(ReportList *reports, PointerRNA *ptr, PropertyRNA *prop, FCurve *fcu, float cfra, float curval, eBezTriple_KeyframeType keytype, eInsertKeyFlags flag) { /* F-Curve not editable? */ if (fcurve_is_keyframable(fcu) == 0) { BKE_reportf( reports, RPT_ERROR, "F-Curve with path '%s[%d]' cannot be keyframed, ensure that it is not locked or sampled, " "and try removing F-Modifiers", fcu->rna_path, fcu->array_index); return false; } /* adjust frame on which to add keyframe */ if ((flag & INSERTKEY_DRIVER) && (fcu->driver)) { PathResolvedRNA anim_rna; if (RNA_path_resolved_create(ptr, prop, fcu->array_index, &anim_rna)) { /* for making it easier to add corrective drivers... */ cfra = evaluate_driver(&anim_rna, fcu->driver, fcu->driver, cfra); } else { cfra = 0.0f; } } /* adjust coordinates for cycle aware insertion */ if (flag & INSERTKEY_CYCLE_AWARE) { if (remap_cyclic_keyframe_location(fcu, &cfra, &curval) != FCU_CYCLE_PERFECT) { /* inhibit action from insert_vert_fcurve unless it's a perfect cycle */ flag &= ~INSERTKEY_CYCLE_AWARE; } } /* only insert keyframes where they are needed */ if (flag & INSERTKEY_NEEDED) { short insert_mode; /* check whether this curve really needs a new keyframe */ insert_mode = new_key_needed(fcu, cfra, curval); /* only return success if keyframe added */ if (insert_mode == KEYNEEDED_DONTADD) { return false; } /* insert new keyframe at current frame */ if (insert_vert_fcurve(fcu, cfra, curval, keytype, flag) < 0) { return false; } /* delete keyframe immediately before/after newly added */ switch (insert_mode) { case KEYNEEDED_DELPREV: delete_fcurve_key(fcu, fcu->totvert - 2, 1); break; case KEYNEEDED_DELNEXT: delete_fcurve_key(fcu, 1, 1); break; } return true; } else { /* just insert keyframe */ return insert_vert_fcurve(fcu, cfra, curval, keytype, flag) >= 0; } } /* Secondary Keyframing API call: * Use this when validation of necessary animation data is not necessary, * since an RNA-pointer to the necessary data being keyframed, * and a pointer to the F-Curve to use have both been provided. * * This function can't keyframe quaternion channels on some NLA strip types. * * keytype is the "keyframe type" (eBezTriple_KeyframeType), as shown in the Dope Sheet. * * The flag argument is used for special settings that alter the behavior of * the keyframe insertion. These include the 'visual' keyframing modes, quick refresh, * and extra keyframe filtering. */ bool insert_keyframe_direct(ReportList *reports, PointerRNA ptr, PropertyRNA *prop, FCurve *fcu, float cfra, eBezTriple_KeyframeType keytype, struct NlaKeyframingContext *nla_context, eInsertKeyFlags flag) { float curval = 0.0f; /* no F-Curve to add keyframe to? */ if (fcu == NULL) { BKE_report(reports, RPT_ERROR, "No F-Curve to add keyframes to"); return false; } /* if no property given yet, try to validate from F-Curve info */ if ((ptr.owner_id == NULL) && (ptr.data == NULL)) { BKE_report( reports, RPT_ERROR, "No RNA pointer available to retrieve values for keyframing from"); return false; } if (prop == NULL) { PointerRNA tmp_ptr; /* try to get property we should be affecting */ if (RNA_path_resolve_property(&ptr, fcu->rna_path, &tmp_ptr, &prop) == false) { /* property not found... */ const char *idname = (ptr.owner_id) ? ptr.owner_id->name : TIP_("<No ID pointer>"); BKE_reportf(reports, RPT_ERROR, "Could not insert keyframe, as RNA path is invalid for the given ID (ID = %s, " "path = %s)", idname, fcu->rna_path); return false; } else { /* property found, so overwrite 'ptr' to make later code easier */ ptr = tmp_ptr; } } /* update F-Curve flags to ensure proper behavior for property type */ update_autoflags_fcurve_direct(fcu, prop); /* Obtain the value to insert. */ float value_buffer[RNA_MAX_ARRAY_LENGTH]; int value_count; int index = fcu->array_index; float *values = get_keyframe_values(reports, ptr, prop, index, nla_context, flag, value_buffer, RNA_MAX_ARRAY_LENGTH, &value_count, NULL); if (values == NULL) { /* This happens if NLA rejects this insertion. */ return false; } if (index >= 0 && index < value_count) { curval = values[index]; } if (values != value_buffer) { MEM_freeN(values); } return insert_keyframe_value(reports, &ptr, prop, fcu, cfra, curval, keytype, flag); } /* Find or create the FCurve based on the given path, and insert the specified value into it. */ static bool insert_keyframe_fcurve_value(Main *bmain, ReportList *reports, PointerRNA *ptr, PropertyRNA *prop, bAction *act, const char group[], const char rna_path[], int array_index, float cfra, float curval, eBezTriple_KeyframeType keytype, eInsertKeyFlags flag) { /* make sure the F-Curve exists * - if we're replacing keyframes only, DO NOT create new F-Curves if they do not exist yet * but still try to get the F-Curve if it exists... */ bool can_create_curve = (flag & (INSERTKEY_REPLACE | INSERTKEY_AVAILABLE)) == 0; FCurve *fcu = can_create_curve ? ED_action_fcurve_ensure(bmain, act, group, ptr, rna_path, array_index) : ED_action_fcurve_find(act, rna_path, array_index); /* we may not have a F-Curve when we're replacing only... */ if (fcu) { /* set color mode if the F-Curve is new (i.e. without any keyframes) */ if ((fcu->totvert == 0) && (flag & INSERTKEY_XYZ2RGB)) { /* for Loc/Rot/Scale and also Color F-Curves, the color of the F-Curve in the Graph Editor, * is determined by the array index for the F-Curve */ PropertySubType prop_subtype = RNA_property_subtype(prop); if (ELEM(prop_subtype, PROP_TRANSLATION, PROP_XYZ, PROP_EULER, PROP_COLOR, PROP_COORDS)) { fcu->color_mode = FCURVE_COLOR_AUTO_RGB; } else if (ELEM(prop_subtype, PROP_QUATERNION)) { fcu->color_mode = FCURVE_COLOR_AUTO_YRGB; } } /* update F-Curve flags to ensure proper behavior for property type */ update_autoflags_fcurve_direct(fcu, prop); /* insert keyframe */ return insert_keyframe_value(reports, ptr, prop, fcu, cfra, curval, keytype, flag); } else { return false; } } /** * Main Keyframing API call * * Use this when validation of necessary animation data is necessary, since it may not exist yet. * * The flag argument is used for special settings that alter the behavior of * the keyframe insertion. These include the 'visual' keyframing modes, quick refresh, * and extra keyframe filtering. * * index of -1 keys all array indices * * \return The number of key-frames inserted. */ int insert_keyframe(Main *bmain, ReportList *reports, ID *id, bAction *act, const char group[], const char rna_path[], int array_index, float cfra, eBezTriple_KeyframeType keytype, ListBase *nla_cache, eInsertKeyFlags flag) { PointerRNA id_ptr, ptr; PropertyRNA *prop = NULL; AnimData *adt; ListBase tmp_nla_cache = {NULL, NULL}; NlaKeyframingContext *nla_context = NULL; int ret = 0; /* validate pointer first - exit if failure */ if (id == NULL) { BKE_reportf(reports, RPT_ERROR, "No ID block to insert keyframe in (path = %s)", rna_path); return 0; } RNA_id_pointer_create(id, &id_ptr); if (RNA_path_resolve_property(&id_ptr, rna_path, &ptr, &prop) == false) { BKE_reportf( reports, RPT_ERROR, "Could not insert keyframe, as RNA path is invalid for the given ID (ID = %s, path = %s)", (id) ? id->name : TIP_("<Missing ID block>"), rna_path); return 0; } /* if no action is provided, keyframe to the default one attached to this ID-block */ if (act == NULL) { /* get action to add F-Curve+keyframe to */ act = ED_id_action_ensure(bmain, id); if (act == NULL) { BKE_reportf(reports, RPT_ERROR, "Could not insert keyframe, as this type does not support animation data (ID = " "%s, path = %s)", id->name, rna_path); return 0; } } /* apply NLA-mapping to frame to use (if applicable) */ adt = BKE_animdata_from_id(id); if (adt && adt->action == act) { /* Get NLA context for value remapping. */ nla_context = BKE_animsys_get_nla_keyframing_context( nla_cache ? nla_cache : &tmp_nla_cache, &id_ptr, adt, cfra, false); /* Apply NLA-mapping to frame. */ cfra = BKE_nla_tweakedit_remap(adt, cfra, NLATIME_CONVERT_UNMAP); } /* Obtain values to insert. */ float value_buffer[RNA_MAX_ARRAY_LENGTH]; int value_count; bool force_all; float *values = get_keyframe_values(reports, ptr, prop, array_index, nla_context, flag, value_buffer, RNA_MAX_ARRAY_LENGTH, &value_count, &force_all); if (values != NULL) { /* Key the entire array. */ if (array_index == -1 || force_all) { /* In force mode, if any of the curves succeeds, drop the replace mode and restart. */ if (force_all && (flag & (INSERTKEY_REPLACE | INSERTKEY_AVAILABLE)) != 0) { int exclude = -1; for (array_index = 0; array_index < value_count; array_index++) { if (insert_keyframe_fcurve_value(bmain, reports, &ptr, prop, act, group, rna_path, array_index, cfra, values[array_index], keytype, flag)) { ret++; exclude = array_index; break; } } if (exclude != -1) { flag &= ~(INSERTKEY_REPLACE | INSERTKEY_AVAILABLE); for (array_index = 0; array_index < value_count; array_index++) { if (array_index != exclude) { ret += insert_keyframe_fcurve_value(bmain, reports, &ptr, prop, act, group, rna_path, array_index, cfra, values[array_index], keytype, flag); } } } } /* Simply insert all channels. */ else { for (array_index = 0; array_index < value_count; array_index++) { ret += insert_keyframe_fcurve_value(bmain, reports, &ptr, prop, act, group, rna_path, array_index, cfra, values[array_index], keytype, flag); } } } /* Key a single index. */ else { if (array_index >= 0 && array_index < value_count) { ret += insert_keyframe_fcurve_value(bmain, reports, &ptr, prop, act, group, rna_path, array_index, cfra, values[array_index], keytype, flag); } } if (values != value_buffer) { MEM_freeN(values); } } BKE_animsys_free_nla_keyframing_context_cache(&tmp_nla_cache); if (ret) { if (act != NULL) { DEG_id_tag_update(&act->id, ID_RECALC_ANIMATION_NO_FLUSH); } if (adt != NULL && adt->action != NULL && adt->action != act) { DEG_id_tag_update(&adt->action->id, ID_RECALC_ANIMATION_NO_FLUSH); } } return ret; } /* ************************************************** */ /* KEYFRAME DELETION */ /* Main Keyframing API call: * Use this when validation of necessary animation data isn't necessary as it * already exists. It will delete a keyframe at the current frame. * * The flag argument is used for special settings that alter the behavior of * the keyframe deletion. These include the quick refresh options. */ /** * \note caller needs to run #BKE_nla_tweakedit_remap to get NLA relative frame. * caller should also check #BKE_fcurve_is_protected before keying. */ static bool delete_keyframe_fcurve(AnimData *adt, FCurve *fcu, float cfra) { bool found; int i; /* try to find index of beztriple to get rid of */ i = binarysearch_bezt_index(fcu->bezt, cfra, fcu->totvert, &found); if (found) { /* delete the key at the index (will sanity check + do recalc afterwards) */ delete_fcurve_key(fcu, i, 1); /* Only delete curve too if it won't be doing anything anymore */ if (BKE_fcurve_is_empty(fcu)) { ANIM_fcurve_delete_from_animdata(NULL, adt, fcu); } /* return success */ return true; } return false; } static void deg_tag_after_keyframe_delete(Main *bmain, ID *id, AnimData *adt) { if (adt->action == NULL) { /* In the case last f-curve was removed need to inform dependency graph * about relations update, since it needs to get rid of animation operation * for this data-block. */ DEG_id_tag_update_ex(bmain, id, ID_RECALC_ANIMATION_NO_FLUSH); DEG_relations_tag_update(bmain); } else { DEG_id_tag_update_ex(bmain, &adt->action->id, ID_RECALC_ANIMATION_NO_FLUSH); } } /** * \return The number of key-frames deleted. */ int delete_keyframe(Main *bmain, ReportList *reports, ID *id, bAction *act, const char rna_path[], int array_index, float cfra) { AnimData *adt = BKE_animdata_from_id(id); PointerRNA id_ptr, ptr; PropertyRNA *prop; int array_index_max = array_index + 1; int ret = 0; /* sanity checks */ if (ELEM(NULL, id, adt)) { BKE_report(reports, RPT_ERROR, "No ID block and/or AnimData to delete keyframe from"); return 0; } /* validate pointer first - exit if failure */ RNA_id_pointer_create(id, &id_ptr); if (RNA_path_resolve_property(&id_ptr, rna_path, &ptr, &prop) == false) { BKE_reportf( reports, RPT_ERROR, "Could not delete keyframe, as RNA path is invalid for the given ID (ID = %s, path = %s)", id->name, rna_path); return 0; } /* get F-Curve * Note: here is one of the places where we don't want new Action + F-Curve added! * so 'add' var must be 0 */ if (act == NULL) { /* if no action is provided, use the default one attached to this ID-block * - if it doesn't exist, then we're out of options... */ if (adt->action) { act = adt->action; /* apply NLA-mapping to frame to use (if applicable) */ cfra = BKE_nla_tweakedit_remap(adt, cfra, NLATIME_CONVERT_UNMAP); } else { BKE_reportf(reports, RPT_ERROR, "No action to delete keyframes from for ID = %s", id->name); return 0; } } /* key entire array convenience method */ if (array_index == -1) { array_index = 0; array_index_max = RNA_property_array_length(&ptr, prop); /* for single properties, increase max_index so that the property itself gets included, * but don't do this for standard arrays since that can cause corruption issues * (extra unused curves) */ if (array_index_max == array_index) { array_index_max++; } } /* will only loop once unless the array index was -1 */ for (; array_index < array_index_max; array_index++) { FCurve *fcu = ED_action_fcurve_find(act, rna_path, array_index); /* check if F-Curve exists and/or whether it can be edited */ if (fcu == NULL) { continue; } if (BKE_fcurve_is_protected(fcu)) { BKE_reportf(reports, RPT_WARNING, "Not deleting keyframe for locked F-Curve '%s' for %s '%s'", fcu->rna_path, BKE_idtype_idcode_to_name(GS(id->name)), id->name + 2); continue; } ret += delete_keyframe_fcurve(adt, fcu, cfra); } if (ret) { deg_tag_after_keyframe_delete(bmain, id, adt); } /* return success/failure */ return ret; } /* ************************************************** */ /* KEYFRAME CLEAR */ /** * Main Keyframing API call: * Use this when validation of necessary animation data isn't necessary as it * already exists. It will clear the current buttons fcurve(s). * * The flag argument is used for special settings that alter the behavior of * the keyframe deletion. These include the quick refresh options. * * \return The number of f-curves removed. */ static int clear_keyframe(Main *bmain, ReportList *reports, ID *id, bAction *act, const char rna_path[], int array_index, eInsertKeyFlags UNUSED(flag)) { AnimData *adt = BKE_animdata_from_id(id); PointerRNA id_ptr, ptr; PropertyRNA *prop; int array_index_max = array_index + 1; int ret = 0; /* sanity checks */ if (ELEM(NULL, id, adt)) { BKE_report(reports, RPT_ERROR, "No ID block and/or AnimData to delete keyframe from"); return 0; } /* validate pointer first - exit if failure */ RNA_id_pointer_create(id, &id_ptr); if (RNA_path_resolve_property(&id_ptr, rna_path, &ptr, &prop) == false) { BKE_reportf( reports, RPT_ERROR, "Could not clear keyframe, as RNA path is invalid for the given ID (ID = %s, path = %s)", id->name, rna_path); return 0; } /* get F-Curve * Note: here is one of the places where we don't want new Action + F-Curve added! * so 'add' var must be 0 */ if (act == NULL) { /* if no action is provided, use the default one attached to this ID-block * - if it doesn't exist, then we're out of options... */ if (adt->action) { act = adt->action; } else { BKE_reportf(reports, RPT_ERROR, "No action to delete keyframes from for ID = %s", id->name); return 0; } } /* key entire array convenience method */ if (array_index == -1) { array_index = 0; array_index_max = RNA_property_array_length(&ptr, prop); /* for single properties, increase max_index so that the property itself gets included, * but don't do this for standard arrays since that can cause corruption issues * (extra unused curves) */ if (array_index_max == array_index) { array_index_max++; } } /* will only loop once unless the array index was -1 */ for (; array_index < array_index_max; array_index++) { FCurve *fcu = ED_action_fcurve_find(act, rna_path, array_index); /* check if F-Curve exists and/or whether it can be edited */ if (fcu == NULL) { continue; } if (BKE_fcurve_is_protected(fcu)) { BKE_reportf(reports, RPT_WARNING, "Not clearing all keyframes from locked F-Curve '%s' for %s '%s'", fcu->rna_path, BKE_idtype_idcode_to_name(GS(id->name)), id->name + 2); continue; } ANIM_fcurve_delete_from_animdata(NULL, adt, fcu); /* return success */ ret++; } if (ret) { deg_tag_after_keyframe_delete(bmain, id, adt); } /* return success/failure */ return ret; } /* ******************************************* */ /* KEYFRAME MODIFICATION */ /* mode for commonkey_modifykey */ enum { COMMONKEY_MODE_INSERT = 0, COMMONKEY_MODE_DELETE, } /*eCommonModifyKey_Modes*/; /* Polling callback for use with ANIM_*_keyframe() operators * This is based on the standard ED_operator_areaactive callback, * except that it does special checks for a few spacetypes too... */ static bool modify_key_op_poll(bContext *C) { ScrArea *area = CTX_wm_area(C); Scene *scene = CTX_data_scene(C); /* if no area or active scene */ if (ELEM(NULL, area, scene)) { return false; } /* should be fine */ return true; } /* Insert Key Operator ------------------------ */ static int insert_key_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); Object *obedit = CTX_data_edit_object(C); bool ob_edit_mode = false; float cfra = (float)CFRA; // XXX for now, don't bother about all the yucky offset crap int num_channels; KeyingSet *ks = keyingset_get_from_op_with_error(op, op->type->prop, scene); if (ks == NULL) { return OPERATOR_CANCELLED; } /* exit the edit mode to make sure that those object data properties that have been * updated since the last switching to the edit mode will be keyframed correctly */ if (obedit && ANIM_keyingset_find_id(ks, (ID *)obedit->data)) { ED_object_mode_toggle(C, OB_MODE_EDIT); ob_edit_mode = true; } /* try to insert keyframes for the channels specified by KeyingSet */ num_channels = ANIM_apply_keyingset(C, NULL, NULL, ks, MODIFYKEY_MODE_INSERT, cfra); if (G.debug & G_DEBUG) { BKE_reportf(op->reports, RPT_INFO, "Keying set '%s' - successfully added %d keyframes", ks->name, num_channels); } /* restore the edit mode if necessary */ if (ob_edit_mode) { ED_object_mode_toggle(C, OB_MODE_EDIT); } /* report failure or do updates? */ if (num_channels < 0) { BKE_report(op->reports, RPT_ERROR, "No suitable context info for active keying set"); return OPERATOR_CANCELLED; } else if (num_channels > 0) { /* if the appropriate properties have been set, make a note that we've inserted something */ if (RNA_boolean_get(op->ptr, "confirm_success")) { BKE_reportf(op->reports, RPT_INFO, "Successfully added %d keyframes for keying set '%s'", num_channels, ks->name); } /* send notifiers that keyframes have been changed */ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_ADDED, NULL); } else { BKE_report(op->reports, RPT_WARNING, "Keying set failed to insert any keyframes"); } return OPERATOR_FINISHED; } void ANIM_OT_keyframe_insert(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Insert Keyframe"; ot->idname = "ANIM_OT_keyframe_insert"; ot->description = "Insert keyframes on the current frame for all properties in the specified Keying Set"; /* callbacks */ ot->exec = insert_key_exec; ot->poll = modify_key_op_poll; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* keyingset to use (dynamic enum) */ prop = RNA_def_enum( ot->srna, "type", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use"); RNA_def_enum_funcs(prop, ANIM_keying_sets_enum_itemf); RNA_def_property_flag(prop, PROP_HIDDEN); ot->prop = prop; /* confirm whether a keyframe was added by showing a popup * - by default, this is enabled, since this operator is assumed to be called independently */ prop = RNA_def_boolean(ot->srna, "confirm_success", 1, "Confirm Successful Insert", "Show a popup when the keyframes get successfully added"); RNA_def_property_flag(prop, PROP_HIDDEN); } /* Clone of 'ANIM_OT_keyframe_insert' which uses a name for the keying set instead of an enum. */ void ANIM_OT_keyframe_insert_by_name(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Insert Keyframe (by name)"; ot->idname = "ANIM_OT_keyframe_insert_by_name"; ot->description = "Alternate access to 'Insert Keyframe' for keymaps to use"; /* callbacks */ ot->exec = insert_key_exec; ot->poll = modify_key_op_poll; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* keyingset to use (idname) */ prop = RNA_def_string_file_path(ot->srna, "type", "Type", MAX_ID_NAME - 2, "", ""); RNA_def_property_flag(prop, PROP_HIDDEN); ot->prop = prop; /* confirm whether a keyframe was added by showing a popup * - by default, this is enabled, since this operator is assumed to be called independently */ prop = RNA_def_boolean(ot->srna, "confirm_success", 1, "Confirm Successful Insert", "Show a popup when the keyframes get successfully added"); RNA_def_property_flag(prop, PROP_HIDDEN); } /* Insert Key Operator (With Menu) ------------------------ */ /* This operator checks if a menu should be shown for choosing the KeyingSet to use, * then calls the menu if necessary before */ static int insert_key_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) { Scene *scene = CTX_data_scene(C); /* if prompting or no active Keying Set, show the menu */ if ((scene->active_keyingset == 0) || RNA_boolean_get(op->ptr, "always_prompt")) { uiPopupMenu *pup; uiLayout *layout; /* call the menu, which will call this operator again, hence the canceled */ pup = UI_popup_menu_begin(C, WM_operatortype_name(op->type, op->ptr), ICON_NONE); layout = UI_popup_menu_layout(pup); uiItemsEnumO(layout, "ANIM_OT_keyframe_insert_menu", "type"); UI_popup_menu_end(C, pup); return OPERATOR_INTERFACE; } else { /* just call the exec() on the active keyingset */ RNA_enum_set(op->ptr, "type", 0); RNA_boolean_set(op->ptr, "confirm_success", true); return op->type->exec(C, op); } } void ANIM_OT_keyframe_insert_menu(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Insert Keyframe Menu"; ot->idname = "ANIM_OT_keyframe_insert_menu"; ot->description = "Insert Keyframes for specified Keying Set, with menu of available Keying Sets if undefined"; /* callbacks */ ot->invoke = insert_key_menu_invoke; ot->exec = insert_key_exec; ot->poll = ED_operator_areaactive; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* keyingset to use (dynamic enum) */ prop = RNA_def_enum( ot->srna, "type", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use"); RNA_def_enum_funcs(prop, ANIM_keying_sets_enum_itemf); RNA_def_property_flag(prop, PROP_HIDDEN); ot->prop = prop; /* confirm whether a keyframe was added by showing a popup * - by default, this is disabled so that if a menu is shown, this doesn't come up too */ // XXX should this just be always on? prop = RNA_def_boolean(ot->srna, "confirm_success", 0, "Confirm Successful Insert", "Show a popup when the keyframes get successfully added"); RNA_def_property_flag(prop, PROP_HIDDEN); /* whether the menu should always be shown * - by default, the menu should only be shown when there is no active Keying Set (2.5 behavior), * although in some cases it might be useful to always shown (pre 2.5 behavior) */ prop = RNA_def_boolean(ot->srna, "always_prompt", 0, "Always Show Menu", ""); RNA_def_property_flag(prop, PROP_HIDDEN); } /* Delete Key Operator ------------------------ */ static int delete_key_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); float cfra = (float)CFRA; // XXX for now, don't bother about all the yucky offset crap int num_channels; KeyingSet *ks = keyingset_get_from_op_with_error(op, op->type->prop, scene); if (ks == NULL) { return OPERATOR_CANCELLED; } const int prop_type = RNA_property_type(op->type->prop); if (prop_type == PROP_ENUM) { int type = RNA_property_enum_get(op->ptr, op->type->prop); ks = ANIM_keyingset_get_from_enum_type(scene, type); if (ks == NULL) { BKE_report(op->reports, RPT_ERROR, "No active Keying Set"); return OPERATOR_CANCELLED; } } else if (prop_type == PROP_STRING) { char type_id[MAX_ID_NAME - 2]; RNA_property_string_get(op->ptr, op->type->prop, type_id); ks = ANIM_keyingset_get_from_idname(scene, type_id); if (ks == NULL) { BKE_reportf(op->reports, RPT_ERROR, "Active Keying Set '%s' not found", type_id); return OPERATOR_CANCELLED; } } else { BLI_assert(0); } /* report failure */ if (ks == NULL) { BKE_report(op->reports, RPT_ERROR, "No active Keying Set"); return OPERATOR_CANCELLED; } /* try to delete keyframes for the channels specified by KeyingSet */ num_channels = ANIM_apply_keyingset(C, NULL, NULL, ks, MODIFYKEY_MODE_DELETE, cfra); if (G.debug & G_DEBUG) { printf("KeyingSet '%s' - Successfully removed %d Keyframes\n", ks->name, num_channels); } /* report failure or do updates? */ if (num_channels < 0) { BKE_report(op->reports, RPT_ERROR, "No suitable context info for active keying set"); return OPERATOR_CANCELLED; } else if (num_channels > 0) { /* if the appropriate properties have been set, make a note that we've inserted something */ if (RNA_boolean_get(op->ptr, "confirm_success")) { BKE_reportf(op->reports, RPT_INFO, "Successfully removed %d keyframes for keying set '%s'", num_channels, ks->name); } /* send notifiers that keyframes have been changed */ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_REMOVED, NULL); } else { BKE_report(op->reports, RPT_WARNING, "Keying set failed to remove any keyframes"); } return OPERATOR_FINISHED; } void ANIM_OT_keyframe_delete(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Delete Keying-Set Keyframe"; ot->idname = "ANIM_OT_keyframe_delete"; ot->description = "Delete keyframes on the current frame for all properties in the specified Keying Set"; /* callbacks */ ot->exec = delete_key_exec; ot->poll = modify_key_op_poll; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* keyingset to use (dynamic enum) */ prop = RNA_def_enum( ot->srna, "type", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use"); RNA_def_enum_funcs(prop, ANIM_keying_sets_enum_itemf); RNA_def_property_flag(prop, PROP_HIDDEN); ot->prop = prop; /* confirm whether a keyframe was added by showing a popup * - by default, this is enabled, since this operator is assumed to be called independently */ RNA_def_boolean(ot->srna, "confirm_success", 1, "Confirm Successful Delete", "Show a popup when the keyframes get successfully removed"); } void ANIM_OT_keyframe_delete_by_name(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Delete Keying-Set Keyframe (by name)"; ot->idname = "ANIM_OT_keyframe_delete_by_name"; ot->description = "Alternate access to 'Delete Keyframe' for keymaps to use"; /* callbacks */ ot->exec = delete_key_exec; ot->poll = modify_key_op_poll; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* keyingset to use (idname) */ prop = RNA_def_string_file_path(ot->srna, "type", "Type", MAX_ID_NAME - 2, "", ""); RNA_def_property_flag(prop, PROP_HIDDEN); ot->prop = prop; /* confirm whether a keyframe was added by showing a popup * - by default, this is enabled, since this operator is assumed to be called independently */ RNA_def_boolean(ot->srna, "confirm_success", 1, "Confirm Successful Delete", "Show a popup when the keyframes get successfully removed"); } /* Delete Key Operator ------------------------ */ /* NOTE: Although this version is simpler than the more generic version for KeyingSets, * it is more useful for animators working in the 3D view. */ static int clear_anim_v3d_exec(bContext *C, wmOperator *UNUSED(op)) { bool changed = false; CTX_DATA_BEGIN (C, Object *, ob, selected_objects) { /* just those in active action... */ if ((ob->adt) && (ob->adt->action)) { AnimData *adt = ob->adt; bAction *act = adt->action; FCurve *fcu, *fcn; for (fcu = act->curves.first; fcu; fcu = fcn) { bool can_delete = false; fcn = fcu->next; /* in pose mode, only delete the F-Curve if it belongs to a selected bone */ if (ob->mode & OB_MODE_POSE) { if ((fcu->rna_path) && strstr(fcu->rna_path, "pose.bones[")) { bPoseChannel *pchan; char *bone_name; /* get bone-name, and check if this bone is selected */ bone_name = BLI_str_quoted_substrN(fcu->rna_path, "pose.bones["); pchan = BKE_pose_channel_find_name(ob->pose, bone_name); if (bone_name) { MEM_freeN(bone_name); } /* delete if bone is selected*/ if ((pchan) && (pchan->bone)) { if (pchan->bone->flag & BONE_SELECTED) { can_delete = true; } } } } else { /* object mode - all of Object's F-Curves are affected */ can_delete = true; } /* delete F-Curve completely */ if (can_delete) { ANIM_fcurve_delete_from_animdata(NULL, adt, fcu); DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); changed = true; } } /* Delete the action itself if it is empty. */ if (ANIM_remove_empty_action_from_animdata(adt)) { changed = true; } } } CTX_DATA_END; if (!changed) { return OPERATOR_CANCELLED; } /* send updates */ WM_event_add_notifier(C, NC_OBJECT | ND_KEYS, NULL); return OPERATOR_FINISHED; } void ANIM_OT_keyframe_clear_v3d(wmOperatorType *ot) { /* identifiers */ ot->name = "Remove Animation"; ot->description = "Remove all keyframe animation for selected objects"; ot->idname = "ANIM_OT_keyframe_clear_v3d"; /* callbacks */ ot->invoke = WM_operator_confirm; ot->exec = clear_anim_v3d_exec; ot->poll = ED_operator_areaactive; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int delete_key_v3d_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); float cfra = (float)CFRA; int selected_objects_len = 0; int selected_objects_success_len = 0; int success_multi = 0; CTX_DATA_BEGIN (C, Object *, ob, selected_objects) { ID *id = &ob->id; int success = 0; selected_objects_len += 1; /* just those in active action... */ if ((ob->adt) && (ob->adt->action)) { AnimData *adt = ob->adt; bAction *act = adt->action; FCurve *fcu, *fcn; const float cfra_unmap = BKE_nla_tweakedit_remap(adt, cfra, NLATIME_CONVERT_UNMAP); for (fcu = act->curves.first; fcu; fcu = fcn) { fcn = fcu->next; /* don't touch protected F-Curves */ if (BKE_fcurve_is_protected(fcu)) { BKE_reportf(op->reports, RPT_WARNING, "Not deleting keyframe for locked F-Curve '%s', object '%s'", fcu->rna_path, id->name + 2); continue; } /* Special exception for bones, as this makes this operator more convenient to use * NOTE: This is only done in pose mode. * In object mode, we're dealing with the entire object. */ if ((ob->mode & OB_MODE_POSE) && strstr(fcu->rna_path, "pose.bones[\"")) { bPoseChannel *pchan; char *bone_name; /* get bone-name, and check if this bone is selected */ bone_name = BLI_str_quoted_substrN(fcu->rna_path, "pose.bones["); pchan = BKE_pose_channel_find_name(ob->pose, bone_name); if (bone_name) { MEM_freeN(bone_name); } /* skip if bone is not selected */ if ((pchan) && (pchan->bone)) { /* bones are only selected/editable if visible... */ bArmature *arm = (bArmature *)ob->data; /* skipping - not visible on currently visible layers */ if ((arm->layer & pchan->bone->layer) == 0) { continue; } /* skipping - is currently hidden */ if (pchan->bone->flag & BONE_HIDDEN_P) { continue; } /* selection flag... */ if ((pchan->bone->flag & BONE_SELECTED) == 0) { continue; } } } /* delete keyframes on current frame * WARNING: this can delete the next F-Curve, hence the "fcn" copying */ success += delete_keyframe_fcurve(adt, fcu, cfra_unmap); } DEG_id_tag_update(&ob->adt->action->id, ID_RECALC_ANIMATION_NO_FLUSH); } /* Only for reporting. */ if (success) { selected_objects_success_len += 1; success_multi += success; } DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); } CTX_DATA_END; /* report success (or failure) */ if (selected_objects_success_len) { BKE_reportf(op->reports, RPT_INFO, "%d object(s) successfully had %d keyframes removed", selected_objects_success_len, success_multi); } else { BKE_reportf( op->reports, RPT_ERROR, "No keyframes removed from %d object(s)", selected_objects_len); } /* send updates */ WM_event_add_notifier(C, NC_OBJECT | ND_KEYS, NULL); return OPERATOR_FINISHED; } void ANIM_OT_keyframe_delete_v3d(wmOperatorType *ot) { /* identifiers */ ot->name = "Delete Keyframe"; ot->description = "Remove keyframes on current frame for selected objects and bones"; ot->idname = "ANIM_OT_keyframe_delete_v3d"; /* callbacks */ ot->invoke = WM_operator_confirm; ot->exec = delete_key_v3d_exec; ot->poll = ED_operator_areaactive; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /* Insert Key Button Operator ------------------------ */ static int insert_key_button_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); ToolSettings *ts = scene->toolsettings; PointerRNA ptr = {NULL}; PropertyRNA *prop = NULL; char *path; uiBut *but; float cfra = (float)CFRA; bool changed = false; int index; const bool all = RNA_boolean_get(op->ptr, "all"); eInsertKeyFlags flag = INSERTKEY_NOFLAGS; /* flags for inserting keyframes */ flag = ANIM_get_keyframing_flags(scene, true); /* try to insert keyframe using property retrieved from UI */ if (!(but = UI_context_active_but_prop_get(C, &ptr, &prop, &index))) { /* pass event on if no active button found */ return (OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH); } if ((ptr.owner_id && ptr.data && prop) && RNA_property_animateable(&ptr, prop)) { if (ptr.type == &RNA_NlaStrip) { /* Handle special properties for NLA Strips, whose F-Curves are stored on the * strips themselves. These are stored separately or else the properties will * not have any effect. */ NlaStrip *strip = ptr.data; FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), index); if (fcu) { changed = insert_keyframe_direct( op->reports, ptr, prop, fcu, cfra, ts->keyframe_type, NULL, 0); } else { BKE_report(op->reports, RPT_ERROR, "This property cannot be animated as it will not get updated correctly"); } } else if (UI_but_flag_is_set(but, UI_BUT_DRIVEN)) { /* Driven property - Find driver */ FCurve *fcu; bool driven, special; fcu = rna_get_fcurve_context_ui(C, &ptr, prop, index, NULL, NULL, &driven, &special); if (fcu && driven) { changed = insert_keyframe_direct( op->reports, ptr, prop, fcu, cfra, ts->keyframe_type, NULL, INSERTKEY_DRIVER); } } else { /* standard properties */ path = RNA_path_from_ID_to_property(&ptr, prop); if (path) { const char *identifier = RNA_property_identifier(prop); const char *group = NULL; /* Special exception for keyframing transforms: * Set "group" for this manually, instead of having them appearing at the bottom * (ungrouped) part of the channels list. * Leaving these ungrouped is not a nice user behavior in this case. * * TODO: Perhaps we can extend this behavior in future for other properties... */ if (ptr.type == &RNA_PoseBone) { bPoseChannel *pchan = ptr.data; group = pchan->name; } else if ((ptr.type == &RNA_Object) && (strstr(identifier, "location") || strstr(identifier, "rotation") || strstr(identifier, "scale"))) { /* NOTE: Keep this label in sync with the "ID" case in * keyingsets_utils.py :: get_transform_generators_base_info() */ group = "Object Transforms"; } if (all) { /* -1 indicates operating on the entire array (or the property itself otherwise) */ index = -1; } changed = (insert_keyframe(bmain, op->reports, ptr.owner_id, NULL, group, path, index, cfra, ts->keyframe_type, NULL, flag) != 0); MEM_freeN(path); } else { BKE_report(op->reports, RPT_WARNING, "Failed to resolve path to property, " "try manually specifying this using a Keying Set instead"); } } } else { if (prop && !RNA_property_animateable(&ptr, prop)) { BKE_reportf(op->reports, RPT_WARNING, "\"%s\" property cannot be animated", RNA_property_identifier(prop)); } else { BKE_reportf(op->reports, RPT_WARNING, "Button doesn't appear to have any property information attached (ptr.data = " "%p, prop = %p)", ptr.data, (void *)prop); } } if (changed) { ID *id = ptr.owner_id; AnimData *adt = BKE_animdata_from_id(id); if (adt->action != NULL) { DEG_id_tag_update(&adt->action->id, ID_RECALC_ANIMATION_NO_FLUSH); } DEG_id_tag_update(id, ID_RECALC_ANIMATION_NO_FLUSH); /* send updates */ UI_context_update_anim_flag(C); /* send notifiers that keyframes have been changed */ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_ADDED, NULL); } return (changed) ? OPERATOR_FINISHED : OPERATOR_CANCELLED; } void ANIM_OT_keyframe_insert_button(wmOperatorType *ot) { /* identifiers */ ot->name = "Insert Keyframe (Buttons)"; ot->idname = "ANIM_OT_keyframe_insert_button"; ot->description = "Insert a keyframe for current UI-active property"; /* callbacks */ ot->exec = insert_key_button_exec; ot->poll = modify_key_op_poll; /* flags */ ot->flag = OPTYPE_UNDO | OPTYPE_INTERNAL; /* properties */ RNA_def_boolean(ot->srna, "all", 1, "All", "Insert a keyframe for all element of the array"); } /* Delete Key Button Operator ------------------------ */ static int delete_key_button_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); PointerRNA ptr = {NULL}; PropertyRNA *prop = NULL; Main *bmain = CTX_data_main(C); char *path; float cfra = (float)CFRA; // XXX for now, don't bother about all the yucky offset crap bool changed = false; int index; const bool all = RNA_boolean_get(op->ptr, "all"); /* try to insert keyframe using property retrieved from UI */ if (!UI_context_active_but_prop_get(C, &ptr, &prop, &index)) { /* pass event on if no active button found */ return (OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH); } if (ptr.owner_id && ptr.data && prop) { if (BKE_nlastrip_has_curves_for_property(&ptr, prop)) { /* Handle special properties for NLA Strips, whose F-Curves are stored on the * strips themselves. These are stored separately or else the properties will * not have any effect. */ ID *id = ptr.owner_id; NlaStrip *strip = ptr.data; FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), 0); if (fcu) { if (BKE_fcurve_is_protected(fcu)) { BKE_reportf( op->reports, RPT_WARNING, "Not deleting keyframe for locked F-Curve for NLA Strip influence on %s - %s '%s'", strip->name, BKE_idtype_idcode_to_name(GS(id->name)), id->name + 2); } else { /* remove the keyframe directly * NOTE: cannot use delete_keyframe_fcurve(), as that will free the curve, * and delete_keyframe() expects the FCurve to be part of an action */ bool found = false; int i; /* try to find index of beztriple to get rid of */ i = binarysearch_bezt_index(fcu->bezt, cfra, fcu->totvert, &found); if (found) { /* delete the key at the index (will sanity check + do recalc afterwards) */ delete_fcurve_key(fcu, i, 1); changed = true; } } } } else { /* standard properties */ path = RNA_path_from_ID_to_property(&ptr, prop); if (path) { if (all) { /* -1 indicates operating on the entire array (or the property itself otherwise) */ index = -1; } changed = delete_keyframe(bmain, op->reports, ptr.owner_id, NULL, path, index, cfra) != 0; MEM_freeN(path); } else if (G.debug & G_DEBUG) { printf("Button Delete-Key: no path to property\n"); } } } else if (G.debug & G_DEBUG) { printf("ptr.data = %p, prop = %p\n", ptr.data, (void *)prop); } if (changed) { /* send updates */ UI_context_update_anim_flag(C); /* send notifiers that keyframes have been changed */ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_REMOVED, NULL); } return (changed) ? OPERATOR_FINISHED : OPERATOR_CANCELLED; } void ANIM_OT_keyframe_delete_button(wmOperatorType *ot) { /* identifiers */ ot->name = "Delete Keyframe (Buttons)"; ot->idname = "ANIM_OT_keyframe_delete_button"; ot->description = "Delete current keyframe of current UI-active property"; /* callbacks */ ot->exec = delete_key_button_exec; ot->poll = modify_key_op_poll; /* flags */ ot->flag = OPTYPE_UNDO | OPTYPE_INTERNAL; /* properties */ RNA_def_boolean(ot->srna, "all", 1, "All", "Delete keyframes from all elements of the array"); } /* Clear Key Button Operator ------------------------ */ static int clear_key_button_exec(bContext *C, wmOperator *op) { PointerRNA ptr = {NULL}; PropertyRNA *prop = NULL; Main *bmain = CTX_data_main(C); char *path; bool changed = false; int index; const bool all = RNA_boolean_get(op->ptr, "all"); /* try to insert keyframe using property retrieved from UI */ if (!UI_context_active_but_prop_get(C, &ptr, &prop, &index)) { /* pass event on if no active button found */ return (OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH); } if (ptr.owner_id && ptr.data && prop) { path = RNA_path_from_ID_to_property(&ptr, prop); if (path) { if (all) { /* -1 indicates operating on the entire array (or the property itself otherwise) */ index = -1; } changed |= (clear_keyframe(bmain, op->reports, ptr.owner_id, NULL, path, index, 0) != 0); MEM_freeN(path); } else if (G.debug & G_DEBUG) { printf("Button Clear-Key: no path to property\n"); } } else if (G.debug & G_DEBUG) { printf("ptr.data = %p, prop = %p\n", ptr.data, (void *)prop); } if (changed) { /* send updates */ UI_context_update_anim_flag(C); /* send notifiers that keyframes have been changed */ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_REMOVED, NULL); } return (changed) ? OPERATOR_FINISHED : OPERATOR_CANCELLED; } void ANIM_OT_keyframe_clear_button(wmOperatorType *ot) { /* identifiers */ ot->name = "Clear Keyframe (Buttons)"; ot->idname = "ANIM_OT_keyframe_clear_button"; ot->description = "Clear all keyframes on the currently active property"; /* callbacks */ ot->exec = clear_key_button_exec; ot->poll = modify_key_op_poll; /* flags */ ot->flag = OPTYPE_UNDO | OPTYPE_INTERNAL; /* properties */ RNA_def_boolean(ot->srna, "all", 1, "All", "Clear keyframes from all elements of the array"); } /* ******************************************* */ /* AUTO KEYFRAME */ bool autokeyframe_cfra_can_key(const Scene *scene, ID *id) { float cfra = (float)CFRA; // XXX for now, this will do /* only filter if auto-key mode requires this */ if (IS_AUTOKEY_ON(scene) == 0) { return false; } if (IS_AUTOKEY_MODE(scene, EDITKEYS)) { /* Replace Mode: * For whole block, only key if there's a keyframe on that frame already * This is a valid assumption when we're blocking + tweaking */ return id_frame_has_keyframe(id, cfra, ANIMFILTER_KEYS_LOCAL); } else { /* Normal Mode (or treat as being normal mode): * * Just in case the flags aren't set properly (i.e. only on/off is set, without a mode) * let's set the "normal" flag too, so that it will all be sane everywhere... */ scene->toolsettings->autokey_mode = AUTOKEY_MODE_NORMAL; /* Can insert anytime we like... */ return true; } } /* ******************************************* */ /* KEYFRAME DETECTION */ /* --------------- API/Per-Datablock Handling ------------------- */ /* Checks if some F-Curve has a keyframe for a given frame */ bool fcurve_frame_has_keyframe(FCurve *fcu, float frame, short filter) { /* quick sanity check */ if (ELEM(NULL, fcu, fcu->bezt)) { return false; } /* we either include all regardless of muting, or only non-muted */ if ((filter & ANIMFILTER_KEYS_MUTED) || (fcu->flag & FCURVE_MUTED) == 0) { bool replace; int i = binarysearch_bezt_index(fcu->bezt, frame, fcu->totvert, &replace); /* binarysearch_bezt_index will set replace to be 0 or 1 * - obviously, 1 represents a match */ if (replace) { /* sanity check: 'i' may in rare cases exceed arraylen */ if ((i >= 0) && (i < fcu->totvert)) { return true; } } } return false; } /* Returns whether the current value of a given property differs from the interpolated value. */ bool fcurve_is_changed(PointerRNA ptr, PropertyRNA *prop, FCurve *fcu, float frame) { PathResolvedRNA anim_rna; anim_rna.ptr = ptr; anim_rna.prop = prop; anim_rna.prop_index = fcu->array_index; float buffer[RNA_MAX_ARRAY_LENGTH]; int count, index = fcu->array_index; float *values = setting_get_rna_values(&ptr, prop, buffer, RNA_MAX_ARRAY_LENGTH, &count); float fcurve_val = calculate_fcurve(&anim_rna, fcu, frame); float cur_val = (index >= 0 && index < count) ? values[index] : 0.0f; if (values != buffer) { MEM_freeN(values); } return !compare_ff_relative(fcurve_val, cur_val, FLT_EPSILON, 64); } /** * Checks whether an Action has a keyframe for a given frame * Since we're only concerned whether a keyframe exists, * we can simply loop until a match is found. */ static bool action_frame_has_keyframe(bAction *act, float frame, short filter) { FCurve *fcu; /* can only find if there is data */ if (act == NULL) { return false; } /* if only check non-muted, check if muted */ if ((filter & ANIMFILTER_KEYS_MUTED) || (act->flag & ACT_MUTED)) { return false; } /* loop over F-Curves, using binary-search to try to find matches * - this assumes that keyframes are only beztriples */ for (fcu = act->curves.first; fcu; fcu = fcu->next) { /* only check if there are keyframes (currently only of type BezTriple) */ if (fcu->bezt && fcu->totvert) { if (fcurve_frame_has_keyframe(fcu, frame, filter)) { return true; } } } /* nothing found */ return false; } /* Checks whether an Object has a keyframe for a given frame */ static bool object_frame_has_keyframe(Object *ob, float frame, short filter) { /* error checking */ if (ob == NULL) { return false; } /* check own animation data - specifically, the action it contains */ if ((ob->adt) && (ob->adt->action)) { /* T41525 - When the active action is a NLA strip being edited, * we need to correct the frame number to "look inside" the * remapped action */ float ob_frame = BKE_nla_tweakedit_remap(ob->adt, frame, NLATIME_CONVERT_UNMAP); if (action_frame_has_keyframe(ob->adt->action, ob_frame, filter)) { return true; } } /* try shapekey keyframes (if available, and allowed by filter) */ if (!(filter & ANIMFILTER_KEYS_LOCAL) && !(filter & ANIMFILTER_KEYS_NOSKEY)) { Key *key = BKE_key_from_object(ob); /* shapekeys can have keyframes ('Relative Shape Keys') * or depend on time (old 'Absolute Shape Keys') */ /* 1. test for relative (with keyframes) */ if (id_frame_has_keyframe((ID *)key, frame, filter)) { return true; } /* 2. test for time */ /* TODO... yet to be implemented (this feature may evolve before then anyway) */ } /* try materials */ if (!(filter & ANIMFILTER_KEYS_LOCAL) && !(filter & ANIMFILTER_KEYS_NOMAT)) { /* if only active, then we can skip a lot of looping */ if (filter & ANIMFILTER_KEYS_ACTIVE) { Material *ma = BKE_object_material_get(ob, (ob->actcol + 1)); /* we only retrieve the active material... */ if (id_frame_has_keyframe((ID *)ma, frame, filter)) { return true; } } else { int a; /* loop over materials */ for (a = 0; a < ob->totcol; a++) { Material *ma = BKE_object_material_get(ob, a + 1); if (id_frame_has_keyframe((ID *)ma, frame, filter)) { return true; } } } } /* nothing found */ return false; } /* --------------- API ------------------- */ /* Checks whether a keyframe exists for the given ID-block one the given frame */ bool id_frame_has_keyframe(ID *id, float frame, short filter) { /* sanity checks */ if (id == NULL) { return false; } /* perform special checks for 'macro' types */ switch (GS(id->name)) { case ID_OB: /* object */ return object_frame_has_keyframe((Object *)id, frame, filter); #if 0 // XXX TODO... for now, just use 'normal' behavior case ID_SCE: /* scene */ break; #endif default: /* 'normal type' */ { AnimData *adt = BKE_animdata_from_id(id); /* only check keyframes in active action */ if (adt) { return action_frame_has_keyframe(adt->action, frame, filter); } break; } } /* no keyframe found */ return false; } /* ************************************************** */ bool ED_autokeyframe_object(bContext *C, Scene *scene, Object *ob, KeyingSet *ks) { /* auto keyframing */ if (autokeyframe_cfra_can_key(scene, &ob->id)) { ListBase dsources = {NULL, NULL}; /* Now insert the key-frame(s) using the Keying Set: * 1) Add data-source override for the Object. * 2) Insert key-frames. * 3) Free the extra info. */ ANIM_relative_keyingset_add_source(&dsources, &ob->id, NULL, NULL); ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, (float)CFRA); BLI_freelistN(&dsources); return true; } else { return false; } } bool ED_autokeyframe_pchan( bContext *C, Scene *scene, Object *ob, bPoseChannel *pchan, KeyingSet *ks) { if (autokeyframe_cfra_can_key(scene, &ob->id)) { ListBase dsources = {NULL, NULL}; /* Now insert the keyframe(s) using the Keying Set: * 1) Add data-source override for the pose-channel. * 2) Insert key-frames. * 3) Free the extra info. */ ANIM_relative_keyingset_add_source(&dsources, &ob->id, &RNA_PoseBone, pchan); ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, (float)CFRA); BLI_freelistN(&dsources); /* clear any unkeyed tags */ if (pchan->bone) { pchan->bone->flag &= ~BONE_UNKEYED; } return true; } else { /* add unkeyed tags */ if (pchan->bone) { pchan->bone->flag |= BONE_UNKEYED; } return false; } } /** * Use for auto-keyframing from the UI. */ bool ED_autokeyframe_property( bContext *C, Scene *scene, PointerRNA *ptr, PropertyRNA *prop, int rnaindex, float cfra) { Main *bmain = CTX_data_main(C); ID *id; bAction *action; FCurve *fcu; bool driven; bool special; bool changed = false; fcu = rna_get_fcurve_context_ui(C, ptr, prop, rnaindex, NULL, &action, &driven, &special); if (fcu == NULL) { return changed; } if (special) { /* NLA Strip property */ if (IS_AUTOKEY_ON(scene)) { ReportList *reports = CTX_wm_reports(C); ToolSettings *ts = scene->toolsettings; changed = insert_keyframe_direct(reports, *ptr, prop, fcu, cfra, ts->keyframe_type, NULL, 0); WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL); } } else if (driven) { /* Driver - Try to insert keyframe using the driver's input as the frame, * making it easier to set up corrective drivers */ if (IS_AUTOKEY_ON(scene)) { ReportList *reports = CTX_wm_reports(C); ToolSettings *ts = scene->toolsettings; changed = insert_keyframe_direct( reports, *ptr, prop, fcu, cfra, ts->keyframe_type, NULL, INSERTKEY_DRIVER); WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL); } } else { id = ptr->owner_id; /* TODO: this should probably respect the keyingset only option for anim */ if (autokeyframe_cfra_can_key(scene, id)) { ReportList *reports = CTX_wm_reports(C); ToolSettings *ts = scene->toolsettings; const eInsertKeyFlags flag = ANIM_get_keyframing_flags(scene, true); /* Note: We use rnaindex instead of fcu->array_index, * because a button may control all items of an array at once. * E.g., color wheels (see T42567). */ BLI_assert((fcu->array_index == rnaindex) || (rnaindex == -1)); changed = insert_keyframe(bmain, reports, id, action, ((fcu->grp) ? (fcu->grp->name) : (NULL)), fcu->rna_path, rnaindex, cfra, ts->keyframe_type, NULL, flag) != 0; WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, NULL); } } return changed; } /* -------------------------------------------------------------------- */ /** \name Internal Utilities * \{ */ /** Use for insert/delete key-frame. */ static KeyingSet *keyingset_get_from_op_with_error(wmOperator *op, PropertyRNA *prop, Scene *scene) { KeyingSet *ks = NULL; const int prop_type = RNA_property_type(prop); if (prop_type == PROP_ENUM) { int type = RNA_property_enum_get(op->ptr, prop); ks = ANIM_keyingset_get_from_enum_type(scene, type); if (ks == NULL) { BKE_report(op->reports, RPT_ERROR, "No active Keying Set"); } } else if (prop_type == PROP_STRING) { char type_id[MAX_ID_NAME - 2]; RNA_property_string_get(op->ptr, prop, type_id); ks = ANIM_keyingset_get_from_idname(scene, type_id); if (ks == NULL) { BKE_reportf(op->reports, RPT_ERROR, "Keying set '%s' not found", type_id); } } else { BLI_assert(0); } return ks; } /** \} */
867787.c
/* GTK - The GIMP Toolkit * Copyright (C) 2018, Red Hat, 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; either * version 2 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 "config.h" #include "gtkcolorpickershellprivate.h" #include <gio/gio.h> struct _GtkColorPickerShell { GObject parent_instance; GDBusProxy *shell_proxy; GTask *task; }; struct _GtkColorPickerShellClass { GObjectClass parent_class; }; static GInitableIface *initable_parent_iface; static void gtk_color_picker_shell_initable_iface_init (GInitableIface *iface); static void gtk_color_picker_shell_iface_init (GtkColorPickerInterface *iface); G_DEFINE_TYPE_WITH_CODE (GtkColorPickerShell, gtk_color_picker_shell, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, gtk_color_picker_shell_initable_iface_init) G_IMPLEMENT_INTERFACE (GTK_TYPE_COLOR_PICKER, gtk_color_picker_shell_iface_init)) static gboolean gtk_color_picker_shell_initable_init (GInitable *initable, GCancellable *cancellable, GError **error) { GtkColorPickerShell *picker = GTK_COLOR_PICKER_SHELL (initable); char *owner; picker->shell_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.gnome.Shell.Screenshot", "/org/gnome/Shell/Screenshot", "org.gnome.Shell.Screenshot", NULL, error); if (picker->shell_proxy == NULL) { g_debug ("Failed to create shell screenshot proxy"); return FALSE; } owner = g_dbus_proxy_get_name_owner (picker->shell_proxy); if (owner == NULL) { g_debug ("org.gnome.Shell.Screenshot not provided"); g_clear_object (&picker->shell_proxy); return FALSE; } g_free (owner); return TRUE; } static void gtk_color_picker_shell_initable_iface_init (GInitableIface *iface) { initable_parent_iface = g_type_interface_peek_parent (iface); iface->init = gtk_color_picker_shell_initable_init; } static void gtk_color_picker_shell_init (GtkColorPickerShell *picker) { } static void gtk_color_picker_shell_finalize (GObject *object) { GtkColorPickerShell *picker = GTK_COLOR_PICKER_SHELL (object); g_clear_object (&picker->shell_proxy); G_OBJECT_CLASS (gtk_color_picker_shell_parent_class)->finalize (object); } static void gtk_color_picker_shell_class_init (GtkColorPickerShellClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); object_class->finalize = gtk_color_picker_shell_finalize; } GtkColorPicker * gtk_color_picker_shell_new (void) { return GTK_COLOR_PICKER (g_initable_new (GTK_TYPE_COLOR_PICKER_SHELL, NULL, NULL, NULL)); } static void color_picked (GObject *source, GAsyncResult *res, gpointer data) { GtkColorPickerShell *picker = GTK_COLOR_PICKER_SHELL (data); GError *error = NULL; GVariant *ret, *dict; ret = g_dbus_proxy_call_finish (picker->shell_proxy, res, &error); if (ret == NULL) { g_task_return_error (picker->task, error); } else { double d1, d2, d3; g_variant_get (ret, "(@a{sv})", &dict); if (!g_variant_lookup (dict, "color", "(ddd)", &d1, &d2, &d3)) g_task_return_new_error (picker->task, G_IO_ERROR, G_IO_ERROR_FAILED, "No color received"); else g_task_return_pointer (picker->task, gdk_rgba_copy (&(GdkRGBA){d1, d2, d3, 1.0f}), (GDestroyNotify)gdk_rgba_free); g_variant_unref (dict); g_variant_unref (ret); } g_clear_object (&picker->task); } static void gtk_color_picker_shell_pick (GtkColorPicker *cp, GAsyncReadyCallback callback, gpointer user_data) { GtkColorPickerShell *picker = GTK_COLOR_PICKER_SHELL (cp); if (picker->task) return; picker->task = g_task_new (picker, NULL, callback, user_data); g_dbus_proxy_call (picker->shell_proxy, "PickColor", NULL, 0, -1, NULL, color_picked, picker); } static GdkRGBA * gtk_color_picker_shell_pick_finish (GtkColorPicker *cp, GAsyncResult *res, GError **error) { g_return_val_if_fail (g_task_is_valid (res, cp), NULL); return g_task_propagate_pointer (G_TASK (res), error); } static void gtk_color_picker_shell_iface_init (GtkColorPickerInterface *iface) { iface->pick = gtk_color_picker_shell_pick; iface->pick_finish = gtk_color_picker_shell_pick_finish; }
753763.c
/* This file handles the EXEC system call. It performs the work as follows: * - see if the permissions allow the file to be executed * - read the header and extract the sizes * - fetch the initial args and environment from the user space * - allocate the memory for the new process * - copy the initial stack from MM to the process * - read in the text and data segments and copy to the process * - take care of setuid and setgid bits * - fix up 'mproc' table * - tell kernel about EXEC * - save offset to initial argc (for ps) * * The entry points into this file are: * do_exec: perform the EXEC system call * rw_seg: read or write a segment from or to a file * find_share: find a process whose text segment can be shared */ #include "mm.h" #include <sys/stat.h> #include <minix/callnr.h> #include <a.out.h> #include <signal.h> #include <string.h> #include "mproc.h" #include "param.h" FORWARD _PROTOTYPE( int new_mem, (struct mproc *sh_mp, vir_bytes text_bytes, vir_bytes data_bytes, vir_bytes bss_bytes, vir_bytes stk_bytes, phys_bytes tot_bytes) ); FORWARD _PROTOTYPE( void patch_ptr, (char stack[ARG_MAX], vir_bytes base) ); FORWARD _PROTOTYPE( int insert_arg, (char stack[ARG_MAX], vir_bytes *stk_bytes, char *arg, int replace) ); FORWARD _PROTOTYPE( char *patch_stack, (int fd, char stack[ARG_MAX], vir_bytes *stk_bytes, char *script) ); FORWARD _PROTOTYPE( int read_header, (int fd, int *ft, vir_bytes *text_bytes, vir_bytes *data_bytes, vir_bytes *bss_bytes, phys_bytes *tot_bytes, long *sym_bytes, vir_clicks sc, vir_bytes *pc) ); #define ESCRIPT (-2000) /* Returned by read_header for a #! script. */ #define PTRSIZE sizeof(char *) /* Size of pointers in argv[] and envp[]. */ /*===========================================================================* * do_exec * *===========================================================================*/ PUBLIC int do_exec() { /* Perform the execve(name, argv, envp) call. The user library builds a * complete stack image, including pointers, args, environ, etc. The stack * is copied to a buffer inside MM, and then to the new core image. */ register struct mproc *rmp; struct mproc *sh_mp; int m, r, fd, ft, sn; static char mbuf[ARG_MAX]; /* buffer for stack and zeroes */ static char name_buf[PATH_MAX]; /* the name of the file to exec */ char *new_sp, *name, *basename; vir_bytes src, dst, text_bytes, data_bytes, bss_bytes, stk_bytes, vsp; phys_bytes tot_bytes; /* total space for program, including gap */ long sym_bytes; vir_clicks sc; struct stat s_buf[2], *s_p; vir_bytes pc; /* Do some validity checks. */ rmp = mp; stk_bytes = (vir_bytes) stack_bytes; if (stk_bytes > ARG_MAX) return(ENOMEM); /* stack too big */ if (exec_len <= 0 || exec_len > PATH_MAX) return(EINVAL); /* Get the exec file name and see if the file is executable. */ src = (vir_bytes) exec_name; dst = (vir_bytes) name_buf; r = sys_copy(who, D, (phys_bytes) src, MM_PROC_NR, D, (phys_bytes) dst, (phys_bytes) exec_len); if (r != OK) return(r); /* file name not in user data segment */ /* Fetch the stack from the user before destroying the old core image. */ src = (vir_bytes) stack_ptr; dst = (vir_bytes) mbuf; r = sys_copy(who, D, (phys_bytes) src, MM_PROC_NR, D, (phys_bytes) dst, (phys_bytes)stk_bytes); if (r != OK) return(EACCES); /* can't fetch stack (e.g. bad virtual addr) */ r = 0; /* r = 0 (first attempt), or 1 (interpreted script) */ name = name_buf; /* name of file to exec. */ do { s_p = &s_buf[r]; tell_fs(CHDIR, who, FALSE, 0); /* switch to the user's FS environ */ fd = allowed(name, s_p, X_BIT); /* is file executable? */ if (fd < 0) return(fd); /* file was not executable */ /* Read the file header and extract the segment sizes. */ sc = (stk_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT; m = read_header(fd, &ft, &text_bytes, &data_bytes, &bss_bytes, &tot_bytes, &sym_bytes, sc, &pc); if (m != ESCRIPT || ++r > 1) break; } while ((name = patch_stack(fd, mbuf, &stk_bytes, name_buf)) != NULL); if (m < 0) { close(fd); /* something wrong with header */ return(stk_bytes > ARG_MAX ? ENOMEM : ENOEXEC); } /* Can the process' text be shared with that of one already running? */ sh_mp = find_share(rmp, s_p->st_ino, s_p->st_dev, s_p->st_ctime); /* Allocate new memory and release old memory. Fix map and tell kernel. */ r = new_mem(sh_mp, text_bytes, data_bytes, bss_bytes, stk_bytes, tot_bytes); if (r != OK) { close(fd); /* insufficient core or program too big */ return(r); } /* Save file identification to allow it to be shared. */ rmp->mp_ino = s_p->st_ino; rmp->mp_dev = s_p->st_dev; rmp->mp_ctime = s_p->st_ctime; /* Patch up stack and copy it from MM to new core image. */ vsp = (vir_bytes) rmp->mp_seg[S].mem_vir << CLICK_SHIFT; vsp += (vir_bytes) rmp->mp_seg[S].mem_len << CLICK_SHIFT; vsp -= stk_bytes; patch_ptr(mbuf, vsp); src = (vir_bytes) mbuf; r = sys_copy(MM_PROC_NR, D, (phys_bytes) src, who, D, (phys_bytes) vsp, (phys_bytes)stk_bytes); if (r != OK) panic("do_exec stack copy err on", who); /* Read in text and data segments. */ if (sh_mp != NULL) { lseek(fd, (off_t) text_bytes, SEEK_CUR); /* shared: skip text */ } else { rw_seg(0, fd, who, T, text_bytes); } rw_seg(0, fd, who, D, data_bytes); close(fd); /* don't need exec file any more */ /* Take care of setuid/setgid bits. */ if ((rmp->mp_flags & TRACED) == 0) { /* suppress if tracing */ if (s_buf[0].st_mode & I_SET_UID_BIT) { rmp->mp_effuid = s_buf[0].st_uid; tell_fs(SETUID,who, (int)rmp->mp_realuid, (int)rmp->mp_effuid); } if (s_buf[0].st_mode & I_SET_GID_BIT) { rmp->mp_effgid = s_buf[0].st_gid; tell_fs(SETGID,who, (int)rmp->mp_realgid, (int)rmp->mp_effgid); } } /* Save offset to initial argc (for ps) */ rmp->mp_procargs = vsp; /* Fix 'mproc' fields, tell kernel that exec is done, reset caught sigs. */ for (sn = 1; sn <= _NSIG; sn++) { if (sigismember(&rmp->mp_catch, sn)) { sigdelset(&rmp->mp_catch, sn); rmp->mp_sigact[sn].sa_handler = SIG_DFL; sigemptyset(&rmp->mp_sigact[sn].sa_mask); } } rmp->mp_flags &= ~SEPARATE; /* turn off SEPARATE bit */ rmp->mp_flags |= ft; /* turn it on for separate I & D files */ new_sp = (char *) vsp; tell_fs(EXEC, who, 0, 0); /* allow FS to handle FD_CLOEXEC files */ /* System will save command line for debugging, ps(1) output, etc. */ basename = strrchr(name, '/'); if (basename == NULL) basename = name; else basename++; sys_exec(who, new_sp, rmp->mp_flags & TRACED, basename, pc); return(E_NO_MESSAGE); /* no reply, new program just runs */ } /*===========================================================================* * read_header * *===========================================================================*/ PRIVATE int read_header(fd, ft, text_bytes, data_bytes, bss_bytes, tot_bytes, sym_bytes, sc, pc) int fd; /* file descriptor for reading exec file */ int *ft; /* place to return ft number */ vir_bytes *text_bytes; /* place to return text size */ vir_bytes *data_bytes; /* place to return initialized data size */ vir_bytes *bss_bytes; /* place to return bss size */ phys_bytes *tot_bytes; /* place to return total size */ long *sym_bytes; /* place to return symbol table size */ vir_clicks sc; /* stack size in clicks */ vir_bytes *pc; /* program entry point (initial PC) */ { /* Read the header and extract the text, data, bss and total sizes from it. */ int m, ct; vir_clicks tc, dc, s_vir, dvir; phys_clicks totc; struct exec hdr; /* a.out header is read in here */ /* Read the header and check the magic number. The standard MINIX header * is defined in <a.out.h>. It consists of 8 chars followed by 6 longs. * Then come 4 more longs that are not used here. * Byte 0: magic number 0x01 * Byte 1: magic number 0x03 * Byte 2: normal = 0x10 (not checked, 0 is OK), separate I/D = 0x20 * Byte 3: CPU type, Intel 16 bit = 0x04, Intel 32 bit = 0x10, * Motorola = 0x0B, Sun SPARC = 0x17 * Byte 4: Header length = 0x20 * Bytes 5-7 are not used. * * Now come the 6 longs * Bytes 8-11: size of text segments in bytes * Bytes 12-15: size of initialized data segment in bytes * Bytes 16-19: size of bss in bytes * Bytes 20-23: program entry point * Bytes 24-27: total memory allocated to program (text, data + stack) * Bytes 28-31: size of symbol table in bytes * The longs are represented in a machine dependent order, * little-endian on the 8088, big-endian on the 68000. * The header is followed directly by the text and data segments, and the * symbol table (if any). The sizes are given in the header. Only the * text and data segments are copied into memory by exec. The header is * used here only. The symbol table is for the benefit of a debugger and * is ignored here. */ if ((m= read(fd, &hdr, A_MINHDR)) < 2) return(ENOEXEC); /* Interpreted script? */ if (((char *) &hdr)[0] == '#' && ((char *) &hdr)[1] == '!') return(ESCRIPT); if (m != A_MINHDR) return(ENOEXEC); /* Check magic number, cpu type, and flags. */ if (BADMAG(hdr)) return(ENOEXEC); #if (CHIP == INTEL && _WORD_SIZE == 2) if (hdr.a_cpu != A_I8086) return(ENOEXEC); #endif #if (CHIP == INTEL && _WORD_SIZE == 4) if (hdr.a_cpu != A_I80386) return(ENOEXEC); #endif if ((hdr.a_flags & ~(A_NSYM | A_EXEC | A_SEP)) != 0) return(ENOEXEC); *ft = ( (hdr.a_flags & A_SEP) ? SEPARATE : 0); /* separate I & D or not */ /* Get text and data sizes. */ *text_bytes = (vir_bytes) hdr.a_text; /* text size in bytes */ *data_bytes = (vir_bytes) hdr.a_data; /* data size in bytes */ *bss_bytes = (vir_bytes) hdr.a_bss; /* bss size in bytes */ *tot_bytes = hdr.a_total; /* total bytes to allocate for prog */ *sym_bytes = hdr.a_syms; /* symbol table size in bytes */ if (*tot_bytes == 0) return(ENOEXEC); if (*ft != SEPARATE) { /* If I & D space is not separated, it is all considered data. Text=0*/ *data_bytes += *text_bytes; *text_bytes = 0; } *pc = hdr.a_entry; /* initial address to start execution */ /* Check to see if segment sizes are feasible. */ tc = ((unsigned long) *text_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT; dc = (*data_bytes + *bss_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT; totc = (*tot_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT; if (dc >= totc) return(ENOEXEC); /* stack must be at least 1 click */ dvir = (*ft == SEPARATE ? 0 : tc); s_vir = dvir + (totc - sc); m = size_ok(*ft, tc, dc, sc, dvir, s_vir); ct = hdr.a_hdrlen & BYTE; /* header length */ if (ct > A_MINHDR) lseek(fd, (off_t) ct, SEEK_SET); /* skip unused hdr */ return(m); } /*===========================================================================* * new_mem * *===========================================================================*/ PRIVATE int new_mem(sh_mp, text_bytes, data_bytes,bss_bytes,stk_bytes,tot_bytes) struct mproc *sh_mp; /* text can be shared with this process */ vir_bytes text_bytes; /* text segment size in bytes */ vir_bytes data_bytes; /* size of initialized data in bytes */ vir_bytes bss_bytes; /* size of bss in bytes */ vir_bytes stk_bytes; /* size of initial stack segment in bytes */ phys_bytes tot_bytes; /* total memory to allocate, including gap */ { /* Allocate new memory and release the old memory. Change the map and report * the new map to the kernel. Zero the new core image's bss, gap and stack. */ register struct mproc *rmp; vir_clicks text_clicks, data_clicks, gap_clicks, stack_clicks, tot_clicks; phys_clicks new_base; static char zero[1024]; /* used to zero bss */ phys_bytes bytes, base, count, bss_offset; /* No need to allocate text if it can be shared. */ if (sh_mp != NULL) text_bytes = 0; /* Allow the old data to be swapped out to make room. (Which is really a * waste of time, because we are going to throw it away anyway.) */ rmp->mp_flags |= WAITING; /* Acquire the new memory. Each of the 4 parts: text, (data+bss), gap, * and stack occupies an integral number of clicks, starting at click * boundary. The data and bss parts are run together with no space. */ text_clicks = ((unsigned long) text_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT; data_clicks = (data_bytes + bss_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT; stack_clicks = (stk_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT; tot_clicks = (tot_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT; gap_clicks = tot_clicks - data_clicks - stack_clicks; if ( (int) gap_clicks < 0) return(ENOMEM); /* Try to allocate memory for the new process. */ new_base = alloc_mem(text_clicks + tot_clicks); if (new_base == NO_MEM) return(EAGAIN); /* We've got memory for the new core image. Release the old one. */ rmp = mp; if (find_share(rmp, rmp->mp_ino, rmp->mp_dev, rmp->mp_ctime) == NULL) { /* No other process shares the text segment, so free it. */ free_mem(rmp->mp_seg[T].mem_phys, rmp->mp_seg[T].mem_len); } /* Free the data and stack segments. */ free_mem(rmp->mp_seg[D].mem_phys, rmp->mp_seg[S].mem_vir + rmp->mp_seg[S].mem_len - rmp->mp_seg[D].mem_vir); /* We have now passed the point of no return. The old core image has been * forever lost, memory for a new core image has been allocated. Set up * and report new map. */ if (sh_mp != NULL) { /* Share the text segment. */ rmp->mp_seg[T] = sh_mp->mp_seg[T]; } else { rmp->mp_seg[T].mem_phys = new_base; rmp->mp_seg[T].mem_vir = 0; rmp->mp_seg[T].mem_len = text_clicks; } rmp->mp_seg[D].mem_phys = new_base + text_clicks; rmp->mp_seg[D].mem_vir = 0; rmp->mp_seg[D].mem_len = data_clicks; rmp->mp_seg[S].mem_phys = rmp->mp_seg[D].mem_phys + data_clicks + gap_clicks; rmp->mp_seg[S].mem_vir = rmp->mp_seg[D].mem_vir + data_clicks + gap_clicks; rmp->mp_seg[S].mem_len = stack_clicks; #if (CHIP == M68000) rmp->mp_seg[T].mem_vir = 0; rmp->mp_seg[D].mem_vir = rmp->mp_seg[T].mem_len; rmp->mp_seg[S].mem_vir = rmp->mp_seg[D].mem_vir + rmp->mp_seg[D].mem_len + gap_clicks; #endif sys_newmap(who, rmp->mp_seg); /* report new map to the kernel */ /* The old memory may have been swapped out, but the new memory is real. */ rmp->mp_flags &= ~(WAITING|ONSWAP|SWAPIN); /* Zero the bss, gap, and stack segment. */ bytes = (phys_bytes)(data_clicks + gap_clicks + stack_clicks) << CLICK_SHIFT; base = (phys_bytes) rmp->mp_seg[D].mem_phys << CLICK_SHIFT; bss_offset = (data_bytes >> CLICK_SHIFT) << CLICK_SHIFT; base += bss_offset; bytes -= bss_offset; while (bytes > 0) { count = MIN(bytes, (phys_bytes) sizeof(zero)); if (sys_copy(MM_PROC_NR, D, (phys_bytes) zero, ABS, 0, base, count) != OK) { panic("new_mem can't zero", NO_NUM); } base += count; bytes -= count; } return(OK); } /*===========================================================================* * patch_ptr * *===========================================================================*/ PRIVATE void patch_ptr(stack, base) char stack[ARG_MAX]; /* pointer to stack image within MM */ vir_bytes base; /* virtual address of stack base inside user */ { /* When doing an exec(name, argv, envp) call, the user builds up a stack * image with arg and env pointers relative to the start of the stack. Now * these pointers must be relocated, since the stack is not positioned at * address 0 in the user's address space. */ char **ap, flag; vir_bytes v; flag = 0; /* counts number of 0-pointers seen */ ap = (char **) stack; /* points initially to 'nargs' */ ap++; /* now points to argv[0] */ while (flag < 2) { if (ap >= (char **) &stack[ARG_MAX]) return; /* too bad */ if (*ap != NULL) { v = (vir_bytes) *ap; /* v is relative pointer */ v += base; /* relocate it */ *ap = (char *) v; /* put it back */ } else { flag++; } ap++; } } /*===========================================================================* * insert_arg * *===========================================================================*/ PRIVATE int insert_arg(stack, stk_bytes, arg, replace) char stack[ARG_MAX]; /* pointer to stack image within MM */ vir_bytes *stk_bytes; /* size of initial stack */ char *arg; /* argument to prepend/replace as new argv[0] */ int replace; { /* Patch the stack so that arg will become argv[0]. Be careful, the stack may * be filled with garbage, although it normally looks like this: * nargs argv[0] ... argv[nargs-1] NULL envp[0] ... NULL * followed by the strings "pointed" to by the argv[i] and the envp[i]. The * pointers are really offsets from the start of stack. * Return true iff the operation succeeded. */ int offset, a0, a1, old_bytes = *stk_bytes; /* Prepending arg adds at least one string and a zero byte. */ offset = strlen(arg) + 1; a0 = (int) ((char **) stack)[1]; /* argv[0] */ if (a0 < 4 * PTRSIZE || a0 >= old_bytes) return(FALSE); a1 = a0; /* a1 will point to the strings to be moved */ if (replace) { /* Move a1 to the end of argv[0][] (argv[1] if nargs > 1). */ do { if (a1 == old_bytes) return(FALSE); --offset; } while (stack[a1++] != 0); } else { offset += PTRSIZE; /* new argv[0] needs new pointer in argv[] */ a0 += PTRSIZE; /* location of new argv[0][]. */ } /* stack will grow by offset bytes (or shrink by -offset bytes) */ if ((*stk_bytes += offset) > ARG_MAX) return(FALSE); /* Reposition the strings by offset bytes */ memmove(stack + a1 + offset, stack + a1, old_bytes - a1); strcpy(stack + a0, arg); /* Put arg in the new space. */ if (!replace) { /* Make space for a new argv[0]. */ memmove(stack + 2 * PTRSIZE, stack + 1 * PTRSIZE, a0 - 2 * PTRSIZE); ((char **) stack)[0]++; /* nargs++; */ } /* Now patch up argv[] and envp[] by offset. */ patch_ptr(stack, (vir_bytes) offset); ((char **) stack)[1] = (char *) a0; /* set argv[0] correctly */ return(TRUE); } /*===========================================================================* * patch_stack * *===========================================================================*/ PRIVATE char *patch_stack(fd, stack, stk_bytes, script) int fd; /* file descriptor to open script file */ char stack[ARG_MAX]; /* pointer to stack image within MM */ vir_bytes *stk_bytes; /* size of initial stack */ char *script; /* name of script to interpret */ { /* Patch the argument vector to include the path name of the script to be * interpreted, and all strings on the #! line. Returns the path name of * the interpreter. */ char *sp, *interp = NULL; int n; enum { INSERT=FALSE, REPLACE=TRUE }; /* Make script[] the new argv[0]. */ if (!insert_arg(stack, stk_bytes, script, REPLACE)) return(NULL); if (lseek(fd, 2L, 0) == -1 /* just behind the #! */ || (n= read(fd, script, PATH_MAX)) < 0 /* read line one */ || (sp= memchr(script, '\n', n)) == NULL) /* must be a proper line */ return(NULL); /* Move sp backwards through script[], prepending each string to stack. */ for (;;) { /* skip spaces behind argument. */ while (sp > script && (*--sp == ' ' || *sp == '\t')) {} if (sp == script) break; sp[1] = 0; /* Move to the start of the argument. */ while (sp > script && sp[-1] != ' ' && sp[-1] != '\t') --sp; interp = sp; if (!insert_arg(stack, stk_bytes, sp, INSERT)) return(NULL); } /* Round *stk_bytes up to the size of a pointer for alignment contraints. */ *stk_bytes= ((*stk_bytes + PTRSIZE - 1) / PTRSIZE) * PTRSIZE; close(fd); return(interp); } /*===========================================================================* * rw_seg * *===========================================================================*/ PUBLIC void rw_seg(rw, fd, proc, seg, seg_bytes0) int rw; /* 0 = read, 1 = write */ int fd; /* file descriptor to read from / write to */ int proc; /* process number */ int seg; /* T, D, or S */ phys_bytes seg_bytes0; /* how much is to be transferred? */ { /* Transfer text or data from/to a file and copy to/from a process segment. * This procedure is a little bit tricky. The logical way to transfer a * segment would be block by block and copying each block to/from the user * space one at a time. This is too slow, so we do something dirty here, * namely send the user space and virtual address to the file system in the * upper 10 bits of the file descriptor, and pass it the user virtual address * instead of a MM address. The file system extracts these parameters when * gets a read or write call from the memory manager, which is the only process * that is permitted to use this trick. The file system then copies the whole * segment directly to/from user space, bypassing MM completely. * * The byte count on read is usually smaller than the segment count, because * a segment is padded out to a click multiple, and the data segment is only * partially initialized. */ int new_fd, bytes, r; char *ubuf_ptr; struct mem_map *sp = &mproc[proc].mp_seg[seg]; phys_bytes seg_bytes = seg_bytes0; new_fd = (proc << 7) | (seg << 5) | fd; ubuf_ptr = (char *) ((vir_bytes) sp->mem_vir << CLICK_SHIFT); while (seg_bytes != 0) { bytes = MIN((INT_MAX / BLOCK_SIZE) * BLOCK_SIZE, seg_bytes); if (rw == 0) { r = read(new_fd, ubuf_ptr, bytes); } else { r = write(new_fd, ubuf_ptr, bytes); } if (r != bytes) break; ubuf_ptr += bytes; seg_bytes -= bytes; } } /*===========================================================================* * find_share * *===========================================================================*/ PUBLIC struct mproc *find_share(mp_ign, ino, dev, ctime) struct mproc *mp_ign; /* process that should not be looked at */ ino_t ino; /* parameters that uniquely identify a file */ dev_t dev; time_t ctime; { /* Look for a process that is the file <ino, dev, ctime> in execution. Don't * accidentally "find" mp_ign, because it is the process on whose behalf this * call is made. */ struct mproc *sh_mp; for (sh_mp = &mproc[INIT_PROC_NR]; sh_mp < &mproc[NR_PROCS]; sh_mp++) { if (!(sh_mp->mp_flags & SEPARATE)) continue; if (sh_mp == mp_ign) continue; if (sh_mp->mp_ino != ino) continue; if (sh_mp->mp_dev != dev) continue; if (sh_mp->mp_ctime != ctime) continue; return sh_mp; } return(NULL); }
774025.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> enum { C_DIR, C_LNK, C_SOCK, C_FIFO, C_EXEC, C_BLK, C_CHR, C_SUID, C_SGID, C_WSDIR, C_WDIR, C_NUMCOLORS }; static const char colors[C_NUMCOLORS][6] = { "34", "35", "32", "33", "31", "34;46", "34;43", "30;41", "30;46", "30;42", "30;43" }; static int colortype(mode_t mode) { switch (mode & S_IFMT) { case S_IFDIR: if (mode & S_IWOTH) { if (mode & S_ISTXT) return C_WSDIR; return C_WDIR; } return C_DIR; case S_IFLNK: return C_LNK; case S_IFSOCK: return C_SOCK; case S_IFIFO: return C_FIFO; case S_IFBLK: return C_BLK; case S_IFCHR: return C_CHR; default: break; } if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) { if (mode & S_ISUID) return C_SUID; if (mode & S_ISGID) return C_SGID; return C_EXEC; } return -1; } int main(void) { char *pos; char line[4096]; struct stat st; int x; while (fgets(line, sizeof(line), stdin) != NULL) { if ((pos = strrchr(line, '\n')) != NULL) *pos = '\0'; if (lstat(line, &st) < 0) { printf("%s\n", line); continue; } if ((x = colortype(st.st_mode)) == -1) { printf("%s\n", line); continue; } printf("\e[%sm%s\e[m\n", colors[x], line); } fflush(stdout); _exit(0); }
193195.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* bignum_sqr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: acazuc <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/19 16:54:54 by acazuc #+# #+# */ /* Updated: 2018/10/19 16:55:22 by acazuc ### ########.fr */ /* */ /* ************************************************************************** */ #include "bignum.h" int bignum_sqr(t_bignum *r, t_bignum *a) { return (bignum_mul(r, a, a)); }
332509.c
/** * * Copyright 2016-2020 Netflix, Inc. * * Licensed under the BSD+Patent License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSDplusPatent * * 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 <stdio.h> #include <stdlib.h> #include <string.h> #include "read_frame.h" int vifdiff(int (*read_frame)(float *ref_data, float *main_data, float *temp_data, int stride, void *user_data), void *user_data, int w, int h, const char *fmt); static void usage(void) { puts("usage: vmaf_feature app fmt ref dis w h\n" "apps:\n" "\tvifdiff\n" "fmts:\n" "\tyuv420p\n" "\tyuv422p\n" "\tyuv444p\n" "\tyuv420p10le\n" "\tyuv422p10le\n" "\tyuv444p10le" ); } int run_vmaf(const char *app, const char *fmt, const char *ref_path, const char *dis_path, int w, int h) { int ret = 0; struct data *s; s = (struct data *)malloc(sizeof(struct data)); s->format = fmt; s->width = w; s->height = h; ret = get_frame_offset(fmt, w, h, &(s->offset)); if (ret) { goto fail_or_end; } if (!(s->ref_rfile = fopen(ref_path, "rb"))) { fprintf(stderr, "fopen ref_path %s failed.\n", ref_path); ret = 1; goto fail_or_end; } if (!(s->dis_rfile = fopen(dis_path, "rb"))) { fprintf(stderr, "fopen ref_path %s failed.\n", dis_path); ret = 1; goto fail_or_end; } if (!strcmp(app, "vifdiff")) ret = vifdiff(read_frame, s, w, h, fmt); else ret = 2; fail_or_end: if (s->ref_rfile) { fclose(s->ref_rfile); } if (s->dis_rfile) { fclose(s->dis_rfile); } if (s) { free(s); } return ret; } int main(int argc, const char **argv) { const char *app; const char *ref_path; const char *dis_path; const char *fmt; int w; int h; if (argc < 7) { usage(); return 2; } app = argv[1]; fmt = argv[2]; ref_path = argv[3]; dis_path = argv[4]; w = atoi(argv[5]); h = atoi(argv[6]); if (w <= 0 || h <= 0) { usage(); return 2; } return run_vmaf(app, fmt, ref_path, dis_path, w, h); }
841349.c
/* A program to search an element in a given array in linear time */ #include <stdio.h> int search(int a[], int key, int size) { int present = 0; int index = 0; for(; index < size; index++) { if(a[index] == key) { present = 1; break; } } return present; } int main() { int n; printf("Enter the number of elements:"); scanf("%d",&n); int *arr=(int *)malloc(n*sizeof(int)); for(int i=0;i<n;i++) scanf("%d",&arr[i]); printf("Enter the key to be found\n"); int key; scanf("%d", &key); if(search(arr, key, sizeof(arr)/sizeof(arr[0])) == 1) { printf("Found\n"); } else { printf("Not Found\n"); } return 0; }
274878.c
#include <stdio.h> #include <stdlib.h> #include "UniformBuffer.h" #include "Graphics.h" UniformBuffer UniformBufferCreate(Pipeline pipeline, int binding) { UniformBuffer uniformBuffer = malloc(sizeof(struct UniformBuffer)); *uniformBuffer = (struct UniformBuffer){ 0 }; bool foundBinding = false; for (int i = 0; i < pipeline->StageCount; i++) { for (int j = 0; j < pipeline->Stages[i].BindingCount; j++) { SpvReflectDescriptorBinding * bindingInfo = pipeline->Stages[i].DescriptorInfo.bindings[j]; if (bindingInfo->binding == binding && bindingInfo->descriptor_type == SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER) { //memcpy(&uniformBuffer->Info, &binding->block, sizeof(binding->block)); uniformBuffer->Info = bindingInfo->block; foundBinding = true; } } } if (!foundBinding) { abort(); } uniformBuffer->Size = uniformBuffer->Info.size; VkBufferCreateInfo bufferInfo = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = uniformBuffer->Info.size, .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, }; VmaAllocationCreateInfo allocationInfo = { .usage = VMA_MEMORY_USAGE_CPU_ONLY, }; VmaAllocationInfo info; vmaCreateBuffer(Graphics.Allocator, &bufferInfo, &allocationInfo, &uniformBuffer->Buffer, &uniformBuffer->Allocation, &info); return uniformBuffer; } void UniformBufferSetVariable(UniformBuffer uniformBuffer, const char * variable, void * value) { void * data; vmaMapMemory(Graphics.Allocator, uniformBuffer->Allocation, &data); for (int i = 0; i < uniformBuffer->Info.member_count; i++) { if (strcmp(uniformBuffer->Info.members[i].name, variable) == 0) { unsigned int offset = uniformBuffer->Info.members[i].offset; unsigned int size = uniformBuffer->Info.members[i].size; memcpy((unsigned char *)data + offset, value, size); } } vmaUnmapMemory(Graphics.Allocator, uniformBuffer->Allocation); } void UniformBufferQueueDestroy(UniformBuffer uniformBuffer) { ListPush(Graphics.FrameResources[Graphics.FrameIndex].Queues[GraphicsQueueDestroyUniformBuffer], uniformBuffer); } void UniformBufferDestroy(UniformBuffer uniformBuffer) { vmaDestroyBuffer(Graphics.Allocator, uniformBuffer->Buffer, uniformBuffer->Allocation); free(uniformBuffer); }
84007.c
int *nondet_pointer(); int main() { int some_array[10]; int *p = some_array; int *q = nondet_pointer(); int index; __CPROVER_assume(index >= 0 && index < 10); __CPROVER_assume(q == p + index); *q = 123; __CPROVER_assert(some_array[index] == 123, "value of array[index]"); return 0; }
794563.c
/* * Authored by Alex Hultman, 2018-2019. * Intellectual property of third-party. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef LIBUS_USE_OPENSSL /* These are in sni_tree.cpp */ void *sni_new(); void sni_free(void *sni, void(*cb)(void *)); int sni_add(void *sni, const char *hostname, void *user); void *sni_remove(void *sni, const char *hostname); void *sni_find(void *sni, const char *hostname); #include "libusockets.h" #include "internal/internal.h" #include <string.h> /* This module contains the entire OpenSSL implementation * of the SSL socket and socket context interfaces. */ #include <openssl/ssl.h> #include <openssl/bio.h> #include <openssl/err.h> /* We do not want to block the loop with tons and tons of CPU-intensive work. * Spread it out during many loop iterations, prioritizing already open connections, * they are far easier on CPU */ static const int MAX_HANDSHAKES_PER_LOOP_ITERATION = 5; struct loop_ssl_data { char *ssl_read_input, *ssl_read_output; unsigned int ssl_read_input_length; unsigned int ssl_read_input_offset; struct us_socket_t *ssl_socket; int last_write_was_msg_more; int msg_more; // these are used to throttle SSL handshakes per loop iteration long long last_iteration_nr; int handshake_budget; BIO *shared_rbio; BIO *shared_wbio; BIO_METHOD *shared_biom; }; struct us_internal_ssl_socket_context_t { struct us_socket_context_t sc; // this thing can be shared with other socket contexts via socket transfer! // maybe instead of holding once you hold many, a vector or set // when a socket that belongs to another socket context transfers to a new socket context SSL_CTX *ssl_context; int is_parent; /* These decorate the base implementation */ struct us_internal_ssl_socket_t *(*on_open)(struct us_internal_ssl_socket_t *, int is_client, char *ip, int ip_length); struct us_internal_ssl_socket_t *(*on_data)(struct us_internal_ssl_socket_t *, char *data, int length); struct us_internal_ssl_socket_t *(*on_writable)(struct us_internal_ssl_socket_t *); struct us_internal_ssl_socket_t *(*on_close)(struct us_internal_ssl_socket_t *, int code, void *reason); /* Called for missing SNI hostnames, if not NULL */ void (*on_server_name)(struct us_internal_ssl_socket_context_t *, const char *hostname); /* Pointer to sni tree, created when the context is created and freed likewise when freed */ void *sni; }; // same here, should or shouldn't it contain s? struct us_internal_ssl_socket_t { struct us_socket_t s; SSL *ssl; int ssl_write_wants_read; // we use this for now int ssl_read_wants_write; }; int passphrase_cb(char *buf, int size, int rwflag, void *u) { const char *passphrase = (const char *) u; size_t passphrase_length = strlen(passphrase); memcpy(buf, passphrase, passphrase_length); // put null at end? no? return (int) passphrase_length; } int BIO_s_custom_create(BIO *bio) { BIO_set_init(bio, 1); return 1; } long BIO_s_custom_ctrl(BIO *bio, int cmd, long num, void *user) { switch(cmd) { case BIO_CTRL_FLUSH: return 1; default: return 0; } } int BIO_s_custom_write(BIO *bio, const char *data, int length) { struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) BIO_get_data(bio); //printf("BIO_s_custom_write\n"); loop_ssl_data->last_write_was_msg_more = loop_ssl_data->msg_more || length == 16413; int written = us_socket_write(0, loop_ssl_data->ssl_socket, data, length, loop_ssl_data->last_write_was_msg_more); if (!written) { BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_WRITE); return -1; } //printf("BIO_s_custom_write returns: %d\n", ret); return written; } int BIO_s_custom_read(BIO *bio, char *dst, int length) { struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) BIO_get_data(bio); //printf("BIO_s_custom_read\n"); if (!loop_ssl_data->ssl_read_input_length) { BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_READ); return -1; } if ((unsigned int) length > loop_ssl_data->ssl_read_input_length) { length = loop_ssl_data->ssl_read_input_length; } memcpy(dst, loop_ssl_data->ssl_read_input + loop_ssl_data->ssl_read_input_offset, length); loop_ssl_data->ssl_read_input_offset += length; loop_ssl_data->ssl_read_input_length -= length; return length; } struct us_internal_ssl_socket_t *ssl_on_open(struct us_internal_ssl_socket_t *s, int is_client, char *ip, int ip_length) { struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); struct us_loop_t *loop = us_socket_context_loop(0, &context->sc); struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; s->ssl = SSL_new(context->ssl_context); s->ssl_write_wants_read = 0; s->ssl_read_wants_write = 0; SSL_set_bio(s->ssl, loop_ssl_data->shared_rbio, loop_ssl_data->shared_wbio); BIO_up_ref(loop_ssl_data->shared_rbio); BIO_up_ref(loop_ssl_data->shared_wbio); if (is_client) { SSL_set_connect_state(s->ssl); } else { SSL_set_accept_state(s->ssl); } return (struct us_internal_ssl_socket_t *) context->on_open(s, is_client, ip, ip_length); } /* This one is a helper; it is entirely shared with non-SSL so can be removed */ struct us_internal_ssl_socket_t *us_internal_ssl_socket_close(struct us_internal_ssl_socket_t *s, int code, void *reason) { return (struct us_internal_ssl_socket_t *) us_socket_close(0, (struct us_socket_t *) s, code, reason); } struct us_internal_ssl_socket_t *ssl_on_close(struct us_internal_ssl_socket_t *s, int code, void *reason) { struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); SSL_free(s->ssl); return context->on_close(s, code, reason); } struct us_internal_ssl_socket_t *ssl_on_end(struct us_internal_ssl_socket_t *s) { // struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); // whatever state we are in, a TCP FIN is always an answered shutdown /* Todo: this should report CLEANLY SHUTDOWN as reason */ return us_internal_ssl_socket_close(s, 0, NULL); } // this whole function needs a complete clean-up struct us_internal_ssl_socket_t *ssl_on_data(struct us_internal_ssl_socket_t *s, void *data, int length) { // note: this context can change when we adopt the socket! struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); struct us_loop_t *loop = us_socket_context_loop(0, &context->sc); struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; // note: if we put data here we should never really clear it (not in write either, it still should be available for SSL_write to read from!) loop_ssl_data->ssl_read_input = data; loop_ssl_data->ssl_read_input_length = length; loop_ssl_data->ssl_read_input_offset = 0; loop_ssl_data->ssl_socket = &s->s; loop_ssl_data->msg_more = 0; if (us_internal_ssl_socket_is_shut_down(s)) { int ret; if ((ret = SSL_shutdown(s->ssl)) == 1) { // two phase shutdown is complete here //printf("Two step SSL shutdown complete\n"); /* Todo: this should also report some kind of clean shutdown */ return us_internal_ssl_socket_close(s, 0, NULL); } else if (ret < 0) { int err = SSL_get_error(s->ssl, ret); if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { // we need to clear the error queue in case these added to the thread local queue ERR_clear_error(); } } // no further processing of data when in shutdown state return s; } // bug checking: this loop needs a lot of attention and clean-ups and check-ups int read = 0; restart: while (1) { int just_read = SSL_read(s->ssl, loop_ssl_data->ssl_read_output + LIBUS_RECV_BUFFER_PADDING + read, LIBUS_RECV_BUFFER_LENGTH - read); if (just_read <= 0) { int err = SSL_get_error(s->ssl, just_read); // as far as I know these are the only errors we want to handle if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) { // clear per thread error queue if it may contain something if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { ERR_clear_error(); } // terminate connection here return us_internal_ssl_socket_close(s, 0, NULL); } else { // emit the data we have and exit if (err == SSL_ERROR_WANT_WRITE) { // here we need to trigger writable event next ssl_read! s->ssl_read_wants_write = 1; } // assume we emptied the input buffer fully or error here as well! if (loop_ssl_data->ssl_read_input_length) { return us_internal_ssl_socket_close(s, 0, NULL); } // cannot emit zero length to app if (!read) { break; } context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); s = context->on_data(s, loop_ssl_data->ssl_read_output + LIBUS_RECV_BUFFER_PADDING, read); if (us_socket_is_closed(0, &s->s)) { return s; } break; } } read += just_read; // at this point we might be full and need to emit the data to application and start over if (read == LIBUS_RECV_BUFFER_LENGTH) { context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); // emit data and restart s = context->on_data(s, loop_ssl_data->ssl_read_output + LIBUS_RECV_BUFFER_PADDING, read); if (us_socket_is_closed(0, &s->s)) { return s; } read = 0; goto restart; } } // trigger writable if we failed last write with want read if (s->ssl_write_wants_read) { s->ssl_write_wants_read = 0; // make sure to update context before we call (context can change if the user adopts the socket!) context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); s = (struct us_internal_ssl_socket_t *) context->sc.on_writable(&s->s); // cast here! // if we are closed here, then exit if (us_socket_is_closed(0, &s->s)) { return s; } } // check this then? if (SSL_get_shutdown(s->ssl) & SSL_RECEIVED_SHUTDOWN) { //printf("SSL_RECEIVED_SHUTDOWN\n"); //exit(-2); // not correct anyways! s = us_internal_ssl_socket_close(s, 0, NULL); //us_ } return s; } struct us_internal_ssl_socket_t *ssl_on_writable(struct us_internal_ssl_socket_t *s) { struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); // todo: cork here so that we efficiently output both from reading and from writing? if (s->ssl_read_wants_write) { s->ssl_read_wants_write = 0; // make sure to update context before we call (context can change if the user adopts the socket!) context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); // if this one fails to write data, it sets ssl_read_wants_write again s = (struct us_internal_ssl_socket_t *) context->sc.on_data(&s->s, 0, 0); // cast here! } // should this one come before we have read? should it come always? spurious on_writable is okay s = context->on_writable(s); return s; } /* Lazily inits loop ssl data first time */ void us_internal_init_loop_ssl_data(struct us_loop_t *loop) { if (!loop->data.ssl_data) { struct loop_ssl_data *loop_ssl_data = malloc(sizeof(struct loop_ssl_data)); loop_ssl_data->ssl_read_output = malloc(LIBUS_RECV_BUFFER_LENGTH + LIBUS_RECV_BUFFER_PADDING * 2); OPENSSL_init_ssl(0, NULL); loop_ssl_data->shared_biom = BIO_meth_new(BIO_TYPE_MEM, "µS BIO"); BIO_meth_set_create(loop_ssl_data->shared_biom, BIO_s_custom_create); BIO_meth_set_write(loop_ssl_data->shared_biom, BIO_s_custom_write); BIO_meth_set_read(loop_ssl_data->shared_biom, BIO_s_custom_read); BIO_meth_set_ctrl(loop_ssl_data->shared_biom, BIO_s_custom_ctrl); loop_ssl_data->shared_rbio = BIO_new(loop_ssl_data->shared_biom); loop_ssl_data->shared_wbio = BIO_new(loop_ssl_data->shared_biom); BIO_set_data(loop_ssl_data->shared_rbio, loop_ssl_data); BIO_set_data(loop_ssl_data->shared_wbio, loop_ssl_data); // reset handshake budget (doesn't matter what loop nr we start on) loop_ssl_data->last_iteration_nr = 0; loop_ssl_data->handshake_budget = MAX_HANDSHAKES_PER_LOOP_ITERATION; loop->data.ssl_data = loop_ssl_data; } } /* Called by loop free, clears any loop ssl data */ void us_internal_free_loop_ssl_data(struct us_loop_t *loop) { struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; if (loop_ssl_data) { free(loop_ssl_data->ssl_read_output); BIO_free(loop_ssl_data->shared_rbio); BIO_free(loop_ssl_data->shared_wbio); BIO_meth_free(loop_ssl_data->shared_biom); free(loop_ssl_data); } } // we ignore reading data for ssl sockets that are // in init state, if our so called budget for doing // so won't allow it. here we actually use // the kernel buffering to our advantage int ssl_ignore_data(struct us_internal_ssl_socket_t *s) { // fast path just checks for init if (!SSL_in_init(s->ssl)) { return 0; } // this path is run for all ssl sockets that are in init and just got data event from polling struct us_loop_t *loop = s->s.context->loop; struct loop_ssl_data *loop_ssl_data = loop->data.ssl_data; // reset handshake budget if new iteration if (loop_ssl_data->last_iteration_nr != us_loop_iteration_number(loop)) { loop_ssl_data->last_iteration_nr = us_loop_iteration_number(loop); loop_ssl_data->handshake_budget = MAX_HANDSHAKES_PER_LOOP_ITERATION; } if (loop_ssl_data->handshake_budget) { loop_ssl_data->handshake_budget--; return 0; } // ignore this data event return 1; } /* Per-context functions */ void *us_internal_ssl_socket_context_get_native_handle(struct us_internal_ssl_socket_context_t *context) { return context->ssl_context; } struct us_internal_ssl_socket_context_t *us_internal_create_child_ssl_socket_context(struct us_internal_ssl_socket_context_t *context, int context_ext_size) { /* Create a new non-SSL context */ struct us_socket_context_options_t options = {0}; struct us_internal_ssl_socket_context_t *child_context = (struct us_internal_ssl_socket_context_t *) us_create_socket_context(0, context->sc.loop, sizeof(struct us_internal_ssl_socket_context_t) + context_ext_size, options); /* The only thing we share is SSL_CTX */ child_context->ssl_context = context->ssl_context; child_context->is_parent = 0; return child_context; } /* Common function for creating a context from options. * We must NOT free a SSL_CTX with only SSL_CTX_free! Also free any password */ void free_ssl_context(SSL_CTX *ssl_context) { if (!ssl_context) { return; } /* If we have set a password string, free it here */ void *password = SSL_CTX_get_default_passwd_cb_userdata(ssl_context); /* OpenSSL returns NULL if we have no set password */ free(password); SSL_CTX_free(ssl_context); } /* This function should take any options and return SSL_CTX - which has to be free'd with * our destructor function - free_ssl_context() */ SSL_CTX *create_ssl_context_from_options(struct us_socket_context_options_t options) { /* Create the context */ SSL_CTX *ssl_context = SSL_CTX_new(TLS_method()); /* Default options we rely on - changing these will break our logic */ SSL_CTX_set_read_ahead(ssl_context, 1); SSL_CTX_set_mode(ssl_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); /* Anything below TLS 1.2 is disabled */ SSL_CTX_set_min_proto_version(ssl_context, TLS1_2_VERSION); /* The following are helpers. You may easily implement whatever you want by using the native handle directly */ /* Important option for lowering memory usage, but lowers performance slightly */ if (options.ssl_prefer_low_memory_usage) { SSL_CTX_set_mode(ssl_context, SSL_MODE_RELEASE_BUFFERS); } if (options.passphrase) { /* When freeing the CTX we need to check SSL_CTX_get_default_passwd_cb_userdata and * free it if set */ SSL_CTX_set_default_passwd_cb_userdata(ssl_context, (void *) strdup(options.passphrase)); SSL_CTX_set_default_passwd_cb(ssl_context, passphrase_cb); } /* This one most probably do not need the cert_file_name string to be kept alive */ if (options.cert_file_name) { if (SSL_CTX_use_certificate_chain_file(ssl_context, options.cert_file_name) != 1) { free_ssl_context(ssl_context); return NULL; } } /* Same as above - we can discard this string afterwards I suppose */ if (options.key_file_name) { if (SSL_CTX_use_PrivateKey_file(ssl_context, options.key_file_name, SSL_FILETYPE_PEM) != 1) { free_ssl_context(ssl_context); return NULL; } } if (options.ca_file_name) { STACK_OF(X509_NAME) *ca_list; ca_list = SSL_load_client_CA_file(options.ca_file_name); if(ca_list == NULL) { free_ssl_context(ssl_context); return NULL; } SSL_CTX_set_client_CA_list(ssl_context, ca_list); if (SSL_CTX_load_verify_locations(ssl_context, options.ca_file_name, NULL) != 1) { free_ssl_context(ssl_context); return NULL; } SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, NULL); } if (options.dh_params_file_name) { /* Set up ephemeral DH parameters. */ DH *dh_2048 = NULL; FILE *paramfile; paramfile = fopen(options.dh_params_file_name, "r"); if (paramfile) { dh_2048 = PEM_read_DHparams(paramfile, NULL, NULL, NULL); fclose(paramfile); } else { free_ssl_context(ssl_context); return NULL; } if (dh_2048 == NULL) { free_ssl_context(ssl_context); return NULL; } const long set_tmp_dh = SSL_CTX_set_tmp_dh(ssl_context, dh_2048); DH_free(dh_2048); if (set_tmp_dh != 1) { free_ssl_context(ssl_context); return NULL; } /* OWASP Cipher String 'A+' (https://www.owasp.org/index.php/TLS_Cipher_String_Cheat_Sheet) */ if (SSL_CTX_set_cipher_list(ssl_context, "DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256") != 1) { free_ssl_context(ssl_context); return NULL; } } /* This must be free'd with free_ssl_context, not SSL_CTX_free */ return ssl_context; } /* Todo: return error on failure? */ void us_internal_ssl_socket_context_add_server_name(struct us_internal_ssl_socket_context_t *context, const char *hostname_pattern, struct us_socket_context_options_t options) { /* Try and construct an SSL_CTX from options */ SSL_CTX *ssl_context = create_ssl_context_from_options(options); /* We do not want to hold any nullptr's in our SNI tree */ if (ssl_context) { if (sni_add(context->sni, hostname_pattern, ssl_context)) { /* If we already had that name, ignore */ free_ssl_context(ssl_context); } } } void us_internal_ssl_socket_context_on_server_name(struct us_internal_ssl_socket_context_t *context, void (*cb)(struct us_internal_ssl_socket_context_t *, const char *hostname)) { context->on_server_name = cb; } void us_internal_ssl_socket_context_remove_server_name(struct us_internal_ssl_socket_context_t *context, const char *hostname_pattern) { /* The same thing must happen for sni_free, that's why we have a callback */ SSL_CTX *sni_node_ssl_context = (SSL_CTX *) sni_remove(context->sni, hostname_pattern); free_ssl_context(sni_node_ssl_context); } /* Returns NULL or SSL_CTX. May call missing server name callback */ SSL_CTX *resolve_context(struct us_internal_ssl_socket_context_t *context, const char *hostname) { /* Try once first */ void *user = sni_find(context->sni, hostname); if (!user) { /* Emit missing hostname then try again */ if (!context->on_server_name) { /* We have no callback registered, so fail */ return NULL; } context->on_server_name(context, hostname); /* Last try */ user = sni_find(context->sni, hostname); } return user; } // arg is context int sni_cb(SSL *ssl, int *al, void *arg) { if (ssl) { const char *hostname = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (hostname && hostname[0]) { /* Try and resolve (match) required hostname with what we have registered */ SSL_CTX *resolved_ssl_context = resolve_context((struct us_internal_ssl_socket_context_t *) arg, hostname); if (resolved_ssl_context) { //printf("Did find matching SNI context for hostname: <%s>!\n", hostname); SSL_set_SSL_CTX(ssl, resolved_ssl_context); } else { /* Call a blocking callback notifying of missing context */ } } return SSL_TLSEXT_ERR_OK; } /* Can we even come here ever? */ return SSL_TLSEXT_ERR_NOACK; } struct us_internal_ssl_socket_context_t *us_internal_create_ssl_socket_context(struct us_loop_t *loop, int context_ext_size, struct us_socket_context_options_t options) { /* If we haven't initialized the loop data yet, do so . * This is needed because loop data holds shared OpenSSL data and * the function is also responsible for initializing OpenSSL */ us_internal_init_loop_ssl_data(loop); /* First of all we try and create the SSL context from options */ SSL_CTX *ssl_context = create_ssl_context_from_options(options); if (!ssl_context) { /* We simply fail early if we cannot even create the OpenSSL context */ return NULL; } /* Otherwise ee continue by creating a non-SSL context, but with larger ext to hold our SSL stuff */ struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_create_socket_context(0, loop, sizeof(struct us_internal_ssl_socket_context_t) + context_ext_size, options); /* I guess this is the only optional callback */ context->on_server_name = NULL; /* Then we extend its SSL parts */ context->ssl_context = ssl_context;//create_ssl_context_from_options(options); context->is_parent = 1; /* We, as parent context, may ignore data */ context->sc.ignore_data = (int (*)(struct us_socket_t *)) ssl_ignore_data; /* Parent contexts may use SNI */ SSL_CTX_set_tlsext_servername_callback(context->ssl_context, sni_cb); SSL_CTX_set_tlsext_servername_arg(context->ssl_context, context); /* Also create the SNI tree */ context->sni = sni_new(); return context; } /* Our destructor for hostnames, used below */ void sni_hostname_destructor(void *user) { /* Some nodes hold null, so this one must ignore this case */ free_ssl_context((SSL_CTX *) user); } void us_internal_ssl_socket_context_free(struct us_internal_ssl_socket_context_t *context) { /* If we are parent then we need to free our OpenSSL context */ if (context->is_parent) { free_ssl_context(context->ssl_context); /* Here we need to register a temporary callback for all still-existing hostnames * and their contexts. Only parents have an SNI tree */ sni_free(context->sni, sni_hostname_destructor); } us_socket_context_free(0, &context->sc); } struct us_listen_socket_t *us_internal_ssl_socket_context_listen(struct us_internal_ssl_socket_context_t *context, const char *host, int port, int options, int socket_ext_size) { return us_socket_context_listen(0, &context->sc, host, port, options, sizeof(struct us_internal_ssl_socket_t) - sizeof(struct us_socket_t) + socket_ext_size); } struct us_internal_ssl_socket_t *us_internal_ssl_socket_context_connect(struct us_internal_ssl_socket_context_t *context, const char *host, int port, const char *source_host, int options, int socket_ext_size) { return (struct us_internal_ssl_socket_t *) us_socket_context_connect(0, &context->sc, host, port, source_host, options, sizeof(struct us_internal_ssl_socket_t) - sizeof(struct us_socket_t) + socket_ext_size); } void us_internal_ssl_socket_context_on_open(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_open)(struct us_internal_ssl_socket_t *s, int is_client, char *ip, int ip_length)) { us_socket_context_on_open(0, &context->sc, (struct us_socket_t *(*)(struct us_socket_t *, int, char *, int)) ssl_on_open); context->on_open = on_open; } void us_internal_ssl_socket_context_on_close(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_close)(struct us_internal_ssl_socket_t *s, int code, void *reason)) { us_socket_context_on_close(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *, int, void *)) ssl_on_close); context->on_close = on_close; } void us_internal_ssl_socket_context_on_data(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_data)(struct us_internal_ssl_socket_t *s, char *data, int length)) { us_socket_context_on_data(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *, char *, int)) ssl_on_data); context->on_data = on_data; } void us_internal_ssl_socket_context_on_writable(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_writable)(struct us_internal_ssl_socket_t *s)) { us_socket_context_on_writable(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *)) ssl_on_writable); context->on_writable = on_writable; } void us_internal_ssl_socket_context_on_timeout(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_timeout)(struct us_internal_ssl_socket_t *s)) { us_socket_context_on_timeout(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *)) on_timeout); } /* We do not really listen to passed FIN-handler, we entirely override it with our handler since SSL doesn't really have support for half-closed sockets */ void us_internal_ssl_socket_context_on_end(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_end)(struct us_internal_ssl_socket_t *)) { us_socket_context_on_end(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *)) ssl_on_end); } void us_internal_ssl_socket_context_on_connect_error(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *(*on_connect_error)(struct us_internal_ssl_socket_t *, int code)) { us_socket_context_on_connect_error(0, (struct us_socket_context_t *) context, (struct us_socket_t *(*)(struct us_socket_t *, int)) on_connect_error); } void *us_internal_ssl_socket_context_ext(struct us_internal_ssl_socket_context_t *context) { return context + 1; } /* Per socket functions */ void *us_internal_ssl_socket_get_native_handle(struct us_internal_ssl_socket_t *s) { return s->ssl; } int us_internal_ssl_socket_write(struct us_internal_ssl_socket_t *s, const char *data, int length, int msg_more) { if (us_socket_is_closed(0, &s->s) || us_internal_ssl_socket_is_shut_down(s)) { return 0; } struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); struct us_loop_t *loop = us_socket_context_loop(0, &context->sc); struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; // it makes literally no sense to touch this here! it should start at 0 and ONLY be set and reset by the on_data function! // the way is is now, triggering a write from a read will essentially delete all input data! // what we need to do is to check if this ever is non-zero and print a warning loop_ssl_data->ssl_read_input_length = 0; loop_ssl_data->ssl_socket = &s->s; loop_ssl_data->msg_more = msg_more; loop_ssl_data->last_write_was_msg_more = 0; //printf("Calling SSL_write\n"); int written = SSL_write(s->ssl, data, length); //printf("Returning from SSL_write\n"); loop_ssl_data->msg_more = 0; if (loop_ssl_data->last_write_was_msg_more && !msg_more) { us_socket_flush(0, &s->s); } if (written > 0) { return written; } else { int err = SSL_get_error(s->ssl, written); if (err == SSL_ERROR_WANT_READ) { // here we need to trigger writable event next ssl_read! s->ssl_write_wants_read = 1; } else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { // these two errors may add to the error queue, which is per thread and must be cleared ERR_clear_error(); // all errors here except for want write are critical and should not happen } return 0; } } void *us_internal_ssl_socket_ext(struct us_internal_ssl_socket_t *s) { return s + 1; } int us_internal_ssl_socket_is_shut_down(struct us_internal_ssl_socket_t *s) { return us_socket_is_shut_down(0, &s->s) || SSL_get_shutdown(s->ssl) & SSL_SENT_SHUTDOWN; } void us_internal_ssl_socket_shutdown(struct us_internal_ssl_socket_t *s) { if (!us_socket_is_closed(0, &s->s) && !us_internal_ssl_socket_is_shut_down(s)) { struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s); struct us_loop_t *loop = us_socket_context_loop(0, &context->sc); struct loop_ssl_data *loop_ssl_data = (struct loop_ssl_data *) loop->data.ssl_data; // also makes no sense to touch this here! // however the idea is that if THIS socket is not the same as ssl_socket then this data is not for me // but this is not correct as it is currently anyways, any data available should be properly reset loop_ssl_data->ssl_read_input_length = 0; // essentially we need two of these: one for CURRENT CALL and one for CURRENT SOCKET WITH DATA // if those match in the BIO function then you may read, if not then you may not read // we need ssl_read_socket to be set in on_data and checked in the BIO loop_ssl_data->ssl_socket = &s->s; loop_ssl_data->msg_more = 0; // sets SSL_SENT_SHUTDOWN no matter what (not actually true if error!) int ret = SSL_shutdown(s->ssl); if (ret == 0) { ret = SSL_shutdown(s->ssl); } if (ret < 0) { int err = SSL_get_error(s->ssl, ret); if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) { // clear ERR_clear_error(); } // we get here if we are shutting down while still in init us_socket_shutdown(0, &s->s); } } } struct us_internal_ssl_socket_t *us_internal_ssl_socket_context_adopt_socket(struct us_internal_ssl_socket_context_t *context, struct us_internal_ssl_socket_t *s, int ext_size) { // todo: this is completely untested return (struct us_internal_ssl_socket_t *) us_socket_context_adopt_socket(0, &context->sc, &s->s, sizeof(struct us_internal_ssl_socket_t) - sizeof(struct us_socket_t) + ext_size); } #endif
333681.c
#include "../src/symbolTable.h" #include "stdio.h" extern SymbolTableStackEntryPtr top; int main() { initSymbolTable(); // create a new type structure for a integer variable Type *typ_int = (Type *)malloc(sizeof(Type)); typ_int->kind = INT; // create a new type structure for a integer variable Type *typ_void = (Type *)malloc(sizeof(Type)); typ_void->kind = VOID; // create a new type structure for a integer variable Type *typ_func = (Type *)malloc(sizeof(Type)); typ_func->kind = FUNCTION; // create a new type structure for a integer variable Type *typ_array = (Type *)malloc(sizeof(Type)); typ_array->kind = ARRAY; typ_array->dimension = 10; ElementPtr s; symInsert("main", typ_func, 2); enterScope(); printf("----- SYMBOLTABLE -----\n"); printSymbolTable(); printf("\n"); symInsert("x", typ_int, 4); symInsert("d", typ_int, 4); symInsert("D", typ_int, 13); printf("----- SYMBOLTABLE -----\n"); printSymbolTable(); printf("\n"); s = symLookup("D"); printElement(s); printf("\n"); s = symLookup("d"); printElement(s); printf("\n"); enterScope(); symInsert("?", typ_int, 9); printf("----- SYMBOLTABLE -----\n"); printSymbolTable(); printf("\n"); s = symLookup("x"); printElement(s); printf("\n"); symInsert("y", typ_array, 5); s = symLookup("main"); printElement(s); printf("\n"); s = symLookup("x"); printElement(s); printf("\n"); s = symLookup("y"); printElement(s); printf("\n"); leaveScope(); //This must return symbol table entry for counter on line 10 s = symLookup("x"); printElement(s); printf("\n"); leaveScope(); s = symLookup("x"); printElement(s); printf("\n"); leaveScope(); s = symLookup("x"); printElement(s); printf("\n"); leaveScope(); s = symLookup("x"); printElement(s); printf("\n"); }
154395.c
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Stig S�ther Bakken <[email protected]> | +----------------------------------------------------------------------+ */ #include <math.h> /* modf() */ #include "php.h" #include "ext/standard/head.h" #include "php_string.h" #include "zend_execute.h" #include <stdio.h> #include <locale.h> #ifdef ZTS #include "ext/standard/php_string.h" #define LCONV_DECIMAL_POINT (*lconv.decimal_point) #else #define LCONV_DECIMAL_POINT (*lconv->decimal_point) #endif #define ALIGN_LEFT 0 #define ALIGN_RIGHT 1 #define ADJ_WIDTH 1 #define ADJ_PRECISION 2 #define NUM_BUF_SIZE 500 #define FLOAT_PRECISION 6 #define MAX_FLOAT_PRECISION 53 #if 0 /* trick to control varargs functions through cpp */ # define PRINTF_DEBUG(arg) php_printf arg #else # define PRINTF_DEBUG(arg) #endif static const char hexchars[] = "0123456789abcdef"; static const char HEXCHARS[] = "0123456789ABCDEF"; /* php_spintf_appendchar() {{{ */ inline static void php_sprintf_appendchar(zend_string **buffer, size_t *pos, char add) { if ((*pos + 1) >= ZSTR_LEN(*buffer)) { PRINTF_DEBUG(("%s(): ereallocing buffer to %d bytes\n", get_active_function_name(), ZSTR_LEN(*buffer))); *buffer = zend_string_extend(*buffer, ZSTR_LEN(*buffer) << 1, 0); } PRINTF_DEBUG(("sprintf: appending '%c', pos=\n", add, *pos)); ZSTR_VAL(*buffer)[(*pos)++] = add; } /* }}} */ /* php_spintf_appendchar() {{{ */ inline static void php_sprintf_appendchars(zend_string **buffer, size_t *pos, char *add, size_t len) { if ((*pos + len) >= ZSTR_LEN(*buffer)) { size_t nlen = ZSTR_LEN(*buffer); PRINTF_DEBUG(("%s(): ereallocing buffer to %d bytes\n", get_active_function_name(), ZSTR_LEN(*buffer))); do { nlen = nlen << 1; } while ((*pos + len) >= nlen); *buffer = zend_string_extend(*buffer, nlen, 0); } PRINTF_DEBUG(("sprintf: appending \"%s\", pos=\n", add, *pos)); memcpy(ZSTR_VAL(*buffer) + (*pos), add, len); *pos += len; } /* }}} */ /* php_spintf_appendstring() {{{ */ inline static void php_sprintf_appendstring(zend_string **buffer, size_t *pos, char *add, size_t min_width, size_t max_width, char padding, size_t alignment, size_t len, int neg, int expprec, int always_sign) { register size_t npad; size_t req_size; size_t copy_len; size_t m_width; copy_len = (expprec ? MIN(max_width, len) : len); npad = (min_width < copy_len) ? 0 : min_width - copy_len; PRINTF_DEBUG(("sprintf: appendstring(%x, %d, %d, \"%s\", %d, '%c', %d)\n", *buffer, *pos, ZSTR_LEN(*buffer), add, min_width, padding, alignment)); m_width = MAX(min_width, copy_len); if(m_width > INT_MAX - *pos - 1) { zend_error_noreturn(E_ERROR, "Field width %zd is too long", m_width); } req_size = *pos + m_width + 1; if (req_size > ZSTR_LEN(*buffer)) { size_t size = ZSTR_LEN(*buffer); while (req_size > size) { if (size > ZEND_SIZE_MAX/2) { zend_error_noreturn(E_ERROR, "Field width %zd is too long", req_size); } size <<= 1; } PRINTF_DEBUG(("sprintf ereallocing buffer to %d bytes\n", size)); *buffer = zend_string_extend(*buffer, size, 0); } if (alignment == ALIGN_RIGHT) { if ((neg || always_sign) && padding=='0') { ZSTR_VAL(*buffer)[(*pos)++] = (neg) ? '-' : '+'; add++; len--; copy_len--; } while (npad-- > 0) { ZSTR_VAL(*buffer)[(*pos)++] = padding; } } PRINTF_DEBUG(("sprintf: appending \"%s\"\n", add)); memcpy(&ZSTR_VAL(*buffer)[*pos], add, copy_len + 1); *pos += copy_len; if (alignment == ALIGN_LEFT) { while (npad--) { ZSTR_VAL(*buffer)[(*pos)++] = padding; } } } /* }}} */ /* php_spintf_appendint() {{{ */ inline static void php_sprintf_appendint(zend_string **buffer, size_t *pos, zend_long number, size_t width, char padding, size_t alignment, int always_sign) { char numbuf[NUM_BUF_SIZE]; register zend_ulong magn, nmagn; register unsigned int i = NUM_BUF_SIZE - 1, neg = 0; PRINTF_DEBUG(("sprintf: appendint(%x, %x, %x, %d, %d, '%c', %d)\n", *buffer, pos, &ZSTR_LEN(*buffer), number, width, padding, alignment)); if (number < 0) { neg = 1; magn = ((zend_ulong) -(number + 1)) + 1; } else { magn = (zend_ulong) number; } /* Can't right-pad 0's on integers */ if(alignment==0 && padding=='0') padding=' '; numbuf[i] = '\0'; do { nmagn = magn / 10; numbuf[--i] = (unsigned char)(magn - (nmagn * 10)) + '0'; magn = nmagn; } while (magn > 0 && i > 1); if (neg) { numbuf[--i] = '-'; } else if (always_sign) { numbuf[--i] = '+'; } PRINTF_DEBUG(("sprintf: appending %d as \"%s\", i=%d\n", number, &numbuf[i], i)); php_sprintf_appendstring(buffer, pos, &numbuf[i], width, 0, padding, alignment, (NUM_BUF_SIZE - 1) - i, neg, 0, always_sign); } /* }}} */ /* php_spintf_appenduint() {{{ */ inline static void php_sprintf_appenduint(zend_string **buffer, size_t *pos, zend_ulong number, size_t width, char padding, size_t alignment) { char numbuf[NUM_BUF_SIZE]; register zend_ulong magn, nmagn; register unsigned int i = NUM_BUF_SIZE - 1; PRINTF_DEBUG(("sprintf: appenduint(%x, %x, %x, %d, %d, '%c', %d)\n", *buffer, pos, &ZSTR_LEN(*buffer), number, width, padding, alignment)); magn = (zend_ulong) number; /* Can't right-pad 0's on integers */ if (alignment == 0 && padding == '0') padding = ' '; numbuf[i] = '\0'; do { nmagn = magn / 10; numbuf[--i] = (unsigned char)(magn - (nmagn * 10)) + '0'; magn = nmagn; } while (magn > 0 && i > 0); PRINTF_DEBUG(("sprintf: appending %d as \"%s\", i=%d\n", number, &numbuf[i], i)); php_sprintf_appendstring(buffer, pos, &numbuf[i], width, 0, padding, alignment, (NUM_BUF_SIZE - 1) - i, 0, 0, 0); } /* }}} */ /* php_spintf_appenddouble() {{{ */ inline static void php_sprintf_appenddouble(zend_string **buffer, size_t *pos, double number, size_t width, char padding, size_t alignment, int precision, int adjust, char fmt, int always_sign ) { char num_buf[NUM_BUF_SIZE]; char *s = NULL; size_t s_len = 0; int is_negative = 0; #ifdef ZTS struct lconv lconv; #else struct lconv *lconv; #endif PRINTF_DEBUG(("sprintf: appenddouble(%x, %x, %x, %f, %d, '%c', %d, %c)\n", *buffer, pos, &ZSTR_LEN(*buffer), number, width, padding, alignment, fmt)); if ((adjust & ADJ_PRECISION) == 0) { precision = FLOAT_PRECISION; } else if (precision > MAX_FLOAT_PRECISION) { php_error_docref(NULL, E_NOTICE, "Requested precision of %d digits was truncated to PHP maximum of %d digits", precision, MAX_FLOAT_PRECISION); precision = MAX_FLOAT_PRECISION; } if (zend_isnan(number)) { is_negative = (number<0); php_sprintf_appendstring(buffer, pos, "NaN", 3, 0, padding, alignment, 3, is_negative, 0, always_sign); return; } if (zend_isinf(number)) { is_negative = (number<0); php_sprintf_appendstring(buffer, pos, "INF", 3, 0, padding, alignment, 3, is_negative, 0, always_sign); return; } switch (fmt) { case 'e': case 'E': case 'f': case 'F': #ifdef ZTS localeconv_r(&lconv); #else lconv = localeconv(); #endif s = php_conv_fp((fmt == 'f')?'F':fmt, number, 0, precision, (fmt == 'f')?LCONV_DECIMAL_POINT:'.', &is_negative, &num_buf[1], &s_len); if (is_negative) { num_buf[0] = '-'; s = num_buf; s_len++; } else if (always_sign) { num_buf[0] = '+'; s = num_buf; s_len++; } break; case 'g': case 'G': if (precision == 0) precision = 1; /* * * We use &num_buf[ 1 ], so that we have room for the sign */ #ifdef ZTS localeconv_r(&lconv); #else lconv = localeconv(); #endif s = php_gcvt(number, precision, LCONV_DECIMAL_POINT, (fmt == 'G')?'E':'e', &num_buf[1]); is_negative = 0; if (*s == '-') { is_negative = 1; s = &num_buf[1]; } else if (always_sign) { num_buf[0] = '+'; s = num_buf; } s_len = strlen(s); break; } php_sprintf_appendstring(buffer, pos, s, width, 0, padding, alignment, s_len, is_negative, 0, always_sign); } /* }}} */ /* php_spintf_appendd2n() {{{ */ inline static void php_sprintf_append2n(zend_string **buffer, size_t *pos, zend_long number, size_t width, char padding, size_t alignment, int n, const char *chartable, int expprec) { char numbuf[NUM_BUF_SIZE]; register zend_ulong num; register zend_ulong i = NUM_BUF_SIZE - 1; register int andbits = (1 << n) - 1; PRINTF_DEBUG(("sprintf: append2n(%x, %x, %x, %d, %d, '%c', %d, %d, %x)\n", *buffer, pos, &ZSTR_LEN(*buffer), number, width, padding, alignment, n, chartable)); PRINTF_DEBUG(("sprintf: append2n 2^%d andbits=%x\n", n, andbits)); num = (zend_ulong) number; numbuf[i] = '\0'; do { numbuf[--i] = chartable[(num & andbits)]; num >>= n; } while (num > 0); php_sprintf_appendstring(buffer, pos, &numbuf[i], width, 0, padding, alignment, (NUM_BUF_SIZE - 1) - i, 0, expprec, 0); } /* }}} */ /* php_spintf_getnumber() {{{ */ inline static int php_sprintf_getnumber(char **buffer, size_t *len) { char *endptr; register zend_long num = ZEND_STRTOL(*buffer, &endptr, 10); register size_t i; if (endptr != NULL) { i = (endptr - *buffer); *len -= i; *buffer = endptr; } PRINTF_DEBUG(("sprintf_getnumber: number was %d bytes long\n", i)); if (num >= INT_MAX || num < 0) { return -1; } else { return (int) num; } } /* }}} */ /* php_formatted_print() {{{ * New sprintf implementation for PHP. * * Modifiers: * * " " pad integers with spaces * "-" left adjusted field * n field size * "."n precision (floats only) * "+" Always place a sign (+ or -) in front of a number * * Type specifiers: * * "%" literal "%", modifiers are ignored. * "b" integer argument is printed as binary * "c" integer argument is printed as a single character * "d" argument is an integer * "f" the argument is a float * "o" integer argument is printed as octal * "s" argument is a string * "x" integer argument is printed as lowercase hexadecimal * "X" integer argument is printed as uppercase hexadecimal * * nb_additional_parameters is used for throwing errors: * - -1: ValueError is thrown (for vsprintf where args originates from an array) * - 0 or more: ArgumentCountError is thrown */ static zend_string * php_formatted_print(char *format, size_t format_len, zval *args, int argc, int nb_additional_parameters) { size_t size = 240, outpos = 0; int alignment, currarg, adjusting, argnum, width, precision; char *temppos, padding; zend_string *result; int always_sign; int bad_arg_number = 0; result = zend_string_alloc(size, 0); currarg = 0; argnum = 0; while (format_len) { int expprec; zval *tmp; temppos = memchr(format, '%', format_len); if (!temppos) { php_sprintf_appendchars(&result, &outpos, format, format_len); break; } else if (temppos != format) { php_sprintf_appendchars(&result, &outpos, format, temppos - format); format_len -= temppos - format; format = temppos; } format++; /* skip the '%' */ format_len--; if (*format == '%') { php_sprintf_appendchar(&result, &outpos, '%'); format++; format_len--; } else { /* starting a new format specifier, reset variables */ alignment = ALIGN_RIGHT; adjusting = 0; padding = ' '; always_sign = 0; expprec = 0; PRINTF_DEBUG(("sprintf: first looking at '%c', inpos=%d\n", *format, format - Z_STRVAL_P(z_format))); if (isalpha((int)*format)) { width = precision = 0; argnum = currarg++; } else { /* first look for argnum */ temppos = format; while (isdigit((int)*temppos)) temppos++; if (*temppos == '$') { argnum = php_sprintf_getnumber(&format, &format_len); if (argnum <= 0) { zend_string_efree(result); zend_value_error("Argument number must be greater than zero"); return NULL; } argnum--; format++; /* skip the '$' */ format_len--; } else { argnum = currarg++; } /* after argnum comes modifiers */ PRINTF_DEBUG(("sprintf: looking for modifiers\n" "sprintf: now looking at '%c', inpos=%d\n", *format, format - Z_STRVAL_P(z_format))); for (;; format++, format_len--) { if (*format == ' ' || *format == '0') { padding = *format; } else if (*format == '-') { alignment = ALIGN_LEFT; /* space padding, the default */ } else if (*format == '+') { always_sign = 1; } else if (*format == '\'' && format_len > 1) { format++; format_len--; padding = *format; } else { PRINTF_DEBUG(("sprintf: end of modifiers\n")); break; } } PRINTF_DEBUG(("sprintf: padding='%c'\n", padding)); PRINTF_DEBUG(("sprintf: alignment=%s\n", (alignment == ALIGN_LEFT) ? "left" : "right")); /* after modifiers comes width */ if (isdigit((int)*format)) { PRINTF_DEBUG(("sprintf: getting width\n")); if ((width = php_sprintf_getnumber(&format, &format_len)) < 0) { efree(result); zend_value_error("Width must be greater than zero and less than %d", INT_MAX); return NULL; } adjusting |= ADJ_WIDTH; } else { width = 0; } PRINTF_DEBUG(("sprintf: width=%d\n", width)); /* after width and argnum comes precision */ if (*format == '.') { format++; format_len--; PRINTF_DEBUG(("sprintf: getting precision\n")); if (isdigit((int)*format)) { if ((precision = php_sprintf_getnumber(&format, &format_len)) < 0) { efree(result); zend_value_error("Precision must be greater than zero and less than %d", INT_MAX); return NULL; } adjusting |= ADJ_PRECISION; expprec = 1; } else { precision = 0; } } else { precision = 0; } PRINTF_DEBUG(("sprintf: precision=%d\n", precision)); } if (*format == 'l') { format++; format_len--; } PRINTF_DEBUG(("sprintf: format character='%c'\n", *format)); if (argnum >= argc) { bad_arg_number = 1; continue; } /* now we expect to find a type specifier */ tmp = &args[argnum]; switch (*format) { case 's': { zend_string *t; zend_string *str = zval_get_tmp_string(tmp, &t); php_sprintf_appendstring(&result, &outpos, ZSTR_VAL(str), width, precision, padding, alignment, ZSTR_LEN(str), 0, expprec, 0); zend_tmp_string_release(t); break; } case 'd': php_sprintf_appendint(&result, &outpos, zval_get_long(tmp), width, padding, alignment, always_sign); break; case 'u': php_sprintf_appenduint(&result, &outpos, zval_get_long(tmp), width, padding, alignment); break; case 'g': case 'G': case 'e': case 'E': case 'f': case 'F': php_sprintf_appenddouble(&result, &outpos, zval_get_double(tmp), width, padding, alignment, precision, adjusting, *format, always_sign ); break; case 'c': php_sprintf_appendchar(&result, &outpos, (char) zval_get_long(tmp)); break; case 'o': php_sprintf_append2n(&result, &outpos, zval_get_long(tmp), width, padding, alignment, 3, hexchars, expprec); break; case 'x': php_sprintf_append2n(&result, &outpos, zval_get_long(tmp), width, padding, alignment, 4, hexchars, expprec); break; case 'X': php_sprintf_append2n(&result, &outpos, zval_get_long(tmp), width, padding, alignment, 4, HEXCHARS, expprec); break; case 'b': php_sprintf_append2n(&result, &outpos, zval_get_long(tmp), width, padding, alignment, 1, hexchars, expprec); break; case '%': php_sprintf_appendchar(&result, &outpos, '%'); break; case '\0': if (!format_len) { goto exit; } break; default: break; } format++; format_len--; } } if (bad_arg_number == 1) { efree(result); if (nb_additional_parameters == -1) { zend_value_error("The arguments array must contain %d items, %d given", argnum + 1, argc); } else { zend_argument_count_error("%d parameters are required, %d given", argnum + nb_additional_parameters + 1, argc + nb_additional_parameters); } return NULL; } exit: /* possibly, we have to make sure we have room for the terminating null? */ ZSTR_VAL(result)[outpos]=0; ZSTR_LEN(result) = outpos; return result; } /* }}} */ /* php_formatted_print_get_array() {{{ */ static zval* php_formatted_print_get_array(zval *array, int *argc) { zval *args, *zv; int n; if (Z_TYPE_P(array) != IS_ARRAY) { convert_to_array(array); } n = zend_hash_num_elements(Z_ARRVAL_P(array)); args = (zval *)safe_emalloc(n, sizeof(zval), 0); n = 0; ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(array), zv) { ZVAL_COPY_VALUE(&args[n], zv); n++; } ZEND_HASH_FOREACH_END(); *argc = n; return args; } /* }}} */ /* {{{ proto string sprintf(string format [, mixed arg1 [, mixed ...]]) Return a formatted string */ PHP_FUNCTION(user_sprintf) { zend_string *result; char *format; size_t format_len; zval *args; int argc; ZEND_PARSE_PARAMETERS_START(1, -1) Z_PARAM_STRING(format, format_len) Z_PARAM_VARIADIC('*', args, argc) ZEND_PARSE_PARAMETERS_END(); result = php_formatted_print(format, format_len, args, argc, 1); if (result == NULL) { return; } RETVAL_STR(result); } /* }}} */ /* {{{ proto string vsprintf(string format, array args) Return a formatted string */ PHP_FUNCTION(vsprintf) { zend_string *result; char *format; size_t format_len; zval *array, *args; int argc; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_STRING(format, format_len) Z_PARAM_ZVAL(array) ZEND_PARSE_PARAMETERS_END(); args = php_formatted_print_get_array(array, &argc); result = php_formatted_print(format, format_len, args, argc, -1); efree(args); if (result == NULL) { return; } RETVAL_STR(result); } /* }}} */ /* {{{ proto int printf(string format [, mixed arg1 [, mixed ...]]) Output a formatted string */ PHP_FUNCTION(user_printf) { zend_string *result; size_t rlen; char *format; size_t format_len; zval *args; int argc; ZEND_PARSE_PARAMETERS_START(1, -1) Z_PARAM_STRING(format, format_len) Z_PARAM_VARIADIC('*', args, argc) ZEND_PARSE_PARAMETERS_END(); result = php_formatted_print(format, format_len, args, argc, 1); if (result == NULL) { return; } rlen = PHPWRITE(ZSTR_VAL(result), ZSTR_LEN(result)); zend_string_efree(result); RETURN_LONG(rlen); } /* }}} */ /* {{{ proto int vprintf(string format, array args) Output a formatted string */ PHP_FUNCTION(vprintf) { zend_string *result; size_t rlen; char *format; size_t format_len; zval *array, *args; int argc; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_STRING(format, format_len) Z_PARAM_ZVAL(array) ZEND_PARSE_PARAMETERS_END(); args = php_formatted_print_get_array(array, &argc); result = php_formatted_print(format, format_len, args, argc, -1); efree(args); if (result == NULL) { return; } rlen = PHPWRITE(ZSTR_VAL(result), ZSTR_LEN(result)); zend_string_efree(result); RETURN_LONG(rlen); } /* }}} */ /* {{{ proto int fprintf(resource stream, string format [, mixed arg1 [, mixed ...]]) Output a formatted string into a stream */ PHP_FUNCTION(fprintf) { php_stream *stream; char *format; size_t format_len; zval *arg1, *args; int argc; zend_string *result; if (ZEND_NUM_ARGS() < 2) { WRONG_PARAM_COUNT; } ZEND_PARSE_PARAMETERS_START(2, -1) Z_PARAM_RESOURCE(arg1) Z_PARAM_STRING(format, format_len) Z_PARAM_VARIADIC('*', args, argc) ZEND_PARSE_PARAMETERS_END(); php_stream_from_zval(stream, arg1); result = php_formatted_print(format, format_len, args, argc, 2); if (result == NULL) { return; } php_stream_write(stream, ZSTR_VAL(result), ZSTR_LEN(result)); RETVAL_LONG(ZSTR_LEN(result)); zend_string_efree(result); } /* }}} */ /* {{{ proto int vfprintf(resource stream, string format, array args) Output a formatted string into a stream */ PHP_FUNCTION(vfprintf) { php_stream *stream; char *format; size_t format_len; zval *arg1, *array, *args; int argc; zend_string *result; if (ZEND_NUM_ARGS() != 3) { WRONG_PARAM_COUNT; } ZEND_PARSE_PARAMETERS_START(3, 3) Z_PARAM_RESOURCE(arg1) Z_PARAM_STRING(format, format_len) Z_PARAM_ZVAL(array) ZEND_PARSE_PARAMETERS_END(); php_stream_from_zval(stream, arg1); args = php_formatted_print_get_array(array, &argc); result = php_formatted_print(format, format_len, args, argc, -1); efree(args); if (result == NULL) { return; } php_stream_write(stream, ZSTR_VAL(result), ZSTR_LEN(result)); RETVAL_LONG(ZSTR_LEN(result)); zend_string_efree(result); } /* }}} */
455840.c
/* * Safe malloc * * Author: Yule Sui * Date: 02/04/2014 */ #include "aliascheck.h" void fun() { int *p = SAFEMALLOC(1); int *q = &p; int *r = p; free(r); } int main() { fun(); }
224430.c
/* * Copyright (c) 2012 Linutronix GmbH * Copyright (c) 2014 sigma star gmbh * Author: Richard Weinberger <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2. * * 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 <linux/crc32.h> #include <linux/bitmap.h> #include "ubi.h" /** * init_seen - allocate memory for used for debugging. * @ubi: UBI device description object */ static inline unsigned long *init_seen(struct ubi_device *ubi) { unsigned long *ret; if (!ubi_dbg_chk_fastmap(ubi)) return NULL; ret = kcalloc(BITS_TO_LONGS(ubi->peb_count), sizeof(unsigned long), GFP_KERNEL); if (!ret) return ERR_PTR(-ENOMEM); return ret; } /** * free_seen - free the seen logic integer array. * @seen: integer array of @ubi->peb_count size */ static inline void free_seen(unsigned long *seen) { kfree(seen); } /** * set_seen - mark a PEB as seen. * @ubi: UBI device description object * @pnum: The PEB to be makred as seen * @seen: integer array of @ubi->peb_count size */ static inline void set_seen(struct ubi_device *ubi, int pnum, unsigned long *seen) { if (!ubi_dbg_chk_fastmap(ubi) || !seen) return; set_bit(pnum, seen); } /** * self_check_seen - check whether all PEB have been seen by fastmap. * @ubi: UBI device description object * @seen: integer array of @ubi->peb_count size */ static int self_check_seen(struct ubi_device *ubi, unsigned long *seen) { int pnum, ret = 0; if (!ubi_dbg_chk_fastmap(ubi) || !seen) return 0; for (pnum = 0; pnum < ubi->peb_count; pnum++) { if (test_bit(pnum, seen) && ubi->lookuptbl[pnum]) { ubi_err(ubi, "self-check failed for PEB %d, fastmap didn't see it", pnum); ret = -EINVAL; } } return ret; } /** * ubi_calc_fm_size - calculates the fastmap size in bytes for an UBI device. * @ubi: UBI device description object */ size_t ubi_calc_fm_size(struct ubi_device *ubi) { size_t size; size = sizeof(struct ubi_fm_sb) + sizeof(struct ubi_fm_hdr) + sizeof(struct ubi_fm_scan_pool) + sizeof(struct ubi_fm_scan_pool) + (ubi->peb_count * sizeof(struct ubi_fm_ec)) + (sizeof(struct ubi_fm_eba) + (ubi->peb_count * sizeof(__be32))) + sizeof(struct ubi_fm_volhdr) * UBI_MAX_VOLUMES; return roundup(size, ubi->leb_size); } /** * new_fm_vhdr - allocate a new volume header for fastmap usage. * @ubi: UBI device description object * @vol_id: the VID of the new header * * Returns a new struct ubi_vid_hdr on success. * NULL indicates out of memory. */ static struct ubi_vid_io_buf *new_fm_vbuf(struct ubi_device *ubi, int vol_id) { struct ubi_vid_io_buf *new; struct ubi_vid_hdr *vh; new = ubi_alloc_vid_buf(ubi, GFP_KERNEL); if (!new) goto out; vh = ubi_get_vid_hdr(new); vh->vol_type = UBI_VID_DYNAMIC; vh->vol_id = cpu_to_be32(vol_id); /* UBI implementations without fastmap support have to delete the * fastmap. */ vh->compat = UBI_COMPAT_DELETE; out: return new; } /** * add_aeb - create and add a attach erase block to a given list. * @ai: UBI attach info object * @list: the target list * @pnum: PEB number of the new attach erase block * @ec: erease counter of the new LEB * @scrub: scrub this PEB after attaching * * Returns 0 on success, < 0 indicates an internal error. */ static int add_aeb(struct ubi_attach_info *ai, struct list_head *list, int pnum, int ec, int scrub) { struct ubi_ainf_peb *aeb; aeb = ubi_alloc_aeb(ai, pnum, ec); if (!aeb) return -ENOMEM; aeb->lnum = -1; aeb->scrub = scrub; aeb->copy_flag = aeb->sqnum = 0; ai->ec_sum += aeb->ec; ai->ec_count++; if (ai->max_ec < aeb->ec) ai->max_ec = aeb->ec; if (ai->min_ec > aeb->ec) ai->min_ec = aeb->ec; list_add_tail(&aeb->u.list, list); return 0; } /** * add_vol - create and add a new volume to ubi_attach_info. * @ai: ubi_attach_info object * @vol_id: VID of the new volume * @used_ebs: number of used EBS * @data_pad: data padding value of the new volume * @vol_type: volume type * @last_eb_bytes: number of bytes in the last LEB * * Returns the new struct ubi_ainf_volume on success. * NULL indicates an error. */ static struct ubi_ainf_volume *add_vol(struct ubi_attach_info *ai, int vol_id, int used_ebs, int data_pad, u8 vol_type, int last_eb_bytes) { struct ubi_ainf_volume *av; av = ubi_add_av(ai, vol_id); if (IS_ERR(av)) return av; av->data_pad = data_pad; av->last_data_size = last_eb_bytes; av->compat = 0; av->vol_type = vol_type; if (av->vol_type == UBI_STATIC_VOLUME) av->used_ebs = used_ebs; dbg_bld("found volume (ID %i)", vol_id); return av; } /** * assign_aeb_to_av - assigns a SEB to a given ainf_volume and removes it * from it's original list. * @ai: ubi_attach_info object * @aeb: the to be assigned SEB * @av: target scan volume */ static void assign_aeb_to_av(struct ubi_attach_info *ai, struct ubi_ainf_peb *aeb, struct ubi_ainf_volume *av) { struct ubi_ainf_peb *tmp_aeb; struct rb_node **p = &av->root.rb_node, *parent = NULL; while (*p) { parent = *p; tmp_aeb = rb_entry(parent, struct ubi_ainf_peb, u.rb); if (aeb->lnum != tmp_aeb->lnum) { if (aeb->lnum < tmp_aeb->lnum) p = &(*p)->rb_left; else p = &(*p)->rb_right; continue; } else break; } list_del(&aeb->u.list); av->leb_count++; rb_link_node(&aeb->u.rb, parent, p); rb_insert_color(&aeb->u.rb, &av->root); } /** * update_vol - inserts or updates a LEB which was found a pool. * @ubi: the UBI device object * @ai: attach info object * @av: the volume this LEB belongs to * @new_vh: the volume header derived from new_aeb * @new_aeb: the AEB to be examined * * Returns 0 on success, < 0 indicates an internal error. */ static int update_vol(struct ubi_device *ubi, struct ubi_attach_info *ai, struct ubi_ainf_volume *av, struct ubi_vid_hdr *new_vh, struct ubi_ainf_peb *new_aeb) { struct rb_node **p = &av->root.rb_node, *parent = NULL; struct ubi_ainf_peb *aeb, *victim; int cmp_res; while (*p) { parent = *p; aeb = rb_entry(parent, struct ubi_ainf_peb, u.rb); if (be32_to_cpu(new_vh->lnum) != aeb->lnum) { if (be32_to_cpu(new_vh->lnum) < aeb->lnum) p = &(*p)->rb_left; else p = &(*p)->rb_right; continue; } /* This case can happen if the fastmap gets written * because of a volume change (creation, deletion, ..). * Then a PEB can be within the persistent EBA and the pool. */ if (aeb->pnum == new_aeb->pnum) { ubi_assert(aeb->lnum == new_aeb->lnum); ubi_free_aeb(ai, new_aeb); return 0; } cmp_res = ubi_compare_lebs(ubi, aeb, new_aeb->pnum, new_vh); if (cmp_res < 0) return cmp_res; /* new_aeb is newer */ if (cmp_res & 1) { victim = ubi_alloc_aeb(ai, aeb->pnum, aeb->ec); if (!victim) return -ENOMEM; list_add_tail(&victim->u.list, &ai->erase); if (av->highest_lnum == be32_to_cpu(new_vh->lnum)) av->last_data_size = be32_to_cpu(new_vh->data_size); dbg_bld("vol %i: AEB %i's PEB %i is the newer", av->vol_id, aeb->lnum, new_aeb->pnum); aeb->ec = new_aeb->ec; aeb->pnum = new_aeb->pnum; aeb->copy_flag = new_vh->copy_flag; aeb->scrub = new_aeb->scrub; aeb->sqnum = new_aeb->sqnum; ubi_free_aeb(ai, new_aeb); /* new_aeb is older */ } else { dbg_bld("vol %i: AEB %i's PEB %i is old, dropping it", av->vol_id, aeb->lnum, new_aeb->pnum); list_add_tail(&new_aeb->u.list, &ai->erase); } return 0; } /* This LEB is new, let's add it to the volume */ if (av->highest_lnum <= be32_to_cpu(new_vh->lnum)) { av->highest_lnum = be32_to_cpu(new_vh->lnum); av->last_data_size = be32_to_cpu(new_vh->data_size); } if (av->vol_type == UBI_STATIC_VOLUME) av->used_ebs = be32_to_cpu(new_vh->used_ebs); av->leb_count++; rb_link_node(&new_aeb->u.rb, parent, p); rb_insert_color(&new_aeb->u.rb, &av->root); return 0; } /** * process_pool_aeb - we found a non-empty PEB in a pool. * @ubi: UBI device object * @ai: attach info object * @new_vh: the volume header derived from new_aeb * @new_aeb: the AEB to be examined * * Returns 0 on success, < 0 indicates an internal error. */ static int process_pool_aeb(struct ubi_device *ubi, struct ubi_attach_info *ai, struct ubi_vid_hdr *new_vh, struct ubi_ainf_peb *new_aeb) { int vol_id = be32_to_cpu(new_vh->vol_id); struct ubi_ainf_volume *av; if (vol_id == UBI_FM_SB_VOLUME_ID || vol_id == UBI_FM_DATA_VOLUME_ID) { ubi_free_aeb(ai, new_aeb); return 0; } /* Find the volume this SEB belongs to */ av = ubi_find_av(ai, vol_id); if (!av) { ubi_err(ubi, "orphaned volume in fastmap pool!"); ubi_free_aeb(ai, new_aeb); return UBI_BAD_FASTMAP; } ubi_assert(vol_id == av->vol_id); return update_vol(ubi, ai, av, new_vh, new_aeb); } /** * unmap_peb - unmap a PEB. * If fastmap detects a free PEB in the pool it has to check whether * this PEB has been unmapped after writing the fastmap. * * @ai: UBI attach info object * @pnum: The PEB to be unmapped */ static void unmap_peb(struct ubi_attach_info *ai, int pnum) { struct ubi_ainf_volume *av; struct rb_node *node, *node2; struct ubi_ainf_peb *aeb; ubi_rb_for_each_entry(node, av, &ai->volumes, rb) { ubi_rb_for_each_entry(node2, aeb, &av->root, u.rb) { if (aeb->pnum == pnum) { rb_erase(&aeb->u.rb, &av->root); av->leb_count--; ubi_free_aeb(ai, aeb); return; } } } } /** * scan_pool - scans a pool for changed (no longer empty PEBs). * @ubi: UBI device object * @ai: attach info object * @pebs: an array of all PEB numbers in the to be scanned pool * @pool_size: size of the pool (number of entries in @pebs) * @max_sqnum: pointer to the maximal sequence number * @free: list of PEBs which are most likely free (and go into @ai->free) * * Returns 0 on success, if the pool is unusable UBI_BAD_FASTMAP is returned. * < 0 indicates an internal error. */ static int scan_pool(struct ubi_device *ubi, struct ubi_attach_info *ai, __be32 *pebs, int pool_size, unsigned long long *max_sqnum, struct list_head *free) { struct ubi_vid_io_buf *vb; struct ubi_vid_hdr *vh; struct ubi_ec_hdr *ech; struct ubi_ainf_peb *new_aeb; int i, pnum, err, ret = 0; ech = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL); if (!ech) return -ENOMEM; vb = ubi_alloc_vid_buf(ubi, GFP_KERNEL); if (!vb) { kfree(ech); return -ENOMEM; } vh = ubi_get_vid_hdr(vb); dbg_bld("scanning fastmap pool: size = %i", pool_size); /* * Now scan all PEBs in the pool to find changes which have been made * after the creation of the fastmap */ for (i = 0; i < pool_size; i++) { int scrub = 0; int image_seq; pnum = be32_to_cpu(pebs[i]); if (ubi_io_is_bad(ubi, pnum)) { ubi_err(ubi, "bad PEB in fastmap pool!"); ret = UBI_BAD_FASTMAP; goto out; } err = ubi_io_read_ec_hdr(ubi, pnum, ech, 0); if (err && err != UBI_IO_BITFLIPS) { ubi_err(ubi, "unable to read EC header! PEB:%i err:%i", pnum, err); ret = err > 0 ? UBI_BAD_FASTMAP : err; goto out; } else if (err == UBI_IO_BITFLIPS) scrub = 1; /* * Older UBI implementations have image_seq set to zero, so * we shouldn't fail if image_seq == 0. */ image_seq = be32_to_cpu(ech->image_seq); if (image_seq && (image_seq != ubi->image_seq)) { ubi_err(ubi, "bad image seq: 0x%x, expected: 0x%x", be32_to_cpu(ech->image_seq), ubi->image_seq); ret = UBI_BAD_FASTMAP; goto out; } err = ubi_io_read_vid_hdr(ubi, pnum, vb, 0); if (err == UBI_IO_FF || err == UBI_IO_FF_BITFLIPS) { unsigned long long ec = be64_to_cpu(ech->ec); unmap_peb(ai, pnum); dbg_bld("Adding PEB to free: %i", pnum); if (err == UBI_IO_FF_BITFLIPS) scrub = 1; add_aeb(ai, free, pnum, ec, scrub); continue; } else if (err == 0 || err == UBI_IO_BITFLIPS) { dbg_bld("Found non empty PEB:%i in pool", pnum); if (err == UBI_IO_BITFLIPS) scrub = 1; new_aeb = ubi_alloc_aeb(ai, pnum, be64_to_cpu(ech->ec)); if (!new_aeb) { ret = -ENOMEM; goto out; } new_aeb->lnum = be32_to_cpu(vh->lnum); new_aeb->sqnum = be64_to_cpu(vh->sqnum); new_aeb->copy_flag = vh->copy_flag; new_aeb->scrub = scrub; if (*max_sqnum < new_aeb->sqnum) *max_sqnum = new_aeb->sqnum; err = process_pool_aeb(ubi, ai, vh, new_aeb); if (err) { ret = err > 0 ? UBI_BAD_FASTMAP : err; goto out; } } else { /* We are paranoid and fall back to scanning mode */ ubi_err(ubi, "fastmap pool PEBs contains damaged PEBs!"); ret = err > 0 ? UBI_BAD_FASTMAP : err; goto out; } } out: ubi_free_vid_buf(vb); kfree(ech); return ret; } /** * count_fastmap_pebs - Counts the PEBs found by fastmap. * @ai: The UBI attach info object */ static int count_fastmap_pebs(struct ubi_attach_info *ai) { struct ubi_ainf_peb *aeb; struct ubi_ainf_volume *av; struct rb_node *rb1, *rb2; int n = 0; list_for_each_entry(aeb, &ai->erase, u.list) n++; list_for_each_entry(aeb, &ai->free, u.list) n++; ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) n++; return n; } /** * ubi_attach_fastmap - creates ubi_attach_info from a fastmap. * @ubi: UBI device object * @ai: UBI attach info object * @fm: the fastmap to be attached * * Returns 0 on success, UBI_BAD_FASTMAP if the found fastmap was unusable. * < 0 indicates an internal error. */ static int ubi_attach_fastmap(struct ubi_device *ubi, struct ubi_attach_info *ai, struct ubi_fastmap_layout *fm) { struct list_head used, free; struct ubi_ainf_volume *av; struct ubi_ainf_peb *aeb, *tmp_aeb, *_tmp_aeb; struct ubi_fm_sb *fmsb; struct ubi_fm_hdr *fmhdr; struct ubi_fm_scan_pool *fmpl, *fmpl_wl; struct ubi_fm_ec *fmec; struct ubi_fm_volhdr *fmvhdr; struct ubi_fm_eba *fm_eba; int ret, i, j, pool_size, wl_pool_size; size_t fm_pos = 0, fm_size = ubi->fm_size; unsigned long long max_sqnum = 0; void *fm_raw = ubi->fm_buf; INIT_LIST_HEAD(&used); INIT_LIST_HEAD(&free); ai->min_ec = UBI_MAX_ERASECOUNTER; fmsb = (struct ubi_fm_sb *)(fm_raw); ai->max_sqnum = fmsb->sqnum; fm_pos += sizeof(struct ubi_fm_sb); if (fm_pos >= fm_size) goto fail_bad; fmhdr = (struct ubi_fm_hdr *)(fm_raw + fm_pos); fm_pos += sizeof(*fmhdr); if (fm_pos >= fm_size) goto fail_bad; if (be32_to_cpu(fmhdr->magic) != UBI_FM_HDR_MAGIC) { ubi_err(ubi, "bad fastmap header magic: 0x%x, expected: 0x%x", be32_to_cpu(fmhdr->magic), UBI_FM_HDR_MAGIC); goto fail_bad; } fmpl = (struct ubi_fm_scan_pool *)(fm_raw + fm_pos); fm_pos += sizeof(*fmpl); if (fm_pos >= fm_size) goto fail_bad; if (be32_to_cpu(fmpl->magic) != UBI_FM_POOL_MAGIC) { ubi_err(ubi, "bad fastmap pool magic: 0x%x, expected: 0x%x", be32_to_cpu(fmpl->magic), UBI_FM_POOL_MAGIC); goto fail_bad; } fmpl_wl = (struct ubi_fm_scan_pool *)(fm_raw + fm_pos); fm_pos += sizeof(*fmpl_wl); if (fm_pos >= fm_size) goto fail_bad; if (be32_to_cpu(fmpl_wl->magic) != UBI_FM_POOL_MAGIC) { ubi_err(ubi, "bad fastmap WL pool magic: 0x%x, expected: 0x%x", be32_to_cpu(fmpl_wl->magic), UBI_FM_POOL_MAGIC); goto fail_bad; } pool_size = be16_to_cpu(fmpl->size); wl_pool_size = be16_to_cpu(fmpl_wl->size); fm->max_pool_size = be16_to_cpu(fmpl->max_size); fm->max_wl_pool_size = be16_to_cpu(fmpl_wl->max_size); if (pool_size > UBI_FM_MAX_POOL_SIZE || pool_size < 0) { ubi_err(ubi, "bad pool size: %i", pool_size); goto fail_bad; } if (wl_pool_size > UBI_FM_MAX_POOL_SIZE || wl_pool_size < 0) { ubi_err(ubi, "bad WL pool size: %i", wl_pool_size); goto fail_bad; } if (fm->max_pool_size > UBI_FM_MAX_POOL_SIZE || fm->max_pool_size < 0) { ubi_err(ubi, "bad maximal pool size: %i", fm->max_pool_size); goto fail_bad; } if (fm->max_wl_pool_size > UBI_FM_MAX_POOL_SIZE || fm->max_wl_pool_size < 0) { ubi_err(ubi, "bad maximal WL pool size: %i", fm->max_wl_pool_size); goto fail_bad; } /* read EC values from free list */ for (i = 0; i < be32_to_cpu(fmhdr->free_peb_count); i++) { fmec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fm_pos += sizeof(*fmec); if (fm_pos >= fm_size) goto fail_bad; add_aeb(ai, &ai->free, be32_to_cpu(fmec->pnum), be32_to_cpu(fmec->ec), 0); } /* read EC values from used list */ for (i = 0; i < be32_to_cpu(fmhdr->used_peb_count); i++) { fmec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fm_pos += sizeof(*fmec); if (fm_pos >= fm_size) goto fail_bad; add_aeb(ai, &used, be32_to_cpu(fmec->pnum), be32_to_cpu(fmec->ec), 0); } /* read EC values from scrub list */ for (i = 0; i < be32_to_cpu(fmhdr->scrub_peb_count); i++) { fmec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fm_pos += sizeof(*fmec); if (fm_pos >= fm_size) goto fail_bad; add_aeb(ai, &used, be32_to_cpu(fmec->pnum), be32_to_cpu(fmec->ec), 1); } /* read EC values from erase list */ for (i = 0; i < be32_to_cpu(fmhdr->erase_peb_count); i++) { fmec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fm_pos += sizeof(*fmec); if (fm_pos >= fm_size) goto fail_bad; add_aeb(ai, &ai->erase, be32_to_cpu(fmec->pnum), be32_to_cpu(fmec->ec), 1); } ai->mean_ec = div_u64(ai->ec_sum, ai->ec_count); ai->bad_peb_count = be32_to_cpu(fmhdr->bad_peb_count); /* Iterate over all volumes and read their EBA table */ for (i = 0; i < be32_to_cpu(fmhdr->vol_count); i++) { fmvhdr = (struct ubi_fm_volhdr *)(fm_raw + fm_pos); fm_pos += sizeof(*fmvhdr); if (fm_pos >= fm_size) goto fail_bad; if (be32_to_cpu(fmvhdr->magic) != UBI_FM_VHDR_MAGIC) { ubi_err(ubi, "bad fastmap vol header magic: 0x%x, expected: 0x%x", be32_to_cpu(fmvhdr->magic), UBI_FM_VHDR_MAGIC); goto fail_bad; } av = add_vol(ai, be32_to_cpu(fmvhdr->vol_id), be32_to_cpu(fmvhdr->used_ebs), be32_to_cpu(fmvhdr->data_pad), fmvhdr->vol_type, be32_to_cpu(fmvhdr->last_eb_bytes)); if (IS_ERR(av)) { if (PTR_ERR(av) == -EEXIST) ubi_err(ubi, "volume (ID %i) already exists", fmvhdr->vol_id); goto fail_bad; } ai->vols_found++; if (ai->highest_vol_id < be32_to_cpu(fmvhdr->vol_id)) ai->highest_vol_id = be32_to_cpu(fmvhdr->vol_id); fm_eba = (struct ubi_fm_eba *)(fm_raw + fm_pos); fm_pos += sizeof(*fm_eba); fm_pos += (sizeof(__be32) * be32_to_cpu(fm_eba->reserved_pebs)); if (fm_pos >= fm_size) goto fail_bad; if (be32_to_cpu(fm_eba->magic) != UBI_FM_EBA_MAGIC) { ubi_err(ubi, "bad fastmap EBA header magic: 0x%x, expected: 0x%x", be32_to_cpu(fm_eba->magic), UBI_FM_EBA_MAGIC); goto fail_bad; } for (j = 0; j < be32_to_cpu(fm_eba->reserved_pebs); j++) { int pnum = be32_to_cpu(fm_eba->pnum[j]); if (pnum < 0) continue; aeb = NULL; list_for_each_entry(tmp_aeb, &used, u.list) { if (tmp_aeb->pnum == pnum) { aeb = tmp_aeb; break; } } if (!aeb) { ubi_err(ubi, "PEB %i is in EBA but not in used list", pnum); goto fail_bad; } aeb->lnum = j; if (av->highest_lnum <= aeb->lnum) av->highest_lnum = aeb->lnum; assign_aeb_to_av(ai, aeb, av); dbg_bld("inserting PEB:%i (LEB %i) to vol %i", aeb->pnum, aeb->lnum, av->vol_id); } } ret = scan_pool(ubi, ai, fmpl->pebs, pool_size, &max_sqnum, &free); if (ret) goto fail; ret = scan_pool(ubi, ai, fmpl_wl->pebs, wl_pool_size, &max_sqnum, &free); if (ret) goto fail; if (max_sqnum > ai->max_sqnum) ai->max_sqnum = max_sqnum; list_for_each_entry_safe(tmp_aeb, _tmp_aeb, &free, u.list) list_move_tail(&tmp_aeb->u.list, &ai->free); list_for_each_entry_safe(tmp_aeb, _tmp_aeb, &used, u.list) list_move_tail(&tmp_aeb->u.list, &ai->erase); ubi_assert(list_empty(&free)); /* * If fastmap is leaking PEBs (must not happen), raise a * fat warning and fall back to scanning mode. * We do this here because in ubi_wl_init() it's too late * and we cannot fall back to scanning. */ if (WARN_ON(count_fastmap_pebs(ai) != ubi->peb_count - ai->bad_peb_count - fm->used_blocks)) goto fail_bad; return 0; fail_bad: ret = UBI_BAD_FASTMAP; fail: list_for_each_entry_safe(tmp_aeb, _tmp_aeb, &used, u.list) { list_del(&tmp_aeb->u.list); ubi_free_aeb(ai, tmp_aeb); } list_for_each_entry_safe(tmp_aeb, _tmp_aeb, &free, u.list) { list_del(&tmp_aeb->u.list); ubi_free_aeb(ai, tmp_aeb); } return ret; } /** * find_fm_anchor - find the most recent Fastmap superblock (anchor) * @ai: UBI attach info to be filled */ static int find_fm_anchor(struct ubi_attach_info *ai) { int ret = -1; struct ubi_ainf_peb *aeb; unsigned long long max_sqnum = 0; list_for_each_entry(aeb, &ai->fastmap, u.list) { if (aeb->vol_id == UBI_FM_SB_VOLUME_ID && aeb->sqnum > max_sqnum) { max_sqnum = aeb->sqnum; ret = aeb->pnum; } } return ret; } static struct ubi_ainf_peb *clone_aeb(struct ubi_attach_info *ai, struct ubi_ainf_peb *old) { struct ubi_ainf_peb *new; new = ubi_alloc_aeb(ai, old->pnum, old->ec); if (!new) return NULL; new->vol_id = old->vol_id; new->sqnum = old->sqnum; new->lnum = old->lnum; new->scrub = old->scrub; new->copy_flag = old->copy_flag; return new; } /** * ubi_scan_fastmap - scan the fastmap. * @ubi: UBI device object * @ai: UBI attach info to be filled * @scan_ai: UBI attach info from the first 64 PEBs, * used to find the most recent Fastmap data structure * * Returns 0 on success, UBI_NO_FASTMAP if no fastmap was found, * UBI_BAD_FASTMAP if one was found but is not usable. * < 0 indicates an internal error. */ int ubi_scan_fastmap(struct ubi_device *ubi, struct ubi_attach_info *ai, struct ubi_attach_info *scan_ai) { struct ubi_fm_sb *fmsb, *fmsb2; struct ubi_vid_io_buf *vb; struct ubi_vid_hdr *vh; struct ubi_ec_hdr *ech; struct ubi_fastmap_layout *fm; struct ubi_ainf_peb *aeb; int i, used_blocks, pnum, fm_anchor, ret = 0; size_t fm_size; __be32 crc, tmp_crc; unsigned long long sqnum = 0; fm_anchor = find_fm_anchor(scan_ai); if (fm_anchor < 0) return UBI_NO_FASTMAP; /* Copy all (possible) fastmap blocks into our new attach structure. */ list_for_each_entry(aeb, &scan_ai->fastmap, u.list) { struct ubi_ainf_peb *new; new = clone_aeb(ai, aeb); if (!new) return -ENOMEM; list_add(&new->u.list, &ai->fastmap); } down_write(&ubi->fm_protect); memset(ubi->fm_buf, 0, ubi->fm_size); fmsb = kmalloc(sizeof(*fmsb), GFP_KERNEL); if (!fmsb) { ret = -ENOMEM; goto out; } fm = kzalloc(sizeof(*fm), GFP_KERNEL); if (!fm) { ret = -ENOMEM; kfree(fmsb); goto out; } ret = ubi_io_read_data(ubi, fmsb, fm_anchor, 0, sizeof(*fmsb)); if (ret && ret != UBI_IO_BITFLIPS) goto free_fm_sb; else if (ret == UBI_IO_BITFLIPS) fm->to_be_tortured[0] = 1; if (be32_to_cpu(fmsb->magic) != UBI_FM_SB_MAGIC) { ubi_err(ubi, "bad super block magic: 0x%x, expected: 0x%x", be32_to_cpu(fmsb->magic), UBI_FM_SB_MAGIC); ret = UBI_BAD_FASTMAP; goto free_fm_sb; } if (fmsb->version != UBI_FM_FMT_VERSION) { ubi_err(ubi, "bad fastmap version: %i, expected: %i", fmsb->version, UBI_FM_FMT_VERSION); ret = UBI_BAD_FASTMAP; goto free_fm_sb; } used_blocks = be32_to_cpu(fmsb->used_blocks); if (used_blocks > UBI_FM_MAX_BLOCKS || used_blocks < 1) { ubi_err(ubi, "number of fastmap blocks is invalid: %i", used_blocks); ret = UBI_BAD_FASTMAP; goto free_fm_sb; } fm_size = ubi->leb_size * used_blocks; if (fm_size != ubi->fm_size) { ubi_err(ubi, "bad fastmap size: %zi, expected: %zi", fm_size, ubi->fm_size); ret = UBI_BAD_FASTMAP; goto free_fm_sb; } ech = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL); if (!ech) { ret = -ENOMEM; goto free_fm_sb; } vb = ubi_alloc_vid_buf(ubi, GFP_KERNEL); if (!vb) { ret = -ENOMEM; goto free_hdr; } vh = ubi_get_vid_hdr(vb); for (i = 0; i < used_blocks; i++) { int image_seq; pnum = be32_to_cpu(fmsb->block_loc[i]); if (ubi_io_is_bad(ubi, pnum)) { ret = UBI_BAD_FASTMAP; goto free_hdr; } if (i == 0 && pnum != fm_anchor) { ubi_err(ubi, "Fastmap anchor PEB mismatch: PEB: %i vs. %i", pnum, fm_anchor); ret = UBI_BAD_FASTMAP; goto free_hdr; } ret = ubi_io_read_ec_hdr(ubi, pnum, ech, 0); if (ret && ret != UBI_IO_BITFLIPS) { ubi_err(ubi, "unable to read fastmap block# %i EC (PEB: %i)", i, pnum); if (ret > 0) ret = UBI_BAD_FASTMAP; goto free_hdr; } else if (ret == UBI_IO_BITFLIPS) fm->to_be_tortured[i] = 1; image_seq = be32_to_cpu(ech->image_seq); if (!ubi->image_seq) ubi->image_seq = image_seq; /* * Older UBI implementations have image_seq set to zero, so * we shouldn't fail if image_seq == 0. */ if (image_seq && (image_seq != ubi->image_seq)) { ubi_err(ubi, "wrong image seq:%d instead of %d", be32_to_cpu(ech->image_seq), ubi->image_seq); ret = UBI_BAD_FASTMAP; goto free_hdr; } ret = ubi_io_read_vid_hdr(ubi, pnum, vb, 0); if (ret && ret != UBI_IO_BITFLIPS) { ubi_err(ubi, "unable to read fastmap block# %i (PEB: %i)", i, pnum); goto free_hdr; } if (i == 0) { if (be32_to_cpu(vh->vol_id) != UBI_FM_SB_VOLUME_ID) { ubi_err(ubi, "bad fastmap anchor vol_id: 0x%x, expected: 0x%x", be32_to_cpu(vh->vol_id), UBI_FM_SB_VOLUME_ID); ret = UBI_BAD_FASTMAP; goto free_hdr; } } else { if (be32_to_cpu(vh->vol_id) != UBI_FM_DATA_VOLUME_ID) { ubi_err(ubi, "bad fastmap data vol_id: 0x%x, expected: 0x%x", be32_to_cpu(vh->vol_id), UBI_FM_DATA_VOLUME_ID); ret = UBI_BAD_FASTMAP; goto free_hdr; } } if (sqnum < be64_to_cpu(vh->sqnum)) sqnum = be64_to_cpu(vh->sqnum); ret = ubi_io_read_data(ubi, ubi->fm_buf + (ubi->leb_size * i), pnum, 0, ubi->leb_size); if (ret && ret != UBI_IO_BITFLIPS) { ubi_err(ubi, "unable to read fastmap block# %i (PEB: %i, " "err: %i)", i, pnum, ret); goto free_hdr; } } kfree(fmsb); fmsb = NULL; fmsb2 = (struct ubi_fm_sb *)(ubi->fm_buf); tmp_crc = be32_to_cpu(fmsb2->data_crc); fmsb2->data_crc = 0; crc = crc32(UBI_CRC32_INIT, ubi->fm_buf, fm_size); if (crc != tmp_crc) { ubi_err(ubi, "fastmap data CRC is invalid"); ubi_err(ubi, "CRC should be: 0x%x, calc: 0x%x", tmp_crc, crc); ret = UBI_BAD_FASTMAP; goto free_hdr; } fmsb2->sqnum = sqnum; fm->used_blocks = used_blocks; ret = ubi_attach_fastmap(ubi, ai, fm); if (ret) { if (ret > 0) ret = UBI_BAD_FASTMAP; goto free_hdr; } for (i = 0; i < used_blocks; i++) { struct ubi_wl_entry *e; e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL); if (!e) { while (i--) kmem_cache_free(ubi_wl_entry_slab, fm->e[i]); ret = -ENOMEM; goto free_hdr; } e->pnum = be32_to_cpu(fmsb2->block_loc[i]); e->ec = be32_to_cpu(fmsb2->block_ec[i]); fm->e[i] = e; } ubi->fm = fm; ubi->fm_pool.max_size = ubi->fm->max_pool_size; ubi->fm_wl_pool.max_size = ubi->fm->max_wl_pool_size; ubi_msg(ubi, "attached by fastmap"); ubi_msg(ubi, "fastmap pool size: %d", ubi->fm_pool.max_size); ubi_msg(ubi, "fastmap WL pool size: %d", ubi->fm_wl_pool.max_size); ubi->fm_disabled = 0; ubi->fast_attach = 1; ubi_free_vid_buf(vb); kfree(ech); out: up_write(&ubi->fm_protect); if (ret == UBI_BAD_FASTMAP) ubi_err(ubi, "Attach by fastmap failed, doing a full scan!"); return ret; free_hdr: ubi_free_vid_buf(vb); kfree(ech); free_fm_sb: kfree(fmsb); kfree(fm); goto out; } /** * ubi_write_fastmap - writes a fastmap. * @ubi: UBI device object * @new_fm: the to be written fastmap * * Returns 0 on success, < 0 indicates an internal error. */ static int ubi_write_fastmap(struct ubi_device *ubi, struct ubi_fastmap_layout *new_fm) { size_t fm_pos = 0; void *fm_raw; struct ubi_fm_sb *fmsb; struct ubi_fm_hdr *fmh; struct ubi_fm_scan_pool *fmpl, *fmpl_wl; struct ubi_fm_ec *fec; struct ubi_fm_volhdr *fvh; struct ubi_fm_eba *feba; struct ubi_wl_entry *wl_e; struct ubi_volume *vol; struct ubi_vid_io_buf *avbuf, *dvbuf; struct ubi_vid_hdr *avhdr, *dvhdr; struct ubi_work *ubi_wrk; struct rb_node *tmp_rb; int ret, i, j, free_peb_count, used_peb_count, vol_count; int scrub_peb_count, erase_peb_count; unsigned long *seen_pebs = NULL; fm_raw = ubi->fm_buf; memset(ubi->fm_buf, 0, ubi->fm_size); avbuf = new_fm_vbuf(ubi, UBI_FM_SB_VOLUME_ID); if (!avbuf) { ret = -ENOMEM; goto out; } dvbuf = new_fm_vbuf(ubi, UBI_FM_DATA_VOLUME_ID); if (!dvbuf) { ret = -ENOMEM; goto out_kfree; } avhdr = ubi_get_vid_hdr(avbuf); dvhdr = ubi_get_vid_hdr(dvbuf); seen_pebs = init_seen(ubi); if (IS_ERR(seen_pebs)) { ret = PTR_ERR(seen_pebs); goto out_kfree; } spin_lock(&ubi->volumes_lock); spin_lock(&ubi->wl_lock); fmsb = (struct ubi_fm_sb *)fm_raw; fm_pos += sizeof(*fmsb); ubi_assert(fm_pos <= ubi->fm_size); fmh = (struct ubi_fm_hdr *)(fm_raw + fm_pos); fm_pos += sizeof(*fmh); ubi_assert(fm_pos <= ubi->fm_size); fmsb->magic = cpu_to_be32(UBI_FM_SB_MAGIC); fmsb->version = UBI_FM_FMT_VERSION; fmsb->used_blocks = cpu_to_be32(new_fm->used_blocks); /* the max sqnum will be filled in while *reading* the fastmap */ fmsb->sqnum = 0; fmh->magic = cpu_to_be32(UBI_FM_HDR_MAGIC); free_peb_count = 0; used_peb_count = 0; scrub_peb_count = 0; erase_peb_count = 0; vol_count = 0; fmpl = (struct ubi_fm_scan_pool *)(fm_raw + fm_pos); fm_pos += sizeof(*fmpl); fmpl->magic = cpu_to_be32(UBI_FM_POOL_MAGIC); fmpl->size = cpu_to_be16(ubi->fm_pool.size); fmpl->max_size = cpu_to_be16(ubi->fm_pool.max_size); for (i = 0; i < ubi->fm_pool.size; i++) { fmpl->pebs[i] = cpu_to_be32(ubi->fm_pool.pebs[i]); set_seen(ubi, ubi->fm_pool.pebs[i], seen_pebs); } fmpl_wl = (struct ubi_fm_scan_pool *)(fm_raw + fm_pos); fm_pos += sizeof(*fmpl_wl); fmpl_wl->magic = cpu_to_be32(UBI_FM_POOL_MAGIC); fmpl_wl->size = cpu_to_be16(ubi->fm_wl_pool.size); fmpl_wl->max_size = cpu_to_be16(ubi->fm_wl_pool.max_size); for (i = 0; i < ubi->fm_wl_pool.size; i++) { fmpl_wl->pebs[i] = cpu_to_be32(ubi->fm_wl_pool.pebs[i]); set_seen(ubi, ubi->fm_wl_pool.pebs[i], seen_pebs); } ubi_for_each_free_peb(ubi, wl_e, tmp_rb) { fec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fec->pnum = cpu_to_be32(wl_e->pnum); set_seen(ubi, wl_e->pnum, seen_pebs); fec->ec = cpu_to_be32(wl_e->ec); free_peb_count++; fm_pos += sizeof(*fec); ubi_assert(fm_pos <= ubi->fm_size); } fmh->free_peb_count = cpu_to_be32(free_peb_count); ubi_for_each_used_peb(ubi, wl_e, tmp_rb) { fec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fec->pnum = cpu_to_be32(wl_e->pnum); set_seen(ubi, wl_e->pnum, seen_pebs); fec->ec = cpu_to_be32(wl_e->ec); used_peb_count++; fm_pos += sizeof(*fec); ubi_assert(fm_pos <= ubi->fm_size); } ubi_for_each_protected_peb(ubi, i, wl_e) { fec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fec->pnum = cpu_to_be32(wl_e->pnum); set_seen(ubi, wl_e->pnum, seen_pebs); fec->ec = cpu_to_be32(wl_e->ec); used_peb_count++; fm_pos += sizeof(*fec); ubi_assert(fm_pos <= ubi->fm_size); } fmh->used_peb_count = cpu_to_be32(used_peb_count); ubi_for_each_scrub_peb(ubi, wl_e, tmp_rb) { fec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fec->pnum = cpu_to_be32(wl_e->pnum); set_seen(ubi, wl_e->pnum, seen_pebs); fec->ec = cpu_to_be32(wl_e->ec); scrub_peb_count++; fm_pos += sizeof(*fec); ubi_assert(fm_pos <= ubi->fm_size); } fmh->scrub_peb_count = cpu_to_be32(scrub_peb_count); list_for_each_entry(ubi_wrk, &ubi->works, list) { if (ubi_is_erase_work(ubi_wrk)) { wl_e = ubi_wrk->e; ubi_assert(wl_e); fec = (struct ubi_fm_ec *)(fm_raw + fm_pos); fec->pnum = cpu_to_be32(wl_e->pnum); set_seen(ubi, wl_e->pnum, seen_pebs); fec->ec = cpu_to_be32(wl_e->ec); erase_peb_count++; fm_pos += sizeof(*fec); ubi_assert(fm_pos <= ubi->fm_size); } } fmh->erase_peb_count = cpu_to_be32(erase_peb_count); for (i = 0; i < UBI_MAX_VOLUMES + UBI_INT_VOL_COUNT; i++) { vol = ubi->volumes[i]; if (!vol) continue; vol_count++; fvh = (struct ubi_fm_volhdr *)(fm_raw + fm_pos); fm_pos += sizeof(*fvh); ubi_assert(fm_pos <= ubi->fm_size); fvh->magic = cpu_to_be32(UBI_FM_VHDR_MAGIC); fvh->vol_id = cpu_to_be32(vol->vol_id); fvh->vol_type = vol->vol_type; fvh->used_ebs = cpu_to_be32(vol->used_ebs); fvh->data_pad = cpu_to_be32(vol->data_pad); fvh->last_eb_bytes = cpu_to_be32(vol->last_eb_bytes); ubi_assert(vol->vol_type == UBI_DYNAMIC_VOLUME || vol->vol_type == UBI_STATIC_VOLUME); feba = (struct ubi_fm_eba *)(fm_raw + fm_pos); fm_pos += sizeof(*feba) + (sizeof(__be32) * vol->reserved_pebs); ubi_assert(fm_pos <= ubi->fm_size); for (j = 0; j < vol->reserved_pebs; j++) { struct ubi_eba_leb_desc ldesc; ubi_eba_get_ldesc(vol, j, &ldesc); feba->pnum[j] = cpu_to_be32(ldesc.pnum); } feba->reserved_pebs = cpu_to_be32(j); feba->magic = cpu_to_be32(UBI_FM_EBA_MAGIC); } fmh->vol_count = cpu_to_be32(vol_count); fmh->bad_peb_count = cpu_to_be32(ubi->bad_peb_count); avhdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi)); avhdr->lnum = 0; spin_unlock(&ubi->wl_lock); spin_unlock(&ubi->volumes_lock); dbg_bld("writing fastmap SB to PEB %i", new_fm->e[0]->pnum); ret = ubi_io_write_vid_hdr(ubi, new_fm->e[0]->pnum, avbuf); if (ret) { ubi_err(ubi, "unable to write vid_hdr to fastmap SB!"); goto out_kfree; } for (i = 0; i < new_fm->used_blocks; i++) { fmsb->block_loc[i] = cpu_to_be32(new_fm->e[i]->pnum); set_seen(ubi, new_fm->e[i]->pnum, seen_pebs); fmsb->block_ec[i] = cpu_to_be32(new_fm->e[i]->ec); } fmsb->data_crc = 0; fmsb->data_crc = cpu_to_be32(crc32(UBI_CRC32_INIT, fm_raw, ubi->fm_size)); for (i = 1; i < new_fm->used_blocks; i++) { dvhdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi)); dvhdr->lnum = cpu_to_be32(i); dbg_bld("writing fastmap data to PEB %i sqnum %llu", new_fm->e[i]->pnum, be64_to_cpu(dvhdr->sqnum)); ret = ubi_io_write_vid_hdr(ubi, new_fm->e[i]->pnum, dvbuf); if (ret) { ubi_err(ubi, "unable to write vid_hdr to PEB %i!", new_fm->e[i]->pnum); goto out_kfree; } } for (i = 0; i < new_fm->used_blocks; i++) { ret = ubi_io_write_data(ubi, fm_raw + (i * ubi->leb_size), new_fm->e[i]->pnum, 0, ubi->leb_size); if (ret) { ubi_err(ubi, "unable to write fastmap to PEB %i!", new_fm->e[i]->pnum); goto out_kfree; } } ubi_assert(new_fm); ubi->fm = new_fm; ret = self_check_seen(ubi, seen_pebs); dbg_bld("fastmap written!"); out_kfree: ubi_free_vid_buf(avbuf); ubi_free_vid_buf(dvbuf); free_seen(seen_pebs); out: return ret; } /** * erase_block - Manually erase a PEB. * @ubi: UBI device object * @pnum: PEB to be erased * * Returns the new EC value on success, < 0 indicates an internal error. */ static int erase_block(struct ubi_device *ubi, int pnum) { int ret; struct ubi_ec_hdr *ec_hdr; long long ec; ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL); if (!ec_hdr) return -ENOMEM; ret = ubi_io_read_ec_hdr(ubi, pnum, ec_hdr, 0); if (ret < 0) goto out; else if (ret && ret != UBI_IO_BITFLIPS) { ret = -EINVAL; goto out; } ret = ubi_io_sync_erase(ubi, pnum, 0); if (ret < 0) goto out; ec = be64_to_cpu(ec_hdr->ec); ec += ret; if (ec > UBI_MAX_ERASECOUNTER) { ret = -EINVAL; goto out; } ec_hdr->ec = cpu_to_be64(ec); ret = ubi_io_write_ec_hdr(ubi, pnum, ec_hdr); if (ret < 0) goto out; ret = ec; out: kfree(ec_hdr); return ret; } /** * invalidate_fastmap - destroys a fastmap. * @ubi: UBI device object * * This function ensures that upon next UBI attach a full scan * is issued. We need this if UBI is about to write a new fastmap * but is unable to do so. In this case we have two options: * a) Make sure that the current fastmap will not be usued upon * attach time and contine or b) fall back to RO mode to have the * current fastmap in a valid state. * Returns 0 on success, < 0 indicates an internal error. */ static int invalidate_fastmap(struct ubi_device *ubi) { int ret; struct ubi_fastmap_layout *fm; struct ubi_wl_entry *e; struct ubi_vid_io_buf *vb = NULL; struct ubi_vid_hdr *vh; if (!ubi->fm) return 0; ubi->fm = NULL; ret = -ENOMEM; fm = kzalloc(sizeof(*fm), GFP_KERNEL); if (!fm) goto out; vb = new_fm_vbuf(ubi, UBI_FM_SB_VOLUME_ID); if (!vb) goto out_free_fm; vh = ubi_get_vid_hdr(vb); ret = -ENOSPC; e = ubi_wl_get_fm_peb(ubi, 1); if (!e) goto out_free_fm; /* * Create fake fastmap such that UBI will fall back * to scanning mode. */ vh->sqnum = cpu_to_be64(ubi_next_sqnum(ubi)); ret = ubi_io_write_vid_hdr(ubi, e->pnum, vb); if (ret < 0) { ubi_wl_put_fm_peb(ubi, e, 0, 0); goto out_free_fm; } fm->used_blocks = 1; fm->e[0] = e; ubi->fm = fm; out: ubi_free_vid_buf(vb); return ret; out_free_fm: kfree(fm); goto out; } /** * return_fm_pebs - returns all PEBs used by a fastmap back to the * WL sub-system. * @ubi: UBI device object * @fm: fastmap layout object */ static void return_fm_pebs(struct ubi_device *ubi, struct ubi_fastmap_layout *fm) { int i; if (!fm) return; for (i = 0; i < fm->used_blocks; i++) { if (fm->e[i]) { ubi_wl_put_fm_peb(ubi, fm->e[i], i, fm->to_be_tortured[i]); fm->e[i] = NULL; } } } /** * ubi_update_fastmap - will be called by UBI if a volume changes or * a fastmap pool becomes full. * @ubi: UBI device object * * Returns 0 on success, < 0 indicates an internal error. */ int ubi_update_fastmap(struct ubi_device *ubi) { int ret, i, j; struct ubi_fastmap_layout *new_fm, *old_fm; struct ubi_wl_entry *tmp_e; down_write(&ubi->fm_protect); down_write(&ubi->work_sem); down_write(&ubi->fm_eba_sem); ubi_refill_pools(ubi); if (ubi->ro_mode || ubi->fm_disabled) { up_write(&ubi->fm_eba_sem); up_write(&ubi->work_sem); up_write(&ubi->fm_protect); return 0; } ret = ubi_ensure_anchor_pebs(ubi); if (ret) { up_write(&ubi->fm_eba_sem); up_write(&ubi->work_sem); up_write(&ubi->fm_protect); return ret; } new_fm = kzalloc(sizeof(*new_fm), GFP_KERNEL); if (!new_fm) { up_write(&ubi->fm_eba_sem); up_write(&ubi->work_sem); up_write(&ubi->fm_protect); return -ENOMEM; } new_fm->used_blocks = ubi->fm_size / ubi->leb_size; old_fm = ubi->fm; ubi->fm = NULL; if (new_fm->used_blocks > UBI_FM_MAX_BLOCKS) { ubi_err(ubi, "fastmap too large"); ret = -ENOSPC; goto err; } for (i = 1; i < new_fm->used_blocks; i++) { spin_lock(&ubi->wl_lock); tmp_e = ubi_wl_get_fm_peb(ubi, 0); spin_unlock(&ubi->wl_lock); if (!tmp_e) { if (old_fm && old_fm->e[i]) { ret = erase_block(ubi, old_fm->e[i]->pnum); if (ret < 0) { ubi_err(ubi, "could not erase old fastmap PEB"); for (j = 1; j < i; j++) { ubi_wl_put_fm_peb(ubi, new_fm->e[j], j, 0); new_fm->e[j] = NULL; } goto err; } new_fm->e[i] = old_fm->e[i]; old_fm->e[i] = NULL; } else { ubi_err(ubi, "could not get any free erase block"); for (j = 1; j < i; j++) { ubi_wl_put_fm_peb(ubi, new_fm->e[j], j, 0); new_fm->e[j] = NULL; } ret = -ENOSPC; goto err; } } else { new_fm->e[i] = tmp_e; if (old_fm && old_fm->e[i]) { ubi_wl_put_fm_peb(ubi, old_fm->e[i], i, old_fm->to_be_tortured[i]); old_fm->e[i] = NULL; } } } /* Old fastmap is larger than the new one */ if (old_fm && new_fm->used_blocks < old_fm->used_blocks) { for (i = new_fm->used_blocks; i < old_fm->used_blocks; i++) { ubi_wl_put_fm_peb(ubi, old_fm->e[i], i, old_fm->to_be_tortured[i]); old_fm->e[i] = NULL; } } spin_lock(&ubi->wl_lock); tmp_e = ubi_wl_get_fm_peb(ubi, 1); spin_unlock(&ubi->wl_lock); if (old_fm) { /* no fresh anchor PEB was found, reuse the old one */ if (!tmp_e) { ret = erase_block(ubi, old_fm->e[0]->pnum); if (ret < 0) { ubi_err(ubi, "could not erase old anchor PEB"); for (i = 1; i < new_fm->used_blocks; i++) { ubi_wl_put_fm_peb(ubi, new_fm->e[i], i, 0); new_fm->e[i] = NULL; } goto err; } new_fm->e[0] = old_fm->e[0]; new_fm->e[0]->ec = ret; old_fm->e[0] = NULL; } else { /* we've got a new anchor PEB, return the old one */ ubi_wl_put_fm_peb(ubi, old_fm->e[0], 0, old_fm->to_be_tortured[0]); new_fm->e[0] = tmp_e; old_fm->e[0] = NULL; } } else { if (!tmp_e) { ubi_err(ubi, "could not find any anchor PEB"); for (i = 1; i < new_fm->used_blocks; i++) { ubi_wl_put_fm_peb(ubi, new_fm->e[i], i, 0); new_fm->e[i] = NULL; } ret = -ENOSPC; goto err; } new_fm->e[0] = tmp_e; } ret = ubi_write_fastmap(ubi, new_fm); if (ret) goto err; out_unlock: up_write(&ubi->fm_eba_sem); up_write(&ubi->work_sem); up_write(&ubi->fm_protect); kfree(old_fm); return ret; err: ubi_warn(ubi, "Unable to write new fastmap, err=%i", ret); ret = invalidate_fastmap(ubi); if (ret < 0) { ubi_err(ubi, "Unable to invalidate current fastmap!"); ubi_ro_mode(ubi); } else { return_fm_pebs(ubi, old_fm); return_fm_pebs(ubi, new_fm); ret = 0; } kfree(new_fm); goto out_unlock; }
836847.c
// // Created by Vashon on 2020/8/5. // #include "homework_037.h" int *intersection_1(int *nums1, int nums1Size, int *nums2, int nums2Size, int *returnSize) { if (nums1Size == 0 || nums2Size == 0 || !nums1 || !nums2) { *returnSize = 0; return NULL; } // 最大的交集不会超过两数组中最小的数组大小 int max, min, index = 0, *n1, *n2; // n1 保存小数组,n2 保存大数组 if (nums1Size < nums2Size) { min = nums1Size; max = nums2Size; n1 = nums1; n2 = nums2; } else { min = nums2Size; max = nums1Size; n1 = nums2; n2 = nums1; } int *nums = calloc(min, sizeof(int)); assert(nums != NULL); for (int i = 0; i < min; ++i) { bool isExist = false; for (int j = 0; j < max; ++j) { if (n1[i] == n2[j]) { isExist = true; break; } } if (isExist) { // 当大数组存在小数组同样的元素时 isExist = false; for (int k = 0; k < index; ++k) { if (nums[k] == n1[i]) { // 过滤一遍,当数组中未添加该元素才需要添加 isExist = true; break; } } if (!isExist) // 不存在该元素,添加 nums[index++] = n1[i]; } } *returnSize = index; return nums; } int *intersection_2(int *nums1, int nums1Size, int *nums2, int nums2Size, int *returnSize) { if (nums1Size == 0 || nums2Size == 0 || !nums1 || !nums2) { *returnSize = 0; return NULL; } // 最大的交集不会超过两数组中最小的数组大小 int min = nums1Size < nums2Size ? nums1Size : nums2Size, index = 0, *n1 = nums1, *n2 = nums2; // 这里用 calloc 没用 malloc,因为 calloc 初始化的内存默认值为 0,malloc 初始化的内存默认值随机 int *nums = calloc(min, sizeof(int)), *hash = calloc(1024, sizeof(int)); assert(nums != NULL && hash != NULL); for (int i = 0; i < nums1Size; hash[*n1++]++, ++i); // 将值作为下标,并将 hash 表内对应的区域的值增加,也就是非 0 即存在 for (int j = 0; j < nums2Size; ++j) { int position = *n2++; // 取出数组中的元素值 if (hash[position]) { // 当 hash 表中存在改值 hash[position] = 0; // 置 0,防止添加重复的元素 nums[index++] = position; // 将值存到目标数组 } } free(hash); *returnSize = index; return nums; } int compare(const void *nums1, const void *nums2) { return *(int *) nums1 - *(int *) nums2; } int *intersection_3(int *nums1, int nums1Size, int *nums2, int nums2Size, int *returnSize) { if (nums1Size == 0 || nums2Size == 0 || !nums1 || !nums2) { *returnSize = 0; return NULL; } // 两个数组排序 qsort(nums1, nums1Size, sizeof(int), compare); qsort(nums2, nums2Size, sizeof(int), compare); // 为目标数组开辟空间 int *nums = malloc(sizeof(int) * (nums1Size < nums2Size ? nums1Size : nums2Size)), index = 0; assert(nums != NULL); // 归并 for (int i = 0, j = 0; i < nums1Size && j < nums2Size;) { if (nums1[i] < nums2[j]) { i++; } else if (nums1[i] > nums2[j]) { j++; } else { nums[index] = nums1[i]; i++, j++; // 是第一个元素或者不是第一个元素且当前元素与前一个元素不等 if (!index || (nums[index - 1] != nums[index])) index++; } } // 重新分配合适的空间,这一步可以省略 nums = realloc(nums, sizeof(int) * index); *returnSize = index; return nums; } void homework_037_349(void) { }
203376.c
/**************************************************************************** * arch/xtensa/src/esp32/esp32_start.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <nuttx/init.h> #include <nuttx/irq.h> #include "xtensa.h" #include "xtensa_attr.h" #include "hardware/esp32_dport.h" #include "hardware/esp32_rtccntl.h" #include "esp32_clockconfig.h" #include "esp32_region.h" #include "esp32_start.h" #include "esp32_spiram.h" #include "esp32_wdt.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #ifdef CONFIG_DEBUG_FEATURES # define showprogress(c) up_puts(c) #else # define showprogress(c) #endif #ifdef CONFIG_ESP32_APP_FORMAT_MCUBOOT #define PRIMARY_SLOT_OFFSET CONFIG_ESP32_OTA_PRIMARY_SLOT_OFFSET #define HDR_ATTR __attribute__((section(".entry_addr"))) \ __attribute__((used)) /* Cache MMU block size */ #define MMU_BLOCK_SIZE 0x00010000 /* 64 KB */ /* Cache MMU address mask (MMU tables ignore bits which are zero) */ #define MMU_FLASH_MASK (~(MMU_BLOCK_SIZE - 1)) #endif /**************************************************************************** * Private Types ****************************************************************************/ #ifdef CONFIG_ESP32_APP_FORMAT_MCUBOOT extern uint32_t _image_irom_vma; extern uint32_t _image_irom_lma; extern uint32_t _image_irom_size; extern uint32_t _image_drom_vma; extern uint32_t _image_drom_lma; extern uint32_t _image_drom_size; #endif /**************************************************************************** * ROM Function Prototypes ****************************************************************************/ #ifdef CONFIG_ESP32_APP_FORMAT_MCUBOOT extern int ets_printf(const char *fmt, ...); extern void cache_read_enable(int cpu); extern void cache_read_disable(int cpu); extern void cache_flush(int cpu); extern unsigned int cache_flash_mmu_set(int cpu_no, int pid, unsigned int vaddr, unsigned int paddr, int psize, int num); #endif /**************************************************************************** * Private Function Prototypes ****************************************************************************/ #ifdef CONFIG_ESP32_APP_FORMAT_MCUBOOT noreturn_function void __start(void); #endif /**************************************************************************** * Public Functions Prototypes ****************************************************************************/ #ifndef CONFIG_SUPPRESS_UART_CONFIG extern void esp32_lowsetup(void); #endif /**************************************************************************** * Private Data ****************************************************************************/ #ifdef CONFIG_ESP32_APP_FORMAT_MCUBOOT HDR_ATTR static void (*_entry_point)(void) = &__start; #endif /**************************************************************************** * Public Data ****************************************************************************/ /* Address of the CPU0 IDLE thread */ uint32_t g_idlestack[IDLETHREAD_STACKWORDS] aligned_data(16) locate_data(".noinit"); /**************************************************************************** * Private Functions ****************************************************************************/ static noreturn_function void __esp32_start(void) { uint32_t regval; uint32_t sp; /* Make sure that normal interrupts are disabled. This is really only an * issue when we are started in un-usual ways (such as from IRAM). In this * case, we can at least defer some unexpected interrupts left over from * the last program execution. */ up_irq_disable(); /* Move the stack to a known location. Although we were given a stack * pointer at start-up, we don't know where that stack pointer is * positioned with respect to our memory map. The only safe option is to * switch to a well-known IDLE thread stack. */ sp = (uint32_t)g_idlestack + IDLETHREAD_STACKSIZE; __asm__ __volatile__("mov sp, %0\n" : : "r"(sp)); /* Make page 0 access raise an exception */ esp32_region_protection(); /* Move CPU0 exception vectors to IRAM */ __asm__ __volatile__ ("wsr %0, vecbase\n"::"r" (&_init_start)); /* Set .bss to zero */ memset(&_sbss, 0, (&_ebss - &_sbss) * sizeof(_sbss)); /* Make sure that the APP_CPU is disabled for now */ regval = getreg32(DPORT_APPCPU_CTRL_B_REG); regval &= ~DPORT_APPCPU_CLKGATE_EN; putreg32(regval, DPORT_APPCPU_CTRL_B_REG); /* The 2nd stage bootloader enables RTC WDT to check on startup sequence * related issues in application. Hence disable that as we are about to * start the NuttX environment. */ esp32_wdt_early_deinit(); /* Set CPU frequency configured in board.h */ esp32_clockconfig(); #ifndef CONFIG_SUPPRESS_UART_CONFIG /* Configure the UART so we can get debug output */ esp32_lowsetup(); #endif #ifdef USE_EARLYSERIALINIT /* Perform early serial initialization */ xtensa_earlyserialinit(); #endif showprogress("A"); #if defined(CONFIG_ESP32_SPIRAM_BOOT_INIT) esp_spiram_init_cache(); if (esp_spiram_init() != OK) { # if defined(ESP32_SPIRAM_IGNORE_NOTFOUND) mwarn("SPIRAM Initialization failed!\n"); # else PANIC(); # endif } /* Set external memory bss section to zero */ # ifdef CONFIG_XTENSA_EXTMEM_BSS memset(&_sbss_extmem, 0, (&_ebss_extmem - &_sbss_extmem) * sizeof(_sbss_extmem)); # endif #endif /* Initialize onboard resources */ esp32_board_initialize(); showprogress("B"); /* Bring up NuttX */ nx_start(); for (; ; ); /* Should not return */ } /**************************************************************************** * Name: calc_mmu_pages * * Description: * Calculate the number of cache pages to map. * * Input Parameters: * size - Size of data to map * vaddr - Virtual address where data will be mapped * * Returned Value: * Number of cache MMU pages required to do the mapping. * ****************************************************************************/ #ifdef CONFIG_ESP32_APP_FORMAT_MCUBOOT static inline uint32_t calc_mmu_pages(uint32_t size, uint32_t vaddr) { return (size + (vaddr - (vaddr & MMU_FLASH_MASK)) + MMU_BLOCK_SIZE - 1) / MMU_BLOCK_SIZE; } #endif /**************************************************************************** * Name: map_rom_segments * * Description: * Configure the MMU and Cache peripherals for accessing ROM code and data. * * Input Parameters: * None. * * Returned Value: * None. * ****************************************************************************/ #ifdef CONFIG_ESP32_APP_FORMAT_MCUBOOT static int map_rom_segments(void) { uint32_t rc = 0; uint32_t regval; uint32_t drom_lma_aligned; uint32_t drom_vma_aligned; uint32_t drom_page_count; uint32_t irom_lma_aligned; uint32_t irom_vma_aligned; uint32_t irom_page_count; size_t partition_offset = PRIMARY_SLOT_OFFSET; uint32_t app_irom_lma = partition_offset + (uint32_t)&_image_irom_lma; uint32_t app_irom_size = (uint32_t)&_image_irom_size; uint32_t app_irom_vma = (uint32_t)&_image_irom_vma; uint32_t app_drom_lma = partition_offset + (uint32_t)&_image_drom_lma; uint32_t app_drom_size = (uint32_t)&_image_drom_size; uint32_t app_drom_vma = (uint32_t)&_image_drom_vma; volatile uint32_t *pro_flash_mmu_table = (volatile uint32_t *)DPORT_PRO_FLASH_MMU_TABLE_REG; cache_read_disable(0); cache_flush(0); /* Clear the MMU entries that are already set up, so the new app only has * the mappings it creates. */ for (int i = 0; i < DPORT_FLASH_MMU_TABLE_SIZE; i++) { putreg32(DPORT_FLASH_MMU_TABLE_INVALID_VAL, pro_flash_mmu_table++); } drom_lma_aligned = app_drom_lma & MMU_FLASH_MASK; drom_vma_aligned = app_drom_vma & MMU_FLASH_MASK; drom_page_count = calc_mmu_pages(app_drom_size, app_drom_vma); rc = cache_flash_mmu_set(0, 0, drom_vma_aligned, drom_lma_aligned, 64, (int)drom_page_count); rc |= cache_flash_mmu_set(1, 0, drom_vma_aligned, drom_lma_aligned, 64, (int)drom_page_count); irom_lma_aligned = app_irom_lma & MMU_FLASH_MASK; irom_vma_aligned = app_irom_vma & MMU_FLASH_MASK; irom_page_count = calc_mmu_pages(app_irom_size, app_irom_vma); rc |= cache_flash_mmu_set(0, 0, irom_vma_aligned, irom_lma_aligned, 64, (int)irom_page_count); rc |= cache_flash_mmu_set(1, 0, irom_vma_aligned, irom_lma_aligned, 64, (int)irom_page_count); regval = getreg32(DPORT_PRO_CACHE_CTRL1_REG); regval &= ~(DPORT_PRO_CACHE_MASK_IRAM0 | DPORT_PRO_CACHE_MASK_DROM0 | DPORT_PRO_CACHE_MASK_DRAM1); putreg32(regval, DPORT_PRO_CACHE_CTRL1_REG); regval = getreg32(DPORT_APP_CACHE_CTRL1_REG); regval &= ~(DPORT_APP_CACHE_MASK_IRAM0 | DPORT_APP_CACHE_MASK_DROM0 | DPORT_APP_CACHE_MASK_DRAM1); putreg32(regval, DPORT_APP_CACHE_CTRL1_REG); cache_read_enable(0); return (int)rc; } #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: __start * * Description: * We arrive here after the bootloader finished loading the program from * flash. The hardware is mostly uninitialized, and the app CPU is in * reset. We do have a stack, so we can do the initialization in C. * * The app CPU will remain in reset unless CONFIG_SMP is selected and * up_cpu_start() is called later in the bring-up sequence. * ****************************************************************************/ void __start(void) { #ifdef CONFIG_ESP32_APP_FORMAT_MCUBOOT if (map_rom_segments() != 0) { ets_printf("Failed to setup XIP, aborting\n"); while (true); } #endif __esp32_start(); }
899005.c
#include "pinout.h" #define PAGE_SIZE (4*1024) #define BLOCK_SIZE (4*1024) #define RK3288_GPIO(x) (GPIO0_BASE+x*GPIO_LENGTH+(x>0)*GPIO_CHANNEL) #define GPIO_LENGTH 0x00010000 #define GPIO_CHANNEL 0x00020000 #define GPIO0_BASE 0xff750000 #define GPIO_BANK 9 #define RK3288_GRF_PHYS 0xff770000 #define GPIO_BANK_NUM 9 #define RK3288_PMU 0xff730000 #define PMU_GPIO0C_IOMUX 0x008c #define PMU_GPIO0C_P 0x006c #define GPIO_SWPORTA_DR_OFFSET 0x0000 #define GPIO_SWPORTA_DDR_OFFSET 0x0004 #define GPIO_EXT_PORTA_OFFSET 0x0050 #define GRF_GPIO5B_P 0x0184 #define GRF_GPIO5C_P 0x0188 #define GRF_GPIO6A_P 0x0190 #define GRF_GPIO6B_P 0x0194 #define GRF_GPIO6C_P 0x0198 #define GRF_GPIO7A_P 0x01a0 #define GRF_GPIO7B_P 0x01a4 #define GRF_GPIO7C_P 0x01a8 #define GRF_GPIO8A_P 0x01b0 #define GRF_GPIO8B_P 0x01b4 #define GPIO0_C1 17 //7----->17 #define GPIO5_B0 (8+152) //7----->160 #define GPIO5_B1 (9+152) //8----->161 #define GPIO5_B2 (10+152) //7----->162 #define GPIO5_B3 (11+152) //7----->163 #define GPIO5_B4 (12+152) //7----->164 #define GPIO5_B5 (13+152) //7----->165 #define GPIO5_B6 (14+152) //7----->166 #define GPIO5_B7 (15+152) //7----->167 #define GPIO5_C0 (16+152) //7----->168 #define GPIO5_C1 (17+152) //7----->169 #define GPIO5_C2 (18+152) //7----->170 #define GPIO5_C3 (19+152) //7----->171 #define GPIO6_A0 (184) //7----->184 #define GPIO6_A1 (1+184) //7----->185 #define GPIO6_A3 (3+184) //7----->187 #define GPIO6_A4 (4+184) //7----->188 #define GPIO7_A7 (7+216) //7----->223 #define GPIO7_B0 (8+216) //7----->224 #define GPIO7_B1 (9+216) //7----->225 #define GPIO7_B2 (10+216) //7----->226 #define GPIO7_C1 (17+216) //7----->233 #define GPIO7_C2 (18+216) //7----->234 #define GPIO7_C6 (22+216) //7----->238 #define GPIO7_C7 (23+216) //7----->239 #define GPIO8_A3 (3+248) //7----->251 #define GPIO8_A4 (4+248) //3----->252 #define GPIO8_A5 (5+248) //5----->253 #define GPIO8_A6 (6+248) //7----->254 #define GPIO8_A7 (7+248) //7----->255 #define GPIO8_B0 (8+248) //7----->256 #define GPIO8_B1 (9+248) //7----->257 #define GRF_GPIO5B_IOMUX 0x0050 #define GRF_GPIO5C_IOMUX 0x0054 #define GRF_GPIO6A_IOMUX 0x005c #define GRF_GPIO6B_IOMUX 0x0060 #define GRF_GPIO6C_IOMUX 0x0064 #define GRF_GPIO7A_IOMUX 0x006c #define GRF_GPIO7B_IOMUX 0x0070 #define GRF_GPIO7CL_IOMUX 0x0074 #define GRF_GPIO7CH_IOMUX 0x0078 #define GRF_GPIO8A_IOMUX 0x0080 #define GRF_GPIO8B_IOMUX 0x0084 #define PUD_OFF 0 #define PUD_DOWN 2 #define PUD_UP 1 #define RK3288_GRF_PHYS 0xff770000 volatile uint32_t *gpio[GPIO_BANK_NUM]; volatile uint32_t *grf; volatile uint32_t *pmu; int gpio_pin[PIN_NUM]; static void pinModeToGPIO(int pin) { switch (pin) { //GPIO0 case 17: *(pmu + PMU_GPIO0C_IOMUX / 4) = (*(pmu + PMU_GPIO0C_IOMUX / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))); break; //GPIO1D0:act-led case 48: break; //GPIO5B case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: *(grf + GRF_GPIO5B_IOMUX / 4) = (*(grf + GRF_GPIO5B_IOMUX / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))); break; //GPIO5C case 168: case 169: case 170: case 171: *(grf + GRF_GPIO5C_IOMUX / 4) = (*(grf + GRF_GPIO5C_IOMUX / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))); break; //GPIO6A case 184: case 185: case 187: case 188: *(grf + GRF_GPIO6A_IOMUX / 4) = (*(grf + GRF_GPIO6A_IOMUX / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))); break; //GPIO7A7 case 223: *(grf + GRF_GPIO7A_IOMUX / 4) = (*(grf + GRF_GPIO7A_IOMUX / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))); break; //GPIO7B case 224: case 225: case 226: *(grf + GRF_GPIO7B_IOMUX / 4) = (*(grf + GRF_GPIO7B_IOMUX / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))); break; //GPIO7C case 233: case 234: *(grf + GRF_GPIO7CL_IOMUX / 4) = (*(grf + GRF_GPIO7CL_IOMUX / 4) | (0x0f << (16 + (pin % 8)*4))) & (~(0x0f << ((pin % 8)*4))); break; case 238: case 239: *(grf + GRF_GPIO7CH_IOMUX / 4) = (*(grf + GRF_GPIO7CH_IOMUX / 4) | (0x0f << (16 + (pin % 8 - 4)*4))) & (~(0x0f << ((pin % 8 - 4)*4))); break; //GPIO8A case 251: case 254: case 255: case 252: case 253: *(grf + GRF_GPIO8A_IOMUX / 4) = (*(grf + GRF_GPIO8A_IOMUX / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))); break; //GPIO8B case 256: case 257: *(grf + GRF_GPIO8B_IOMUX / 4) = (*(grf + GRF_GPIO8B_IOMUX / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))); break; default: break; } } void pinWrite(int pin, int value) { pin = gpio_pin[pin]; if (value == 1) { if (pin >= 24) { *(gpio[(pin + 8) / 32] + GPIO_SWPORTA_DR_OFFSET / 4) |= (1 << ((pin - 24) % 32)); } else { *(gpio[pin / 32] + GPIO_SWPORTA_DR_OFFSET / 4) |= (1 << (pin % 32)); } } else { if (pin >= 24) { *(gpio[(pin + 8) / 32] + GPIO_SWPORTA_DR_OFFSET / 4) &= ~(1 << ((pin - 24) % 32)); } else { *(gpio[pin / 32] + GPIO_SWPORTA_DR_OFFSET / 4) &= ~(1 << (pin % 32)); } } } int pinRead(int pin) { pin = gpio_pin[pin]; int value, mask; if (pin >= 24) { mask = (1 << (pin - 24) % 32); value = (((*(gpio[(pin - 24) / 32 + 1] + GPIO_EXT_PORTA_OFFSET / 4)) & mask)>>(pin - 24) % 32); } else { mask = (1 << pin % 32); value = (((*(gpio[pin / 32] + GPIO_EXT_PORTA_OFFSET / 4)) & mask) >> pin % 32); } return value; } void pinLow(int pin) { pin = gpio_pin[pin]; if (pin >= 24) { *(gpio[(pin + 8) / 32] + GPIO_SWPORTA_DR_OFFSET / 4) &= ~(1 << ((pin - 24) % 32)); } else { *(gpio[pin / 32] + GPIO_SWPORTA_DR_OFFSET / 4) &= ~(1 << (pin % 32)); } } void pinHigh(int pin) { pin = gpio_pin[pin]; if (pin >= 24) { *(gpio[(pin + 8) / 32] + GPIO_SWPORTA_DR_OFFSET / 4) |= (1 << ((pin - 24) % 32)); } else { *(gpio[pin / 32] + GPIO_SWPORTA_DR_OFFSET / 4) |= (1 << (pin % 32)); } } void pinModeIn(int pin) { pin = gpio_pin[pin]; pinModeToGPIO(pin); if (pin >= 24) { *(gpio[(pin + 8) / 32] + GPIO_SWPORTA_DDR_OFFSET / 4) &= ~(1 << ((pin + 8) % 32)); } else { *(gpio[pin / 32] + GPIO_SWPORTA_DDR_OFFSET / 4) &= ~(1 << (pin % 32)); } } void pinModeOut(int pin) { pin = gpio_pin[pin]; pinModeToGPIO(pin); if (pin >= 24) { *(gpio[(pin + 8) / 32] + GPIO_SWPORTA_DDR_OFFSET / 4) |= (1 << ((pin + 8) % 32)); } else { *(gpio[pin / 32] + GPIO_SWPORTA_DDR_OFFSET / 4) |= (1 << (pin % 32)); } } void pinPUD(int pin, int pud) { pin = gpio_pin[pin]; static int bit0, bit1; if (pud == PUD_UP) { bit0 = 1; bit1 = 0; } else if (pud == PUD_DOWN) { bit0 = 0; bit1 = 1; } else { bit0 = 0; bit1 = 0; } switch (pin) { //GPIO0 case 17: *(pmu + PMU_GPIO0C_P / 4) = (*(grf + PMU_GPIO0C_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; //case 17 : value = 0x00000003; break; //GPIO5B case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: *(grf + GRF_GPIO5B_P / 4) = (*(grf + GRF_GPIO5B_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; //GPIO5C case 168: case 169: case 170: case 171: *(grf + GRF_GPIO5C_P / 4) = (*(grf + GRF_GPIO5C_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; //GPIO6A case 184: case 185: case 187: case 188: *(grf + GRF_GPIO6A_P / 4) = (*(grf + GRF_GPIO6A_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; //GPIO7A7 case 223: *(grf + GRF_GPIO7A_P / 4) = (*(grf + GRF_GPIO7A_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; //GPIO7B case 224: case 225: case 226: *(grf + GRF_GPIO7B_P / 4) = (*(grf + GRF_GPIO7B_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; //GPIO7C case 233: case 234: case 238: case 239: *(grf + GRF_GPIO7C_P / 4) = (*(grf + GRF_GPIO7C_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; //GPIO8A case 251: case 254: case 255: case 252: case 253: *(grf + GRF_GPIO8A_P / 4) = (*(grf + GRF_GPIO8A_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; //GPIO8B case 256: case 257: *(grf + GRF_GPIO8B_P / 4) = (*(grf + GRF_GPIO8B_P / 4) | (0x03 << ((pin % 8)*2 + 16))) & (~(0x03 << ((pin % 8)*2))) | (bit1 << ((pin % 8)*2 + 1)) | (bit0 << ((pin % 8)*2)); break; default: break; } } int checkPin(int pin) { if (pin < 0 || pin >= PIN_NUM) { return 0; } if (gpio_pin[pin] == -1) { return 0; } return 1; } static void parse_pin(int *npin, const char *name) { if (strlen(name) < 4) { goto failed; } if (*name != 'P') { goto failed; } int p1, p3; char p2; name++; int n = sscanf(name, "%d%c%d", &p1, &p2, &p3); if (n != 3) { goto failed; } int pp1 = p1 * 32 - 8; if (pp1 < 0) { pp1 = 0; } int pp2 = (p2 - 'A')*8 + p3; *npin = pp1 + pp2; // printf("%s %d %d\n",name, pp1, pp2); return; failed: *npin = -1; } static void makeData() { for (int i = 0; i < PIN_NUM; i++) { parse_pin(gpio_pin + i, physToGpio[i]); } } int gpioSetup() { int fd; if ((fd = open("/dev/mem", O_RDWR | O_SYNC | O_CLOEXEC)) < 0) { fprintf(stderr, "%s(): ", __func__); perror("open()"); return 0; } for (int i = 0; i < GPIO_BANK_NUM; i++) { gpio[i] = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, RK3288_GPIO(i)); if (gpio[i] == MAP_FAILED) { fprintf(stderr, "%s(): ", __func__); perror("mmap1()"); close(fd); return 0; } } grf = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, RK3288_GRF_PHYS); if (grf == MAP_FAILED) { fprintf(stderr, "%s(): ", __func__); perror("mmap2()"); close(fd); return 0; } pmu = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, RK3288_PMU); if (pmu == MAP_FAILED) { fprintf(stderr, "%s(): ", __func__); perror("mmap3()"); close(fd); return 0; } close(fd); makeData(); return 1; } void gpioFree() { if(grf !=NULL && grf!=MAP_FAILED){ if(munmap((void*)grf, PAGE_SIZE)!=0){ perrord("munmap()"); } } if(pmu !=NULL && pmu!=MAP_FAILED){ if(munmap((void*)pmu, PAGE_SIZE)!=0){ perrord("munmap()"); } } }
4511.c
/* trec_eval.c implements standard information retrieval evaluation * measures. This code originated in the trec_eval program written by * Chris Buckley and Gerard Salton. They originally published under * this license: * * Copyright (c) 1991, 1990, 1984 - Gerard Salton, Chris Buckley. * Permission is granted for use of this file in unmodified form for * research purposes. Please contact the SMART project to obtain * permission for other uses. * * This code was modified and redistributed with permission from Chris * Buckley. * */ #include "firstinclude.h" #include "trec_eval.h" #include "chash.h" #include "str.h" #include <stdlib.h> #include <string.h> /* Defined constants that are collection/purpose dependent */ /* Number of cutoffs for recall,precision, and rel_precis measures. */ /* CUTOFF_VALUES gives the number of retrieved docs that these * evaluation measures are applied at. */ #define NUM_CUTOFF 9 #define CUTOFF_VALUES {5, 10, 15, 20, 30, 100, 200, 500, 1000} /* Maximum fallout value, expressed in number of non-rel docs retrieved. */ /* (Make the approximation that number of non-rel docs in collection */ /* is equal to the number of number of docs in collection) */ #define MAX_FALL_RET 142 /* Maximum multiple of R (number of rel docs for this query) to calculate */ /* R-based precision at */ #define MAX_RPREC 2.0 /* Defined constants that are collection/purpose independent. If you * change these, you probably need to change comments and documentation, * and some variable names may not be appropriate any more! */ #define NUM_RP_PTS 11 #define THREE_PTS {2, 5, 8} #define NUM_FR_PTS 11 #define NUM_PREC_PTS 11 typedef struct { int qid; /* query id (for overall average figures, this gives number of queries in run) */ /* Summary Numbers over all queries */ long num_rel; /* Number of relevant docs */ long num_ret; /* Number of retrieved docs */ long num_rel_ret; /* Number of relevant retrieved docs */ float avg_doc_prec; /* Average of precision over all relevant documents (query independent) */ /* Measures after num_ret docs */ float exact_recall; /* Recall after num_ret docs */ float exact_precis; /* Precision after num_ret docs */ float exact_rel_precis; /* Relative Precision (or recall) */ /* Defined to be precision / max possible precision */ /* Measures after each document */ float recall_cut[NUM_CUTOFF]; /* Recall after cutoff[i] docs */ float precis_cut[NUM_CUTOFF]; /* precision after cutoff[i] docs. If less than cutoff[i] docs retrieved, then assume an additional cutoff[i]-num_ret non-relevant docs are retrieved. */ float rel_precis_cut /* Relative precision after cutoff[i] */ [NUM_CUTOFF]; /* docs */ /* Measures after each rel doc */ float av_recall_precis; /* average(integral) of precision at all rel doc ranks */ float int_av_recall_precis; /* Same as above, but the precision values have been interpolated, so that prec(X) is actually MAX prec(Y) for all Y >= X */ float int_recall_precis /* interpolated precision at 0.1 */ [NUM_RP_PTS]; /* increments of recall */ float int_av3_recall_precis; /* interpolated average at 3 intermediate points */ float int_av11_recall_precis; /* interpolated average at NUM_RP_PTS intermediate points (recall_level) */ /* Measures after each non-rel doc */ float fall_recall[NUM_FR_PTS]; /* max recall after each non-rel doc, at 11 points starting at 0.0 and ending at MAX_FALL_RET /num_docs */ float av_fall_recall; /* Average of fallout-recall, after each non-rel doc until fallout of MAX_FALL_RET / num_docs achieved */ /* Measures after R-related cutoffs. R is the number of relevant * docs for a particular query, but note that these cutoffs are * after R docs, whether relevant or non-relevant, have been * retrieved. R-related cutoffs are really only applicable to a * situtation where there are many relevant docs per query (or lots * of queries). */ float R_recall_precis; /* Recall or precision after R docs (note they are equal at this point) */ float av_R_precis; /* Average (or integral) of precision at each doc until R docs have been retrieved */ float R_prec_cut[NUM_PREC_PTS]; /* Precision measured after multiples of R docs have been retrieved. 11 equal points, with max multiple having value MAX_RPREC */ float int_R_recall_precis; /* Interpolated precision after R docs Prec(X) = MAX(prec(Y)) for all Y>=X */ float int_av_R_precis; /* Interpolated */ float int_R_prec_cut /* Interpolated */ [NUM_PREC_PTS]; } TREC_EVAL; typedef struct { long int did; /* document id */ long int rank; /* Rank of this document */ char action; /* what action a user has taken with doc */ char rel; /* whether doc judged relevant(1) or not(0) */ char iter; /* Number of feedback runs for this query */ char trtup_unused; /* Presently unused field */ float sim; /* similarity of did to qid */ } TR_TUP; typedef struct { int qid; /* query id */ long int num_tr; /* Number of tuples for tr_vec */ TR_TUP *tr; /* tuples. Invariant: tr sorted increasing did */ } TR_VEC; typedef struct { char *docno; float sim; long int rank; } TEXT_TR; typedef struct { int qid; long int num_text_tr; long int max_num_text_tr; TEXT_TR *text_tr; } TREC_TOP; #define TR_INCR 250 #define MAX(A,B) ((A) > (B) ? (A) : (B)) #define MIN(A,B) ((A) > (B) ? (B) : (A)) #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #define UNDEF -1 #define MAX_LINE_LENGTH 100 /* currently I'm assuming there are only 1000 queries _ever_ used at * TREC, which is probably unrealistic. This assumption makes things * easier, and if there are more queries used (ie higher query numbers * used) then the following number just needs to be increased. */ #define INTERPOLATED000 0 #define INTERPOLATED010 1 #define INTERPOLATED020 2 #define INTERPOLATED030 3 #define INTERPOLATED040 4 #define INTERPOLATED050 5 #define INTERPOLATED060 6 #define INTERPOLATED070 7 #define INTERPOLATED080 8 #define INTERPOLATED090 9 #define INTERPOLATED100 10 #define PRECISION_AT_5 0 #define PRECISION_AT_10 1 #define PRECISION_AT_15 2 #define PRECISION_AT_20 3 #define PRECISION_AT_30 4 #define PRECISION_AT_100 5 #define PRECISION_AT_200 6 #define PRECISION_AT_500 7 #define PRECISION_AT_1000 8 #define TREC_DOCUMENT_NUMBER_MAX_LENGTH 50 typedef struct { int query_id; /* Holds query ID */ char trec_document_number[TREC_DOCUMENT_NUMBER_MAX_LENGTH]; /* TREC document ID */ float score; /* accumulator score of document */ } result_tuple; struct treceval_qrels { struct chash *judgements; /* Hash table that contains as keys all relevance judgements in the format of "QID TRECDOCNO", for instance "381 FBIS3-1" */ int number_of_judged_queries; /* This many queries have relevance judgements */ int lowest_query_id; /* The lowest query Id that has a relevance judgement */ /* Each query contains this many judgements */ int *number_of_judgements_for_query; }; struct treceval { result_tuple *tuples; /* Stores unevaluated result tuples */ unsigned int cached_results; /* Number of tuples in cache */ unsigned int cache_size; /* Cache size in tuples */ }; static int init_tr_trec_eval(TREC_EVAL * eval); static int tr_trec_eval(TR_VEC * tr_vec, TREC_EVAL * eval, long int num_rel); static int close_tr_trec_eval(TREC_EVAL * eval); static int trvec_trec_eval(TR_VEC * tr_vec, TREC_EVAL * eval, long int num_rel); static int comp_tr_tup_did(const void *, const void *); static int comp_sim_docno(const void *, const void *); static int get_trec_top(TREC_TOP * trec_top, const struct treceval *result_cache, unsigned int *up_to, unsigned int to_position); static int form_and_eval_trvec(TREC_EVAL * eval_accum, TREC_TOP * trec_top, const struct treceval_qrels * qrels); static void evaluate_trec_results(unsigned int from_position, unsigned int to_position, const struct treceval *result_cache, const struct treceval_qrels *qrels, struct treceval_results *evaluated_results) { TREC_TOP trec_top; TREC_EVAL eval_accum; unsigned int up_to = from_position; init_tr_trec_eval(&eval_accum); trec_top.max_num_text_tr = 0; trec_top.text_tr = NULL; evaluated_results->queries = 0; while (get_trec_top(&trec_top, result_cache, &up_to, to_position) != 0) { form_and_eval_trvec(&eval_accum, &trec_top, qrels); evaluated_results->queries++; } /* Finish evaluation computation */ close_tr_trec_eval(&eval_accum); evaluated_results->retrieved = eval_accum.num_ret; evaluated_results->relevant = eval_accum.num_rel; evaluated_results->relevant_retrieved = eval_accum.num_rel_ret; evaluated_results->interpolated_rp[INTERPOLATED000] = eval_accum.int_recall_precis[0]; evaluated_results->interpolated_rp[INTERPOLATED010] = eval_accum.int_recall_precis[1]; evaluated_results->interpolated_rp[INTERPOLATED020] = eval_accum.int_recall_precis[2]; evaluated_results->interpolated_rp[INTERPOLATED030] = eval_accum.int_recall_precis[3]; evaluated_results->interpolated_rp[INTERPOLATED040] = eval_accum.int_recall_precis[4]; evaluated_results->interpolated_rp[INTERPOLATED050] = eval_accum.int_recall_precis[5]; evaluated_results->interpolated_rp[INTERPOLATED060] = eval_accum.int_recall_precis[6]; evaluated_results->interpolated_rp[INTERPOLATED070] = eval_accum.int_recall_precis[7]; evaluated_results->interpolated_rp[INTERPOLATED080] = eval_accum.int_recall_precis[8]; evaluated_results->interpolated_rp[INTERPOLATED090] = eval_accum.int_recall_precis[9]; evaluated_results->interpolated_rp[INTERPOLATED100] = eval_accum.int_recall_precis[10]; evaluated_results->average_precision = eval_accum.av_recall_precis; evaluated_results->precision_at[PRECISION_AT_5] = eval_accum.precis_cut[0]; evaluated_results->precision_at[PRECISION_AT_10] = eval_accum.precis_cut[1]; evaluated_results->precision_at[PRECISION_AT_15] = eval_accum.precis_cut[2]; evaluated_results->precision_at[PRECISION_AT_20] = eval_accum.precis_cut[3]; evaluated_results->precision_at[PRECISION_AT_30] = eval_accum.precis_cut[4]; evaluated_results->precision_at[PRECISION_AT_100] = eval_accum.precis_cut[5]; evaluated_results->precision_at[PRECISION_AT_200] = eval_accum.precis_cut[6]; evaluated_results->precision_at[PRECISION_AT_500] = eval_accum.precis_cut[7]; evaluated_results->precision_at[PRECISION_AT_1000] = eval_accum.precis_cut[8]; evaluated_results->rprecision = eval_accum.R_recall_precis; if (trec_top.text_tr != NULL) { free(trec_top.text_tr); } return; } static int form_and_eval_trvec(TREC_EVAL * eval_accum, TREC_TOP * trec_top, const struct treceval_qrels *qrels) { TR_TUP *tr_tup; long i; TR_TUP *start_tr_tup = NULL; /* Space reserved for output TR_TUP tuples */ long max_tr_tup = 0; TR_VEC tr_vec; char judgement[MAX_LINE_LENGTH]; void **dummy_pointer = NULL; /* Reserve space for output tr_tups, if needed */ if (trec_top->num_text_tr > max_tr_tup) { if (max_tr_tup > 0) { (void) free((char *) start_tr_tup); } max_tr_tup += trec_top->num_text_tr; if ((start_tr_tup = (TR_TUP *) malloc((unsigned) max_tr_tup * sizeof(TR_TUP))) == NULL) { return (UNDEF); } } /* Sort trec_top by sim, breaking ties lexicographically using docno */ qsort((char *) trec_top->text_tr, (int) trec_top->num_text_tr, sizeof(TEXT_TR), comp_sim_docno); /* Add ranks to trec_top (starting at 1) */ for (i = 0; i < trec_top->num_text_tr; i++) { trec_top->text_tr[i].rank = i + 1; } /* for each tuple in trec_top check the hash table which documents * * are relevant. Once relevance is known, convert trec_top tuple * * into TR_TUP. */ tr_tup = start_tr_tup; for (i = 0; i < trec_top->num_text_tr; i++) { sprintf(judgement, "%d %s", trec_top->qid, trec_top->text_tr[i].docno); if (chash_ptr_ptr_find(qrels->judgements, judgement, &dummy_pointer) != CHASH_OK) { /* Document is non-relevant */ tr_tup->rel = 0; } else { /* Document is relevant */ tr_tup->rel = 1; } tr_tup->did = i; tr_tup->rank = trec_top->text_tr[i].rank; tr_tup->sim = trec_top->text_tr[i].sim; tr_tup->action = 0; tr_tup->iter = 0; tr_tup++; } /* Form and output the full TR_VEC object for this qid */ /* Sort trec_top tr_tups by did */ qsort((char *) start_tr_tup, (int) trec_top->num_text_tr, sizeof(TR_TUP), comp_tr_tup_did); tr_vec.qid = trec_top->qid; tr_vec.num_tr = trec_top->num_text_tr; tr_vec.tr = start_tr_tup; /* Accumulate this tr_vec's eval figures in eval_accum */ tr_trec_eval(&tr_vec, eval_accum, qrels->number_of_judgements_for_query[trec_top->qid - qrels->lowest_query_id]); free(start_tr_tup); return (1); } static int comp_sim_docno(const void *vptr1, const void *vptr2) { const TEXT_TR *ptr1 = vptr1, *ptr2 = vptr2; if (ptr1->sim > ptr2->sim) return (-1); if (ptr1->sim < ptr2->sim) return (1); return (strcmp(ptr2->docno, ptr1->docno)); } static int comp_tr_tup_did(const void *vptr1, const void *vptr2) { const TR_TUP *ptr1 = vptr1, *ptr2 = vptr2; return (ptr1->did - ptr2->did); } /* Get entire trec_top vector for next query */ static int get_trec_top(TREC_TOP * trec_top, const struct treceval *result_cache, unsigned int *up_to, unsigned int to_position) { int qid; /* have already processed all tuples in this result set */ if (*up_to >= to_position) { return 0; } trec_top->num_text_tr = 0; qid = trec_top->qid = result_cache->tuples[trec_top->num_text_tr + *up_to].query_id; while (qid == trec_top->qid) { /* Make sure enough space is reserved for next tuple */ if (trec_top->num_text_tr >= trec_top->max_num_text_tr) { if (trec_top->max_num_text_tr == 0) { if ((trec_top->text_tr = (TEXT_TR *) malloc((unsigned) TR_INCR * sizeof(TEXT_TR))) == NULL) { return (0); } } else if ((trec_top->text_tr = (TEXT_TR *) realloc((char *) trec_top->text_tr, (unsigned) (trec_top->max_num_text_tr + TR_INCR) * sizeof(TEXT_TR))) == NULL) { return (0); } trec_top->max_num_text_tr += TR_INCR; } trec_top->text_tr[trec_top->num_text_tr].docno = result_cache->tuples[trec_top->num_text_tr + *up_to].trec_document_number; trec_top->text_tr[trec_top->num_text_tr].sim = result_cache->tuples[trec_top->num_text_tr + *up_to].score; trec_top->num_text_tr++; /* are we at the end of the results? */ if ((trec_top->num_text_tr + *up_to) >= to_position) { *up_to += trec_top->num_text_tr; return (1); } qid = result_cache->tuples[trec_top->num_text_tr + *up_to].query_id; } *up_to += trec_top->num_text_tr; return (1); } /******************** PROCEDURE DESCRIPTION ************************ *0 Given a tr file, evaluate it using trec, returning the evaluation in eval *2 tr_trec_eval (tr_file, eval, inst) *3 char *tr_file; *3 TREC_EVAL *eval; *3 int inst; *4 init_tr_trec_eval (spec, unused) *5 "eval.tr_file" *5 "eval.tr_file.rmode" *5 "eval.trace" *4 close_tr_trec_eval (inst) *7 Evaluate the given tr_file, returning the average over all queries of *7 each query's evaluation. Eval->qid will contain the number of queries *7 evaluated. Tr_file is taken from the argument tr_file if *7 that is valid, else from the spec parameter eval.tr_file. *7 Return 1 if successful, 0 if no queries were evaluated, and UNDEF *7 otherwise *8 Call trvec_smeval for each query in tr_file, and simply average results. *9 Note: Only the max iteration over all queries is averaged. Thus, if *9 query 1 had one iteration of feedback, and query 2 had two iterations of *9 feedback, query 1 will not be included in the final average (or counted *9 in eval->qid). ***********************************************************************/ static int init_tr_trec_eval(TREC_EVAL * eval) { memset(eval, 0, sizeof(*eval)); return (0); } static int tr_trec_eval(TR_VEC * tr_vec, TREC_EVAL * eval, long int num_rel) { long i; int max_iter_achieved; TREC_EVAL query_eval; int max_iter = 0; /* Check that max_iter has not been exceeded. If it has, then have * to throw away all previous results. Also check to see that * max_iter has been achieved. If not, then no docs were retrieved * for this query on this iteration */ max_iter_achieved = 0; for (i = 0; i < tr_vec->num_tr; i++) { if (tr_vec->tr[i].iter > max_iter) { memset((char *) eval, 0, sizeof(TREC_EVAL)); max_iter = tr_vec->tr[i].iter; } if (tr_vec->tr[i].iter == max_iter) { max_iter_achieved++; } } if (max_iter_achieved == 0) { return (0); } /* Evaluate this query */ if (1 == trvec_trec_eval(tr_vec, &query_eval, num_rel)) { if (query_eval.num_ret > 0) { eval->qid++; eval->num_rel += query_eval.num_rel; eval->num_ret += query_eval.num_ret; eval->num_rel_ret += query_eval.num_rel_ret; eval->avg_doc_prec += query_eval.avg_doc_prec; eval->exact_recall += query_eval.exact_recall; eval->exact_precis += query_eval.exact_precis; eval->exact_rel_precis += query_eval.exact_rel_precis; eval->av_recall_precis += query_eval.av_recall_precis; eval->int_av_recall_precis += query_eval.int_av_recall_precis; eval->int_av3_recall_precis += query_eval.int_av3_recall_precis; eval->int_av11_recall_precis += query_eval.int_av11_recall_precis; eval->av_fall_recall += query_eval.av_fall_recall; eval->R_recall_precis += query_eval.R_recall_precis; eval->av_R_precis += query_eval.av_R_precis; eval->int_R_recall_precis += query_eval.int_R_recall_precis; eval->int_av_R_precis += query_eval.int_av_R_precis; for (i = 0; i < NUM_CUTOFF; i++) { eval->recall_cut[i] += query_eval.recall_cut[i]; eval->precis_cut[i] += query_eval.precis_cut[i]; eval->rel_precis_cut[i] += query_eval.rel_precis_cut[i]; } for (i = 0; i < NUM_RP_PTS; i++) eval->int_recall_precis[i] += query_eval.int_recall_precis[i]; for (i = 0; i < NUM_FR_PTS; i++) eval->fall_recall[i] += query_eval.fall_recall[i]; for (i = 0; i < NUM_PREC_PTS; i++) { eval->R_prec_cut[i] += query_eval.R_prec_cut[i]; eval->int_R_prec_cut[i] += query_eval.int_R_prec_cut[i]; } } } return (0); } static int close_tr_trec_eval(TREC_EVAL * eval) { long i; /* Calculate averages (for those eval fields returning averages) */ if (eval->qid > 0) { if (eval->num_rel > 0) { eval->avg_doc_prec /= (float) eval->num_rel; } eval->exact_recall /= (float) eval->qid; eval->exact_precis /= (float) eval->qid; eval->exact_rel_precis /= (float) eval->qid; eval->av_recall_precis /= (float) eval->qid; eval->int_av_recall_precis /= (float) eval->qid; eval->int_av3_recall_precis /= (float) eval->qid; eval->int_av11_recall_precis /= (float) eval->qid; eval->av_fall_recall /= (float) eval->qid; eval->R_recall_precis /= (float) eval->qid; eval->av_R_precis /= (float) eval->qid; eval->int_R_recall_precis /= (float) eval->qid; eval->int_av_R_precis /= (float) eval->qid; for (i = 0; i < NUM_CUTOFF; i++) { eval->recall_cut[i] /= (float) eval->qid; eval->precis_cut[i] /= (float) eval->qid; eval->rel_precis_cut[i] /= (float) eval->qid; } for (i = 0; i < NUM_RP_PTS; i++) { eval->int_recall_precis[i] /= (float) eval->qid; } for (i = 0; i < NUM_FR_PTS; i++) { eval->fall_recall[i] /= (float) eval->qid; } for (i = 0; i < NUM_PREC_PTS; i++) { eval->R_prec_cut[i] /= (float) eval->qid; eval->int_R_prec_cut[i] /= (float) eval->qid; } } return (0); } /* cutoff values for recall precision output */ const static int cutoff[NUM_CUTOFF] = CUTOFF_VALUES; const static int three_pts[3] = THREE_PTS; static int compare_iter_rank(const void *, const void *); static int trvec_trec_eval(TR_VEC * tr_vec, TREC_EVAL * eval, long int num_rel) { /* cutoff values for recall precision output */ double recall, precis, int_precis; /* current recall, precision and interpolated precision values */ long i, j; long rel_so_far; long max_iter; long cut_rp[NUM_RP_PTS]; /* number of rel docs needed to be retrieved for each recall-prec cutoff */ long cut_fr[NUM_FR_PTS]; /* number of non-rel docs needed to be retrieved for each fall-recall cutoff */ long cut_rprec[NUM_PREC_PTS]; /* Number of docs needed to be retrieved for each R-based prec cutoff */ long current_cutoff, current_cut_rp, current_cut_fr, current_cut_rprec; if (tr_vec == (TR_VEC *) NULL) return (UNDEF); /* Initialize everything to 0 */ memset((char *) eval, 0, sizeof(TREC_EVAL)); eval->qid = tr_vec->qid; /* If no relevant docs, then just return */ if (tr_vec->num_tr == 0) { return (0); } eval->num_rel = num_rel; /* Evaluate only the docs on the last iteration of tr_vec */ /* Sort the tr tuples for this query by decreasing iter and * increasing rank */ qsort((char *) tr_vec->tr, (int) tr_vec->num_tr, sizeof(TR_TUP), compare_iter_rank); max_iter = tr_vec->tr[0].iter; rel_so_far = 0; for (j = 0; j < tr_vec->num_tr; j++) { if (tr_vec->tr[j].iter == max_iter) { eval->num_ret++; if (tr_vec->tr[j].rel) rel_so_far++; } else { if (tr_vec->tr[j].rel) eval->num_rel--; } } eval->num_rel_ret = rel_so_far; /* Discover cutoff values for this query */ current_cutoff = NUM_CUTOFF - 1; while (current_cutoff > 0 && cutoff[current_cutoff] > eval->num_ret) { current_cutoff--; } for (i = 0; i < NUM_RP_PTS; i++) { cut_rp[i] = ((eval->num_rel * i) + NUM_RP_PTS - 2) / (NUM_RP_PTS - 1); } current_cut_rp = NUM_RP_PTS - 1; while (current_cut_rp > 0 && cut_rp[current_cut_rp] > eval->num_rel_ret) { current_cut_rp--; } for (i = 0; i < NUM_FR_PTS; i++) { cut_fr[i] = ((MAX_FALL_RET * i) + NUM_FR_PTS - 2) / (NUM_FR_PTS - 1); } current_cut_fr = NUM_FR_PTS - 1; while (current_cut_fr > 0 && cut_fr[current_cut_fr] > eval->num_ret - eval->num_rel_ret) { current_cut_fr--; } for (i = 0; i < NUM_PREC_PTS; i++) { cut_rprec[i] = (long int) (((MAX_RPREC * eval->num_rel * i) + NUM_PREC_PTS - 2) / (NUM_PREC_PTS - 1)); } current_cut_rprec = NUM_PREC_PTS - 1; while (current_cut_rprec > 0 && cut_rprec[current_cut_rprec] > eval->num_ret) { current_cut_rprec--; } /* Note for interpolated precision values (Prec(X) = MAX (PREC(Y)) * for all Y >= X) */ int_precis = (float) rel_so_far / (float) eval->num_ret; for (j = eval->num_ret; j > 0; j--) { recall = (float) rel_so_far / (float) eval->num_rel; precis = (float) rel_so_far / (float) j; if (int_precis < precis) { int_precis = precis; } while (j == cutoff[current_cutoff]) { eval->recall_cut[current_cutoff] = (float) recall; eval->precis_cut[current_cutoff] = (float) precis; eval->rel_precis_cut[current_cutoff] = (float) (j > eval->num_rel ? recall : precis); current_cutoff--; } while (j == cut_rprec[current_cut_rprec]) { eval->R_prec_cut[current_cut_rprec] = (float) precis; eval->int_R_prec_cut[current_cut_rprec] = (float) int_precis; current_cut_rprec--; } if (j == eval->num_rel) { eval->R_recall_precis = (float) precis; eval->int_R_recall_precis = (float) int_precis; } if (j < eval->num_rel) { eval->av_R_precis += (float) precis; eval->int_av_R_precis += (float) int_precis; } if (tr_vec->tr[j - 1].rel) { eval->int_av_recall_precis += (float) int_precis; eval->av_recall_precis += (float) precis; eval->avg_doc_prec += (float) precis; while (rel_so_far == cut_rp[current_cut_rp]) { eval->int_recall_precis[current_cut_rp] = (float) int_precis; current_cut_rp--; } rel_so_far--; } else { /* Note: for fallout-recall, the recall at X non-rel docs is * used for the recall 'after' (X-1) non-rel docs. Ie. * recall_used(X-1 non-rel docs) = MAX (recall(Y)) for Y * retrieved docs where X-1 non-rel retrieved */ while (current_cut_fr >= 0 && j - rel_so_far == cut_fr[current_cut_fr] + 1) { eval->fall_recall[current_cut_fr] = (float) recall; current_cut_fr--; } if (j - rel_so_far < MAX_FALL_RET) { eval->av_fall_recall += (float) recall; } } } /* Fill in the 0.0 value for recall-precision (== max precision at * any point in the retrieval ranking) */ eval->int_recall_precis[0] = (float) int_precis; /* Fill in those cutoff values and averages that were not achieved * because insufficient docs were retrieved. */ for (i = 0; i < NUM_CUTOFF; i++) { if (eval->num_ret < cutoff[i]) { eval->recall_cut[i] = ((float) eval->num_rel_ret / (float) eval->num_rel); eval->precis_cut[i] = ((float) eval->num_rel_ret / (float) cutoff[i]); eval->rel_precis_cut[i] = (cutoff[i] < eval->num_rel) ? eval->precis_cut[i] : eval->recall_cut[i]; } } for (i = 0; i < NUM_FR_PTS; i++) { if (eval->num_ret - eval->num_rel_ret < cut_fr[i]) { eval->fall_recall[i] = (float) eval->num_rel_ret / (float) eval->num_rel; } } if (eval->num_ret - eval->num_rel_ret < MAX_FALL_RET) { eval->av_fall_recall += ((MAX_FALL_RET - (eval->num_ret - eval->num_rel_ret)) * ((float) eval->num_rel_ret / (float) eval->num_rel)); } if (eval->num_rel > eval->num_ret) { eval->R_recall_precis = (float) eval->num_rel_ret / (float) eval->num_rel; eval->int_R_recall_precis = (float) eval->num_rel_ret / (float) eval->num_rel; for (i = eval->num_ret; i < eval->num_rel; i++) { eval->av_R_precis += (float) eval->num_rel_ret / (float) i; eval->int_av_R_precis += (float) eval->num_rel_ret / (float) i; } } for (i = 0; i < NUM_PREC_PTS; i++) { if (eval->num_ret < cut_rprec[i]) { eval->R_prec_cut[i] = (float) eval->num_rel_ret / (float) cut_rprec[i]; eval->int_R_prec_cut[i] = (float) eval->num_rel_ret / (float) cut_rprec[i]; } } /* The following cutoffs/averages are correct, since 0.0 should be * averaged in for the non-retrieved docs: av_recall_precis, * int_av_recall_prec, int_recall_prec, int_av3_recall_precis, * int_av11_recall_precis */ /* Calculate other indirect evaluation measure averages. */ /* average recall-precis of 3 and 11 intermediate points */ eval->int_av3_recall_precis = (eval->int_recall_precis[three_pts[0]] + eval->int_recall_precis[three_pts[1]] + eval->int_recall_precis[three_pts[2]]) / 3.0F; for (i = 0; i < NUM_RP_PTS; i++) { eval->int_av11_recall_precis += eval->int_recall_precis[i]; } eval->int_av11_recall_precis /= NUM_RP_PTS; /* Calculate all the other averages */ if (eval->num_rel_ret > 0) { eval->av_recall_precis /= eval->num_rel; eval->int_av_recall_precis /= eval->num_rel; } eval->av_fall_recall /= MAX_FALL_RET; if (eval->num_rel) { eval->av_R_precis /= eval->num_rel; eval->int_av_R_precis /= eval->num_rel; eval->exact_recall = (float) eval->num_rel_ret / eval->num_rel; eval->exact_precis = (float) eval->num_rel_ret / eval->num_ret; if (eval->num_rel > eval->num_ret) eval->exact_rel_precis = eval->exact_precis; else eval->exact_rel_precis = eval->exact_recall; } return (1); } static int compare_iter_rank(const void *vptr1, const void *vptr2) { const TR_TUP *tr1 = vptr1, *tr2 = vptr2; if (tr1->iter > tr2->iter) { return (-1); } if (tr1->iter < tr2->iter) { return (1); } if (tr1->rank < tr2->rank) { return (-1); } if (tr1->rank > tr2->rank) { return (1); } return (0); } /* Based on Falk Scholer's implementation in awk of the Wilcoxon * Matched-Pairs Signed-Ranks Test or Wilcoxon Signed-Ranks Test */ /** Performs a Wilcoxon signed rank test for a paired-difference experiment * at the 0.05 and 0.10 significance levels. * * The null hypothesis (probability distributions of samples 1 and 2 * are identical) is rejected if * test statistic <= critical value for n = number of observations * * Note that this is a _two-tailed_ test, so that for a level of * significance, ALPHA, the null hypothesis is rejected if the * (absolute value of the) test statistic exceeds the critical value of * the t-distribution at ALPHA/2 */ #define WILCOXON_TABLE_SIZE 50 #define Z_SCORE_TABLE_SIZE 410 #define NEGATIVE -1 #define POSITIVE 1 struct data_point { float absolute_difference; int sign; }; static int compare_data_points(struct data_point *data_point1, struct data_point *data_point2) { if (data_point1->absolute_difference > data_point2->absolute_difference) { return (1); } if (data_point1->absolute_difference < data_point2->absolute_difference) { return (-1); } return (0); } static int calculate_statistics(unsigned int statistic_id, struct treceval_statistics *stats, unsigned int number_of_queries, float *measurements[2]) { unsigned int i = 0; float difference = (float) 0; struct data_point *data_points = NULL; float *ranks; unsigned int non_zero_results_counter = 0; unsigned int counter = 0; float average = (float) 0; unsigned int old_position = 0; float number_of_positive_differences = (float) 0; float number_of_negative_differences = (float) 0; int number_of_queries_improved = 0; int number_of_queries_degraded = 0; float z = (float) 0; float rounded_z = (float) 0; int test_stat = 0; /* Wilcoxon's table of critical values of T at alpha = .1 and .05 */ const int wilcoxon_critical_values[WILCOXON_TABLE_SIZE][2] = { {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {1, -1}, {2, 1}, {4, 2}, {6, 6}, {8, 6}, {11, 8}, {14, 11}, {17, 14}, {21, 17}, {26, 21}, {30, 25}, {36, 30}, {41, 35}, {47, 40}, {54, 46}, {60, 52}, {68, 59}, {75, 66}, {83, 73}, {92, 81}, {101, 90}, {110, 98}, {120, 107}, {130, 117}, {141, 127}, {152, 137}, {163, 148}, {175, 159}, {188, 171}, {201, 183}, {214, 195}, {228, 208}, {242, 222}, {256, 235}, {271, 250}, {287, 264}, {303, 279}, {317, 295}, {336, 311}, {353, 327}, {371, 344}, {389, 361}, {408, 379}, {427, 397}, {446, 415}, {466, 434} }; const float z_scores[Z_SCORE_TABLE_SIZE] = { 0.00000F, 0.00399F, 0.00798F, 0.01197F, 0.01595F, 0.01994F, 0.02392F, 0.02790F, 0.03188F, 0.03586F, 0.03983F, 0.04380F, 0.04776F, 0.05172F, 0.05567F, 1.05962F, 0.06356F, 0.06749F, 0.07142F, 0.07535F, 0.07926F, 0.08317F, 0.08706F, 0.09095F, 0.09483F, 0.09871F, 0.10257F, 0.10642F, 0.11026F, 0.11409F, 0.11791F, 0.12172F, 0.12552F, 0.12930F, 0.13307F, 0.13683F, 0.14058F, 0.14431F, 0.14803F, 0.15173F, 0.15542F, 0.15910F, 0.16276F, 0.16640F, 0.17003F, 0.17364F, 0.17724F, 0.18082F, 0.18439F, 0.18793F, 0.19146F, 0.19497F, 0.19847F, 0.20194F, 0.20540F, 0.20884F, 0.21226F, 0.21566F, 0.21904F, 0.22240F, 0.22575F, 0.22907F, 0.23237F, 0.23565F, 0.23891F, 0.24215F, 0.24537F, 0.24857F, 0.25175F, 0.25490F, 0.25804F, 0.26115F, 0.26424F, 0.26730F, 0.27035F, 0.27337F, 0.27637F, 0.27935F, 0.28230F, 0.28524F, 0.28814F, 0.29103F, 0.29389F, 0.29673F, 0.29955F, 0.30234F, 0.30511F, 0.30785F, 0.31057F, 0.31327F, 0.31594F, 0.31859F, 0.32121F, 0.32381F, 0.32639F, 0.32894F, 0.33147F, 0.33398F, 0.33646F, 0.33891F, 0.34134F, 0.34375F, 0.34614F, 0.34849F, 0.35083F, 0.35314F, 0.35543F, 0.35769F, 0.35993F, 0.36214F, 0.36433F, 0.36650F, 0.36864F, 0.37076F, 0.37286F, 0.37493F, 0.37698F, 0.37900F, 0.38100F, 0.38298F, 0.38493F, 0.38686F, 0.38877F, 0.39065F, 0.39251F, 0.39435F, 0.39617F, 0.39796F, 0.39973F, 0.40147F, 0.40320F, 0.40490F, 0.40658F, 0.40824F, 0.40988F, 0.41149F, 0.41308F, 0.41466F, 0.41621F, 0.41774F, 0.41924F, 0.42073F, 0.42220F, 0.42364F, 0.42507F, 0.42647F, 0.42785F, 0.42922F, 0.43056F, 0.43189F, 0.43319F, 0.43448F, 0.43574F, 0.43699F, 0.43822F, 0.43943F, 0.44062F, 0.44179F, 0.44295F, 0.44408F, 0.44520F, 0.44630F, 0.44738F, 0.44845F, 0.44950F, 0.45053F, 0.45154F, 0.45254F, 0.45352F, 0.45449F, 0.45543F, 0.45637F, 0.45728F, 0.45818F, 0.45907F, 0.45994F, 0.46080F, 0.46164F, 0.46246F, 0.46327F, 0.46407F, 0.46485F, 0.46562F, 0.46638F, 0.46712F, 0.46784F, 0.46856F, 0.46926F, 0.46995F, 0.47062F, 0.47128F, 0.47193F, 0.47257F, 0.47320F, 0.47381F, 0.47441F, 0.47500F, 0.47558F, 0.47615F, 0.47670F, 0.47725F, 0.47778F, 0.47831F, 0.47882F, 0.47932F, 0.47982F, 0.48030F, 0.48077F, 0.48124F, 0.48169F, 0.48214F, 0.48257F, 0.48300F, 0.48341F, 0.48382F, 0.48422F, 0.48461F, 0.48500F, 0.48537F, 0.48574F, 0.48610F, 0.48645F, 0.48679F, 0.48713F, 0.48745F, 0.48778F, 0.48809F, 0.48840F, 0.48870F, 0.48899F, 0.48928F, 0.48956F, 0.48983F, 0.49010F, 0.49036F, 0.49061F, 0.49086F, 0.49111F, 0.49134F, 0.49158F, 0.49180F, 0.49202F, 0.49224F, 0.49245F, 0.49266F, 0.49286F, 0.49305F, 0.49324F, 0.49343F, 0.49361F, 0.49379F, 0.49396F, 0.49413F, 0.49430F, 0.49446F, 0.49461F, 0.49477F, 0.49492F, 0.49506F, 0.49520F, 0.49534F, 0.49547F, 0.49560F, 0.49573F, 0.49585F, 0.49598F, 0.49609F, 0.49621F, 0.49632F, 0.49643F, 0.49653F, 0.49664F, 0.49674F, 0.49683F, 0.49693F, 0.49702F, 0.49711F, 0.49720F, 0.49728F, 0.49736F, 0.49744F, 0.49752F, 0.49760F, 0.49767F, 0.49774F, 0.49781F, 0.49788F, 0.49795F, 0.49801F, 0.49807F, 0.49813F, 0.49819F, 0.49825F, 0.49831F, 0.49836F, 0.49841F, 0.49846F, 0.49851F, 0.49856F, 0.49861F, 0.49865F, 0.49869F, 0.49874F, 0.49878F, 0.49882F, 0.49886F, 0.49889F, 0.49893F, 0.49896F, 0.49900F, 0.49903F, 0.49906F, 0.49910F, 0.49913F, 0.49916F, 0.49918F, 0.49921F, 0.49924F, 0.49926F, 0.49929F, 0.49931F, 0.49934F, 0.49936F, 0.49938F, 0.49940F, 0.49942F, 0.49944F, 0.49946F, 0.49948F, 0.49950F, 0.49952F, 0.49953F, 0.49955F, 0.49957F, 0.49958F, 0.49960F, 0.49961F, 0.49962F, 0.49964F, 0.49965F, 0.49966F, 0.49968F, 0.49969F, 0.49970F, 0.49971F, 0.49972F, 0.49973F, 0.49974F, 0.49975F, 0.49976F, 0.49977F, 0.49978F, 0.49978F, 0.49979F, 0.49980F, 0.49981F, 0.49981F, 0.49982F, 0.49983F, 0.49983F, 0.49984F, 0.49985F, 0.49985F, 0.49986F, 0.49986F, 0.49987F, 0.49987F, 0.49988F, 0.49988F, 0.49989F, 0.49989F, 0.49990F, 0.49990F, 0.49990F, 0.49991F, 0.49991F, 0.49992F, 0.49992F, 0.49992F, 0.49992F, 0.49993F, 0.49993F, 0.49993F, 0.49994F, 0.49994F, 0.49994F, 0.49994F, 0.49995F, 0.49995F, 0.49995F, 0.49995F, 0.49995F, 0.49996F, 0.49996F, 0.49996F, 0.49996F, 0.49996F, 0.49996F, 0.49997F, 0.49997F, 0.49997F, 0.49997F, 0.49997F, 0.49997F, 0.49997F, 0.49997F, 0.49998F, 0.49998F, 0.49998F, 0.49998F }; if (((data_points = malloc(sizeof(*data_points) * number_of_queries)) == NULL) || ((ranks = malloc(sizeof(float) * number_of_queries)) == NULL)) { return (-1); } for (i = 0; i < number_of_queries; i++) { difference = measurements[0][i] - measurements[1][i]; if (difference < (float) 0) { data_points[non_zero_results_counter].sign = NEGATIVE; data_points[non_zero_results_counter].absolute_difference = -difference; non_zero_results_counter++; } else if (difference > 0) { data_points[non_zero_results_counter].sign = POSITIVE; data_points[non_zero_results_counter].absolute_difference = difference; non_zero_results_counter++; } } qsort(data_points, non_zero_results_counter, sizeof(*(data_points)), (int (*)(const void *, const void *)) compare_data_points); /* Resolve rankings of absolute_differences */ counter = 0; while (counter < non_zero_results_counter) { /* reset average at start of every turn */ average = (float) 0; old_position = counter; /* counting duplicates */ while ((counter < (non_zero_results_counter - 1)) && (data_points[counter].absolute_difference == data_points[counter + 1].absolute_difference)) { average += counter; counter++; } if (counter > old_position) { average += counter; counter++; average /= (float) (counter - old_position); for (i = old_position; i < counter; i++) { ranks[i] = average + (float) 1; } } else { ranks[counter] = (float) (counter + 1); counter++; } } /* Summing the '+' and '-' ranks */ for (i = 0; i < non_zero_results_counter; i++) { if (data_points[i].sign == POSITIVE) { number_of_positive_differences += ranks[i]; number_of_queries_degraded++; } else { number_of_negative_differences += ranks[i]; number_of_queries_improved++; } } free(ranks); free(data_points); /* Calculate large-sample approximation (n >= 25) Rejection region: * (a) 2-tailed test: z > z_alpha/2 or z < -z_alpha/2 (b) * right-tailed: z > z_alpha (c) left-tailed: z < -z_alpha */ z = (float) ((number_of_positive_differences - (((float) (non_zero_results_counter * (non_zero_results_counter + 1))) / ((float) 4))) / sqrt(((float) (non_zero_results_counter * (non_zero_results_counter + 1) * ((2 * non_zero_results_counter) + 1))) / ((float) 24))); z *= (float) 100; rounded_z = (float) ((int) z); if ((z - rounded_z) >= 0.5) { rounded_z += (float) 1; } rounded_z /= (float) 100; z = rounded_z; /* Generate test statistic (the smaller of PosSum and NegSum) */ if (number_of_positive_differences > number_of_negative_differences) { test_stat = (int) number_of_negative_differences; } else { test_stat = (int) number_of_positive_differences; } stats->stats[statistic_id].improved = number_of_queries_improved; stats->stats[statistic_id].degraded = number_of_queries_degraded; stats->stats[statistic_id].z_score = z; if (non_zero_results_counter == 0) { stats->stats[statistic_id].hypothesis = NO_DIFF; } else if ((non_zero_results_counter > WILCOXON_TABLE_SIZE) || (wilcoxon_critical_values[non_zero_results_counter - 1][0] == -1)) { stats->stats[statistic_id].hypothesis = OUT_OF_RANGE; } else { if (stats->tailedness == ONE_TAILED) { if (test_stat <= wilcoxon_critical_values[non_zero_results_counter - 1][1]) { stats->stats[statistic_id].hypothesis = REJECTED; stats->stats[statistic_id].confidence = 0.05F; } else { stats->stats[statistic_id].hypothesis = NOT_REJECTED; stats->stats[statistic_id].confidence = 0.05F; } } else { if (test_stat <= wilcoxon_critical_values[non_zero_results_counter - 1][1]) { stats->stats[statistic_id].hypothesis = REJECTED; stats->stats[statistic_id].confidence = 0.05F; } else if (test_stat <= wilcoxon_critical_values[non_zero_results_counter - 1][0]) { stats->stats[statistic_id].hypothesis = REJECTED; stats->stats[statistic_id].confidence = 0.1F; } else { stats->stats[statistic_id].hypothesis = NOT_REJECTED; stats->stats[statistic_id].confidence = 0.1F; } } } if (z < (float) 0) { z *= (float) -1; } if (stats->tailedness == ONE_TAILED) { /* 4.09 is largest z-score in lookup table... */ if ((z * (float) 100) >= Z_SCORE_TABLE_SIZE) { /* value in table is for area */ stats->stats[statistic_id].sign = '<'; stats->stats[statistic_id].actual_confidence = (float) (1 - (0.49998 + 0.5)); } else { /* value in table is for area; mu=0 to z */ stats->stats[statistic_id].sign = '='; stats->stats[statistic_id].actual_confidence = ((float) 1 - (z_scores[(int) (z * (float) 100)] + 0.5F)); } } else { /* 4.09 is largest z-score in lookup table... */ if ((z * (float) 100) >= Z_SCORE_TABLE_SIZE) { /* value in table is for area */ stats->stats[statistic_id].sign = '<'; stats->stats[statistic_id].actual_confidence = ((float) 1 - (0.49998F * (float) 2)); } else { /* value in table is for area; mu=0 to z */ stats->stats[statistic_id].sign = '='; stats->stats[statistic_id].actual_confidence = ((float) 1 - (z_scores[(int) (z * (float) 100)] * (float) 2)); } } return non_zero_results_counter; } static void print_stat(const struct treceval_statistics *stats, const unsigned int id, FILE * output) { if (stats->stats[id].hypothesis == NO_DIFF) { fprintf(stdout, "(runs identical, no stats computed)\n"); } else if (stats->stats[id].hypothesis == OUT_OF_RANGE) { fprintf(stdout, "(out of range) %6.3f %c%6.5f\n", stats->stats[id].z_score, stats->stats[id].sign, stats->stats[id].actual_confidence); } else { if (stats->stats[id].hypothesis == REJECTED) { fprintf(stdout, "rejected at %2.2f %6.3f %c %6.5f\n", stats->stats[id].confidence, stats->stats[id].z_score, stats->stats[id].sign, stats->stats[id].actual_confidence); } else { fprintf(stdout, "not rejd at %2.2f %6.3f %c %6.5f\n", stats->stats[id].confidence, stats->stats[id].z_score, stats->stats[id].sign, stats->stats[id].actual_confidence); } } } int treceval_stats_print(const struct treceval_statistics *stats, FILE *output) { if (stats->tailedness == ONE_TAILED) { fprintf(output, "Wilcoxon signed rank test (one-tailed)\n"); } else { fprintf(output, "Wilcoxon signed rank test (two-tailed)\n"); } if (stats->sample_size <= 0) { return (0); } fprintf(output, "Running Statistics over %d queries.\n", stats->sample_size); fprintf(output, "---------------------------------------------------" "----------------------\n"); fprintf(output, "measures improved degraded Null Hypothesis" " z-score actual p\n"); fprintf(output, "Avg Precision %2d %2d ", stats->stats[0].improved, stats->stats[0].degraded); print_stat(stats, 0, output); fprintf(output, "Precision@ 5 %2d %2d ", stats->stats[1].improved, stats->stats[1].degraded); print_stat(stats, 1, output); fprintf(output, "Precision@ 10 %2d %2d ", stats->stats[2].improved, stats->stats[2].degraded); print_stat(stats, 2, output); fprintf(output, "Precision@ 15 %2d %2d ", stats->stats[3].improved, stats->stats[3].degraded); print_stat(stats, 3, output); fprintf(output, "Precision@ 20 %2d %2d ", stats->stats[4].improved, stats->stats[4].degraded); print_stat(stats, 4, output); fprintf(output, "Precision@ 30 %2d %2d ", stats->stats[5].improved, stats->stats[5].degraded); print_stat(stats, 5, output); fprintf(output, "Precision@ 100 %2d %2d ", stats->stats[6].improved, stats->stats[6].degraded); print_stat(stats, 6, output); fprintf(output, "Precision@ 200 %2d %2d ", stats->stats[7].improved, stats->stats[7].degraded); print_stat(stats, 7, output); fprintf(output, "Precision@ 500 %2d %2d ", stats->stats[8].improved, stats->stats[8].degraded); print_stat(stats, 8, output); fprintf(output, "Precision@1000 %2d %2d ", stats->stats[9].improved, stats->stats[9].degraded); print_stat(stats, 9, output); fprintf(output, "R Precision %2d %2d ", stats->stats[10].improved, stats->stats[10].degraded); print_stat(stats, 10, output); fprintf(output, "---------------------------------------------------" "----------------------\n"); return (1); } static int compare_query_ids(result_tuple *tuple1, result_tuple *tuple2) { if (tuple1->query_id > tuple2->query_id) { return (1); } if (tuple1->query_id < tuple2->query_id) { return (-1); } return (0); } int treceval_stats_calculate(const struct treceval *trec_results_a, const struct treceval *trec_results_b, struct treceval_statistics *stats, const struct treceval_qrels *qrels, treceval_statistics_tailedness tailedness) { unsigned int i = 0; unsigned int start1 = 0; unsigned int start2 = 0; unsigned int end1 = 0; unsigned int end2 = 0; unsigned int query_count = 0; unsigned int max_query_count = 0; unsigned int evaluated1 = 1; unsigned int evaluated2 = 1; struct treceval_results *evaluations[2]; float *measurements[2]; qsort(trec_results_a->tuples, trec_results_a->cached_results, sizeof(*(trec_results_a->tuples)), (int (*)(const void *, const void *)) compare_query_ids); qsort(trec_results_b->tuples, trec_results_b->cached_results, sizeof(*(trec_results_a->tuples)), (int (*)(const void *, const void *)) compare_query_ids); stats->tailedness = tailedness; /* checking whether both results are empty in which case it is * useless to calculate statistics */ if ((trec_results_a->cached_results == 0) || (trec_results_b->cached_results == 0)) { /* need to zero results */ stats->sample_size = 0; for (i = 0; i < 11; i++) { stats->stats[i].improved = 0; stats->stats[i].degraded = 0; stats->stats[i].hypothesis = OUT_OF_RANGE; stats->stats[i].confidence = (float) 0; stats->stats[i].z_score = (float) 0; stats->stats[i].actual_confidence = (float) 0; stats->stats[i].sign = '?'; } return 0; } /* counting query IDs in the first pass only, so we can set enough * results aside */ while ((end1 < trec_results_a->cached_results) || (end2 < trec_results_b->cached_results)) { /* if this input has been evaluated last time 'round (see next * comment) then advance the input for the next evaluation */ if (evaluated1) { start1 = end1; for (; end1 < trec_results_a->cached_results; end1++) { if (trec_results_a->tuples[end1].query_id != trec_results_a->tuples[start1].query_id) { break; } } } if (evaluated2) { start2 = end2; for (; end2 < trec_results_b->cached_results; end2++) { if (trec_results_b->tuples[end2].query_id != trec_results_b->tuples[start2].query_id) { break; } } } /* Checking that both are evaluating the same query. If not, * then have to make sure that only the one with the current * query_id gets evaluated whereas the results for the other is * zeroed. Also have to keep track of which one of the input * should be advanced next. */ evaluated1 = 1; evaluated2 = 1; if (trec_results_a->tuples[start1].query_id != trec_results_b->tuples[start2].query_id) { if (trec_results_a->tuples[start1].query_id > trec_results_b->tuples[start2].query_id) { evaluated1 = 0; } else { evaluated2 = 0; } } max_query_count++; } end1 = 0; end2 = 0; /* setting aside memory */ if (((evaluations[0] = malloc(sizeof(struct treceval_results) * max_query_count)) == NULL) || ((evaluations[1] = malloc(sizeof(struct treceval_results) * max_query_count)) == NULL)) { return (0); } if (((measurements[0] = malloc(sizeof(float) * max_query_count)) == NULL) || ((measurements[1] = malloc(sizeof(float) * max_query_count)) == NULL)) { return (0); } /* need to keep going until both inputs are exhausted */ while ((end1 < trec_results_a->cached_results) || (end2 < trec_results_b->cached_results)) { /* if this input has been evaluated last time 'round (see next * comment) then advance the input for the next evaluation */ if (evaluated1) { start1 = end1; for (; end1 < trec_results_a->cached_results; end1++) { if (trec_results_a->tuples[end1].query_id != trec_results_a->tuples[start1].query_id) { break; } } } if (evaluated2) { start2 = end2; for (; end2 < trec_results_b->cached_results; end2++) { if (trec_results_b->tuples[end2].query_id != trec_results_b->tuples[start2].query_id) { break; } } } /* Checking that both are evaluating the same query. If not, * then have to make sure that only the one with the current * query_id gets evaluated whereas the results for the other is * zeroed. Also have to keep track of which one of the input * should be advanced next. At the same time I changed the two * corresponding lines 50 lines above. */ evaluated1 = 1; evaluated2 = 1; /* FIXME: just fixed a bug whereby I interchanged the * evaluated2/1 lines with each other (without too much thinking * about the problem) and everything seems to be working. * However if there is another problem, it might be worth * investigating this first. */ if (trec_results_a->tuples[start1].query_id == trec_results_b->tuples[start2].query_id) { evaluate_trec_results(start1, end1 - 1, trec_results_a, qrels, &evaluations[0][query_count]); evaluate_trec_results(start2, end2 - 1, trec_results_b, qrels, &evaluations[1][query_count]); } else if (trec_results_a->tuples[start1].query_id < trec_results_b->tuples[start2].query_id) { evaluate_trec_results(start1, end1 - 1, trec_results_a, qrels, &evaluations[0][query_count]); evaluate_trec_results(0, 0, trec_results_b, qrels, &evaluations[1][query_count]); evaluated2 = 0; } else { evaluate_trec_results(0, 0, trec_results_a, qrels, &evaluations[0][query_count]); evaluate_trec_results(start2, end2 - 1, trec_results_b, qrels, &evaluations[1][query_count]); evaluated1 = 0; } query_count++; } stats->sample_size = max_query_count; for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].average_precision; measurements[1][i] = evaluations[1][i].average_precision; } if (calculate_statistics(0, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[0]; measurements[1][i] = evaluations[1][i].precision_at[0]; } if (calculate_statistics(1, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[1]; measurements[1][i] = evaluations[1][i].precision_at[1]; } if (calculate_statistics(2, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[2]; measurements[1][i] = evaluations[1][i].precision_at[2]; } if (calculate_statistics(3, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[3]; measurements[1][i] = evaluations[1][i].precision_at[3]; } if (calculate_statistics(4, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[4]; measurements[1][i] = evaluations[1][i].precision_at[4]; } if (calculate_statistics(5, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[5]; measurements[1][i] = evaluations[1][i].precision_at[5]; } if (calculate_statistics(6, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[6]; measurements[1][i] = evaluations[1][i].precision_at[6]; } if (calculate_statistics(7, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[7]; measurements[1][i] = evaluations[1][i].precision_at[7]; } if (calculate_statistics(8, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].precision_at[8]; measurements[1][i] = evaluations[1][i].precision_at[8]; } if (calculate_statistics(9, stats, max_query_count, measurements) < 0) { return (0); } for (i = 0; i < max_query_count; i++) { measurements[0][i] = evaluations[0][i].rprecision; measurements[1][i] = evaluations[1][i].rprecision; } if (calculate_statistics(10, stats, max_query_count, measurements) < 0) { return (0); } free(measurements[0]); free(measurements[1]); free(evaluations[0]); free(evaluations[1]); return 1; } /* Assumes that the first entry in the relevance judgement contains a * result for the query with the smallest ID. */ struct treceval_qrels *treceval_qrels_new(const char *qrels_file_name) { unsigned int i = 0; struct treceval_qrels *qrels = NULL; FILE *qrels_file = NULL; char line[MAX_LINE_LENGTH]; char *line_pointer = NULL; char *document_number_pointer = NULL; char judgement[MAX_LINE_LENGTH]; int query_id = 0; char *judgement_string = NULL; if ((qrels = malloc(sizeof(struct treceval_qrels))) == NULL) { return NULL; } qrels->number_of_judged_queries = 50; qrels->lowest_query_id = -1; qrels->number_of_judgements_for_query = NULL; /* setting aside memeory for hash table */ if ((qrels->judgements = chash_ptr_new(8, 0.8F, (unsigned int (*)(const void *)) str_hash, (int (*)(const void *, const void *)) str_cmp)) == NULL) { return NULL; } if ((qrels->number_of_judgements_for_query = malloc(sizeof(int) * qrels->number_of_judged_queries)) == NULL) { return NULL; } for (i = 0; i < (unsigned int) qrels->number_of_judged_queries; i++) { qrels->number_of_judgements_for_query[i] = 0; } if ((qrels_file = fopen(qrels_file_name, "r")) == NULL) { return NULL; } /* populating relevance judgements hash table */ while (fgets(line, MAX_LINE_LENGTH, qrels_file) != NULL) { /* Only care whether a document is relevant. */ if (line[strlen(line) - 2] != '0') { line_pointer = line; /* getting Query ID first */ while (*line_pointer != ' ') { line_pointer++; } *line_pointer = '\0'; query_id = atoi(line); /* need to set the lowest query ID if that hasn't been done * before */ if (qrels->lowest_query_id == -1) { qrels->lowest_query_id = query_id; } /* if the query ID had been set before and it was larger * than the current query ID we give up */ else if (query_id < qrels->lowest_query_id) { return NULL; } /* if the current query ID is larger than the number of IDs * we have set space aside for, we need to increas space for * new queries. Note that we assume that we need to have * enough space for all query IDs, from the lowest to the * highest (ie we don't deal with the fact that we might * have a (potentially large) gap in IDs and therefore might * waste (lots of) space. */ else if (query_id >= (qrels->lowest_query_id + qrels->number_of_judged_queries)) { /* need to set aside memory for more queries */ if ((qrels->number_of_judgements_for_query = realloc(qrels->number_of_judgements_for_query, sizeof(int) * (qrels->number_of_judged_queries + 50))) == NULL) { return NULL; } /* need to initialise judgement counts for new queries */ for (i = qrels->number_of_judged_queries; i < (unsigned int) (qrels->number_of_judged_queries + 50); i++) { qrels->number_of_judgements_for_query[i] = 0; } qrels->number_of_judged_queries += 50; } /* Extracting document number. */ strcpy(judgement, line); strcat(judgement, " "); line_pointer += 3; document_number_pointer = line_pointer; while (*line_pointer != ' ') { line_pointer++; } *line_pointer = '\0'; strcat(judgement, document_number_pointer); /* Adding judgement in form "QID TRECDOCNO" (for instance * "381 FBIS3-1") into hash table. Just need to check for * presence when checking if document is relevant. */ if ((judgement_string = malloc(sizeof(*judgement_string) * (strlen(judgement) + 1))) == NULL) { return NULL; } str_cpy(judgement_string, judgement); chash_ptr_ptr_insert(qrels->judgements, judgement_string, NULL); /* Incrementing the count of judgements for this query (so * that average precision can be calculated later. */ qrels->number_of_judgements_for_query[query_id - qrels->lowest_query_id]++; } } fclose(qrels_file); return qrels; } struct treceval *treceval_new() { struct treceval *new_trec_eval = NULL; if ((new_trec_eval = malloc(sizeof(struct treceval))) == NULL) { return NULL; } new_trec_eval->cached_results = 0; new_trec_eval->cache_size = 50; /* setting aside memory for cached results */ if ((new_trec_eval->tuples = malloc(sizeof(result_tuple) * new_trec_eval->cache_size)) == NULL) { return NULL; } return new_trec_eval; } void treceval_qrels_delete(struct treceval_qrels **qrels) { void **dummy_pointer = NULL; char *previous_judgement = NULL; struct chash_iter *iterator = chash_iter_new((*qrels)->judgements); const void *key = NULL; if (*qrels != NULL) { if ((*qrels)->number_of_judgements_for_query != NULL) { free((*qrels)->number_of_judgements_for_query); } if ((*qrels)->judgements != NULL) { while (chash_iter_ptr_ptr_next(iterator, &key, &dummy_pointer) == CHASH_OK) { if (previous_judgement != NULL) { free(previous_judgement); } previous_judgement = (char *) key; } if (previous_judgement != NULL) { free(previous_judgement); } chash_iter_delete(iterator); chash_delete((*qrels)->judgements); } free(*qrels); *qrels = NULL; } } void treceval_delete(struct treceval **trec_results) { if (*trec_results != NULL) { if ((*trec_results)->tuples != NULL) { free((*trec_results)->tuples); } free((*trec_results)); *trec_results = NULL; } } int treceval_add_result(struct treceval *trec_results, const unsigned int query_id, const char *trec_document_number, const float score) { /* if the current cache is exhausted, need to increase the cache size */ if (trec_results->cached_results == trec_results->cache_size) { trec_results->cache_size *= 2; if ((trec_results->tuples = realloc(trec_results->tuples, sizeof(result_tuple) * trec_results->cache_size)) == NULL) { return (0); } } /* copying the result fields into the cache tuple */ trec_results->tuples[trec_results->cached_results].query_id = query_id; if (strlen(trec_document_number) >= (TREC_DOCUMENT_NUMBER_MAX_LENGTH - 1)) { return (0); } strcpy(trec_results->tuples[trec_results->cached_results]. trec_document_number, trec_document_number); trec_results->tuples[trec_results->cached_results].score = score; trec_results->cached_results++; return 1; } void treceval_print_results(struct treceval_results *evaluated_results, const unsigned int number_of_results, FILE *output, int interpolated) { unsigned int i = 0, j = 0; fprintf(output, " Run: "); for (i = 0; i < number_of_results; i++) { fprintf(output, " %6d", i); } fprintf(output, "\n"); fprintf(output, "No. of QIDs: "); for (i = 0; i < number_of_results; i++) { fprintf(output, " %6d", evaluated_results[i].queries); } fprintf(output, "\n"); fprintf(output, "Total number of documents over all queries\n"); fprintf(output, " Retrieved: "); for (i = 0; i < number_of_results; i++) { fprintf(output, " %6d", evaluated_results[i].retrieved); } fprintf(output, "\n"); fprintf(output, " Relevant: "); for (i = 0; i < number_of_results; i++) { fprintf(output, " %6d", evaluated_results[i].relevant); } fprintf(output, "\n"); fprintf(output, " Rel_ret: "); for (i = 0; i < number_of_results; i++) { fprintf(output, " %6d", evaluated_results[i].relevant_retrieved); } fprintf(output, "\n"); if (interpolated) { fprintf(output, "Interpolated Recall - Precision Averages:\n"); fprintf(output, " at 0.00 "); j = 0; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.10 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.20 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.30 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.40 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.50 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.60 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.70 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.80 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 0.90 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); fprintf(output, " at 1.00 "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].interpolated_rp[j]); } fprintf(output, "\n"); } fprintf(output, "Average precision (non-interpolated) "); fprintf(output, "for all rel docs\n"); fprintf(output, " P(avg) "); for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].average_precision); } fprintf(output, "\n"); fprintf(output, "Precision:\n At 5 docs: "); j = 0; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, " At 10 docs: "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, " At 15 docs: "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, " At 20 docs: "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, " At 30 docs: "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, " At 100 docs: "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, " At 200 docs: "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, " At 500 docs: "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, " At 1000 docs: "); j++; for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].precision_at[j]); } fprintf(output, "\n"); fprintf(output, "R-Precision (precision after R (= num_rel for a "); fprintf(output, "query) docs retrieved):\n"); fprintf(output, " Exact: "); for (i = 0; i < number_of_results; i++) { fprintf(output, " %6.4f", evaluated_results[i].rprecision); } fprintf(output, "\n"); fprintf(output, "\n"); } int treceval_evaluate_query(const unsigned int query_id, struct treceval_results *evaluated_results, const struct treceval_qrels *qrels, const struct treceval *trec_results) { unsigned int i = 0; unsigned int start = 0; unsigned int end = 0; /* sorting tuples first */ qsort(trec_results->tuples, trec_results->cached_results, sizeof(*(trec_results->tuples)), (int (*)(const void *, const void *)) compare_query_ids); /* checking whether there are no results or the query_id is out of * bounds */ if ((trec_results->cached_results == 0) || (((unsigned int) trec_results->tuples[0].query_id) > query_id) || ((unsigned int) trec_results->tuples[trec_results->cached_results - 1].query_id < query_id)) { /* abusing way of zeroing the evaluated_results values */ evaluate_trec_results(0, 0, trec_results, qrels, evaluated_results); return 0; } for (i = 0; i < trec_results->cached_results; i++) { if (((unsigned int) trec_results->tuples[i].query_id) == query_id) { start = i; break; } } for (; i < trec_results->cached_results; i++) { if (((unsigned int) trec_results->tuples[i].query_id) != query_id) { end = i - 1; } } /* if this is the last query in the results then the next query id * cannot be found */ if (end == 0) { end = trec_results->cached_results - 1; } evaluate_trec_results(start, end, trec_results, qrels, evaluated_results); return 1; } int treceval_evaluate(const struct treceval *trec_results, const struct treceval_qrels *qrels, struct treceval_results *evaluated_results) { /* sorting tuples first */ qsort(trec_results->tuples, trec_results->cached_results, sizeof(*(trec_results->tuples)), (int (*)(const void *, const void *)) compare_query_ids); evaluate_trec_results(0, trec_results->cached_results, trec_results, qrels, evaluated_results); return 1; }
405408.c
//s11.c #include <std.h> #include "../tharis.h" inherit VAULT; int FLAG; void create(){ ::create(); set_terrain(STONE_BUILDING); set_travel(BACK_ALLEY); set_property("light",2); set_property("indoors",1); set_short("Large dark room"); set_long( @JAVAMAKER %^BLUE%^Large dark room%^RESET%^ This is a large dark room. There is a good sized round table and a set of chairs in the center of the room. You quickly realize that this a meeting place of some form. The room is well swept and clean. The walls are hung with various tapestries. JAVAMAKER ); set_smell("default","The dank musty atmosphere is oppressive."); set_listen("default","You hear the scratching of rats and the trickle of water."); set_items(([ "tapestries":"These hanging hang loosely, covering large portions of the walls. They seem to be generic tapestries of no real consequence.", "table":"This table is well kept and lacks the divots and dings that tables in dark rooms usually have.", ])); set_exits(([ "north":ROOMS"s10", "south":ROOMS"jewelry", ])); set_invis_exits(({"south",})); set_trap_functions(({}),({}),({})); set_pre_exit_functions(({"south",}),({"south_preExit",})); set_post_exit_functions(({}),({})); set_door("door",ROOMS"jewelry","south","Blah"); set_open("door",0); set_locked("door",1); } void reset(){ ::reset(); FLAG = 0; } void init(){ ::init(); add_action("pull","pull"); add_action("pull","move"); } int south_preExit(){ if(!FLAG){ tell_object(TP,"You cannot go that way."); return 0; } return 1; } int pull(string str){ if(str != "tapestry" && str != "tapestries") return notify_fail("Pull what?\n"); tell_object(TP,"You notice that one of the tapestries was covering a door to the south."); FLAG = 1; return 1; }
990070.c
/******************************************************************************* * Copyright 2004-2019 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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. *******************************************************************************/ /* // Purpose: // Intel(R) Integrated Performance Primitives. Cryptographic Primitives (ippcp) // Prime Number Primitives. // // Contents: // ippsPrimeSet_BN() // */ #include "owncp.h" #include "pcpprimeg.h" /*F* // Name: ippsPrimeSet_BN // // Purpose: Sets a trial BN for further testing // // Returns: Reason: // ippStsNullPtrErr NULL == pCtx // NULL == pPrime // ippStsContextMatchErr illegal pCtx->idCtx // illegal pPrime->idCtx // ippStsOutOfRangeErr BITSIZE_BNU(BN_NUMBER(pPrime), BN_SIZE(pPrime)) // > PRIME_MAXBITSIZE(pCtx) // ippStsNoErr no error // // Parameters: // pPrime pointer to the BN to be set // pCtx pointer to the context // *F*/ IPPFUN(IppStatus, ippsPrimeSet_BN, (const IppsBigNumState* pPrime, IppsPrimeState* pCtx)) { IPP_BAD_PTR2_RET(pCtx, pPrime); /* use aligned context */ pPrime = (IppsBigNumState*)( IPP_ALIGNED_PTR(pPrime, BN_ALIGNMENT) ); IPP_BADARG_RET(!BN_VALID_ID(pPrime), ippStsContextMatchErr); pCtx = (IppsPrimeState*)( IPP_ALIGNED_PTR(pCtx, PRIME_ALIGNMENT) ); IPP_BADARG_RET(!PRIME_VALID_ID(pCtx), ippStsContextMatchErr); IPP_BADARG_RET(BITSIZE_BNU(BN_NUMBER(pPrime), BN_SIZE(pPrime)) > PRIME_MAXBITSIZE(pCtx), ippStsOutOfRangeErr); { BNU_CHUNK_T* pPrimeU = BN_NUMBER(pPrime); cpSize ns = BN_SIZE(pPrime); cpSize nBits = BITSIZE_BNU(pPrimeU, ns); BNU_CHUNK_T* pPrimeCtx = PRIME_NUMBER(pCtx); BNU_CHUNK_T topMask = MASK_BNU_CHUNK(nBits); ZEXPAND_COPY_BNU(pPrimeCtx, BITS_BNU_CHUNK(PRIME_MAXBITSIZE(pCtx)), pPrimeU, ns); pPrimeCtx[ns-1] &= topMask; return ippStsNoErr; } }
5699.c
/* * QEMU e1000(e) emulation - shared code * * Copyright (c) 2008 Qumranet * * Based on work done by: * Nir Peleg, Tutis Systems Ltd. for Qumranet Inc. * Copyright (c) 2007 Dan Aloni * Copyright (c) 2004 Antony T Curtis * * 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 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 "qemu/osdep.h" #include "hw/hw.h" #include "hw/pci/pci.h" #include "net/net.h" #include "e1000x_common.h" #include "trace.h" bool e1000x_rx_ready(PCIDevice *d, uint32_t *mac) { bool link_up = mac[STATUS] & E1000_STATUS_LU; bool rx_enabled = mac[RCTL] & E1000_RCTL_EN; bool pci_master = d->config[PCI_COMMAND] & PCI_COMMAND_MASTER; if (!link_up || !rx_enabled || !pci_master) { trace_e1000x_rx_can_recv_disabled(link_up, rx_enabled, pci_master); return false; } return true; } bool e1000x_is_vlan_packet(const uint8_t *buf, uint16_t vet) { uint16_t eth_proto = lduw_be_p(buf + 12); bool res = (eth_proto == vet); trace_e1000x_vlan_is_vlan_pkt(res, eth_proto, vet); return res; } bool e1000x_rx_group_filter(uint32_t *mac, const uint8_t *buf) { static const int mta_shift[] = { 4, 3, 2, 0 }; uint32_t f, ra[2], *rp, rctl = mac[RCTL]; for (rp = mac + RA; rp < mac + RA + 32; rp += 2) { if (!(rp[1] & E1000_RAH_AV)) { continue; } ra[0] = cpu_to_le32(rp[0]); ra[1] = cpu_to_le32(rp[1]); if (!memcmp(buf, (uint8_t *)ra, 6)) { trace_e1000x_rx_flt_ucast_match((int)(rp - mac - RA) / 2, MAC_ARG(buf)); return true; } } trace_e1000x_rx_flt_ucast_mismatch(MAC_ARG(buf)); f = mta_shift[(rctl >> E1000_RCTL_MO_SHIFT) & 3]; f = (((buf[5] << 8) | buf[4]) >> f) & 0xfff; if (mac[MTA + (f >> 5)] & (1 << (f & 0x1f))) { e1000x_inc_reg_if_not_full(mac, MPRC); return true; } trace_e1000x_rx_flt_inexact_mismatch(MAC_ARG(buf), (rctl >> E1000_RCTL_MO_SHIFT) & 3, f >> 5, mac[MTA + (f >> 5)]); return false; } bool e1000x_hw_rx_enabled(uint32_t *mac) { if (!(mac[STATUS] & E1000_STATUS_LU)) { trace_e1000x_rx_link_down(mac[STATUS]); return false; } if (!(mac[RCTL] & E1000_RCTL_EN)) { trace_e1000x_rx_disabled(mac[RCTL]); return false; } return true; } bool e1000x_is_oversized(uint32_t *mac, size_t size) { /* this is the size past which hardware will drop packets when setting LPE=0 */ static const int maximum_ethernet_vlan_size = 1522; /* this is the size past which hardware will drop packets when setting LPE=1 */ static const int maximum_ethernet_lpe_size = 16384; if ((size > maximum_ethernet_lpe_size || (size > maximum_ethernet_vlan_size && !(mac[RCTL] & E1000_RCTL_LPE))) && !(mac[RCTL] & E1000_RCTL_SBP)) { e1000x_inc_reg_if_not_full(mac, ROC); trace_e1000x_rx_oversized(size); return true; } return false; } void e1000x_restart_autoneg(uint32_t *mac, uint16_t *phy, QEMUTimer *timer) { e1000x_update_regs_on_link_down(mac, phy); trace_e1000x_link_negotiation_start(); timer_mod(timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 500); } void e1000x_reset_mac_addr(NICState *nic, uint32_t *mac_regs, uint8_t *mac_addr) { int i; mac_regs[RA] = 0; mac_regs[RA + 1] = E1000_RAH_AV; for (i = 0; i < 4; i++) { mac_regs[RA] |= mac_addr[i] << (8 * i); mac_regs[RA + 1] |= (i < 2) ? mac_addr[i + 4] << (8 * i) : 0; } qemu_format_nic_info_str(qemu_get_queue(nic), mac_addr); trace_e1000x_mac_indicate(MAC_ARG(mac_addr)); } void e1000x_update_regs_on_autoneg_done(uint32_t *mac, uint16_t *phy) { e1000x_update_regs_on_link_up(mac, phy); phy[PHY_LP_ABILITY] |= MII_LPAR_LPACK; phy[PHY_STATUS] |= MII_SR_AUTONEG_COMPLETE; trace_e1000x_link_negotiation_done(); } void e1000x_core_prepare_eeprom(uint16_t *eeprom, const uint16_t *templ, uint32_t templ_size, uint16_t dev_id, const uint8_t *macaddr) { uint16_t checksum = 0; int i; memmove(eeprom, templ, templ_size); for (i = 0; i < 3; i++) { eeprom[i] = (macaddr[2 * i + 1] << 8) | macaddr[2 * i]; } eeprom[11] = eeprom[13] = dev_id; for (i = 0; i < EEPROM_CHECKSUM_REG; i++) { checksum += eeprom[i]; } checksum = (uint16_t) EEPROM_SUM - checksum; eeprom[EEPROM_CHECKSUM_REG] = checksum; } uint32_t e1000x_rxbufsize(uint32_t rctl) { rctl &= E1000_RCTL_BSEX | E1000_RCTL_SZ_16384 | E1000_RCTL_SZ_8192 | E1000_RCTL_SZ_4096 | E1000_RCTL_SZ_2048 | E1000_RCTL_SZ_1024 | E1000_RCTL_SZ_512 | E1000_RCTL_SZ_256; switch (rctl) { case E1000_RCTL_BSEX | E1000_RCTL_SZ_16384: return 16384; case E1000_RCTL_BSEX | E1000_RCTL_SZ_8192: return 8192; case E1000_RCTL_BSEX | E1000_RCTL_SZ_4096: return 4096; case E1000_RCTL_SZ_1024: return 1024; case E1000_RCTL_SZ_512: return 512; case E1000_RCTL_SZ_256: return 256; } return 2048; } void e1000x_update_rx_total_stats(uint32_t *mac, size_t data_size, size_t data_fcs_size) { static const int PRCregs[6] = { PRC64, PRC127, PRC255, PRC511, PRC1023, PRC1522 }; e1000x_increase_size_stats(mac, PRCregs, data_fcs_size); e1000x_inc_reg_if_not_full(mac, TPR); mac[GPRC] = mac[TPR]; /* TOR - Total Octets Received: * This register includes bytes received in a packet from the <Destination * Address> field through the <CRC> field, inclusively. * Always include FCS length (4) in size. */ e1000x_grow_8reg_if_not_full(mac, TORL, data_size + 4); mac[GORCL] = mac[TORL]; mac[GORCH] = mac[TORH]; } void e1000x_increase_size_stats(uint32_t *mac, const int *size_regs, int size) { if (size > 1023) { e1000x_inc_reg_if_not_full(mac, size_regs[5]); } else if (size > 511) { e1000x_inc_reg_if_not_full(mac, size_regs[4]); } else if (size > 255) { e1000x_inc_reg_if_not_full(mac, size_regs[3]); } else if (size > 127) { e1000x_inc_reg_if_not_full(mac, size_regs[2]); } else if (size > 64) { e1000x_inc_reg_if_not_full(mac, size_regs[1]); } else if (size == 64) { e1000x_inc_reg_if_not_full(mac, size_regs[0]); } } void e1000x_read_tx_ctx_descr(struct e1000_context_desc *d, e1000x_txd_props *props) { uint32_t op = le32_to_cpu(d->cmd_and_length); props->ipcss = d->lower_setup.ip_fields.ipcss; props->ipcso = d->lower_setup.ip_fields.ipcso; props->ipcse = le16_to_cpu(d->lower_setup.ip_fields.ipcse); props->tucss = d->upper_setup.tcp_fields.tucss; props->tucso = d->upper_setup.tcp_fields.tucso; props->tucse = le16_to_cpu(d->upper_setup.tcp_fields.tucse); props->paylen = op & 0xfffff; props->hdr_len = d->tcp_seg_setup.fields.hdr_len; props->mss = le16_to_cpu(d->tcp_seg_setup.fields.mss); props->ip = (op & E1000_TXD_CMD_IP) ? 1 : 0; props->tcp = (op & E1000_TXD_CMD_TCP) ? 1 : 0; props->tse = (op & E1000_TXD_CMD_TSE) ? 1 : 0; }
34909.c
/* Generated by re2c */ #line 1 "encodings/unicode_group_C_u_encoding_policy_substitute.re" // re2c $INPUT -o $OUTPUT -u --encoding-policy substitute #include <stdio.h> #define YYCTYPE unsigned int bool scan(const YYCTYPE * start, const YYCTYPE * const limit) { __attribute__((unused)) const YYCTYPE * YYMARKER; // silence compiler warnings when YYMARKER is not used # define YYCURSOR start C: #line 14 "encodings/unicode_group_C_u_encoding_policy_substitute.c" { YYCTYPE yych; yych = *YYCURSOR; if (yych <= 0x0000318F) { if (yych <= 0x00000E00) { if (yych <= 0x00000B30) { if (yych <= 0x000009D6) { if (yych <= 0x000006DD) { if (yych <= 0x00000556) { if (yych <= 0x00000383) { if (yych <= 0x000000AC) { if (yych <= 0x0000001F) goto yy2; if (yych <= '~') goto yy4; if (yych >= 0x000000A0) goto yy4; } else { if (yych <= 0x00000377) { if (yych >= 0x000000AE) goto yy4; } else { if (yych <= 0x00000379) goto yy2; if (yych <= 0x0000037F) goto yy4; } } } else { if (yych <= 0x0000038D) { if (yych == 0x0000038B) goto yy2; if (yych <= 0x0000038C) goto yy4; } else { if (yych <= 0x000003A2) { if (yych <= 0x000003A1) goto yy4; } else { if (yych != 0x00000530) goto yy4; } } } } else { if (yych <= 0x00000590) { if (yych <= 0x00000587) { if (yych <= 0x00000558) goto yy2; if (yych != 0x00000560) goto yy4; } else { if (yych <= 0x0000058A) { if (yych >= 0x00000589) goto yy4; } else { if (yych <= 0x0000058C) goto yy2; if (yych <= 0x0000058F) goto yy4; } } } else { if (yych <= 0x000005F4) { if (yych <= 0x000005CF) { if (yych <= 0x000005C7) goto yy4; } else { if (yych <= 0x000005EA) goto yy4; if (yych >= 0x000005F0) goto yy4; } } else { if (yych <= 0x0000061B) { if (yych >= 0x00000606) goto yy4; } else { if (yych <= 0x0000061D) goto yy2; if (yych <= 0x000006DC) goto yy4; } } } } } else { if (yych <= 0x00000983) { if (yych <= 0x0000082D) { if (yych <= 0x0000074C) { if (yych <= 0x0000070D) goto yy4; if (yych <= 0x0000070F) goto yy2; if (yych <= 0x0000074A) goto yy4; } else { if (yych <= 0x000007BF) { if (yych <= 0x000007B1) goto yy4; } else { if (yych <= 0x000007FA) goto yy4; if (yych >= 0x00000800) goto yy4; } } } else { if (yych <= 0x0000085D) { if (yych <= 0x0000083E) { if (yych >= 0x00000830) goto yy4; } else { if (yych <= 0x0000083F) goto yy2; if (yych <= 0x0000085B) goto yy4; } } else { if (yych <= 0x0000089F) { if (yych <= 0x0000085E) goto yy4; } else { if (yych <= 0x000008B2) goto yy4; if (yych >= 0x000008E4) goto yy4; } } } } else { if (yych <= 0x000009B1) { if (yych <= 0x00000990) { if (yych <= 0x00000984) goto yy2; if (yych <= 0x0000098C) goto yy4; if (yych >= 0x0000098F) goto yy4; } else { if (yych <= 0x000009A8) { if (yych >= 0x00000993) goto yy4; } else { if (yych <= 0x000009A9) goto yy2; if (yych <= 0x000009B0) goto yy4; } } } else { if (yych <= 0x000009C4) { if (yych <= 0x000009B5) { if (yych <= 0x000009B2) goto yy4; } else { if (yych <= 0x000009B9) goto yy4; if (yych >= 0x000009BC) goto yy4; } } else { if (yych <= 0x000009C8) { if (yych >= 0x000009C7) goto yy4; } else { if (yych <= 0x000009CA) goto yy2; if (yych <= 0x000009CE) goto yy4; } } } } } } else { if (yych <= 0x00000A5E) { if (yych <= 0x00000A31) { if (yych <= 0x00000A03) { if (yych <= 0x000009DE) { if (yych <= 0x000009D7) goto yy4; if (yych <= 0x000009DB) goto yy2; if (yych <= 0x000009DD) goto yy4; } else { if (yych <= 0x000009E5) { if (yych <= 0x000009E3) goto yy4; } else { if (yych <= 0x000009FB) goto yy4; if (yych >= 0x00000A01) goto yy4; } } } else { if (yych <= 0x00000A10) { if (yych <= 0x00000A04) goto yy2; if (yych <= 0x00000A0A) goto yy4; if (yych >= 0x00000A0F) goto yy4; } else { if (yych <= 0x00000A28) { if (yych >= 0x00000A13) goto yy4; } else { if (yych <= 0x00000A29) goto yy2; if (yych <= 0x00000A30) goto yy4; } } } } else { if (yych <= 0x00000A42) { if (yych <= 0x00000A37) { if (yych == 0x00000A34) goto yy2; if (yych <= 0x00000A36) goto yy4; } else { if (yych <= 0x00000A3B) { if (yych <= 0x00000A39) goto yy4; } else { if (yych != 0x00000A3D) goto yy4; } } } else { if (yych <= 0x00000A50) { if (yych <= 0x00000A48) { if (yych >= 0x00000A47) goto yy4; } else { if (yych <= 0x00000A4A) goto yy2; if (yych <= 0x00000A4D) goto yy4; } } else { if (yych <= 0x00000A58) { if (yych <= 0x00000A51) goto yy4; } else { if (yych != 0x00000A5D) goto yy4; } } } } } else { if (yych <= 0x00000AC6) { if (yych <= 0x00000A92) { if (yych <= 0x00000A83) { if (yych <= 0x00000A65) goto yy2; if (yych <= 0x00000A75) goto yy4; if (yych >= 0x00000A81) goto yy4; } else { if (yych <= 0x00000A8D) { if (yych >= 0x00000A85) goto yy4; } else { if (yych <= 0x00000A8E) goto yy2; if (yych <= 0x00000A91) goto yy4; } } } else { if (yych <= 0x00000AB3) { if (yych <= 0x00000AA9) { if (yych <= 0x00000AA8) goto yy4; } else { if (yych != 0x00000AB1) goto yy4; } } else { if (yych <= 0x00000AB9) { if (yych >= 0x00000AB5) goto yy4; } else { if (yych <= 0x00000ABB) goto yy2; if (yych <= 0x00000AC5) goto yy4; } } } } else { if (yych <= 0x00000AF1) { if (yych <= 0x00000ACF) { if (yych == 0x00000ACA) goto yy2; if (yych <= 0x00000ACD) goto yy4; } else { if (yych <= 0x00000ADF) { if (yych <= 0x00000AD0) goto yy4; } else { if (yych <= 0x00000AE3) goto yy4; if (yych >= 0x00000AE6) goto yy4; } } } else { if (yych <= 0x00000B0E) { if (yych <= 0x00000B03) { if (yych >= 0x00000B01) goto yy4; } else { if (yych <= 0x00000B04) goto yy2; if (yych <= 0x00000B0C) goto yy4; } } else { if (yych <= 0x00000B12) { if (yych <= 0x00000B10) goto yy4; } else { if (yych != 0x00000B29) goto yy4; } } } } } } } else { if (yych <= 0x00000C77) { if (yych <= 0x00000BAD) { if (yych <= 0x00000B77) { if (yych <= 0x00000B4A) { if (yych <= 0x00000B39) { if (yych <= 0x00000B31) goto yy2; if (yych != 0x00000B34) goto yy4; } else { if (yych <= 0x00000B44) { if (yych >= 0x00000B3C) goto yy4; } else { if (yych <= 0x00000B46) goto yy2; if (yych <= 0x00000B48) goto yy4; } } } else { if (yych <= 0x00000B5B) { if (yych <= 0x00000B4D) goto yy4; if (yych <= 0x00000B55) goto yy2; if (yych <= 0x00000B57) goto yy4; } else { if (yych <= 0x00000B5E) { if (yych <= 0x00000B5D) goto yy4; } else { if (yych <= 0x00000B63) goto yy4; if (yych >= 0x00000B66) goto yy4; } } } } else { if (yych <= 0x00000B98) { if (yych <= 0x00000B8A) { if (yych <= 0x00000B81) goto yy2; if (yych != 0x00000B84) goto yy4; } else { if (yych <= 0x00000B90) { if (yych >= 0x00000B8E) goto yy4; } else { if (yych <= 0x00000B91) goto yy2; if (yych <= 0x00000B95) goto yy4; } } } else { if (yych <= 0x00000B9F) { if (yych <= 0x00000B9B) { if (yych <= 0x00000B9A) goto yy4; } else { if (yych != 0x00000B9D) goto yy4; } } else { if (yych <= 0x00000BA4) { if (yych >= 0x00000BA3) goto yy4; } else { if (yych <= 0x00000BA7) goto yy2; if (yych <= 0x00000BAA) goto yy4; } } } } } else { if (yych <= 0x00000C10) { if (yych <= 0x00000BD0) { if (yych <= 0x00000BC5) { if (yych <= 0x00000BB9) goto yy4; if (yych <= 0x00000BBD) goto yy2; if (yych <= 0x00000BC2) goto yy4; } else { if (yych <= 0x00000BC9) { if (yych <= 0x00000BC8) goto yy4; } else { if (yych <= 0x00000BCD) goto yy4; if (yych >= 0x00000BD0) goto yy4; } } } else { if (yych <= 0x00000BFF) { if (yych <= 0x00000BD7) { if (yych >= 0x00000BD7) goto yy4; } else { if (yych <= 0x00000BE5) goto yy2; if (yych <= 0x00000BFA) goto yy4; } } else { if (yych <= 0x00000C04) { if (yych <= 0x00000C03) goto yy4; } else { if (yych != 0x00000C0D) goto yy4; } } } } else { if (yych <= 0x00000C49) { if (yych <= 0x00000C39) { if (yych <= 0x00000C11) goto yy2; if (yych != 0x00000C29) goto yy4; } else { if (yych <= 0x00000C44) { if (yych >= 0x00000C3D) goto yy4; } else { if (yych <= 0x00000C45) goto yy2; if (yych <= 0x00000C48) goto yy4; } } } else { if (yych <= 0x00000C59) { if (yych <= 0x00000C54) { if (yych <= 0x00000C4D) goto yy4; } else { if (yych != 0x00000C57) goto yy4; } } else { if (yych <= 0x00000C63) { if (yych >= 0x00000C60) goto yy4; } else { if (yych <= 0x00000C65) goto yy2; if (yych <= 0x00000C6F) goto yy4; } } } } } } else { if (yych <= 0x00000D3C) { if (yych <= 0x00000CCD) { if (yych <= 0x00000CA8) { if (yych <= 0x00000C84) { if (yych == 0x00000C80) goto yy2; if (yych <= 0x00000C83) goto yy4; } else { if (yych <= 0x00000C8D) { if (yych <= 0x00000C8C) goto yy4; } else { if (yych != 0x00000C91) goto yy4; } } } else { if (yych <= 0x00000CBB) { if (yych <= 0x00000CB3) { if (yych >= 0x00000CAA) goto yy4; } else { if (yych <= 0x00000CB4) goto yy2; if (yych <= 0x00000CB9) goto yy4; } } else { if (yych <= 0x00000CC5) { if (yych <= 0x00000CC4) goto yy4; } else { if (yych != 0x00000CC9) goto yy4; } } } } else { if (yych <= 0x00000CF0) { if (yych <= 0x00000CDE) { if (yych <= 0x00000CD4) goto yy2; if (yych <= 0x00000CD6) goto yy4; if (yych >= 0x00000CDE) goto yy4; } else { if (yych <= 0x00000CE3) { if (yych >= 0x00000CE0) goto yy4; } else { if (yych <= 0x00000CE5) goto yy2; if (yych <= 0x00000CEF) goto yy4; } } } else { if (yych <= 0x00000D0C) { if (yych <= 0x00000D00) { if (yych <= 0x00000CF2) goto yy4; } else { if (yych != 0x00000D04) goto yy4; } } else { if (yych <= 0x00000D10) { if (yych >= 0x00000D0E) goto yy4; } else { if (yych <= 0x00000D11) goto yy2; if (yych <= 0x00000D3A) goto yy4; } } } } } else { if (yych <= 0x00000DB1) { if (yych <= 0x00000D63) { if (yych <= 0x00000D49) { if (yych == 0x00000D45) goto yy2; if (yych <= 0x00000D48) goto yy4; } else { if (yych <= 0x00000D56) { if (yych <= 0x00000D4E) goto yy4; } else { if (yych <= 0x00000D57) goto yy4; if (yych >= 0x00000D60) goto yy4; } } } else { if (yych <= 0x00000D81) { if (yych <= 0x00000D75) { if (yych >= 0x00000D66) goto yy4; } else { if (yych <= 0x00000D78) goto yy2; if (yych <= 0x00000D7F) goto yy4; } } else { if (yych <= 0x00000D84) { if (yych <= 0x00000D83) goto yy4; } else { if (yych <= 0x00000D96) goto yy4; if (yych >= 0x00000D9A) goto yy4; } } } } else { if (yych <= 0x00000DCE) { if (yych <= 0x00000DBD) { if (yych <= 0x00000DB2) goto yy2; if (yych != 0x00000DBC) goto yy4; } else { if (yych <= 0x00000DC6) { if (yych >= 0x00000DC0) goto yy4; } else { if (yych == 0x00000DCA) goto yy4; } } } else { if (yych <= 0x00000DDF) { if (yych <= 0x00000DD5) { if (yych <= 0x00000DD4) goto yy4; } else { if (yych != 0x00000DD7) goto yy4; } } else { if (yych <= 0x00000DEF) { if (yych >= 0x00000DE6) goto yy4; } else { if (yych <= 0x00000DF1) goto yy2; if (yych <= 0x00000DF4) goto yy4; } } } } } } } } else { if (yych <= 0x00001A5E) { if (yych <= 0x000012B5) { if (yych <= 0x00000ED9) { if (yych <= 0x00000EA0) { if (yych <= 0x00000E88) { if (yych <= 0x00000E80) { if (yych <= 0x00000E3A) goto yy4; if (yych <= 0x00000E3E) goto yy2; if (yych <= 0x00000E5B) goto yy4; } else { if (yych <= 0x00000E83) { if (yych <= 0x00000E82) goto yy4; } else { if (yych <= 0x00000E84) goto yy4; if (yych >= 0x00000E87) goto yy4; } } } else { if (yych <= 0x00000E8D) { if (yych == 0x00000E8A) goto yy4; if (yych >= 0x00000E8D) goto yy4; } else { if (yych <= 0x00000E97) { if (yych >= 0x00000E94) goto yy4; } else { if (yych <= 0x00000E98) goto yy2; if (yych <= 0x00000E9F) goto yy4; } } } } else { if (yych <= 0x00000EB9) { if (yych <= 0x00000EA6) { if (yych == 0x00000EA4) goto yy2; if (yych <= 0x00000EA5) goto yy4; } else { if (yych <= 0x00000EA9) { if (yych <= 0x00000EA7) goto yy4; } else { if (yych != 0x00000EAC) goto yy4; } } } else { if (yych <= 0x00000EC5) { if (yych <= 0x00000EBD) { if (yych >= 0x00000EBB) goto yy4; } else { if (yych <= 0x00000EBF) goto yy2; if (yych <= 0x00000EC4) goto yy4; } } else { if (yych <= 0x00000EC7) { if (yych <= 0x00000EC6) goto yy4; } else { if (yych <= 0x00000ECD) goto yy4; if (yych >= 0x00000ED0) goto yy4; } } } } } else { if (yych <= 0x000010CC) { if (yych <= 0x00000F98) { if (yych <= 0x00000F47) { if (yych <= 0x00000EDB) goto yy2; if (yych <= 0x00000EDF) goto yy4; if (yych >= 0x00000F00) goto yy4; } else { if (yych <= 0x00000F6C) { if (yych >= 0x00000F49) goto yy4; } else { if (yych <= 0x00000F70) goto yy2; if (yych <= 0x00000F97) goto yy4; } } } else { if (yych <= 0x00000FDA) { if (yych <= 0x00000FBD) { if (yych <= 0x00000FBC) goto yy4; } else { if (yych != 0x00000FCD) goto yy4; } } else { if (yych <= 0x000010C5) { if (yych >= 0x00001000) goto yy4; } else { if (yych == 0x000010C7) goto yy4; } } } } else { if (yych <= 0x00001258) { if (yych <= 0x00001249) { if (yych <= 0x000010CD) goto yy4; if (yych <= 0x000010CF) goto yy2; if (yych <= 0x00001248) goto yy4; } else { if (yych <= 0x0000124F) { if (yych <= 0x0000124D) goto yy4; } else { if (yych != 0x00001257) goto yy4; } } } else { if (yych <= 0x00001289) { if (yych <= 0x0000125D) { if (yych >= 0x0000125A) goto yy4; } else { if (yych <= 0x0000125F) goto yy2; if (yych <= 0x00001288) goto yy4; } } else { if (yych <= 0x0000128F) { if (yych <= 0x0000128D) goto yy4; } else { if (yych != 0x000012B1) goto yy4; } } } } } } else { if (yych <= 0x00001773) { if (yych <= 0x0000139F) { if (yych <= 0x000012D7) { if (yych <= 0x000012C0) { if (yych <= 0x000012B7) goto yy2; if (yych != 0x000012BF) goto yy4; } else { if (yych <= 0x000012C5) { if (yych >= 0x000012C2) goto yy4; } else { if (yych <= 0x000012C7) goto yy2; if (yych <= 0x000012D6) goto yy4; } } } else { if (yych <= 0x0000135A) { if (yych <= 0x00001311) { if (yych <= 0x00001310) goto yy4; } else { if (yych <= 0x00001315) goto yy4; if (yych >= 0x00001318) goto yy4; } } else { if (yych <= 0x0000137C) { if (yych >= 0x0000135D) goto yy4; } else { if (yych <= 0x0000137F) goto yy2; if (yych <= 0x00001399) goto yy4; } } } } else { if (yych <= 0x00001714) { if (yych <= 0x0000169F) { if (yych <= 0x000013F4) goto yy4; if (yych <= 0x000013FF) goto yy2; if (yych <= 0x0000169C) goto yy4; } else { if (yych <= 0x000016FF) { if (yych <= 0x000016F8) goto yy4; } else { if (yych != 0x0000170D) goto yy4; } } } else { if (yych <= 0x0000175F) { if (yych <= 0x00001736) { if (yych >= 0x00001720) goto yy4; } else { if (yych <= 0x0000173F) goto yy2; if (yych <= 0x00001753) goto yy4; } } else { if (yych <= 0x0000176D) { if (yych <= 0x0000176C) goto yy4; } else { if (yych != 0x00001771) goto yy4; } } } } } else { if (yych <= 0x0000191F) { if (yych <= 0x0000180F) { if (yych <= 0x000017E9) { if (yych <= 0x0000177F) goto yy2; if (yych <= 0x000017DD) goto yy4; if (yych >= 0x000017E0) goto yy4; } else { if (yych <= 0x000017F9) { if (yych >= 0x000017F0) goto yy4; } else { if (yych <= 0x000017FF) goto yy2; if (yych <= 0x0000180D) goto yy4; } } } else { if (yych <= 0x000018AA) { if (yych <= 0x0000181F) { if (yych <= 0x00001819) goto yy4; } else { if (yych <= 0x00001877) goto yy4; if (yych >= 0x00001880) goto yy4; } } else { if (yych <= 0x000018F5) { if (yych >= 0x000018B0) goto yy4; } else { if (yych <= 0x000018FF) goto yy2; if (yych <= 0x0000191E) goto yy4; } } } } else { if (yych <= 0x00001974) { if (yych <= 0x0000193F) { if (yych <= 0x0000192B) goto yy4; if (yych <= 0x0000192F) goto yy2; if (yych <= 0x0000193B) goto yy4; } else { if (yych <= 0x00001943) { if (yych <= 0x00001940) goto yy4; } else { if (yych <= 0x0000196D) goto yy4; if (yych >= 0x00001970) goto yy4; } } } else { if (yych <= 0x000019CF) { if (yych <= 0x000019AB) { if (yych >= 0x00001980) goto yy4; } else { if (yych <= 0x000019AF) goto yy2; if (yych <= 0x000019C9) goto yy4; } } else { if (yych <= 0x000019DD) { if (yych <= 0x000019DA) goto yy4; } else { if (yych <= 0x00001A1B) goto yy4; if (yych >= 0x00001A1E) goto yy4; } } } } } } } else { if (yych <= 0x0000209F) { if (yych <= 0x00001F47) { if (yych <= 0x00001C37) { if (yych <= 0x00001AAF) { if (yych <= 0x00001A89) { if (yych <= 0x00001A5F) goto yy2; if (yych <= 0x00001A7C) goto yy4; if (yych >= 0x00001A7F) goto yy4; } else { if (yych <= 0x00001A99) { if (yych >= 0x00001A90) goto yy4; } else { if (yych <= 0x00001A9F) goto yy2; if (yych <= 0x00001AAD) goto yy4; } } } else { if (yych <= 0x00001B4F) { if (yych <= 0x00001ABE) goto yy4; if (yych <= 0x00001AFF) goto yy2; if (yych <= 0x00001B4B) goto yy4; } else { if (yych <= 0x00001B7F) { if (yych <= 0x00001B7C) goto yy4; } else { if (yych <= 0x00001BF3) goto yy4; if (yych >= 0x00001BFC) goto yy4; } } } } else { if (yych <= 0x00001CF7) { if (yych <= 0x00001C7F) { if (yych <= 0x00001C3A) goto yy2; if (yych <= 0x00001C49) goto yy4; if (yych >= 0x00001C4D) goto yy4; } else { if (yych <= 0x00001CC7) { if (yych >= 0x00001CC0) goto yy4; } else { if (yych <= 0x00001CCF) goto yy2; if (yych <= 0x00001CF6) goto yy4; } } } else { if (yych <= 0x00001F15) { if (yych <= 0x00001CFF) { if (yych <= 0x00001CF9) goto yy4; } else { if (yych <= 0x00001DF5) goto yy4; if (yych >= 0x00001DFC) goto yy4; } } else { if (yych <= 0x00001F1D) { if (yych >= 0x00001F18) goto yy4; } else { if (yych <= 0x00001F1F) goto yy2; if (yych <= 0x00001F45) goto yy4; } } } } } else { if (yych <= 0x00001FDB) { if (yych <= 0x00001F5D) { if (yych <= 0x00001F58) { if (yych <= 0x00001F4D) goto yy4; if (yych <= 0x00001F4F) goto yy2; if (yych <= 0x00001F57) goto yy4; } else { if (yych <= 0x00001F5A) { if (yych <= 0x00001F59) goto yy4; } else { if (yych != 0x00001F5C) goto yy4; } } } else { if (yych <= 0x00001FB5) { if (yych <= 0x00001F7D) { if (yych >= 0x00001F5F) goto yy4; } else { if (yych <= 0x00001F7F) goto yy2; if (yych <= 0x00001FB4) goto yy4; } } else { if (yych <= 0x00001FC5) { if (yych <= 0x00001FC4) goto yy4; } else { if (yych <= 0x00001FD3) goto yy4; if (yych >= 0x00001FD6) goto yy4; } } } } else { if (yych <= 0x0000200F) { if (yych <= 0x00001FF4) { if (yych <= 0x00001FDC) goto yy2; if (yych <= 0x00001FEF) goto yy4; if (yych >= 0x00001FF2) goto yy4; } else { if (yych <= 0x00001FFE) { if (yych >= 0x00001FF6) goto yy4; } else { if (yych <= 0x00001FFF) goto yy2; if (yych <= 0x0000200A) goto yy4; } } } else { if (yych <= 0x00002071) { if (yych <= 0x0000202E) { if (yych <= 0x00002029) goto yy4; } else { if (yych <= 0x0000205F) goto yy4; if (yych >= 0x00002070) goto yy4; } } else { if (yych <= 0x0000208E) { if (yych >= 0x00002074) goto yy4; } else { if (yych <= 0x0000208F) goto yy2; if (yych <= 0x0000209C) goto yy4; } } } } } } else { if (yych <= 0x00002D7E) { if (yych <= 0x00002BC8) { if (yych <= 0x00002426) { if (yych <= 0x000020FF) { if (yych <= 0x000020BD) goto yy4; if (yych <= 0x000020CF) goto yy2; if (yych <= 0x000020F0) goto yy4; } else { if (yych <= 0x0000218F) { if (yych <= 0x00002189) goto yy4; } else { if (yych <= 0x000023FA) goto yy4; if (yych >= 0x00002400) goto yy4; } } } else { if (yych <= 0x00002B75) { if (yych <= 0x0000244A) { if (yych >= 0x00002440) goto yy4; } else { if (yych <= 0x0000245F) goto yy2; if (yych <= 0x00002B73) goto yy4; } } else { if (yych <= 0x00002B97) { if (yych <= 0x00002B95) goto yy4; } else { if (yych <= 0x00002BB9) goto yy4; if (yych >= 0x00002BBD) goto yy4; } } } } else { if (yych <= 0x00002CF8) { if (yych <= 0x00002C2E) { if (yych <= 0x00002BC9) goto yy2; if (yych <= 0x00002BD1) goto yy4; if (yych >= 0x00002C00) goto yy4; } else { if (yych <= 0x00002C5E) { if (yych >= 0x00002C30) goto yy4; } else { if (yych <= 0x00002C5F) goto yy2; if (yych <= 0x00002CF3) goto yy4; } } } else { if (yych <= 0x00002D2D) { if (yych <= 0x00002D26) { if (yych <= 0x00002D25) goto yy4; } else { if (yych <= 0x00002D27) goto yy4; if (yych >= 0x00002D2D) goto yy4; } } else { if (yych <= 0x00002D67) { if (yych >= 0x00002D30) goto yy4; } else { if (yych <= 0x00002D6E) goto yy2; if (yych <= 0x00002D70) goto yy4; } } } } } else { if (yych <= 0x00002E42) { if (yych <= 0x00002DBE) { if (yych <= 0x00002DA7) { if (yych <= 0x00002D96) goto yy4; if (yych <= 0x00002D9F) goto yy2; if (yych <= 0x00002DA6) goto yy4; } else { if (yych <= 0x00002DAF) { if (yych <= 0x00002DAE) goto yy4; } else { if (yych != 0x00002DB7) goto yy4; } } } else { if (yych <= 0x00002DCF) { if (yych <= 0x00002DC6) { if (yych >= 0x00002DC0) goto yy4; } else { if (yych <= 0x00002DC7) goto yy2; if (yych <= 0x00002DCE) goto yy4; } } else { if (yych <= 0x00002DD7) { if (yych <= 0x00002DD6) goto yy4; } else { if (yych != 0x00002DDF) goto yy4; } } } } else { if (yych <= 0x00002FFF) { if (yych <= 0x00002EF3) { if (yych <= 0x00002E7F) goto yy2; if (yych != 0x00002E9A) goto yy4; } else { if (yych <= 0x00002FD5) { if (yych >= 0x00002F00) goto yy4; } else { if (yych <= 0x00002FEF) goto yy2; if (yych <= 0x00002FFB) goto yy4; } } } else { if (yych <= 0x000030FF) { if (yych <= 0x00003040) { if (yych <= 0x0000303F) goto yy4; } else { if (yych <= 0x00003096) goto yy4; if (yych >= 0x00003099) goto yy4; } } else { if (yych <= 0x0000312D) { if (yych >= 0x00003105) goto yy4; } else { if (yych <= 0x00003130) goto yy2; if (yych <= 0x0000318E) goto yy4; } } } } } } } } } else { if (yych <= 0x00011300) { if (yych <= 0x0001003D) { if (yych <= 0x0000ABED) { if (yych <= 0x0000A8D9) { if (yych <= 0x0000A63F) { if (yych <= 0x00004DB5) { if (yych <= 0x000031EF) { if (yych <= 0x000031BA) goto yy4; if (yych <= 0x000031BF) goto yy2; if (yych <= 0x000031E3) goto yy4; } else { if (yych <= 0x0000321F) { if (yych <= 0x0000321E) goto yy4; } else { if (yych != 0x000032FF) goto yy4; } } } else { if (yych <= 0x0000A48C) { if (yych <= 0x00004DBF) goto yy2; if (yych <= 0x00009FCC) goto yy4; if (yych >= 0x0000A000) goto yy4; } else { if (yych <= 0x0000A4C6) { if (yych >= 0x0000A490) goto yy4; } else { if (yych <= 0x0000A4CF) goto yy2; if (yych <= 0x0000A62B) goto yy4; } } } } else { if (yych <= 0x0000A7B1) { if (yych <= 0x0000A6FF) { if (yych == 0x0000A69E) goto yy2; if (yych <= 0x0000A6F7) goto yy4; } else { if (yych <= 0x0000A78F) { if (yych <= 0x0000A78E) goto yy4; } else { if (yych <= 0x0000A7AD) goto yy4; if (yych >= 0x0000A7B0) goto yy4; } } } else { if (yych <= 0x0000A83F) { if (yych <= 0x0000A82B) { if (yych >= 0x0000A7F7) goto yy4; } else { if (yych <= 0x0000A82F) goto yy2; if (yych <= 0x0000A839) goto yy4; } } else { if (yych <= 0x0000A87F) { if (yych <= 0x0000A877) goto yy4; } else { if (yych <= 0x0000A8C4) goto yy4; if (yych >= 0x0000A8CE) goto yy4; } } } } } else { if (yych <= 0x0000AA5B) { if (yych <= 0x0000A9CE) { if (yych <= 0x0000A953) { if (yych <= 0x0000A8DF) goto yy2; if (yych <= 0x0000A8FB) goto yy4; if (yych >= 0x0000A900) goto yy4; } else { if (yych <= 0x0000A97C) { if (yych >= 0x0000A95F) goto yy4; } else { if (yych <= 0x0000A97F) goto yy2; if (yych <= 0x0000A9CD) goto yy4; } } } else { if (yych <= 0x0000AA36) { if (yych <= 0x0000A9DD) { if (yych <= 0x0000A9D9) goto yy4; } else { if (yych != 0x0000A9FF) goto yy4; } } else { if (yych <= 0x0000AA4D) { if (yych >= 0x0000AA40) goto yy4; } else { if (yych <= 0x0000AA4F) goto yy2; if (yych <= 0x0000AA59) goto yy4; } } } } else { if (yych <= 0x0000AB16) { if (yych <= 0x0000AB00) { if (yych <= 0x0000AAC2) goto yy4; if (yych <= 0x0000AADA) goto yy2; if (yych <= 0x0000AAF6) goto yy4; } else { if (yych <= 0x0000AB08) { if (yych <= 0x0000AB06) goto yy4; } else { if (yych <= 0x0000AB0E) goto yy4; if (yych >= 0x0000AB11) goto yy4; } } } else { if (yych <= 0x0000AB2F) { if (yych <= 0x0000AB26) { if (yych >= 0x0000AB20) goto yy4; } else { if (yych <= 0x0000AB27) goto yy2; if (yych <= 0x0000AB2E) goto yy4; } } else { if (yych <= 0x0000AB63) { if (yych <= 0x0000AB5F) goto yy4; } else { if (yych <= 0x0000AB65) goto yy4; if (yych >= 0x0000ABC0) goto yy4; } } } } } } else { if (yych <= 0x0000FDFD) { if (yych <= 0x0000FB1C) { if (yych <= 0x0000D7FF) { if (yych <= 0x0000D7A3) { if (yych <= 0x0000ABEF) goto yy2; if (yych <= 0x0000ABF9) goto yy4; if (yych >= 0x0000AC00) goto yy4; } else { if (yych <= 0x0000D7C6) { if (yych >= 0x0000D7B0) goto yy4; } else { if (yych <= 0x0000D7CA) goto yy2; if (yych <= 0x0000D7FB) goto yy4; } } } else { if (yych <= 0x0000FAD9) { if (yych <= 0x0000F8FF) { if (yych <= 0x0000DFFF) goto yy4; } else { if (yych <= 0x0000FA6D) goto yy4; if (yych >= 0x0000FA70) goto yy4; } } else { if (yych <= 0x0000FB06) { if (yych >= 0x0000FB00) goto yy4; } else { if (yych <= 0x0000FB12) goto yy2; if (yych <= 0x0000FB17) goto yy4; } } } } else { if (yych <= 0x0000FB44) { if (yych <= 0x0000FB3D) { if (yych == 0x0000FB37) goto yy2; if (yych <= 0x0000FB3C) goto yy4; } else { if (yych <= 0x0000FB3F) { if (yych <= 0x0000FB3E) goto yy4; } else { if (yych != 0x0000FB42) goto yy4; } } } else { if (yych <= 0x0000FD4F) { if (yych <= 0x0000FBC1) { if (yych >= 0x0000FB46) goto yy4; } else { if (yych <= 0x0000FBD2) goto yy2; if (yych <= 0x0000FD3F) goto yy4; } } else { if (yych <= 0x0000FD91) { if (yych <= 0x0000FD8F) goto yy4; } else { if (yych <= 0x0000FDC7) goto yy4; if (yych >= 0x0000FDF0) goto yy4; } } } } } else { if (yych <= 0x0000FFC9) { if (yych <= 0x0000FE67) { if (yych <= 0x0000FE2D) { if (yych <= 0x0000FDFF) goto yy2; if (yych <= 0x0000FE19) goto yy4; if (yych >= 0x0000FE20) goto yy4; } else { if (yych <= 0x0000FE52) { if (yych >= 0x0000FE30) goto yy4; } else { if (yych <= 0x0000FE53) goto yy2; if (yych <= 0x0000FE66) goto yy4; } } } else { if (yych <= 0x0000FEFC) { if (yych <= 0x0000FE6F) { if (yych <= 0x0000FE6B) goto yy4; } else { if (yych != 0x0000FE75) goto yy4; } } else { if (yych <= 0x0000FFBE) { if (yych >= 0x0000FF01) goto yy4; } else { if (yych <= 0x0000FFC1) goto yy2; if (yych <= 0x0000FFC7) goto yy4; } } } } else { if (yych <= 0x0000FFEE) { if (yych <= 0x0000FFD9) { if (yych <= 0x0000FFCF) goto yy4; if (yych <= 0x0000FFD1) goto yy2; if (yych <= 0x0000FFD7) goto yy4; } else { if (yych <= 0x0000FFDF) { if (yych <= 0x0000FFDC) goto yy4; } else { if (yych != 0x0000FFE7) goto yy4; } } } else { if (yych <= 0x0001000C) { if (yych <= 0x0000FFFC) { if (yych >= 0x0000FFFC) goto yy4; } else { if (yych <= 0x0000FFFF) goto yy2; if (yych <= 0x0001000B) goto yy4; } } else { if (yych <= 0x00010027) { if (yych <= 0x00010026) goto yy4; } else { if (yych != 0x0001003B) goto yy4; } } } } } } } else { if (yych <= 0x0001097F) { if (yych <= 0x000103FF) { if (yych <= 0x000101FD) { if (yych <= 0x00010106) { if (yych <= 0x0001005D) { if (yych <= 0x0001003E) goto yy2; if (yych <= 0x0001004D) goto yy4; if (yych >= 0x00010050) goto yy4; } else { if (yych <= 0x000100FA) { if (yych >= 0x00010080) goto yy4; } else { if (yych <= 0x000100FF) goto yy2; if (yych <= 0x00010102) goto yy4; } } } else { if (yych <= 0x0001018F) { if (yych <= 0x00010133) goto yy4; if (yych <= 0x00010136) goto yy2; if (yych <= 0x0001018C) goto yy4; } else { if (yych <= 0x0001019F) { if (yych <= 0x0001019B) goto yy4; } else { if (yych <= 0x000101A0) goto yy4; if (yych >= 0x000101D0) goto yy4; } } } } else { if (yych <= 0x0001032F) { if (yych <= 0x000102D0) { if (yych <= 0x0001027F) goto yy2; if (yych <= 0x0001029C) goto yy4; if (yych >= 0x000102A0) goto yy4; } else { if (yych <= 0x000102FB) { if (yych >= 0x000102E0) goto yy4; } else { if (yych <= 0x000102FF) goto yy2; if (yych <= 0x00010323) goto yy4; } } } else { if (yych <= 0x0001039D) { if (yych <= 0x0001034F) { if (yych <= 0x0001034A) goto yy4; } else { if (yych <= 0x0001037A) goto yy4; if (yych >= 0x00010380) goto yy4; } } else { if (yych <= 0x000103C3) { if (yych >= 0x0001039F) goto yy4; } else { if (yych <= 0x000103C7) goto yy2; if (yych <= 0x000103D5) goto yy4; } } } } } else { if (yych <= 0x00010808) { if (yych <= 0x0001056F) { if (yych <= 0x000104FF) { if (yych <= 0x0001049D) goto yy4; if (yych <= 0x0001049F) goto yy2; if (yych <= 0x000104A9) goto yy4; } else { if (yych <= 0x0001052F) { if (yych <= 0x00010527) goto yy4; } else { if (yych <= 0x00010563) goto yy4; if (yych >= 0x0001056F) goto yy4; } } } else { if (yych <= 0x0001075F) { if (yych <= 0x00010736) { if (yych >= 0x00010600) goto yy4; } else { if (yych <= 0x0001073F) goto yy2; if (yych <= 0x00010755) goto yy4; } } else { if (yych <= 0x000107FF) { if (yych <= 0x00010767) goto yy4; } else { if (yych <= 0x00010805) goto yy4; if (yych >= 0x00010808) goto yy4; } } } } else { if (yych <= 0x00010856) { if (yych <= 0x00010838) { if (yych <= 0x00010809) goto yy2; if (yych != 0x00010836) goto yy4; } else { if (yych <= 0x0001083C) { if (yych >= 0x0001083C) goto yy4; } else { if (yych <= 0x0001083E) goto yy2; if (yych <= 0x00010855) goto yy4; } } } else { if (yych <= 0x0001091B) { if (yych <= 0x000108A6) { if (yych <= 0x0001089E) goto yy4; } else { if (yych <= 0x000108AF) goto yy4; if (yych >= 0x00010900) goto yy4; } } else { if (yych <= 0x00010939) { if (yych >= 0x0001091F) goto yy4; } else { if (yych == 0x0001093F) goto yy4; } } } } } } else { if (yych <= 0x00010BFF) { if (yych <= 0x00010A58) { if (yych <= 0x00010A13) { if (yych <= 0x000109FF) { if (yych <= 0x000109B7) goto yy4; if (yych <= 0x000109BD) goto yy2; if (yych <= 0x000109BF) goto yy4; } else { if (yych <= 0x00010A04) { if (yych <= 0x00010A03) goto yy4; } else { if (yych <= 0x00010A06) goto yy4; if (yych >= 0x00010A0C) goto yy4; } } } else { if (yych <= 0x00010A37) { if (yych <= 0x00010A17) { if (yych >= 0x00010A15) goto yy4; } else { if (yych <= 0x00010A18) goto yy2; if (yych <= 0x00010A33) goto yy4; } } else { if (yych <= 0x00010A3E) { if (yych <= 0x00010A3A) goto yy4; } else { if (yych <= 0x00010A47) goto yy4; if (yych >= 0x00010A50) goto yy4; } } } } else { if (yych <= 0x00010B38) { if (yych <= 0x00010AE6) { if (yych <= 0x00010A5F) goto yy2; if (yych <= 0x00010A9F) goto yy4; if (yych >= 0x00010AC0) goto yy4; } else { if (yych <= 0x00010AF6) { if (yych >= 0x00010AEB) goto yy4; } else { if (yych <= 0x00010AFF) goto yy2; if (yych <= 0x00010B35) goto yy4; } } } else { if (yych <= 0x00010B91) { if (yych <= 0x00010B57) { if (yych <= 0x00010B55) goto yy4; } else { if (yych <= 0x00010B72) goto yy4; if (yych >= 0x00010B78) goto yy4; } } else { if (yych <= 0x00010B9C) { if (yych >= 0x00010B99) goto yy4; } else { if (yych <= 0x00010BA8) goto yy2; if (yych <= 0x00010BAF) goto yy4; } } } } } else { if (yych <= 0x00011143) { if (yych <= 0x000110BC) { if (yych <= 0x00010FFF) { if (yych <= 0x00010C48) goto yy4; if (yych <= 0x00010E5F) goto yy2; if (yych <= 0x00010E7E) goto yy4; } else { if (yych <= 0x00011051) { if (yych <= 0x0001104D) goto yy4; } else { if (yych <= 0x0001106F) goto yy4; if (yych >= 0x0001107F) goto yy4; } } } else { if (yych <= 0x000110EF) { if (yych <= 0x000110C1) { if (yych >= 0x000110BE) goto yy4; } else { if (yych <= 0x000110CF) goto yy2; if (yych <= 0x000110E8) goto yy4; } } else { if (yych <= 0x000110FF) { if (yych <= 0x000110F9) goto yy4; } else { if (yych != 0x00011135) goto yy4; } } } } else { if (yych <= 0x000111E0) { if (yych <= 0x000111C8) { if (yych <= 0x0001114F) goto yy2; if (yych <= 0x00011176) goto yy4; if (yych >= 0x00011180) goto yy4; } else { if (yych <= 0x000111CD) { if (yych >= 0x000111CD) goto yy4; } else { if (yych <= 0x000111CF) goto yy2; if (yych <= 0x000111DA) goto yy4; } } } else { if (yych <= 0x0001123D) { if (yych <= 0x000111FF) { if (yych <= 0x000111F4) goto yy4; } else { if (yych != 0x00011212) goto yy4; } } else { if (yych <= 0x000112EA) { if (yych >= 0x000112B0) goto yy4; } else { if (yych <= 0x000112EF) goto yy2; if (yych <= 0x000112F9) goto yy4; } } } } } } } } else { if (yych <= 0x0001D7CB) { if (yych <= 0x00016B61) { if (yych <= 0x00011644) { if (yych <= 0x0001134A) { if (yych <= 0x00011330) { if (yych <= 0x0001130E) { if (yych == 0x00011304) goto yy2; if (yych <= 0x0001130C) goto yy4; } else { if (yych <= 0x00011312) { if (yych <= 0x00011310) goto yy4; } else { if (yych != 0x00011329) goto yy4; } } } else { if (yych <= 0x00011339) { if (yych <= 0x00011331) goto yy2; if (yych != 0x00011334) goto yy4; } else { if (yych <= 0x00011344) { if (yych >= 0x0001133C) goto yy4; } else { if (yych <= 0x00011346) goto yy2; if (yych <= 0x00011348) goto yy4; } } } } else { if (yych <= 0x00011374) { if (yych <= 0x0001135C) { if (yych <= 0x0001134D) goto yy4; if (yych == 0x00011357) goto yy4; } else { if (yych <= 0x00011365) { if (yych <= 0x00011363) goto yy4; } else { if (yych <= 0x0001136C) goto yy4; if (yych >= 0x00011370) goto yy4; } } } else { if (yych <= 0x0001157F) { if (yych <= 0x000114C7) { if (yych >= 0x00011480) goto yy4; } else { if (yych <= 0x000114CF) goto yy2; if (yych <= 0x000114D9) goto yy4; } } else { if (yych <= 0x000115B7) { if (yych <= 0x000115B5) goto yy4; } else { if (yych <= 0x000115C9) goto yy4; if (yych >= 0x00011600) goto yy4; } } } } } else { if (yych <= 0x00012FFF) { if (yych <= 0x000118FE) { if (yych <= 0x000116B7) { if (yych <= 0x0001164F) goto yy2; if (yych <= 0x00011659) goto yy4; if (yych >= 0x00011680) goto yy4; } else { if (yych <= 0x000116C9) { if (yych >= 0x000116C0) goto yy4; } else { if (yych <= 0x0001189F) goto yy2; if (yych <= 0x000118F2) goto yy4; } } } else { if (yych <= 0x00012398) { if (yych <= 0x00011ABF) { if (yych <= 0x000118FF) goto yy4; } else { if (yych <= 0x00011AF8) goto yy4; if (yych >= 0x00012000) goto yy4; } } else { if (yych <= 0x0001246E) { if (yych >= 0x00012400) goto yy4; } else { if (yych <= 0x0001246F) goto yy2; if (yych <= 0x00012474) goto yy4; } } } } else { if (yych <= 0x00016A6F) { if (yych <= 0x00016A3F) { if (yych <= 0x0001342E) goto yy4; if (yych <= 0x000167FF) goto yy2; if (yych <= 0x00016A38) goto yy4; } else { if (yych <= 0x00016A5F) { if (yych <= 0x00016A5E) goto yy4; } else { if (yych <= 0x00016A69) goto yy4; if (yych >= 0x00016A6E) goto yy4; } } } else { if (yych <= 0x00016AFF) { if (yych <= 0x00016AED) { if (yych >= 0x00016AD0) goto yy4; } else { if (yych <= 0x00016AEF) goto yy2; if (yych <= 0x00016AF5) goto yy4; } } else { if (yych <= 0x00016B4F) { if (yych <= 0x00016B45) goto yy4; } else { if (yych != 0x00016B5A) goto yy4; } } } } } } else { if (yych <= 0x0001D454) { if (yych <= 0x0001BC8F) { if (yych <= 0x00016F8E) { if (yych <= 0x00016B8F) { if (yych <= 0x00016B62) goto yy2; if (yych <= 0x00016B77) goto yy4; if (yych >= 0x00016B7D) goto yy4; } else { if (yych <= 0x00016F44) { if (yych >= 0x00016F00) goto yy4; } else { if (yych <= 0x00016F4F) goto yy2; if (yych <= 0x00016F7E) goto yy4; } } } else { if (yych <= 0x0001BC6A) { if (yych <= 0x0001AFFF) { if (yych <= 0x00016F9F) goto yy4; } else { if (yych <= 0x0001B001) goto yy4; if (yych >= 0x0001BC00) goto yy4; } } else { if (yych <= 0x0001BC7C) { if (yych >= 0x0001BC70) goto yy4; } else { if (yych <= 0x0001BC7F) goto yy2; if (yych <= 0x0001BC88) goto yy4; } } } } else { if (yych <= 0x0001D172) { if (yych <= 0x0001CFFF) { if (yych <= 0x0001BC99) goto yy4; if (yych <= 0x0001BC9B) goto yy2; if (yych <= 0x0001BC9F) goto yy4; } else { if (yych <= 0x0001D0FF) { if (yych <= 0x0001D0F5) goto yy4; } else { if (yych <= 0x0001D126) goto yy4; if (yych >= 0x0001D129) goto yy4; } } } else { if (yych <= 0x0001D2FF) { if (yych <= 0x0001D1DD) { if (yych >= 0x0001D17B) goto yy4; } else { if (yych <= 0x0001D1FF) goto yy2; if (yych <= 0x0001D245) goto yy4; } } else { if (yych <= 0x0001D35F) { if (yych <= 0x0001D356) goto yy4; } else { if (yych <= 0x0001D371) goto yy4; if (yych >= 0x0001D400) goto yy4; } } } } } else { if (yych <= 0x0001D506) { if (yych <= 0x0001D4A8) { if (yych <= 0x0001D49F) { if (yych <= 0x0001D455) goto yy2; if (yych != 0x0001D49D) goto yy4; } else { if (yych <= 0x0001D4A2) { if (yych >= 0x0001D4A2) goto yy4; } else { if (yych <= 0x0001D4A4) goto yy2; if (yych <= 0x0001D4A6) goto yy4; } } } else { if (yych <= 0x0001D4BB) { if (yych <= 0x0001D4AD) { if (yych <= 0x0001D4AC) goto yy4; } else { if (yych != 0x0001D4BA) goto yy4; } } else { if (yych <= 0x0001D4C3) { if (yych >= 0x0001D4BD) goto yy4; } else { if (yych <= 0x0001D4C4) goto yy2; if (yych <= 0x0001D505) goto yy4; } } } } else { if (yych <= 0x0001D53E) { if (yych <= 0x0001D515) { if (yych <= 0x0001D50A) goto yy4; if (yych <= 0x0001D50C) goto yy2; if (yych <= 0x0001D514) goto yy4; } else { if (yych <= 0x0001D51D) { if (yych <= 0x0001D51C) goto yy4; } else { if (yych != 0x0001D53A) goto yy4; } } } else { if (yych <= 0x0001D549) { if (yych <= 0x0001D544) { if (yych >= 0x0001D540) goto yy4; } else { if (yych == 0x0001D546) goto yy4; } } else { if (yych <= 0x0001D551) { if (yych <= 0x0001D550) goto yy4; } else { if (yych <= 0x0001D6A5) goto yy4; if (yych >= 0x0001D6A8) goto yy4; } } } } } } } else { if (yych <= 0x0001EFFF) { if (yych <= 0x0001EE53) { if (yych <= 0x0001EE32) { if (yych <= 0x0001EE04) { if (yych <= 0x0001E8C4) { if (yych <= 0x0001D7CD) goto yy2; if (yych <= 0x0001D7FF) goto yy4; if (yych >= 0x0001E800) goto yy4; } else { if (yych <= 0x0001E8D6) { if (yych >= 0x0001E8C7) goto yy4; } else { if (yych <= 0x0001EDFF) goto yy2; if (yych <= 0x0001EE03) goto yy4; } } } else { if (yych <= 0x0001EE23) { if (yych == 0x0001EE20) goto yy2; if (yych <= 0x0001EE22) goto yy4; } else { if (yych <= 0x0001EE26) { if (yych <= 0x0001EE24) goto yy4; } else { if (yych != 0x0001EE28) goto yy4; } } } } else { if (yych <= 0x0001EE46) { if (yych <= 0x0001EE39) { if (yych <= 0x0001EE33) goto yy2; if (yych != 0x0001EE38) goto yy4; } else { if (yych <= 0x0001EE3B) { if (yych >= 0x0001EE3B) goto yy4; } else { if (yych == 0x0001EE42) goto yy4; } } } else { if (yych <= 0x0001EE4B) { if (yych <= 0x0001EE48) { if (yych <= 0x0001EE47) goto yy4; } else { if (yych != 0x0001EE4A) goto yy4; } } else { if (yych <= 0x0001EE4F) { if (yych >= 0x0001EE4D) goto yy4; } else { if (yych <= 0x0001EE50) goto yy2; if (yych <= 0x0001EE52) goto yy4; } } } } } else { if (yych <= 0x0001EE72) { if (yych <= 0x0001EE5D) { if (yych <= 0x0001EE58) { if (yych <= 0x0001EE54) goto yy4; if (yych == 0x0001EE57) goto yy4; } else { if (yych <= 0x0001EE5A) { if (yych <= 0x0001EE59) goto yy4; } else { if (yych != 0x0001EE5C) goto yy4; } } } else { if (yych <= 0x0001EE63) { if (yych <= 0x0001EE5F) { if (yych >= 0x0001EE5F) goto yy4; } else { if (yych <= 0x0001EE60) goto yy2; if (yych <= 0x0001EE62) goto yy4; } } else { if (yych <= 0x0001EE66) { if (yych <= 0x0001EE64) goto yy4; } else { if (yych != 0x0001EE6B) goto yy4; } } } } else { if (yych <= 0x0001EE8A) { if (yych <= 0x0001EE7C) { if (yych <= 0x0001EE73) goto yy2; if (yych != 0x0001EE78) goto yy4; } else { if (yych <= 0x0001EE7E) { if (yych >= 0x0001EE7E) goto yy4; } else { if (yych <= 0x0001EE7F) goto yy2; if (yych <= 0x0001EE89) goto yy4; } } } else { if (yych <= 0x0001EEA9) { if (yych <= 0x0001EEA0) { if (yych <= 0x0001EE9B) goto yy4; } else { if (yych != 0x0001EEA4) goto yy4; } } else { if (yych <= 0x0001EEBB) { if (yych >= 0x0001EEAB) goto yy4; } else { if (yych <= 0x0001EEEF) goto yy2; if (yych <= 0x0001EEF1) goto yy4; } } } } } } else { if (yych <= 0x0001F4FF) { if (yych <= 0x0001F19A) { if (yych <= 0x0001F0CF) { if (yych <= 0x0001F09F) { if (yych <= 0x0001F02B) goto yy4; if (yych <= 0x0001F02F) goto yy2; if (yych <= 0x0001F093) goto yy4; } else { if (yych <= 0x0001F0B0) { if (yych <= 0x0001F0AE) goto yy4; } else { if (yych != 0x0001F0C0) goto yy4; } } } else { if (yych <= 0x0001F10F) { if (yych <= 0x0001F0F5) { if (yych >= 0x0001F0D1) goto yy4; } else { if (yych <= 0x0001F0FF) goto yy2; if (yych <= 0x0001F10C) goto yy4; } } else { if (yych <= 0x0001F12F) { if (yych <= 0x0001F12E) goto yy4; } else { if (yych <= 0x0001F16B) goto yy4; if (yych >= 0x0001F170) goto yy4; } } } } else { if (yych <= 0x0001F2FF) { if (yych <= 0x0001F23A) { if (yych <= 0x0001F1E5) goto yy2; if (yych <= 0x0001F202) goto yy4; if (yych >= 0x0001F210) goto yy4; } else { if (yych <= 0x0001F248) { if (yych >= 0x0001F240) goto yy4; } else { if (yych <= 0x0001F24F) goto yy2; if (yych <= 0x0001F251) goto yy4; } } } else { if (yych <= 0x0001F3CE) { if (yych <= 0x0001F32F) { if (yych <= 0x0001F32C) goto yy4; } else { if (yych <= 0x0001F37D) goto yy4; if (yych >= 0x0001F380) goto yy4; } } else { if (yych <= 0x0001F3F7) { if (yych >= 0x0001F3D4) goto yy4; } else { if (yych <= 0x0001F3FF) goto yy2; if (yych <= 0x0001F4FE) goto yy4; } } } } } else { if (yych <= 0x0001F80B) { if (yych <= 0x0001F6CF) { if (yych <= 0x0001F57A) { if (yych <= 0x0001F54A) goto yy4; if (yych <= 0x0001F54F) goto yy2; if (yych <= 0x0001F579) goto yy4; } else { if (yych <= 0x0001F5A4) { if (yych <= 0x0001F5A3) goto yy4; } else { if (yych <= 0x0001F642) goto yy4; if (yych >= 0x0001F645) goto yy4; } } } else { if (yych <= 0x0001F6FF) { if (yych <= 0x0001F6EC) { if (yych >= 0x0001F6E0) goto yy4; } else { if (yych <= 0x0001F6EF) goto yy2; if (yych <= 0x0001F6F3) goto yy4; } } else { if (yych <= 0x0001F77F) { if (yych <= 0x0001F773) goto yy4; } else { if (yych <= 0x0001F7D4) goto yy4; if (yych >= 0x0001F800) goto yy4; } } } } else { if (yych <= 0x0001FFFF) { if (yych <= 0x0001F859) { if (yych <= 0x0001F80F) goto yy2; if (yych <= 0x0001F847) goto yy4; if (yych >= 0x0001F850) goto yy4; } else { if (yych <= 0x0001F887) { if (yych >= 0x0001F860) goto yy4; } else { if (yych <= 0x0001F88F) goto yy2; if (yych <= 0x0001F8AD) goto yy4; } } } else { if (yych <= 0x0002B81D) { if (yych <= 0x0002A6FF) { if (yych <= 0x0002A6D6) goto yy4; } else { if (yych <= 0x0002B734) goto yy4; if (yych >= 0x0002B740) goto yy4; } } else { if (yych <= 0x0002FA1D) { if (yych >= 0x0002F800) goto yy4; } else { if (yych <= 0x000E00FF) goto yy2; if (yych <= 0x000E01EF) goto yy4; } } } } } } } } } yy2: ++YYCURSOR; #line 13 "encodings/unicode_group_C_u_encoding_policy_substitute.re" { goto C; } #line 2035 "encodings/unicode_group_C_u_encoding_policy_substitute.c" yy4: ++YYCURSOR; #line 14 "encodings/unicode_group_C_u_encoding_policy_substitute.re" { return YYCURSOR == limit; } #line 2040 "encodings/unicode_group_C_u_encoding_policy_substitute.c" } #line 15 "encodings/unicode_group_C_u_encoding_policy_substitute.re" } static const unsigned int chars_C [] = {0x0,0x1f, 0x7f,0x9f, 0xad,0xad, 0x378,0x379, 0x380,0x383, 0x38b,0x38b, 0x38d,0x38d, 0x3a2,0x3a2, 0x530,0x530, 0x557,0x558, 0x560,0x560, 0x588,0x588, 0x58b,0x58c, 0x590,0x590, 0x5c8,0x5cf, 0x5eb,0x5ef, 0x5f5,0x605, 0x61c,0x61d, 0x6dd,0x6dd, 0x70e,0x70f, 0x74b,0x74c, 0x7b2,0x7bf, 0x7fb,0x7ff, 0x82e,0x82f, 0x83f,0x83f, 0x85c,0x85d, 0x85f,0x89f, 0x8b3,0x8e3, 0x984,0x984, 0x98d,0x98e, 0x991,0x992, 0x9a9,0x9a9, 0x9b1,0x9b1, 0x9b3,0x9b5, 0x9ba,0x9bb, 0x9c5,0x9c6, 0x9c9,0x9ca, 0x9cf,0x9d6, 0x9d8,0x9db, 0x9de,0x9de, 0x9e4,0x9e5, 0x9fc,0xa00, 0xa04,0xa04, 0xa0b,0xa0e, 0xa11,0xa12, 0xa29,0xa29, 0xa31,0xa31, 0xa34,0xa34, 0xa37,0xa37, 0xa3a,0xa3b, 0xa3d,0xa3d, 0xa43,0xa46, 0xa49,0xa4a, 0xa4e,0xa50, 0xa52,0xa58, 0xa5d,0xa5d, 0xa5f,0xa65, 0xa76,0xa80, 0xa84,0xa84, 0xa8e,0xa8e, 0xa92,0xa92, 0xaa9,0xaa9, 0xab1,0xab1, 0xab4,0xab4, 0xaba,0xabb, 0xac6,0xac6, 0xaca,0xaca, 0xace,0xacf, 0xad1,0xadf, 0xae4,0xae5, 0xaf2,0xb00, 0xb04,0xb04, 0xb0d,0xb0e, 0xb11,0xb12, 0xb29,0xb29, 0xb31,0xb31, 0xb34,0xb34, 0xb3a,0xb3b, 0xb45,0xb46, 0xb49,0xb4a, 0xb4e,0xb55, 0xb58,0xb5b, 0xb5e,0xb5e, 0xb64,0xb65, 0xb78,0xb81, 0xb84,0xb84, 0xb8b,0xb8d, 0xb91,0xb91, 0xb96,0xb98, 0xb9b,0xb9b, 0xb9d,0xb9d, 0xba0,0xba2, 0xba5,0xba7, 0xbab,0xbad, 0xbba,0xbbd, 0xbc3,0xbc5, 0xbc9,0xbc9, 0xbce,0xbcf, 0xbd1,0xbd6, 0xbd8,0xbe5, 0xbfb,0xbff, 0xc04,0xc04, 0xc0d,0xc0d, 0xc11,0xc11, 0xc29,0xc29, 0xc3a,0xc3c, 0xc45,0xc45, 0xc49,0xc49, 0xc4e,0xc54, 0xc57,0xc57, 0xc5a,0xc5f, 0xc64,0xc65, 0xc70,0xc77, 0xc80,0xc80, 0xc84,0xc84, 0xc8d,0xc8d, 0xc91,0xc91, 0xca9,0xca9, 0xcb4,0xcb4, 0xcba,0xcbb, 0xcc5,0xcc5, 0xcc9,0xcc9, 0xcce,0xcd4, 0xcd7,0xcdd, 0xcdf,0xcdf, 0xce4,0xce5, 0xcf0,0xcf0, 0xcf3,0xd00, 0xd04,0xd04, 0xd0d,0xd0d, 0xd11,0xd11, 0xd3b,0xd3c, 0xd45,0xd45, 0xd49,0xd49, 0xd4f,0xd56, 0xd58,0xd5f, 0xd64,0xd65, 0xd76,0xd78, 0xd80,0xd81, 0xd84,0xd84, 0xd97,0xd99, 0xdb2,0xdb2, 0xdbc,0xdbc, 0xdbe,0xdbf, 0xdc7,0xdc9, 0xdcb,0xdce, 0xdd5,0xdd5, 0xdd7,0xdd7, 0xde0,0xde5, 0xdf0,0xdf1, 0xdf5,0xe00, 0xe3b,0xe3e, 0xe5c,0xe80, 0xe83,0xe83, 0xe85,0xe86, 0xe89,0xe89, 0xe8b,0xe8c, 0xe8e,0xe93, 0xe98,0xe98, 0xea0,0xea0, 0xea4,0xea4, 0xea6,0xea6, 0xea8,0xea9, 0xeac,0xeac, 0xeba,0xeba, 0xebe,0xebf, 0xec5,0xec5, 0xec7,0xec7, 0xece,0xecf, 0xeda,0xedb, 0xee0,0xeff, 0xf48,0xf48, 0xf6d,0xf70, 0xf98,0xf98, 0xfbd,0xfbd, 0xfcd,0xfcd, 0xfdb,0xfff, 0x10c6,0x10c6, 0x10c8,0x10cc, 0x10ce,0x10cf, 0x1249,0x1249, 0x124e,0x124f, 0x1257,0x1257, 0x1259,0x1259, 0x125e,0x125f, 0x1289,0x1289, 0x128e,0x128f, 0x12b1,0x12b1, 0x12b6,0x12b7, 0x12bf,0x12bf, 0x12c1,0x12c1, 0x12c6,0x12c7, 0x12d7,0x12d7, 0x1311,0x1311, 0x1316,0x1317, 0x135b,0x135c, 0x137d,0x137f, 0x139a,0x139f, 0x13f5,0x13ff, 0x169d,0x169f, 0x16f9,0x16ff, 0x170d,0x170d, 0x1715,0x171f, 0x1737,0x173f, 0x1754,0x175f, 0x176d,0x176d, 0x1771,0x1771, 0x1774,0x177f, 0x17de,0x17df, 0x17ea,0x17ef, 0x17fa,0x17ff, 0x180e,0x180f, 0x181a,0x181f, 0x1878,0x187f, 0x18ab,0x18af, 0x18f6,0x18ff, 0x191f,0x191f, 0x192c,0x192f, 0x193c,0x193f, 0x1941,0x1943, 0x196e,0x196f, 0x1975,0x197f, 0x19ac,0x19af, 0x19ca,0x19cf, 0x19db,0x19dd, 0x1a1c,0x1a1d, 0x1a5f,0x1a5f, 0x1a7d,0x1a7e, 0x1a8a,0x1a8f, 0x1a9a,0x1a9f, 0x1aae,0x1aaf, 0x1abf,0x1aff, 0x1b4c,0x1b4f, 0x1b7d,0x1b7f, 0x1bf4,0x1bfb, 0x1c38,0x1c3a, 0x1c4a,0x1c4c, 0x1c80,0x1cbf, 0x1cc8,0x1ccf, 0x1cf7,0x1cf7, 0x1cfa,0x1cff, 0x1df6,0x1dfb, 0x1f16,0x1f17, 0x1f1e,0x1f1f, 0x1f46,0x1f47, 0x1f4e,0x1f4f, 0x1f58,0x1f58, 0x1f5a,0x1f5a, 0x1f5c,0x1f5c, 0x1f5e,0x1f5e, 0x1f7e,0x1f7f, 0x1fb5,0x1fb5, 0x1fc5,0x1fc5, 0x1fd4,0x1fd5, 0x1fdc,0x1fdc, 0x1ff0,0x1ff1, 0x1ff5,0x1ff5, 0x1fff,0x1fff, 0x200b,0x200f, 0x202a,0x202e, 0x2060,0x206f, 0x2072,0x2073, 0x208f,0x208f, 0x209d,0x209f, 0x20be,0x20cf, 0x20f1,0x20ff, 0x218a,0x218f, 0x23fb,0x23ff, 0x2427,0x243f, 0x244b,0x245f, 0x2b74,0x2b75, 0x2b96,0x2b97, 0x2bba,0x2bbc, 0x2bc9,0x2bc9, 0x2bd2,0x2bff, 0x2c2f,0x2c2f, 0x2c5f,0x2c5f, 0x2cf4,0x2cf8, 0x2d26,0x2d26, 0x2d28,0x2d2c, 0x2d2e,0x2d2f, 0x2d68,0x2d6e, 0x2d71,0x2d7e, 0x2d97,0x2d9f, 0x2da7,0x2da7, 0x2daf,0x2daf, 0x2db7,0x2db7, 0x2dbf,0x2dbf, 0x2dc7,0x2dc7, 0x2dcf,0x2dcf, 0x2dd7,0x2dd7, 0x2ddf,0x2ddf, 0x2e43,0x2e7f, 0x2e9a,0x2e9a, 0x2ef4,0x2eff, 0x2fd6,0x2fef, 0x2ffc,0x2fff, 0x3040,0x3040, 0x3097,0x3098, 0x3100,0x3104, 0x312e,0x3130, 0x318f,0x318f, 0x31bb,0x31bf, 0x31e4,0x31ef, 0x321f,0x321f, 0x32ff,0x32ff, 0x4db6,0x4dbf, 0x9fcd,0x9fff, 0xa48d,0xa48f, 0xa4c7,0xa4cf, 0xa62c,0xa63f, 0xa69e,0xa69e, 0xa6f8,0xa6ff, 0xa78f,0xa78f, 0xa7ae,0xa7af, 0xa7b2,0xa7f6, 0xa82c,0xa82f, 0xa83a,0xa83f, 0xa878,0xa87f, 0xa8c5,0xa8cd, 0xa8da,0xa8df, 0xa8fc,0xa8ff, 0xa954,0xa95e, 0xa97d,0xa97f, 0xa9ce,0xa9ce, 0xa9da,0xa9dd, 0xa9ff,0xa9ff, 0xaa37,0xaa3f, 0xaa4e,0xaa4f, 0xaa5a,0xaa5b, 0xaac3,0xaada, 0xaaf7,0xab00, 0xab07,0xab08, 0xab0f,0xab10, 0xab17,0xab1f, 0xab27,0xab27, 0xab2f,0xab2f, 0xab60,0xab63, 0xab66,0xabbf, 0xabee,0xabef, 0xabfa,0xabff, 0xd7a4,0xd7af, 0xd7c7,0xd7ca, 0xd7fc,0xf8ff, 0xfa6e,0xfa6f, 0xfada,0xfaff, 0xfb07,0xfb12, 0xfb18,0xfb1c, 0xfb37,0xfb37, 0xfb3d,0xfb3d, 0xfb3f,0xfb3f, 0xfb42,0xfb42, 0xfb45,0xfb45, 0xfbc2,0xfbd2, 0xfd40,0xfd4f, 0xfd90,0xfd91, 0xfdc8,0xfdef, 0xfdfe,0xfdff, 0xfe1a,0xfe1f, 0xfe2e,0xfe2f, 0xfe53,0xfe53, 0xfe67,0xfe67, 0xfe6c,0xfe6f, 0xfe75,0xfe75, 0xfefd,0xff00, 0xffbf,0xffc1, 0xffc8,0xffc9, 0xffd0,0xffd1, 0xffd8,0xffd9, 0xffdd,0xffdf, 0xffe7,0xffe7, 0xffef,0xfffb, 0xfffe,0xffff, 0x1000c,0x1000c, 0x10027,0x10027, 0x1003b,0x1003b, 0x1003e,0x1003e, 0x1004e,0x1004f, 0x1005e,0x1007f, 0x100fb,0x100ff, 0x10103,0x10106, 0x10134,0x10136, 0x1018d,0x1018f, 0x1019c,0x1019f, 0x101a1,0x101cf, 0x101fe,0x1027f, 0x1029d,0x1029f, 0x102d1,0x102df, 0x102fc,0x102ff, 0x10324,0x1032f, 0x1034b,0x1034f, 0x1037b,0x1037f, 0x1039e,0x1039e, 0x103c4,0x103c7, 0x103d6,0x103ff, 0x1049e,0x1049f, 0x104aa,0x104ff, 0x10528,0x1052f, 0x10564,0x1056e, 0x10570,0x105ff, 0x10737,0x1073f, 0x10756,0x1075f, 0x10768,0x107ff, 0x10806,0x10807, 0x10809,0x10809, 0x10836,0x10836, 0x10839,0x1083b, 0x1083d,0x1083e, 0x10856,0x10856, 0x1089f,0x108a6, 0x108b0,0x108ff, 0x1091c,0x1091e, 0x1093a,0x1093e, 0x10940,0x1097f, 0x109b8,0x109bd, 0x109c0,0x109ff, 0x10a04,0x10a04, 0x10a07,0x10a0b, 0x10a14,0x10a14, 0x10a18,0x10a18, 0x10a34,0x10a37, 0x10a3b,0x10a3e, 0x10a48,0x10a4f, 0x10a59,0x10a5f, 0x10aa0,0x10abf, 0x10ae7,0x10aea, 0x10af7,0x10aff, 0x10b36,0x10b38, 0x10b56,0x10b57, 0x10b73,0x10b77, 0x10b92,0x10b98, 0x10b9d,0x10ba8, 0x10bb0,0x10bff, 0x10c49,0x10e5f, 0x10e7f,0x10fff, 0x1104e,0x11051, 0x11070,0x1107e, 0x110bd,0x110bd, 0x110c2,0x110cf, 0x110e9,0x110ef, 0x110fa,0x110ff, 0x11135,0x11135, 0x11144,0x1114f, 0x11177,0x1117f, 0x111c9,0x111cc, 0x111ce,0x111cf, 0x111db,0x111e0, 0x111f5,0x111ff, 0x11212,0x11212, 0x1123e,0x112af, 0x112eb,0x112ef, 0x112fa,0x11300, 0x11304,0x11304, 0x1130d,0x1130e, 0x11311,0x11312, 0x11329,0x11329, 0x11331,0x11331, 0x11334,0x11334, 0x1133a,0x1133b, 0x11345,0x11346, 0x11349,0x1134a, 0x1134e,0x11356, 0x11358,0x1135c, 0x11364,0x11365, 0x1136d,0x1136f, 0x11375,0x1147f, 0x114c8,0x114cf, 0x114da,0x1157f, 0x115b6,0x115b7, 0x115ca,0x115ff, 0x11645,0x1164f, 0x1165a,0x1167f, 0x116b8,0x116bf, 0x116ca,0x1189f, 0x118f3,0x118fe, 0x11900,0x11abf, 0x11af9,0x11fff, 0x12399,0x123ff, 0x1246f,0x1246f, 0x12475,0x12fff, 0x1342f,0x167ff, 0x16a39,0x16a3f, 0x16a5f,0x16a5f, 0x16a6a,0x16a6d, 0x16a70,0x16acf, 0x16aee,0x16aef, 0x16af6,0x16aff, 0x16b46,0x16b4f, 0x16b5a,0x16b5a, 0x16b62,0x16b62, 0x16b78,0x16b7c, 0x16b90,0x16eff, 0x16f45,0x16f4f, 0x16f7f,0x16f8e, 0x16fa0,0x1afff, 0x1b002,0x1bbff, 0x1bc6b,0x1bc6f, 0x1bc7d,0x1bc7f, 0x1bc89,0x1bc8f, 0x1bc9a,0x1bc9b, 0x1bca0,0x1cfff, 0x1d0f6,0x1d0ff, 0x1d127,0x1d128, 0x1d173,0x1d17a, 0x1d1de,0x1d1ff, 0x1d246,0x1d2ff, 0x1d357,0x1d35f, 0x1d372,0x1d3ff, 0x1d455,0x1d455, 0x1d49d,0x1d49d, 0x1d4a0,0x1d4a1, 0x1d4a3,0x1d4a4, 0x1d4a7,0x1d4a8, 0x1d4ad,0x1d4ad, 0x1d4ba,0x1d4ba, 0x1d4bc,0x1d4bc, 0x1d4c4,0x1d4c4, 0x1d506,0x1d506, 0x1d50b,0x1d50c, 0x1d515,0x1d515, 0x1d51d,0x1d51d, 0x1d53a,0x1d53a, 0x1d53f,0x1d53f, 0x1d545,0x1d545, 0x1d547,0x1d549, 0x1d551,0x1d551, 0x1d6a6,0x1d6a7, 0x1d7cc,0x1d7cd, 0x1d800,0x1e7ff, 0x1e8c5,0x1e8c6, 0x1e8d7,0x1edff, 0x1ee04,0x1ee04, 0x1ee20,0x1ee20, 0x1ee23,0x1ee23, 0x1ee25,0x1ee26, 0x1ee28,0x1ee28, 0x1ee33,0x1ee33, 0x1ee38,0x1ee38, 0x1ee3a,0x1ee3a, 0x1ee3c,0x1ee41, 0x1ee43,0x1ee46, 0x1ee48,0x1ee48, 0x1ee4a,0x1ee4a, 0x1ee4c,0x1ee4c, 0x1ee50,0x1ee50, 0x1ee53,0x1ee53, 0x1ee55,0x1ee56, 0x1ee58,0x1ee58, 0x1ee5a,0x1ee5a, 0x1ee5c,0x1ee5c, 0x1ee5e,0x1ee5e, 0x1ee60,0x1ee60, 0x1ee63,0x1ee63, 0x1ee65,0x1ee66, 0x1ee6b,0x1ee6b, 0x1ee73,0x1ee73, 0x1ee78,0x1ee78, 0x1ee7d,0x1ee7d, 0x1ee7f,0x1ee7f, 0x1ee8a,0x1ee8a, 0x1ee9c,0x1eea0, 0x1eea4,0x1eea4, 0x1eeaa,0x1eeaa, 0x1eebc,0x1eeef, 0x1eef2,0x1efff, 0x1f02c,0x1f02f, 0x1f094,0x1f09f, 0x1f0af,0x1f0b0, 0x1f0c0,0x1f0c0, 0x1f0d0,0x1f0d0, 0x1f0f6,0x1f0ff, 0x1f10d,0x1f10f, 0x1f12f,0x1f12f, 0x1f16c,0x1f16f, 0x1f19b,0x1f1e5, 0x1f203,0x1f20f, 0x1f23b,0x1f23f, 0x1f249,0x1f24f, 0x1f252,0x1f2ff, 0x1f32d,0x1f32f, 0x1f37e,0x1f37f, 0x1f3cf,0x1f3d3, 0x1f3f8,0x1f3ff, 0x1f4ff,0x1f4ff, 0x1f54b,0x1f54f, 0x1f57a,0x1f57a, 0x1f5a4,0x1f5a4, 0x1f643,0x1f644, 0x1f6d0,0x1f6df, 0x1f6ed,0x1f6ef, 0x1f6f4,0x1f6ff, 0x1f774,0x1f77f, 0x1f7d5,0x1f7ff, 0x1f80c,0x1f80f, 0x1f848,0x1f84f, 0x1f85a,0x1f85f, 0x1f888,0x1f88f, 0x1f8ae,0x1ffff, 0x2a6d7,0x2a6ff, 0x2b735,0x2b73f, 0x2b81e,0x2f7ff, 0x2fa1e,0xe00ff, 0xe01f0,0x10ffff, 0x20,0x20}; static unsigned int encode_utf32 (const unsigned int * ranges, unsigned int ranges_count, unsigned int * s) { unsigned int * const s_start = s; for (unsigned int i = 0; i < ranges_count; i += 2) for (unsigned int j = ranges[i]; j <= ranges[i + 1]; ++j) *s++ = j; return s - s_start; } int main () { unsigned int * buffer_C = new unsigned int [1001307]; YYCTYPE * s = (YYCTYPE *) buffer_C; unsigned int buffer_len = encode_utf32 (chars_C, sizeof (chars_C) / sizeof (unsigned int), buffer_C); /* convert 32-bit code units to YYCTYPE; reuse the same buffer */ for (unsigned int i = 0; i < buffer_len; ++i) s[i] = buffer_C[i]; if (!scan (s, s + buffer_len)) printf("test 'C' failed\n"); delete [] buffer_C; return 0; }
543979.c
/****************************************************************************** * * Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ #define _RTL8188E_PHYCFG_C_ #include <drv_types.h> #include <rtl8188e_hal.h> /*---------------------------Define Local Constant---------------------------*/ /* Channel switch:The size of command tables for switch channel*/ #define MAX_PRECMD_CNT 16 #define MAX_RFDEPENDCMD_CNT 16 #define MAX_POSTCMD_CNT 16 #define MAX_DOZE_WAITING_TIMES_9x 64 /*---------------------------Define Local Constant---------------------------*/ /*------------------------Define global variable-----------------------------*/ /*------------------------Define local variable------------------------------*/ /*--------------------Define export function prototype-----------------------*/ /* Please refer to header file *--------------------Define export function prototype-----------------------*/ /*----------------------------Function Body----------------------------------*/ /* * 1. BB register R/W API * */ #if (SIC_ENABLE == 1) static BOOLEAN sic_IsSICReady( IN PADAPTER Adapter ) { BOOLEAN bRet = _FALSE; u32 retryCnt = 0; u8 sic_cmd = 0xff; while (1) { if (retryCnt++ >= SIC_MAX_POLL_CNT) { /* RTPRINT(FPHY, (PHY_SICR|PHY_SICW), ("[SIC], sic_IsSICReady() return FALSE\n")); */ return _FALSE; } /* if(RT_SDIO_CANNOT_IO(Adapter)) */ /* return _FALSE; */ sic_cmd = rtw_read8(Adapter, SIC_CMD_REG); /* sic_cmd = PlatformEFIORead1Byte(Adapter, SIC_CMD_REG); */ #if (SIC_HW_SUPPORT == 1) sic_cmd &= 0xf0; /* [7:4] */ #endif /* RTPRINT(FPHY, (PHY_SICR|PHY_SICW), ("[SIC], sic_IsSICReady(), readback 0x%x=0x%x\n", SIC_CMD_REG, sic_cmd)); */ if (sic_cmd == SIC_CMD_READY) return _TRUE; else { rtw_msleep_os(1); /* delay_ms(1); */ } } return bRet; } /* u32 sic_CalculateBitShift( u32 BitMask ) { u32 i; for(i=0; i<=31; i++) { if ( ((BitMask>>i) & 0x1 ) == 1) break; } return i; } */ static u32 sic_Read4Byte( PVOID Adapter, u32 offset ) { u32 u4ret = 0xffffffff; #if RTL8188E_SUPPORT == 1 u8 retry = 0; #endif /* RTPRINT(FPHY, PHY_SICR, ("[SIC], sic_Read4Byte(): read offset(%#x)\n", offset)); */ if (sic_IsSICReady(Adapter)) { #if (SIC_HW_SUPPORT == 1) rtw_write8(Adapter, SIC_CMD_REG, SIC_CMD_PREREAD); /* PlatformEFIOWrite1Byte(Adapter, SIC_CMD_REG, SIC_CMD_PREREAD); */ /* RTPRINT(FPHY, PHY_SICR, ("write cmdreg 0x%x = 0x%x\n", SIC_CMD_REG, SIC_CMD_PREREAD)); */ #endif rtw_write8(Adapter, SIC_ADDR_REG, (u8)(offset & 0xff)); /* PlatformEFIOWrite1Byte(Adapter, SIC_ADDR_REG, (u1Byte)(offset&0xff)); */ /* RTPRINT(FPHY, PHY_SICR, ("write 0x%x = 0x%x\n", SIC_ADDR_REG, (u1Byte)(offset&0xff))); */ rtw_write8(Adapter, SIC_ADDR_REG + 1, (u8)((offset & 0xff00) >> 8)); /* PlatformEFIOWrite1Byte(Adapter, SIC_ADDR_REG+1, (u1Byte)((offset&0xff00)>>8)); */ /* RTPRINT(FPHY, PHY_SICR, ("write 0x%x = 0x%x\n", SIC_ADDR_REG+1, (u1Byte)((offset&0xff00)>>8))); */ rtw_write8(Adapter, SIC_CMD_REG, SIC_CMD_READ); /* PlatformEFIOWrite1Byte(Adapter, SIC_CMD_REG, SIC_CMD_READ); */ /* RTPRINT(FPHY, PHY_SICR, ("write cmdreg 0x%x = 0x%x\n", SIC_CMD_REG, SIC_CMD_READ)); */ #if RTL8188E_SUPPORT == 1 retry = 4; while (retry--) { rtw_udelay_os(50); /* PlatformStallExecution(50); */ } #else rtw_udelay_os(200); /* PlatformStallExecution(200); */ #endif if (sic_IsSICReady(Adapter)) { u4ret = rtw_read32(Adapter, SIC_DATA_REG); /* u4ret = PlatformEFIORead4Byte(Adapter, SIC_DATA_REG); */ /* RTPRINT(FPHY, PHY_SICR, ("read 0x%x = 0x%x\n", SIC_DATA_REG, u4ret)); */ /* DbgPrint("<===Read 0x%x = 0x%x\n", offset, u4ret); */ } } return u4ret; } static VOID sic_Write4Byte( PVOID Adapter, u32 offset, u32 data ) { #if RTL8188E_SUPPORT == 1 u8 retry = 6; #endif /* DbgPrint("=>Write 0x%x = 0x%x\n", offset, data); */ /* RTPRINT(FPHY, PHY_SICW, ("[SIC], sic_Write4Byte(): write offset(%#x)=0x%x\n", offset, data)); */ if (sic_IsSICReady(Adapter)) { #if (SIC_HW_SUPPORT == 1) rtw_write8(Adapter, SIC_CMD_REG, SIC_CMD_PREWRITE); /* PlatformEFIOWrite1Byte(Adapter, SIC_CMD_REG, SIC_CMD_PREWRITE); */ /* RTPRINT(FPHY, PHY_SICW, ("write data 0x%x = 0x%x\n", SIC_CMD_REG, SIC_CMD_PREWRITE)); */ #endif rtw_write8(Adapter, SIC_ADDR_REG, (u8)(offset & 0xff)); /* PlatformEFIOWrite1Byte(Adapter, SIC_ADDR_REG, (u1Byte)(offset&0xff)); */ /* RTPRINT(FPHY, PHY_SICW, ("write 0x%x=0x%x\n", SIC_ADDR_REG, (u1Byte)(offset&0xff))); */ rtw_write8(Adapter, SIC_ADDR_REG + 1, (u8)((offset & 0xff00) >> 8)); /* PlatformEFIOWrite1Byte(Adapter, SIC_ADDR_REG+1, (u1Byte)((offset&0xff00)>>8)); */ /* RTPRINT(FPHY, PHY_SICW, ("write 0x%x=0x%x\n", (SIC_ADDR_REG+1), (u1Byte)((offset&0xff00)>>8))); */ rtw_write32(Adapter, SIC_DATA_REG, (u32)data); /* PlatformEFIOWrite4Byte(Adapter, SIC_DATA_REG, (u4Byte)data); */ /* RTPRINT(FPHY, PHY_SICW, ("write data 0x%x = 0x%x\n", SIC_DATA_REG, data)); */ rtw_write8(Adapter, SIC_CMD_REG, SIC_CMD_WRITE); /* PlatformEFIOWrite1Byte(Adapter, SIC_CMD_REG, SIC_CMD_WRITE); */ /* RTPRINT(FPHY, PHY_SICW, ("write data 0x%x = 0x%x\n", SIC_CMD_REG, SIC_CMD_WRITE)); */ #if RTL8188E_SUPPORT == 1 while (retry--) { rtw_udelay_os(50); /* PlatformStallExecution(50); */ } #else rtw_udelay_os(150); /* PlatformStallExecution(150); */ #endif } } /* ************************************************************ * extern function * ************************************************************ */ static VOID SIC_SetBBReg( IN PADAPTER Adapter, IN u32 RegAddr, IN u32 BitMask, IN u32 Data ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); u32 OriginalValue, BitShift; u16 BBWaitCounter = 0; /* RTPRINT(FPHY, PHY_SICW, ("[SIC], SIC_SetBBReg() start\n")); */ #if 0 while (PlatformAtomicExchange(&pHalData->bChangeBBInProgress, _TRUE) == _TRUE) { BBWaitCounter++; delay_ms(10); /* 1 ms */ if ((BBWaitCounter > 100) || RT_CANNOT_IO(Adapter)) { /* Wait too long, return FALSE to avoid to be stuck here. */ RTPRINT(FPHY, PHY_SICW, ("[SIC], SIC_SetBBReg(), Fail to set BB offset(%#x)!!, WaitCnt(%d)\n", RegAddr, BBWaitCounter)); return; } } #endif /* */ /* Critical section start */ /* */ /* RTPRINT(FPHY, PHY_SICW, ("[SIC], SIC_SetBBReg(), mask=0x%x, addr[0x%x]=0x%x\n", BitMask, RegAddr, Data)); */ if (BitMask != bMaskDWord) { /* if not "double word" write */ OriginalValue = sic_Read4Byte(Adapter, RegAddr); /* BitShift = sic_CalculateBitShift(BitMask); */ BitShift = PHY_CalculateBitShift(BitMask); Data = (((OriginalValue)&(~BitMask)) | (Data << BitShift)); } sic_Write4Byte(Adapter, RegAddr, Data); /* PlatformAtomicExchange(&pHalData->bChangeBBInProgress, _FALSE); */ /* RTPRINT(FPHY, PHY_SICW, ("[SIC], SIC_SetBBReg() end\n")); */ } static u32 SIC_QueryBBReg( IN PADAPTER Adapter, IN u32 RegAddr, IN u32 BitMask ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); u32 ReturnValue = 0, OriginalValue, BitShift; u16 BBWaitCounter = 0; /* RTPRINT(FPHY, PHY_SICR, ("[SIC], SIC_QueryBBReg() start\n")); */ #if 0 while (PlatformAtomicExchange(&pHalData->bChangeBBInProgress, _TRUE) == _TRUE) { BBWaitCounter++; delay_ms(10); /* 10 ms */ if ((BBWaitCounter > 100) || RT_CANNOT_IO(Adapter)) { /* Wait too long, return FALSE to avoid to be stuck here. */ RTPRINT(FPHY, PHY_SICW, ("[SIC], SIC_QueryBBReg(), Fail to query BB offset(%#x)!!, WaitCnt(%d)\n", RegAddr, BBWaitCounter)); return ReturnValue; } } #endif OriginalValue = sic_Read4Byte(Adapter, RegAddr); /* BitShift = sic_CalculateBitShift(BitMask); */ BitShift = PHY_CalculateBitShift(BitMask); ReturnValue = (OriginalValue & BitMask) >> BitShift; /* RTPRINT(FPHY, PHY_SICR, ("[SIC], SIC_QueryBBReg(), 0x%x=0x%x\n", RegAddr, OriginalValue)); */ /* RTPRINT(FPHY, PHY_SICR, ("[SIC], SIC_QueryBBReg() end\n")); */ /* PlatformAtomicExchange(&pHalData->bChangeBBInProgress, _FALSE); */ return ReturnValue; } VOID SIC_Init( IN PADAPTER Adapter ) { /* Here we need to write 0x1b8~0x1bf = 0 after fw is downloaded */ /* because for 8723E at beginning 0x1b8=0x1e, that will cause */ /* sic always not be ready */ #if (SIC_HW_SUPPORT == 1) /* RTPRINT(FPHY, PHY_SICR, ("[SIC], SIC_Init(), write 0x%x = 0x%x\n", */ /* SIC_INIT_REG, SIC_INIT_VAL)); */ rtw_write8(Adapter, SIC_INIT_REG, SIC_INIT_VAL); /* PlatformEFIOWrite1Byte(Adapter, SIC_INIT_REG, SIC_INIT_VAL); */ /* RTPRINT(FPHY, PHY_SICR, ("[SIC], SIC_Init(), write 0x%x = 0x%x\n", */ /* SIC_CMD_REG, SIC_CMD_INIT)); */ rtw_write8(Adapter, SIC_CMD_REG, SIC_CMD_INIT); /* PlatformEFIOWrite1Byte(Adapter, SIC_CMD_REG, SIC_CMD_INIT); */ #else /* RTPRINT(FPHY, PHY_SICR, ("[SIC], SIC_Init(), write 0x1b8~0x1bf = 0x0\n")); */ rtw_write32(Adapter, SIC_CMD_REG, 0); /* PlatformEFIOWrite4Byte(Adapter, SIC_CMD_REG, 0); */ rtw_write32(Adapter, SIC_CMD_REG + 4, 0); /* PlatformEFIOWrite4Byte(Adapter, SIC_CMD_REG+4, 0); */ #endif } static BOOLEAN SIC_LedOff( IN PADAPTER Adapter ) { /* When SIC is enabled, led pin will be used as debug pin, */ /* so don't execute led function when SIC is enabled. */ return _TRUE; } #endif /** * Function: PHY_QueryBBReg * * OverView: Read "sepcific bits" from BB register * * Input: * PADAPTER Adapter, * u4Byte RegAddr, //The target address to be readback * u4Byte BitMask //The target bit position in the target address * //to be readback * Output: None * Return: u4Byte Data //The readback register value * Note: This function is equal to "GetRegSetting" in PHY programming guide */ u32 PHY_QueryBBReg8188E( IN PADAPTER Adapter, IN u32 RegAddr, IN u32 BitMask ) { u32 ReturnValue = 0, OriginalValue, BitShift; u16 BBWaitCounter = 0; #if (DISABLE_BB_RF == 1) return 0; #endif #if (SIC_ENABLE == 1) return SIC_QueryBBReg(Adapter, RegAddr, BitMask); #endif OriginalValue = rtw_read32(Adapter, RegAddr); BitShift = PHY_CalculateBitShift(BitMask); ReturnValue = (OriginalValue & BitMask) >> BitShift; /* RTPRINT(FPHY, PHY_BBR, ("BBR MASK=0x%lx Addr[0x%lx]=0x%lx\n", BitMask, RegAddr, OriginalValue)); */ return ReturnValue; } /** * Function: PHY_SetBBReg * * OverView: Write "Specific bits" to BB register (page 8~) * * Input: * PADAPTER Adapter, * u4Byte RegAddr, //The target address to be modified * u4Byte BitMask //The target bit position in the target address * //to be modified * u4Byte Data //The new register value in the target bit position * //of the target address * * Output: None * Return: None * Note: This function is equal to "PutRegSetting" in PHY programming guide */ VOID PHY_SetBBReg8188E( IN PADAPTER Adapter, IN u32 RegAddr, IN u32 BitMask, IN u32 Data ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); /* u16 BBWaitCounter = 0; */ u32 OriginalValue, BitShift; #if (DISABLE_BB_RF == 1) return; #endif #if (SIC_ENABLE == 1) SIC_SetBBReg(Adapter, RegAddr, BitMask, Data); return; #endif if (BitMask != bMaskDWord) { /* if not "double word" write */ OriginalValue = rtw_read32(Adapter, RegAddr); BitShift = PHY_CalculateBitShift(BitMask); Data = ((OriginalValue & (~BitMask)) | ((Data << BitShift) & BitMask)); } rtw_write32(Adapter, RegAddr, Data); /* RTPRINT(FPHY, PHY_BBW, ("BBW MASK=0x%lx Addr[0x%lx]=0x%lx\n", BitMask, RegAddr, Data)); */ } /* * 2. RF register R/W API * ** * Function: phy_RFSerialRead * * OverView: Read regster from RF chips * * Input: * PADAPTER Adapter, * u8 eRFPath, //Radio path of A/B/C/D * u4Byte Offset, //The target address to be read * * Output: None * Return: u4Byte reback value * Note: Threre are three types of serial operations: * 1. Software serial write * 2. Hardware LSSI-Low Speed Serial Interface * 3. Hardware HSSI-High speed * serial write. Driver need to implement (1) and (2). * This function is equal to the combination of RF_ReadReg() and RFLSSIRead() */ static u32 phy_RFSerialRead( IN PADAPTER Adapter, IN u8 eRFPath, IN u32 Offset ) { u32 retValue = 0; HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); BB_REGISTER_DEFINITION_T *pPhyReg = &pHalData->PHYRegDef[eRFPath]; u32 NewOffset; u32 tmplong, tmplong2; u8 RfPiEnable = 0; _enter_critical_mutex(&(adapter_to_dvobj(Adapter)->rf_read_reg_mutex) , NULL); #if 0 if (pHalData->RFChipID == RF_8225 && Offset > 0x24) /* 36 valid regs */ return retValue; if (pHalData->RFChipID == RF_8256 && Offset > 0x2D) /* 45 valid regs */ return retValue; #endif /* */ /* Make sure RF register offset is correct */ /* */ Offset &= 0xff; /* */ /* Switch page for 8256 RF IC */ /* */ NewOffset = Offset; /* 2009/06/17 MH We can not execute IO for power save or other accident mode. */ /* if(RT_CANNOT_IO(Adapter)) */ /* { */ /* RTPRINT(FPHY, PHY_RFR, ("phy_RFSerialRead return all one\n")); */ /* return 0xFFFFFFFF; */ /* } */ /* For 92S LSSI Read RFLSSIRead */ /* For RF A/B write 0x824/82c(does not work in the future) */ /* We must use 0x824 for RF A and B to execute read trigger */ tmplong = phy_query_bb_reg(Adapter, rFPGA0_XA_HSSIParameter2, bMaskDWord); if (eRFPath == RF_PATH_A) tmplong2 = tmplong; else tmplong2 = phy_query_bb_reg(Adapter, pPhyReg->rfHSSIPara2, bMaskDWord); tmplong2 = (tmplong2 & (~bLSSIReadAddress)) | (NewOffset << 23) | bLSSIReadEdge; /* T65 RF */ phy_set_bb_reg(Adapter, rFPGA0_XA_HSSIParameter2, bMaskDWord, tmplong & (~bLSSIReadEdge)); rtw_udelay_os(10);/* PlatformStallExecution(10); */ phy_set_bb_reg(Adapter, pPhyReg->rfHSSIPara2, bMaskDWord, tmplong2); rtw_udelay_os(100);/* PlatformStallExecution(100); */ /* phy_set_bb_reg(Adapter, rFPGA0_XA_HSSIParameter2, bMaskDWord, tmplong|bLSSIReadEdge); */ rtw_udelay_os(10);/* PlatformStallExecution(10); */ if (eRFPath == RF_PATH_A) RfPiEnable = (u8)phy_query_bb_reg(Adapter, rFPGA0_XA_HSSIParameter1, BIT8); else if (eRFPath == RF_PATH_B) RfPiEnable = (u8)phy_query_bb_reg(Adapter, rFPGA0_XB_HSSIParameter1, BIT8); if (RfPiEnable) { /* Read from BBreg8b8, 12 bits for 8190, 20bits for T65 RF */ retValue = phy_query_bb_reg(Adapter, pPhyReg->rfLSSIReadBackPi, bLSSIReadBackData); /* RTW_INFO("Readback from RF-PI : 0x%x\n", retValue); */ } else { /* Read from BBreg8a0, 12 bits for 8190, 20 bits for T65 RF */ retValue = phy_query_bb_reg(Adapter, pPhyReg->rfLSSIReadBack, bLSSIReadBackData); /* RTW_INFO("Readback from RF-SI : 0x%x\n", retValue); */ } /* RTW_INFO("RFR-%d Addr[0x%x]=0x%x\n", eRFPath, pPhyReg->rfLSSIReadBack, retValue); */ _exit_critical_mutex(&(adapter_to_dvobj(Adapter)->rf_read_reg_mutex) , NULL); return retValue; } /** * Function: phy_RFSerialWrite * * OverView: Write data to RF register (page 8~) * * Input: * PADAPTER Adapter, * u8 eRFPath, //Radio path of A/B/C/D * u4Byte Offset, //The target address to be read * u4Byte Data //The new register Data in the target bit position * //of the target to be read * * Output: None * Return: None * Note: Threre are three types of serial operations: * 1. Software serial write * 2. Hardware LSSI-Low Speed Serial Interface * 3. Hardware HSSI-High speed * serial write. Driver need to implement (1) and (2). * This function is equal to the combination of RF_ReadReg() and RFLSSIRead() * * Note: For RF8256 only * The total count of RTL8256(Zebra4) register is around 36 bit it only employs * 4-bit RF address. RTL8256 uses "register mode control bit" (Reg00[12], Reg00[10]) * to access register address bigger than 0xf. See "Appendix-4 in PHY Configuration * programming guide" for more details. * Thus, we define a sub-finction for RTL8526 register address conversion * =========================================================== * Register Mode RegCTL[1] RegCTL[0] Note * (Reg00[12]) (Reg00[10]) * =========================================================== * Reg_Mode0 0 x Reg 0 ~15(0x0 ~ 0xf) * ------------------------------------------------------------------ * Reg_Mode1 1 0 Reg 16 ~30(0x1 ~ 0xf) * ------------------------------------------------------------------ * Reg_Mode2 1 1 Reg 31 ~ 45(0x1 ~ 0xf) * ------------------------------------------------------------------ * * 2008/09/02 MH Add 92S RF definition * * * */ static VOID phy_RFSerialWrite( IN PADAPTER Adapter, IN u8 eRFPath, IN u32 Offset, IN u32 Data ) { u32 DataAndAddr = 0; HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); BB_REGISTER_DEFINITION_T *pPhyReg = &pHalData->PHYRegDef[eRFPath]; u32 NewOffset; #if 0 /* <Roger_TODO> We should check valid regs for RF_6052 case. */ if (pHalData->RFChipID == RF_8225 && Offset > 0x24) /* 36 valid regs */ return; if (pHalData->RFChipID == RF_8256 && Offset > 0x2D) /* 45 valid regs */ return; #endif /* 2009/06/17 MH We can not execute IO for power save or other accident mode. */ /* if(RT_CANNOT_IO(Adapter)) */ /* { */ /* RTPRINT(FPHY, PHY_RFW, ("phy_RFSerialWrite stop\n")); */ /* return; */ /* } */ Offset &= 0xff; /* */ /* Shadow Update */ /* */ /* PHY_RFShadowWrite(Adapter, eRFPath, Offset, Data); */ /* */ /* Switch page for 8256 RF IC */ /* */ NewOffset = Offset; /* */ /* Put write addr in [5:0] and write data in [31:16] */ /* */ /* DataAndAddr = (Data<<16) | (NewOffset&0x3f); */ DataAndAddr = ((NewOffset << 20) | (Data & 0x000fffff)) & 0x0fffffff; /* T65 RF */ /* */ /* Write Operation */ /* */ phy_set_bb_reg(Adapter, pPhyReg->rf3wireOffset, bMaskDWord, DataAndAddr); /* RTPRINT(FPHY, PHY_RFW, ("RFW-%d Addr[0x%lx]=0x%lx\n", eRFPath, pPhyReg->rf3wireOffset, DataAndAddr)); */ } /** * Function: PHY_QueryRFReg * * OverView: Query "Specific bits" to RF register (page 8~) * * Input: * PADAPTER Adapter, * u8 eRFPath, //Radio path of A/B/C/D * u4Byte RegAddr, //The target address to be read * u4Byte BitMask //The target bit position in the target address * //to be read * * Output: None * Return: u4Byte Readback value * Note: This function is equal to "GetRFRegSetting" in PHY programming guide */ u32 PHY_QueryRFReg8188E( IN PADAPTER Adapter, IN u8 eRFPath, IN u32 RegAddr, IN u32 BitMask ) { u32 Original_Value, Readback_Value, BitShift; /* HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); */ /* u8 RFWaitCounter = 0; */ /* _irqL irqL; */ #if (DISABLE_BB_RF == 1) return 0; #endif #ifdef CONFIG_USB_HCI /* PlatformAcquireMutex(&pHalData->mxRFOperate); */ #else /* _enter_critical(&pHalData->rf_lock, &irqL); */ #endif Original_Value = phy_RFSerialRead(Adapter, eRFPath, RegAddr); BitShift = PHY_CalculateBitShift(BitMask); Readback_Value = (Original_Value & BitMask) >> BitShift; #ifdef CONFIG_USB_HCI /* PlatformReleaseMutex(&pHalData->mxRFOperate); */ #else /* _exit_critical(&pHalData->rf_lock, &irqL); */ #endif /* RTPRINT(FPHY, PHY_RFR, ("RFR-%d MASK=0x%lx Addr[0x%lx]=0x%lx\n", eRFPath, BitMask, RegAddr, Original_Value));//BitMask(%#lx),BitMask, */ return Readback_Value; } /** * Function: PHY_SetRFReg * * OverView: Write "Specific bits" to RF register (page 8~) * * Input: * PADAPTER Adapter, * u8 eRFPath, //Radio path of A/B/C/D * u4Byte RegAddr, //The target address to be modified * u4Byte BitMask //The target bit position in the target address * //to be modified * u4Byte Data //The new register Data in the target bit position * //of the target address * * Output: None * Return: None * Note: This function is equal to "PutRFRegSetting" in PHY programming guide */ VOID PHY_SetRFReg8188E( IN PADAPTER Adapter, IN u8 eRFPath, IN u32 RegAddr, IN u32 BitMask, IN u32 Data ) { /* HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); */ /* u1Byte RFWaitCounter = 0; */ u32 Original_Value, BitShift; /* _irqL irqL; */ #if (DISABLE_BB_RF == 1) return; #endif /* RTPRINT(FINIT, INIT_RF, ("phy_set_rf_reg(): RegAddr(%#lx), BitMask(%#lx), Data(%#lx), eRFPath(%#x)\n", */ /* RegAddr, BitMask, Data, eRFPath)); */ #ifdef CONFIG_USB_HCI /* PlatformAcquireMutex(&pHalData->mxRFOperate); */ #else /* _enter_critical(&pHalData->rf_lock, &irqL); */ #endif /* RF data is 12 bits only */ if (BitMask != bRFRegOffsetMask) { Original_Value = phy_RFSerialRead(Adapter, eRFPath, RegAddr); BitShift = PHY_CalculateBitShift(BitMask); Data = ((Original_Value & (~BitMask)) | (Data << BitShift)); } phy_RFSerialWrite(Adapter, eRFPath, RegAddr, Data); #ifdef CONFIG_USB_HCI /* PlatformReleaseMutex(&pHalData->mxRFOperate); */ #else /* _exit_critical(&pHalData->rf_lock, &irqL); */ #endif /* phy_query_rf_reg(Adapter,eRFPath,RegAddr,BitMask); */ } /* * 3. Initial MAC/BB/RF config by reading MAC/BB/RF txt. * */ /*----------------------------------------------------------------------------- * Function: PHY_MACConfig8192C * * Overview: Condig MAC by header file or parameter file. * * Input: NONE * * Output: NONE * * Return: NONE * * Revised History: * When Who Remark * 08/12/2008 MHC Create Version 0. * *---------------------------------------------------------------------------*/ s32 PHY_MACConfig8188E(PADAPTER Adapter) { int rtStatus = _SUCCESS; HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); u16 val = 0; /* */ /* Config MAC */ /* */ #ifdef CONFIG_LOAD_PHY_PARA_FROM_FILE rtStatus = phy_ConfigMACWithParaFile(Adapter, PHY_FILE_MAC_REG); if (rtStatus == _FAIL) #endif { #ifdef CONFIG_EMBEDDED_FWIMG if (HAL_STATUS_FAILURE == odm_config_mac_with_header_file(&pHalData->odmpriv)) rtStatus = _FAIL; else rtStatus = _SUCCESS; #endif/* CONFIG_EMBEDDED_FWIMG */ } /* 2010.07.13 AMPDU aggregation number B */ val |= MAX_AGGR_NUM; val = val << 8; val |= MAX_AGGR_NUM; rtw_write16(Adapter, REG_MAX_AGGR_NUM, val); /* rtw_write8(Adapter, REG_MAX_AGGR_NUM, 0x0B); */ return rtStatus; } /*----------------------------------------------------------------------------- * Function: phy_InitBBRFRegisterDefinition * * OverView: Initialize Register definition offset for Radio Path A/B/C/D * * Input: * PADAPTER Adapter, * * Output: None * Return: None * Note: The initialization value is constant and it should never be changes -----------------------------------------------------------------------------*/ static VOID phy_InitBBRFRegisterDefinition( IN PADAPTER Adapter ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); /* RF Interface Sowrtware Control */ pHalData->PHYRegDef[RF_PATH_A].rfintfs = rFPGA0_XAB_RFInterfaceSW; /* 16 LSBs if read 32-bit from 0x870 */ pHalData->PHYRegDef[RF_PATH_B].rfintfs = rFPGA0_XAB_RFInterfaceSW; /* 16 MSBs if read 32-bit from 0x870 (16-bit for 0x872) */ pHalData->PHYRegDef[RF_PATH_C].rfintfs = rFPGA0_XCD_RFInterfaceSW;/* 16 LSBs if read 32-bit from 0x874 */ pHalData->PHYRegDef[RF_PATH_D].rfintfs = rFPGA0_XCD_RFInterfaceSW;/* 16 MSBs if read 32-bit from 0x874 (16-bit for 0x876) */ /* RF Interface Output (and Enable) */ pHalData->PHYRegDef[RF_PATH_A].rfintfo = rFPGA0_XA_RFInterfaceOE; /* 16 LSBs if read 32-bit from 0x860 */ pHalData->PHYRegDef[RF_PATH_B].rfintfo = rFPGA0_XB_RFInterfaceOE; /* 16 LSBs if read 32-bit from 0x864 */ /* RF Interface (Output and) Enable */ pHalData->PHYRegDef[RF_PATH_A].rfintfe = rFPGA0_XA_RFInterfaceOE; /* 16 MSBs if read 32-bit from 0x860 (16-bit for 0x862) */ pHalData->PHYRegDef[RF_PATH_B].rfintfe = rFPGA0_XB_RFInterfaceOE; /* 16 MSBs if read 32-bit from 0x864 (16-bit for 0x866) */ /* Addr of LSSI. Wirte RF register by driver */ pHalData->PHYRegDef[RF_PATH_A].rf3wireOffset = rFPGA0_XA_LSSIParameter; /* LSSI Parameter */ pHalData->PHYRegDef[RF_PATH_B].rf3wireOffset = rFPGA0_XB_LSSIParameter; /* Tranceiver A~D HSSI Parameter-2 */ pHalData->PHYRegDef[RF_PATH_A].rfHSSIPara2 = rFPGA0_XA_HSSIParameter2; /* wire control parameter2 */ pHalData->PHYRegDef[RF_PATH_B].rfHSSIPara2 = rFPGA0_XB_HSSIParameter2; /* wire control parameter2 */ /* Tranceiver LSSI Readback SI mode */ pHalData->PHYRegDef[RF_PATH_A].rfLSSIReadBack = rFPGA0_XA_LSSIReadBack; pHalData->PHYRegDef[RF_PATH_B].rfLSSIReadBack = rFPGA0_XB_LSSIReadBack; pHalData->PHYRegDef[RF_PATH_C].rfLSSIReadBack = rFPGA0_XC_LSSIReadBack; pHalData->PHYRegDef[RF_PATH_D].rfLSSIReadBack = rFPGA0_XD_LSSIReadBack; /* Tranceiver LSSI Readback PI mode */ pHalData->PHYRegDef[RF_PATH_A].rfLSSIReadBackPi = TransceiverA_HSPI_Readback; pHalData->PHYRegDef[RF_PATH_B].rfLSSIReadBackPi = TransceiverB_HSPI_Readback; /* pHalData->PHYRegDef[RF_PATH_C].rfLSSIReadBackPi = rFPGA0_XC_LSSIReadBack; */ /* pHalData->PHYRegDef[RF_PATH_D].rfLSSIReadBackPi = rFPGA0_XD_LSSIReadBack; */ } static VOID phy_BB8192C_Config_1T( IN PADAPTER Adapter ) { #if 0 /* for path - A */ phy_set_bb_reg(Adapter, rFPGA0_TxInfo, 0x3, 0x1); phy_set_bb_reg(Adapter, rFPGA1_TxInfo, 0x0303, 0x0101); phy_set_bb_reg(Adapter, 0xe74, 0x0c000000, 0x1); phy_set_bb_reg(Adapter, 0xe78, 0x0c000000, 0x1); phy_set_bb_reg(Adapter, 0xe7c, 0x0c000000, 0x1); phy_set_bb_reg(Adapter, 0xe80, 0x0c000000, 0x1); phy_set_bb_reg(Adapter, 0xe88, 0x0c000000, 0x1); #endif /* for path - B */ phy_set_bb_reg(Adapter, rFPGA0_TxInfo, 0x3, 0x2); phy_set_bb_reg(Adapter, rFPGA1_TxInfo, 0x300033, 0x200022); /* 20100519 Joseph: Add for 1T2R config. Suggested by Kevin, Jenyu and Yunan. */ phy_set_bb_reg(Adapter, rCCK0_AFESetting, bMaskByte3, 0x45); phy_set_bb_reg(Adapter, rOFDM0_TRxPathEnable, bMaskByte0, 0x23); phy_set_bb_reg(Adapter, rOFDM0_AGCParameter1, 0x30, 0x1); /* B path first AGC */ phy_set_bb_reg(Adapter, 0xe74, 0x0c000000, 0x2); phy_set_bb_reg(Adapter, 0xe78, 0x0c000000, 0x2); phy_set_bb_reg(Adapter, 0xe7c, 0x0c000000, 0x2); phy_set_bb_reg(Adapter, 0xe80, 0x0c000000, 0x2); phy_set_bb_reg(Adapter, 0xe88, 0x0c000000, 0x2); } /* Joseph test: new initialize order!! * Test only!! This part need to be re-organized. * Now it is just for 8256. */ static int phy_BB8190_Config_HardCode( IN PADAPTER Adapter ) { /* RT_ASSERT(FALSE, ("This function is not implement yet!!\n")); */ return _SUCCESS; } static int phy_BB8188E_Config_ParaFile( IN PADAPTER Adapter ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); int rtStatus = _SUCCESS; /* */ /* 1. Read PHY_REG.TXT BB INIT!! */ /* */ #ifdef CONFIG_LOAD_PHY_PARA_FROM_FILE if (phy_ConfigBBWithParaFile(Adapter, PHY_FILE_PHY_REG, CONFIG_BB_PHY_REG) == _FAIL) #endif { #ifdef CONFIG_EMBEDDED_FWIMG if (HAL_STATUS_FAILURE == odm_config_bb_with_header_file(&pHalData->odmpriv, CONFIG_BB_PHY_REG)) rtStatus = _FAIL; #endif } if (rtStatus != _SUCCESS) { goto phy_BB8190_Config_ParaFile_Fail; } #if (MP_DRIVER == 1) /* */ /* 1.1 Read PHY_REG_MP.TXT BB INIT!! */ /* */ if (Adapter->registrypriv.mp_mode == 1) { /* 3 Read PHY_REG.TXT BB INIT!! */ #ifdef CONFIG_LOAD_PHY_PARA_FROM_FILE if (phy_ConfigBBWithMpParaFile(Adapter, PHY_FILE_PHY_REG_MP) == _FAIL) #endif { #ifdef CONFIG_EMBEDDED_FWIMG if (HAL_STATUS_SUCCESS != odm_config_bb_with_header_file(&pHalData->odmpriv, CONFIG_BB_PHY_REG_MP)) rtStatus = _FAIL; #endif } if (rtStatus != _SUCCESS) { RTW_INFO("phy_BB8188E_Config_ParaFile():Write BB Reg MP Fail!!"); goto phy_BB8190_Config_ParaFile_Fail; } } #endif /* #if (MP_DRIVER == 1) */ /* */ /* 3. BB AGC table Initialization */ /* */ #ifdef CONFIG_LOAD_PHY_PARA_FROM_FILE if (phy_ConfigBBWithParaFile(Adapter, PHY_FILE_AGC_TAB, CONFIG_BB_AGC_TAB) == _FAIL) #endif { #ifdef CONFIG_EMBEDDED_FWIMG if (HAL_STATUS_FAILURE == odm_config_bb_with_header_file(&pHalData->odmpriv, CONFIG_BB_AGC_TAB)) rtStatus = _FAIL; #endif } if (rtStatus != _SUCCESS) { goto phy_BB8190_Config_ParaFile_Fail; } phy_BB8190_Config_ParaFile_Fail: return rtStatus; } int PHY_BBConfig8188E( IN PADAPTER Adapter ) { int rtStatus = _SUCCESS; HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); u32 RegVal; u8 TmpU1B = 0; u8 value8; phy_InitBBRFRegisterDefinition(Adapter); /* Enable BB and RF */ RegVal = rtw_read16(Adapter, REG_SYS_FUNC_EN); rtw_write16(Adapter, REG_SYS_FUNC_EN, (u16)(RegVal | BIT13 | BIT0 | BIT1)); /* 20090923 Joseph: Advised by Steven and Jenyu. Power sequence before init RF. */ /* rtw_write8(Adapter, REG_AFE_PLL_CTRL, 0x83); */ /* rtw_write8(Adapter, REG_AFE_PLL_CTRL+1, 0xdb); */ rtw_write8(Adapter, REG_RF_CTRL, RF_EN | RF_RSTB | RF_SDMRSTB); #ifdef CONFIG_USB_HCI rtw_write8(Adapter, REG_SYS_FUNC_EN, FEN_USBA | FEN_USBD | FEN_BB_GLB_RSTn | FEN_BBRSTB); #else rtw_write8(Adapter, REG_SYS_FUNC_EN, FEN_PPLL | FEN_PCIEA | FEN_DIO_PCIE | FEN_BB_GLB_RSTn | FEN_BBRSTB); #endif #if 0 #ifdef CONFIG_USB_HCI /* To Fix MAC loopback mode fail. Suggested by SD4 Johnny. 2010.03.23. */ rtw_write8(Adapter, REG_LDOHCI12_CTRL, 0x0f); rtw_write8(Adapter, 0x15, 0xe9); #endif rtw_write8(Adapter, REG_AFE_XTAL_CTRL + 1, 0x80); #endif #ifdef CONFIG_USB_HCI /* rtw_write8(Adapter, 0x15, 0xe9); */ #endif #ifdef CONFIG_PCI_HCI /* Force use left antenna by default for 88C. */ if (Adapter->ledpriv.LedStrategy != SW_LED_MODE10) { RegVal = rtw_read32(Adapter, REG_LEDCFG0); rtw_write32(Adapter, REG_LEDCFG0, RegVal | BIT23); } #endif /* */ /* Config BB and AGC */ /* */ rtStatus = phy_BB8188E_Config_ParaFile(Adapter); hal_set_crystal_cap(Adapter, pHalData->crystal_cap); return rtStatus; } int PHY_RFConfig8188E( IN PADAPTER Adapter ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); int rtStatus = _SUCCESS; /* */ /* RF config */ /* */ rtStatus = PHY_RF6052_Config8188E(Adapter); #if 0 switch (pHalData->rf_chip) { case RF_6052: rtStatus = PHY_RF6052_Config(Adapter); break; case RF_8225: rtStatus = PHY_RF8225_Config(Adapter); break; case RF_8256: rtStatus = PHY_RF8256_Config(Adapter); break; case RF_8258: break; case RF_PSEUDO_11N: rtStatus = PHY_RF8225_Config(Adapter); break; default: /* for MacOs Warning: "RF_TYPE_MIN" not handled in switch */ break; } #endif return rtStatus; } /*----------------------------------------------------------------------------- * Function: PHY_ConfigRFWithParaFile() * * Overview: This function read RF parameters from general file format, and do RF 3-wire * * Input: PADAPTER Adapter * ps1Byte pFileName * u8 eRFPath * * Output: NONE * * Return: RT_STATUS_SUCCESS: configuration file exist * * Note: Delay may be required for RF configuration *---------------------------------------------------------------------------*/ int rtl8188e_PHY_ConfigRFWithParaFile( IN PADAPTER Adapter, IN u8 *pFileName, IN u8 eRFPath ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); int rtStatus = _SUCCESS; return rtStatus; } /* **************************************** * The following is for High Power PA * **************************************** */ #define HighPowerRadioAArrayLen 22 /* This is for High power PA */ u32 Rtl8192S_HighPower_RadioA_Array[HighPowerRadioAArrayLen] = { 0x013, 0x00029ea4, 0x013, 0x00025e74, 0x013, 0x00020ea4, 0x013, 0x0001ced0, 0x013, 0x00019f40, 0x013, 0x00014e70, 0x013, 0x000106a0, 0x013, 0x0000c670, 0x013, 0x000082a0, 0x013, 0x00004270, 0x013, 0x00000240, }; /* **************************************** *----------------------------------------------------------------------------- * Function: GetTxPowerLevel8190() * * Overview: This function is export to "common" moudule * * Input: PADAPTER Adapter * psByte Power Level * * Output: NONE * * Return: NONE * *---------------------------------------------------------------------------*/ VOID PHY_GetTxPowerLevel8188E( IN PADAPTER Adapter, OUT s32 *powerlevel ) { #if 0 HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); s4Byte TxPwrDbm = 13; if (pMgntInfo->ClientConfigPwrInDbm != UNSPECIFIED_PWR_DBM) *powerlevel = pMgntInfo->ClientConfigPwrInDbm; else *powerlevel = TxPwrDbm; #endif } /*----------------------------------------------------------------------------- * Function: SetTxPowerLevel8190() * * Overview: This function is export to "HalCommon" moudule * We must consider RF path later!!!!!!! * * Input: PADAPTER Adapter * u1Byte channel * * Output: NONE * * Return: NONE * 2008/11/04 MHC We remove EEPROM_93C56. * We need to move CCX relative code to independet file. * 2009/01/21 MHC Support new EEPROM format from SD3 requirement. * *---------------------------------------------------------------------------*/ VOID PHY_SetTxPowerLevel8188E( IN PADAPTER Adapter, IN u8 Channel ) { /* RTW_INFO("==>PHY_SetTxPowerLevel8188E()\n"); */ phy_set_tx_power_level_by_path(Adapter, Channel, ODM_RF_PATH_A); /* RTW_INFO("<==PHY_SetTxPowerLevel8188E()\n"); */ } VOID PHY_SetTxPowerIndex_8188E( IN PADAPTER Adapter, IN u32 PowerIndex, IN u8 RFPath, IN u8 Rate ) { if (RFPath == ODM_RF_PATH_A) { switch (Rate) { case MGN_1M: phy_set_bb_reg(Adapter, rTxAGC_A_CCK1_Mcs32, bMaskByte1, PowerIndex); break; case MGN_2M: phy_set_bb_reg(Adapter, rTxAGC_B_CCK11_A_CCK2_11, bMaskByte1, PowerIndex); break; case MGN_5_5M: phy_set_bb_reg(Adapter, rTxAGC_B_CCK11_A_CCK2_11, bMaskByte2, PowerIndex); break; case MGN_11M: phy_set_bb_reg(Adapter, rTxAGC_B_CCK11_A_CCK2_11, bMaskByte3, PowerIndex); break; case MGN_6M: phy_set_bb_reg(Adapter, rTxAGC_A_Rate18_06, bMaskByte0, PowerIndex); break; case MGN_9M: phy_set_bb_reg(Adapter, rTxAGC_A_Rate18_06, bMaskByte1, PowerIndex); break; case MGN_12M: phy_set_bb_reg(Adapter, rTxAGC_A_Rate18_06, bMaskByte2, PowerIndex); break; case MGN_18M: phy_set_bb_reg(Adapter, rTxAGC_A_Rate18_06, bMaskByte3, PowerIndex); break; case MGN_24M: phy_set_bb_reg(Adapter, rTxAGC_A_Rate54_24, bMaskByte0, PowerIndex); break; case MGN_36M: phy_set_bb_reg(Adapter, rTxAGC_A_Rate54_24, bMaskByte1, PowerIndex); break; case MGN_48M: phy_set_bb_reg(Adapter, rTxAGC_A_Rate54_24, bMaskByte2, PowerIndex); break; case MGN_54M: phy_set_bb_reg(Adapter, rTxAGC_A_Rate54_24, bMaskByte3, PowerIndex); break; case MGN_MCS0: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs03_Mcs00, bMaskByte0, PowerIndex); break; case MGN_MCS1: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs03_Mcs00, bMaskByte1, PowerIndex); break; case MGN_MCS2: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs03_Mcs00, bMaskByte2, PowerIndex); break; case MGN_MCS3: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs03_Mcs00, bMaskByte3, PowerIndex); break; case MGN_MCS4: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs07_Mcs04, bMaskByte0, PowerIndex); break; case MGN_MCS5: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs07_Mcs04, bMaskByte1, PowerIndex); break; case MGN_MCS6: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs07_Mcs04, bMaskByte2, PowerIndex); break; case MGN_MCS7: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs07_Mcs04, bMaskByte3, PowerIndex); break; case MGN_MCS8: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs11_Mcs08, bMaskByte0, PowerIndex); break; case MGN_MCS9: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs11_Mcs08, bMaskByte1, PowerIndex); break; case MGN_MCS10: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs11_Mcs08, bMaskByte2, PowerIndex); break; case MGN_MCS11: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs11_Mcs08, bMaskByte3, PowerIndex); break; case MGN_MCS12: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs15_Mcs12, bMaskByte0, PowerIndex); break; case MGN_MCS13: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs15_Mcs12, bMaskByte1, PowerIndex); break; case MGN_MCS14: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs15_Mcs12, bMaskByte2, PowerIndex); break; case MGN_MCS15: phy_set_bb_reg(Adapter, rTxAGC_A_Mcs15_Mcs12, bMaskByte3, PowerIndex); break; default: RTW_INFO("Invalid Rate!!\n"); break; } } else if (RFPath == ODM_RF_PATH_B) { switch (Rate) { case MGN_1M: phy_set_bb_reg(Adapter, rTxAGC_B_CCK1_55_Mcs32, bMaskByte1, PowerIndex); break; case MGN_2M: phy_set_bb_reg(Adapter, rTxAGC_B_CCK1_55_Mcs32, bMaskByte2, PowerIndex); break; case MGN_5_5M: phy_set_bb_reg(Adapter, rTxAGC_B_CCK1_55_Mcs32, bMaskByte3, PowerIndex); break; case MGN_11M: phy_set_bb_reg(Adapter, rTxAGC_B_CCK11_A_CCK2_11, bMaskByte0, PowerIndex); break; case MGN_6M: phy_set_bb_reg(Adapter, rTxAGC_B_Rate18_06, bMaskByte0, PowerIndex); break; case MGN_9M: phy_set_bb_reg(Adapter, rTxAGC_B_Rate18_06, bMaskByte1, PowerIndex); break; case MGN_12M: phy_set_bb_reg(Adapter, rTxAGC_B_Rate18_06, bMaskByte2, PowerIndex); break; case MGN_18M: phy_set_bb_reg(Adapter, rTxAGC_B_Rate18_06, bMaskByte3, PowerIndex); break; case MGN_24M: phy_set_bb_reg(Adapter, rTxAGC_B_Rate54_24, bMaskByte0, PowerIndex); break; case MGN_36M: phy_set_bb_reg(Adapter, rTxAGC_B_Rate54_24, bMaskByte1, PowerIndex); break; case MGN_48M: phy_set_bb_reg(Adapter, rTxAGC_B_Rate54_24, bMaskByte2, PowerIndex); break; case MGN_54M: phy_set_bb_reg(Adapter, rTxAGC_B_Rate54_24, bMaskByte3, PowerIndex); break; case MGN_MCS0: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs03_Mcs00, bMaskByte0, PowerIndex); break; case MGN_MCS1: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs03_Mcs00, bMaskByte1, PowerIndex); break; case MGN_MCS2: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs03_Mcs00, bMaskByte2, PowerIndex); break; case MGN_MCS3: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs03_Mcs00, bMaskByte3, PowerIndex); break; case MGN_MCS4: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs07_Mcs04, bMaskByte0, PowerIndex); break; case MGN_MCS5: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs07_Mcs04, bMaskByte1, PowerIndex); break; case MGN_MCS6: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs07_Mcs04, bMaskByte2, PowerIndex); break; case MGN_MCS7: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs07_Mcs04, bMaskByte3, PowerIndex); break; case MGN_MCS8: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs11_Mcs08, bMaskByte0, PowerIndex); break; case MGN_MCS9: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs11_Mcs08, bMaskByte1, PowerIndex); break; case MGN_MCS10: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs11_Mcs08, bMaskByte2, PowerIndex); break; case MGN_MCS11: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs11_Mcs08, bMaskByte3, PowerIndex); break; case MGN_MCS12: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs15_Mcs12, bMaskByte0, PowerIndex); break; case MGN_MCS13: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs15_Mcs12, bMaskByte1, PowerIndex); break; case MGN_MCS14: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs15_Mcs12, bMaskByte2, PowerIndex); break; case MGN_MCS15: phy_set_bb_reg(Adapter, rTxAGC_B_Mcs15_Mcs12, bMaskByte3, PowerIndex); break; default: RTW_INFO("Invalid Rate!!\n"); break; } } else RTW_INFO("Invalid RFPath!!\n"); } u8 phy_GetCurrentTxNum_8188E( IN PADAPTER pAdapter, IN u8 Rate ) { u8 tmpByte = 0; u32 tmpDWord = 0; u8 TxNum = RF_TX_NUM_NONIMPLEMENT; if ((Rate >= MGN_MCS8 && Rate <= MGN_MCS15)) TxNum = RF_2TX; else TxNum = RF_1TX; return TxNum; } s8 tx_power_extra_bias( IN u8 RFPath, IN u8 Rate, IN CHANNEL_WIDTH BandWidth, IN u8 Channel ) { s8 bias = 0; if (Rate == MGN_2M) bias = -9; return bias; } u8 PHY_GetTxPowerIndex_8188E( IN PADAPTER pAdapter, IN u8 RFPath, IN u8 Rate, IN u8 BandWidth, IN u8 Channel, struct txpwr_idx_comp *tic ) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(pAdapter); u8 base_idx = 0, power_idx = 0; s8 by_rate_diff = 0, limit = 0, tpt_offset = 0, extra_bias = 0; u8 txNum = phy_GetCurrentTxNum_8188E(pAdapter, Rate); BOOLEAN bIn24G = _FALSE; base_idx = PHY_GetTxPowerIndexBase(pAdapter, RFPath, Rate, BandWidth, Channel, &bIn24G); by_rate_diff = PHY_GetTxPowerByRate(pAdapter, BAND_ON_2_4G, RFPath, txNum, Rate); limit = PHY_GetTxPowerLimit(pAdapter, pAdapter->registrypriv.RegPwrTblSel, (u8)(!bIn24G), pHalData->current_channel_bw, RFPath, Rate, pHalData->current_channel); tpt_offset = PHY_GetTxPowerTrackingOffset(pAdapter, RFPath, Rate); if (pAdapter->registrypriv.mp_mode != 1) extra_bias = tx_power_extra_bias(RFPath, Rate, BandWidth, Channel); if (tic) { tic->base = base_idx; tic->by_rate = by_rate_diff; tic->limit = limit; tic->tpt = tpt_offset; tic->ebias = extra_bias; } by_rate_diff = by_rate_diff > limit ? limit : by_rate_diff; power_idx = base_idx + by_rate_diff + tpt_offset + extra_bias; if (power_idx > MAX_POWER_INDEX) power_idx = MAX_POWER_INDEX; return power_idx; } /* * Description: * Update transmit power level of all channel supported. * * TODO: * A mode. * By Bruce, 2008-02-04. * */ BOOLEAN PHY_UpdateTxPowerDbm8188E( IN PADAPTER Adapter, IN int powerInDbm ) { return _TRUE; } VOID PHY_ScanOperationBackup8188E( IN PADAPTER Adapter, IN u8 Operation ) { #if 0 IO_TYPE IoType; if (!rtw_is_drv_stopped(padapter)) { switch (Operation) { case SCAN_OPT_BACKUP: IoType = IO_CMD_PAUSE_DM_BY_SCAN; rtw_hal_set_hwreg(Adapter, HW_VAR_IO_CMD, (pu1Byte)&IoType); break; case SCAN_OPT_RESTORE: IoType = IO_CMD_RESUME_DM_BY_SCAN; rtw_hal_set_hwreg(Adapter, HW_VAR_IO_CMD, (pu1Byte)&IoType); break; default: break; } } #endif } void phy_SpurCalibration_8188E( IN PADAPTER Adapter ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); struct PHY_DM_STRUCT *p_dm_odm = &(pHalData->odmpriv); /* DbgPrint("===> phy_SpurCalibration_8188E current_channel_bw = %d, current_channel = %d\n", pHalData->current_channel_bw, pHalData->current_channel);*/ if (pHalData->current_channel_bw == CHANNEL_WIDTH_20 && (pHalData->current_channel == 13 || pHalData->current_channel == 14)) { phy_set_bb_reg(Adapter, rOFDM0_RxDSP, BIT(9), 0x1);/* enable notch filter */ phy_set_bb_reg(Adapter, rOFDM1_IntfDet, BIT(8) | BIT(7) | BIT(6), 0x2); /* intf_TH */ phy_set_bb_reg(Adapter, rOFDM0_RxDSP, BIT(28) | BIT(27) | BIT(26) | BIT(25) | BIT(24), 0x1f); p_dm_odm->is_receiver_blocking_en = false; } else if (pHalData->current_channel_bw == CHANNEL_WIDTH_40 && pHalData->current_channel == 11) { phy_set_bb_reg(Adapter, rOFDM0_RxDSP, BIT(9), 0x1);/* enable notch filter */ phy_set_bb_reg(Adapter, rOFDM1_IntfDet, BIT(8) | BIT(7) | BIT(6), 0x2); /* intf_TH */ phy_set_bb_reg(Adapter, rOFDM0_RxDSP, BIT(28) | BIT(27) | BIT(26) | BIT(25) | BIT(24), 0x1f); p_dm_odm->is_receiver_blocking_en = false; } else { if (Adapter->registrypriv.notch_filter == 0) phy_set_bb_reg(Adapter, rOFDM0_RxDSP, BIT(9), 0x0);/* disable notch filter */ } } /*----------------------------------------------------------------------------- * Function: PHY_SetBWModeCallback8192C() * * Overview: Timer callback function for SetSetBWMode * * Input: PRT_TIMER pTimer * * Output: NONE * * Return: NONE * * Note: (1) We do not take j mode into consideration now * (2) Will two workitem of "switch channel" and "switch channel bandwidth" run * concurrently? *---------------------------------------------------------------------------*/ static VOID _PHY_SetBWMode88E( IN PADAPTER Adapter ) { /* PADAPTER Adapter = (PADAPTER)pTimer->Adapter; */ HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); u8 regBwOpMode; u8 regRRSR_RSC; /* return; */ /* Added it for 20/40 mhz switch time evaluation by guangan 070531 */ /* u4Byte NowL, NowH; */ /* u8Byte BeginTime, EndTime; */ if (pHalData->rf_chip == RF_PSEUDO_11N) { /* pHalData->SetBWModeInProgress= _FALSE; */ return; } /* There is no 40MHz mode in RF_8225. */ if (pHalData->rf_chip == RF_8225) return; if (rtw_is_drv_stopped(Adapter)) return; /* Added it for 20/40 mhz switch time evaluation by guangan 070531 */ /* NowL = PlatformEFIORead4Byte(Adapter, TSFR); */ /* NowH = PlatformEFIORead4Byte(Adapter, TSFR+4); */ /* BeginTime = ((u8Byte)NowH << 32) + NowL; */ /* 3 */ /* 3 */ /* <1>Set MAC register */ /* 3 */ /* Adapter->hal_func.SetBWModeHandler(); */ regBwOpMode = rtw_read8(Adapter, REG_BWOPMODE); regRRSR_RSC = rtw_read8(Adapter, REG_RRSR + 2); /* regBwOpMode = rtw_hal_get_hwreg(Adapter,HW_VAR_BWMODE,(pu1Byte)&regBwOpMode); */ switch (pHalData->current_channel_bw) { case CHANNEL_WIDTH_20: regBwOpMode |= BW_OPMODE_20MHZ; /* 2007/02/07 Mark by Emily becasue we have not verify whether this register works */ rtw_write8(Adapter, REG_BWOPMODE, regBwOpMode); break; case CHANNEL_WIDTH_40: regBwOpMode &= ~BW_OPMODE_20MHZ; /* 2007/02/07 Mark by Emily becasue we have not verify whether this register works */ rtw_write8(Adapter, REG_BWOPMODE, regBwOpMode); regRRSR_RSC = (regRRSR_RSC & 0x90) | (pHalData->nCur40MhzPrimeSC << 5); rtw_write8(Adapter, REG_RRSR + 2, regRRSR_RSC); break; default: break; } /* 3 */ /* 3 */ /* <2>Set PHY related register */ /* 3 */ switch (pHalData->current_channel_bw) { /* 20 MHz channel*/ case CHANNEL_WIDTH_20: phy_set_bb_reg(Adapter, rFPGA0_RFMOD, bRFMOD, 0x0); phy_set_bb_reg(Adapter, rFPGA1_RFMOD, bRFMOD, 0x0); /* phy_set_bb_reg(Adapter, rFPGA0_AnalogParameter2, BIT10, 1); */ break; /* 40 MHz channel*/ case CHANNEL_WIDTH_40: phy_set_bb_reg(Adapter, rFPGA0_RFMOD, bRFMOD, 0x1); phy_set_bb_reg(Adapter, rFPGA1_RFMOD, bRFMOD, 0x1); /* Set Control channel to upper or lower. These settings are required only for 40MHz */ phy_set_bb_reg(Adapter, rCCK0_System, bCCKSideBand, (pHalData->nCur40MhzPrimeSC >> 1)); phy_set_bb_reg(Adapter, rOFDM1_LSTF, 0xC00, pHalData->nCur40MhzPrimeSC); /* phy_set_bb_reg(Adapter, rFPGA0_AnalogParameter2, BIT10, 0); */ phy_set_bb_reg(Adapter, 0x818, (BIT26 | BIT27), (pHalData->nCur40MhzPrimeSC == HAL_PRIME_CHNL_OFFSET_LOWER) ? 2 : 1); break; default: break; } /* Skip over setting of J-mode in BB register here. Default value is "None J mode". Emily 20070315 */ /* Added it for 20/40 mhz switch time evaluation by guangan 070531 */ /* NowL = PlatformEFIORead4Byte(Adapter, TSFR); */ /* NowH = PlatformEFIORead4Byte(Adapter, TSFR+4); */ /* EndTime = ((u8Byte)NowH << 32) + NowL; */ /* 3<3>Set RF related register */ switch (pHalData->rf_chip) { case RF_8225: /* PHY_SetRF8225Bandwidth(Adapter, pHalData->current_channel_bw); */ break; case RF_8256: /* Please implement this function in Hal8190PciPhy8256.c */ /* PHY_SetRF8256Bandwidth(Adapter, pHalData->current_channel_bw); */ break; case RF_8258: /* Please implement this function in Hal8190PciPhy8258.c */ /* PHY_SetRF8258Bandwidth(); */ break; case RF_PSEUDO_11N: /* Do Nothing */ break; case RF_6052: rtl8188e_PHY_RF6052SetBandwidth(Adapter, pHalData->current_channel_bw); break; default: /* RT_ASSERT(FALSE, ("Unknown RFChipID: %d\n", pHalData->RFChipID)); */ break; } /* pHalData->SetBWModeInProgress= FALSE; */ } #if 0 /* ----------------------------------------------------------------------------- * * Function: SetBWMode8190Pci() * * * * Overview: This function is export to "HalCommon" moudule * * * * Input: PADAPTER Adapter * * CHANNEL_WIDTH Bandwidth 20M or 40M * * * * Output: NONE * * * * Return: NONE * * * * Note: We do not take j mode into consideration now * *--------------------------------------------------------------------------- */ #endif VOID PHY_SetBWMode8188E( IN PADAPTER Adapter, IN CHANNEL_WIDTH Bandwidth, /* 20M or 40M */ IN unsigned char Offset /* Upper, Lower, or Don't care */ ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); CHANNEL_WIDTH tmpBW = pHalData->current_channel_bw; /* Modified it for 20/40 mhz switch by guangan 070531 */ /* PMGNT_INFO pMgntInfo=&Adapter->MgntInfo; */ /* return; */ /* if(pHalData->SwChnlInProgress) * if(pMgntInfo->bScanInProgress) * { * return; * } */ /* if(pHalData->SetBWModeInProgress) * { * */ /* Modified it for 20/40 mhz switch by guangan 070531 * PlatformCancelTimer(Adapter, &pHalData->SetBWModeTimer); * */ /* return; * } */ /* if(pHalData->SetBWModeInProgress) */ /* return; */ /* pHalData->SetBWModeInProgress= TRUE; */ pHalData->current_channel_bw = Bandwidth; #if 0 if (Offset == EXTCHNL_OFFSET_LOWER) pHalData->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_UPPER; else if (Offset == EXTCHNL_OFFSET_UPPER) pHalData->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_LOWER; else pHalData->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_DONT_CARE; #else pHalData->nCur40MhzPrimeSC = Offset; #endif if (!RTW_CANNOT_RUN(Adapter)) { #if 0 /* PlatformSetTimer(Adapter, &(pHalData->SetBWModeTimer), 0); */ #else _PHY_SetBWMode88E(Adapter); #endif #if defined(CONFIG_USB_HCI) || defined(CONFIG_SDIO_HCI) if (IS_VENDOR_8188E_I_CUT_SERIES(Adapter)) phy_SpurCalibration_8188E(Adapter); #endif } else { /* pHalData->SetBWModeInProgress= FALSE; */ pHalData->current_channel_bw = tmpBW; } } static void _PHY_SwChnl8188E(PADAPTER Adapter, u8 channel) { u8 eRFPath; u32 param1, param2; HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); if (Adapter->bNotifyChannelChange) RTW_INFO("[%s] ch = %d\n", __FUNCTION__, channel); /* s1. pre common command - CmdID_SetTxPowerLevel */ PHY_SetTxPowerLevel8188E(Adapter, channel); /* s2. RF dependent command - CmdID_RF_WriteReg, param1=RF_CHNLBW, param2=channel */ param1 = RF_CHNLBW; param2 = channel; for (eRFPath = 0; eRFPath < pHalData->NumTotalRFPath; eRFPath++) { pHalData->RfRegChnlVal[eRFPath] = ((pHalData->RfRegChnlVal[eRFPath] & 0xfffffc00) | param2); phy_set_rf_reg(Adapter, eRFPath, param1, bRFRegOffsetMask, pHalData->RfRegChnlVal[eRFPath]); } /* s3. post common command - CmdID_End, None */ } VOID PHY_SwChnl8188E(/* Call after initialization */ IN PADAPTER Adapter, IN u8 channel ) { /* PADAPTER Adapter = ADJUST_TO_ADAPTIVE_ADAPTER(pAdapter, _TRUE); */ HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); u8 tmpchannel = pHalData->current_channel; BOOLEAN bResult = _TRUE; if (pHalData->rf_chip == RF_PSEUDO_11N) { /* pHalData->SwChnlInProgress=FALSE; */ return; /* return immediately if it is peudo-phy */ } /* if(pHalData->SwChnlInProgress) */ /* return; */ /* if(pHalData->SetBWModeInProgress) */ /* return; */ while (pHalData->odmpriv.rf_calibrate_info.is_lck_in_progress) rtw_msleep_os(50); /* -------------------------------------------- */ switch (pHalData->CurrentWirelessMode) { case WIRELESS_MODE_A: case WIRELESS_MODE_N_5G: /* RT_ASSERT((channel>14), ("WIRELESS_MODE_A but channel<=14")); */ break; case WIRELESS_MODE_B: /* RT_ASSERT((channel<=14), ("WIRELESS_MODE_B but channel>14")); */ break; case WIRELESS_MODE_G: case WIRELESS_MODE_N_24G: /* RT_ASSERT((channel<=14), ("WIRELESS_MODE_G but channel>14")); */ break; default: /* RT_ASSERT(FALSE, ("Invalid WirelessMode(%#x)!!\n", pHalData->CurrentWirelessMode)); */ break; } /* -------------------------------------------- */ /* pHalData->SwChnlInProgress = TRUE; */ if (channel == 0) channel = 1; pHalData->current_channel = channel; /* pHalData->SwChnlStage=0; */ /* pHalData->SwChnlStep=0; */ if (!RTW_CANNOT_RUN(Adapter)) { #if 0 /* PlatformSetTimer(Adapter, &(pHalData->SwChnlTimer), 0); */ #else _PHY_SwChnl8188E(Adapter, channel); #endif #if defined(CONFIG_USB_HCI) || defined(CONFIG_SDIO_HCI) if (IS_VENDOR_8188E_I_CUT_SERIES(Adapter)) phy_SpurCalibration_8188E(Adapter); #endif if (!bResult) { /* if(IS_HARDWARE_TYPE_8192SU(Adapter)) */ /* { */ /* pHalData->SwChnlInProgress = FALSE; */ pHalData->current_channel = tmpchannel; /* } */ } } else { /* if(IS_HARDWARE_TYPE_8192SU(Adapter)) */ /* { */ /* pHalData->SwChnlInProgress = FALSE; */ pHalData->current_channel = tmpchannel; /* } */ } } VOID PHY_SetSwChnlBWMode8188E( IN PADAPTER Adapter, IN u8 channel, IN CHANNEL_WIDTH Bandwidth, IN u8 Offset40, IN u8 Offset80 ) { /* RTW_INFO("%s()===>\n",__FUNCTION__); */ PHY_SwChnl8188E(Adapter, channel); PHY_SetBWMode8188E(Adapter, Bandwidth, Offset40); /* RTW_INFO("<==%s()\n",__FUNCTION__); */ } static VOID _PHY_SetRFPathSwitch( IN PADAPTER pAdapter, IN BOOLEAN bMain, IN BOOLEAN is2T ) { u8 u1bTmp; if (!rtw_is_hw_init_completed(pAdapter)) { u1bTmp = rtw_read8(pAdapter, REG_LEDCFG2) | BIT7; rtw_write8(pAdapter, REG_LEDCFG2, u1bTmp); /* phy_set_bb_reg(pAdapter, REG_LEDCFG0, BIT23, 0x01); */ phy_set_bb_reg(pAdapter, rFPGA0_XAB_RFParameter, BIT13, 0x01); } if (is2T) { if (bMain) phy_set_bb_reg(pAdapter, rFPGA0_XB_RFInterfaceOE, BIT5 | BIT6, 0x1); /* 92C_Path_A */ else phy_set_bb_reg(pAdapter, rFPGA0_XB_RFInterfaceOE, BIT5 | BIT6, 0x2); /* BT */ } else { if (bMain) phy_set_bb_reg(pAdapter, rFPGA0_XA_RFInterfaceOE, 0x300, 0x2); /* Main */ else phy_set_bb_reg(pAdapter, rFPGA0_XA_RFInterfaceOE, 0x300, 0x1); /* Aux */ } } /* return value TRUE => Main; FALSE => Aux */ static BOOLEAN _PHY_QueryRFPathSwitch( IN PADAPTER pAdapter, IN BOOLEAN is2T ) { /* if(is2T) * return _TRUE; */ if (!rtw_is_hw_init_completed(pAdapter)) { phy_set_bb_reg(pAdapter, REG_LEDCFG0, BIT23, 0x01); phy_set_bb_reg(pAdapter, rFPGA0_XAB_RFParameter, BIT13, 0x01); } if (is2T) { if (phy_query_bb_reg(pAdapter, rFPGA0_XB_RFInterfaceOE, BIT5 | BIT6) == 0x01) return _TRUE; else return _FALSE; } else { if (phy_query_bb_reg(pAdapter, rFPGA0_XA_RFInterfaceOE, 0x300) == 0x02) return _TRUE; else return _FALSE; } } static VOID _PHY_DumpRFReg(IN PADAPTER pAdapter) { u32 rfRegValue, rfRegOffset; /* RTPRINT(FINIT, INIT_RF, ("PHY_DumpRFReg()====>\n")); */ for (rfRegOffset = 0x00; rfRegOffset <= 0x30; rfRegOffset++) { rfRegValue = phy_query_rf_reg(pAdapter, RF_PATH_A, rfRegOffset, bMaskDWord); /* RTPRINT(FINIT, INIT_RF, (" 0x%02x = 0x%08x\n",rfRegOffset,rfRegValue)); */ } /* RTPRINT(FINIT, INIT_RF, ("<===== PHY_DumpRFReg()\n")); */ } /* * Move from phycfg.c to gen.c to be code independent later * * -------------------------Move to other DIR later---------------------------- */ #ifdef CONFIG_USB_HCI /* * Description: * To dump all Tx FIFO LLT related link-list table. * Added by Roger, 2009.03.10. * */ VOID DumpBBDbgPort_92CU( IN PADAPTER Adapter ) { phy_set_bb_reg(Adapter, 0x0908, 0xffff, 0x0000); phy_set_bb_reg(Adapter, 0x0908, 0xffff, 0x0803); phy_set_bb_reg(Adapter, 0x0908, 0xffff, 0x0a06); phy_set_bb_reg(Adapter, 0x0908, 0xffff, 0x0007); phy_set_bb_reg(Adapter, 0x0908, 0xffff, 0x0100); phy_set_bb_reg(Adapter, 0x0a28, 0x00ff0000, 0x000f0000); phy_set_bb_reg(Adapter, 0x0908, 0xffff, 0x0100); phy_set_bb_reg(Adapter, 0x0a28, 0x00ff0000, 0x00150000); } #endif VOID PHY_SetRFEReg_8188E( IN PADAPTER Adapter ) { u8 u1tmp = 0; HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); if ((pHalData->ExternalPA_2G == 0) && (pHalData->ExternalLNA_2G == 0)) return; switch (pHalData->rfe_type) { /* 88EU rfe_type should always be 0 */ case 0: default: phy_set_bb_reg(Adapter, 0x40, BIT2|BIT3, 0x3); /*0x3 << 2*/ phy_set_bb_reg(Adapter, 0xEE8, BIT28, 0x1); phy_set_bb_reg(Adapter, 0x87C, BIT0, 0x0); break; } }
879543.c
/* * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "internal/cryptlib.h" #include <openssl/cmac.h> struct CMAC_CTX_st { /* Cipher context to use */ EVP_CIPHER_CTX *cctx; /* Keys k1 and k2 */ unsigned char k1[EVP_MAX_BLOCK_LENGTH]; unsigned char k2[EVP_MAX_BLOCK_LENGTH]; /* Temporary block */ unsigned char tbl[EVP_MAX_BLOCK_LENGTH]; /* Last (possibly partial) block */ unsigned char last_block[EVP_MAX_BLOCK_LENGTH]; /* Number of bytes in last block: -1 means context not initialised */ int nlast_block; }; /* Make temporary keys K1 and K2 */ static void make_kn(unsigned char *k1, const unsigned char *l, int bl) { int i; unsigned char c = l[0], carry = c >> 7, cnext; /* Shift block to left, including carry */ for (i = 0; i < bl - 1; i++, c = cnext) k1[i] = (c << 1) | ((cnext = l[i + 1]) >> 7); /* If MSB set fixup with R */ k1[i] = (c << 1) ^ ((0 - carry) & (bl == 16 ? 0x87 : 0x1b)); } CMAC_CTX *CMAC_CTX_new(void) { CMAC_CTX *ctx; ctx = OPENSSL_malloc(sizeof(*ctx)); if (ctx == NULL) return NULL; ctx->cctx = EVP_CIPHER_CTX_new(); if (ctx->cctx == NULL) { OPENSSL_free(ctx); return NULL; } ctx->nlast_block = -1; return ctx; } void CMAC_CTX_cleanup(CMAC_CTX *ctx) { EVP_CIPHER_CTX_reset(ctx->cctx); OPENSSL_cleanse(ctx->tbl, EVP_MAX_BLOCK_LENGTH); OPENSSL_cleanse(ctx->k1, EVP_MAX_BLOCK_LENGTH); OPENSSL_cleanse(ctx->k2, EVP_MAX_BLOCK_LENGTH); OPENSSL_cleanse(ctx->last_block, EVP_MAX_BLOCK_LENGTH); ctx->nlast_block = -1; } EVP_CIPHER_CTX *CMAC_CTX_get0_cipher_ctx(CMAC_CTX *ctx) { return ctx->cctx; } void CMAC_CTX_free(CMAC_CTX *ctx) { if (!ctx) return; CMAC_CTX_cleanup(ctx); EVP_CIPHER_CTX_free(ctx->cctx); OPENSSL_free(ctx); } int CMAC_CTX_copy(CMAC_CTX *out, const CMAC_CTX *in) { int bl; if (in->nlast_block == -1) return 0; if (!EVP_CIPHER_CTX_copy(out->cctx, in->cctx)) return 0; bl = EVP_CIPHER_CTX_block_size(in->cctx); memcpy(out->k1, in->k1, bl); memcpy(out->k2, in->k2, bl); memcpy(out->tbl, in->tbl, bl); memcpy(out->last_block, in->last_block, bl); out->nlast_block = in->nlast_block; return 1; } int CMAC_Init(CMAC_CTX *ctx, const void *key, size_t keylen, const EVP_CIPHER *cipher, ENGINE *impl) { static const unsigned char zero_iv[EVP_MAX_BLOCK_LENGTH] = { 0 }; /* All zeros means restart */ if (!key && !cipher && !impl && keylen == 0) { /* Not initialised */ if (ctx->nlast_block == -1) return 0; if (!EVP_EncryptInit_ex(ctx->cctx, NULL, NULL, NULL, zero_iv)) return 0; memset(ctx->tbl, 0, EVP_CIPHER_CTX_block_size(ctx->cctx)); ctx->nlast_block = 0; return 1; } /* Initialise context */ if (cipher && !EVP_EncryptInit_ex(ctx->cctx, cipher, impl, NULL, NULL)) return 0; /* Non-NULL key means initialisation complete */ if (key) { int bl; if (!EVP_CIPHER_CTX_cipher(ctx->cctx)) return 0; if (!EVP_CIPHER_CTX_set_key_length(ctx->cctx, keylen)) return 0; if (!EVP_EncryptInit_ex(ctx->cctx, NULL, NULL, key, zero_iv)) return 0; bl = EVP_CIPHER_CTX_block_size(ctx->cctx); if (!EVP_Cipher(ctx->cctx, ctx->tbl, zero_iv, bl)) return 0; make_kn(ctx->k1, ctx->tbl, bl); make_kn(ctx->k2, ctx->k1, bl); OPENSSL_cleanse(ctx->tbl, bl); /* Reset context again ready for first data block */ if (!EVP_EncryptInit_ex(ctx->cctx, NULL, NULL, NULL, zero_iv)) return 0; /* Zero tbl so resume works */ memset(ctx->tbl, 0, bl); ctx->nlast_block = 0; } return 1; } int CMAC_Update(CMAC_CTX *ctx, const void *in, size_t dlen) { const unsigned char *data = in; size_t bl; if (ctx->nlast_block == -1) return 0; if (dlen == 0) return 1; bl = EVP_CIPHER_CTX_block_size(ctx->cctx); /* Copy into partial block if we need to */ if (ctx->nlast_block > 0) { size_t nleft; nleft = bl - ctx->nlast_block; if (dlen < nleft) nleft = dlen; memcpy(ctx->last_block + ctx->nlast_block, data, nleft); dlen -= nleft; ctx->nlast_block += nleft; /* If no more to process return */ if (dlen == 0) return 1; data += nleft; /* Else not final block so encrypt it */ if (!EVP_Cipher(ctx->cctx, ctx->tbl, ctx->last_block, bl)) return 0; } /* Encrypt all but one of the complete blocks left */ while (dlen > bl) { if (!EVP_Cipher(ctx->cctx, ctx->tbl, data, bl)) return 0; dlen -= bl; data += bl; } /* Copy any data left to last block buffer */ memcpy(ctx->last_block, data, dlen); ctx->nlast_block = dlen; return 1; } int CMAC_Final(CMAC_CTX *ctx, unsigned char *out, size_t *poutlen) { int i, bl, lb; if (ctx->nlast_block == -1) return 0; bl = EVP_CIPHER_CTX_block_size(ctx->cctx); *poutlen = (size_t)bl; if (!out) return 1; lb = ctx->nlast_block; /* Is last block complete? */ if (lb == bl) { for (i = 0; i < bl; i++) out[i] = ctx->last_block[i] ^ ctx->k1[i]; } else { ctx->last_block[lb] = 0x80; if (bl - lb > 1) memset(ctx->last_block + lb + 1, 0, bl - lb - 1); for (i = 0; i < bl; i++) out[i] = ctx->last_block[i] ^ ctx->k2[i]; } if (!EVP_Cipher(ctx->cctx, out, out, bl)) { OPENSSL_cleanse(out, bl); return 0; } return 1; } int CMAC_resume(CMAC_CTX *ctx) { if (ctx->nlast_block == -1) return 0; /* * The buffer "tbl" contains the last fully encrypted block which is the * last IV (or all zeroes if no last encrypted block). The last block has * not been modified since CMAC_final(). So reinitialising using the last * decrypted block will allow CMAC to continue after calling * CMAC_Final(). */ return EVP_EncryptInit_ex(ctx->cctx, NULL, NULL, NULL, ctx->tbl); }
404780.c
/****************************************************************************** * Automatically generated file. Please don't change anything. * *****************************************************************************/ #include <stdlib.h> #include <lua.h> #include <lauxlib.h> #include "iup.h" #include "iuplua.h" #include "iupcontrols.h" #include "il.h" static int colorbar_switch_cb(Ihandle *self, int p0, int p1) { lua_State *L = iuplua_call_start(self, "switch_cb"); lua_pushinteger(L, p0); lua_pushinteger(L, p1); return iuplua_call(L, 2); } static int colorbar_select_cb(Ihandle *self, int p0, int p1) { lua_State *L = iuplua_call_start(self, "select_cb"); lua_pushinteger(L, p0); lua_pushinteger(L, p1); return iuplua_call(L, 2); } static char * colorbar_cell_cb(Ihandle *self, int p0) { lua_State *L = iuplua_call_start(self, "cell_cb"); lua_pushinteger(L, p0); return iuplua_call_ret_s(L, 1); } static int colorbar_extended_cb(Ihandle *self, int p0) { lua_State *L = iuplua_call_start(self, "extended_cb"); lua_pushinteger(L, p0); return iuplua_call(L, 1); } static int Colorbar(lua_State *L) { Ihandle *ih = IupColorbar(); iuplua_plugstate(L, ih); iuplua_pushihandle_raw(L, ih); return 1; } int iupcolorbarlua_open(lua_State * L) { iuplua_register(L, Colorbar, "Colorbar"); iuplua_register_cb(L, "SWITCH_CB", (lua_CFunction)colorbar_switch_cb, NULL); iuplua_register_cb(L, "SELECT_CB", (lua_CFunction)colorbar_select_cb, NULL); iuplua_register_cb(L, "CELL_CB", (lua_CFunction)colorbar_cell_cb, NULL); iuplua_register_cb(L, "EXTENDED_CB", (lua_CFunction)colorbar_extended_cb, NULL); #ifdef IUPLUA_USELOH #include "colorbar.loh" #else #ifdef IUPLUA_USELH #include "colorbar.lh" #else iuplua_dofile(L, "colorbar.lua"); #endif #endif return 0; }
362941.c
/******************************************************************************* * Agere Systems Inc. * Wireless device driver for Linux (wlags49). * * Copyright (c) 1998-2003 Agere Systems Inc. * All rights reserved. * http://www.agere.com * * Initially developed by TriplePoint, Inc. * http://www.triplepoint.com * *------------------------------------------------------------------------------ * * This file contains the main driver entry points and other adapter * specific routines. * *------------------------------------------------------------------------------ * * SOFTWARE LICENSE * * This software is provided subject to the following terms and conditions, * which you should read carefully before using the software. Using this * software indicates your acceptance of these terms and conditions. If you do * not agree with these terms and conditions, do not use the software. * * Copyright © 2003 Agere Systems Inc. * All rights reserved. * * Redistribution and use in source or binary forms, with or without * modifications, 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 as comments in the code as * well as in the documentation and/or other materials provided with the * distribution. * * . Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following Disclaimer in the documentation * and/or other materials provided with the distribution. * * . Neither the name of Agere Systems Inc. nor the names of the contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * Disclaimer * * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. 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, INCLUDING, BUT NOT LIMITED TO, 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. * ******************************************************************************/ /******************************************************************************* * constant definitions ******************************************************************************/ /* Allow support for calling system fcns to access F/W iamge file */ #define __KERNEL_SYSCALLS__ /******************************************************************************* * include files ******************************************************************************/ #include <wl_version.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/types.h> #include <linux/kernel.h> // #include <linux/sched.h> // #include <linux/ptrace.h> // #include <linux/slab.h> // #include <linux/ctype.h> // #include <linux/string.h> // #include <linux/timer.h> //#include <linux/interrupt.h> // #include <linux/tqueue.h> // #include <linux/in.h> // #include <linux/delay.h> // #include <asm/io.h> // #include <asm/system.h> // #include <asm/bitops.h> #include <linux/unistd.h> #include <asm/uaccess.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> // #include <linux/skbuff.h> // #include <linux/if_arp.h> // #include <linux/ioport.h> #define BIN_DL 0 #if BIN_DL #include <linux/vmalloc.h> #endif // BIN_DL #include <debug.h> #include <hcf.h> #include <dhf.h> //in order to get around:: wl_main.c:2229: `HREG_EV_RDMAD' undeclared (first use in this function) #include <hcfdef.h> #include <wl_if.h> #include <wl_internal.h> #include <wl_util.h> #include <wl_main.h> #include <wl_netdev.h> #include <wl_wext.h> #ifdef USE_PROFILE #include <wl_profile.h> #endif /* USE_PROFILE */ #ifdef BUS_PCMCIA #include <wl_cs.h> #endif /* BUS_PCMCIA */ #ifdef BUS_PCI #include <wl_pci.h> #endif /* BUS_PCI */ /******************************************************************************* * macro defintions ******************************************************************************/ #define VALID_PARAM(C) \ { \ if (!(C)) \ { \ printk(KERN_INFO "Wireless, parameter error: \"%s\"\n", #C); \ goto failed; \ } \ } /******************************************************************************* * local functions ******************************************************************************/ void wl_isr_handler( unsigned long p ); #if 0 //SCULL_USE_PROC /* don't waste space if unused */ //int scull_read_procmem(char *buf, char **start, off_t offset, int len, int unused); int scull_read_procmem(char *buf, char **start, off_t offset, int len, int *eof, void *data ); static int write_int(struct file *file, const char *buffer, unsigned long count, void *data); static void proc_write(const char *name, write_proc_t *w, void *data); #endif /* SCULL_USE_PROC */ /******************************************************************************* * module parameter definitions - set with 'insmod' ******************************************************************************/ static p_u16 irq_mask = 0xdeb8; // IRQ3,4,5,7,9,10,11,12,14,15 static p_s8 irq_list[4] = { -1 }; #if 0 MODULE_PARM(irq_mask, "h"); MODULE_PARM_DESC(irq_mask, "IRQ mask [0xdeb8]"); MODULE_PARM(irq_list, "1-4b"); MODULE_PARM_DESC(irq_list, "IRQ list [<irq_mask>]"); #endif static p_u8 PARM_AUTHENTICATION = PARM_DEFAULT_AUTHENTICATION; static p_u16 PARM_AUTH_KEY_MGMT_SUITE = PARM_DEFAULT_AUTH_KEY_MGMT_SUITE; static p_u16 PARM_BRSC_2GHZ = PARM_DEFAULT_BRSC_2GHZ; static p_u16 PARM_BRSC_5GHZ = PARM_DEFAULT_BRSC_5GHZ; static p_u16 PARM_COEXISTENCE = PARM_DEFAULT_COEXISTENCE; static p_u16 PARM_CONNECTION_CONTROL = PARM_DEFAULT_CONNECTION_CONTROL; //;?rename and move static p_char *PARM_CREATE_IBSS = PARM_DEFAULT_CREATE_IBSS_STR; static p_char *PARM_DESIRED_SSID = PARM_DEFAULT_SSID; static p_char *PARM_DOWNLOAD_FIRMWARE = ""; static p_u16 PARM_ENABLE_ENCRYPTION = PARM_DEFAULT_ENABLE_ENCRYPTION; static p_char *PARM_EXCLUDE_UNENCRYPTED = PARM_DEFAULT_EXCLUDE_UNENCRYPTED_STR; static p_char *PARM_INTRA_BSS_RELAY = PARM_DEFAULT_INTRA_BSS_RELAY_STR; static p_char *PARM_KEY1 = ""; static p_char *PARM_KEY2 = ""; static p_char *PARM_KEY3 = ""; static p_char *PARM_KEY4 = ""; static p_char *PARM_LOAD_BALANCING = PARM_DEFAULT_LOAD_BALANCING_STR; static p_u16 PARM_MAX_SLEEP = PARM_DEFAULT_MAX_PM_SLEEP; static p_char *PARM_MEDIUM_DISTRIBUTION = PARM_DEFAULT_MEDIUM_DISTRIBUTION_STR; static p_char *PARM_MICROWAVE_ROBUSTNESS = PARM_DEFAULT_MICROWAVE_ROBUSTNESS_STR; static p_char *PARM_MULTICAST_PM_BUFFERING = PARM_DEFAULT_MULTICAST_PM_BUFFERING_STR; static p_u16 PARM_MULTICAST_RATE = PARM_DEFAULT_MULTICAST_RATE_2GHZ; static p_char *PARM_MULTICAST_RX = PARM_DEFAULT_MULTICAST_RX_STR; static p_u8 PARM_NETWORK_ADDR[ETH_ALEN] = PARM_DEFAULT_NETWORK_ADDR; static p_u16 PARM_OWN_ATIM_WINDOW = PARM_DEFAULT_OWN_ATIM_WINDOW; static p_u16 PARM_OWN_BEACON_INTERVAL = PARM_DEFAULT_OWN_BEACON_INTERVAL; static p_u8 PARM_OWN_CHANNEL = PARM_DEFAULT_OWN_CHANNEL; static p_u8 PARM_OWN_DTIM_PERIOD = PARM_DEFAULT_OWN_DTIM_PERIOD; static p_char *PARM_OWN_NAME = PARM_DEFAULT_OWN_NAME; static p_char *PARM_OWN_SSID = PARM_DEFAULT_SSID; static p_u16 PARM_PM_ENABLED = WVLAN_PM_STATE_DISABLED; static p_u16 PARM_PM_HOLDOVER_DURATION = PARM_DEFAULT_PM_HOLDOVER_DURATION; static p_u8 PARM_PORT_TYPE = PARM_DEFAULT_PORT_TYPE; static p_char *PARM_PROMISCUOUS_MODE = PARM_DEFAULT_PROMISCUOUS_MODE_STR; static p_char *PARM_REJECT_ANY = PARM_DEFAULT_REJECT_ANY_STR; #ifdef USE_WDS static p_u16 PARM_RTS_THRESHOLD1 = PARM_DEFAULT_RTS_THRESHOLD; static p_u16 PARM_RTS_THRESHOLD2 = PARM_DEFAULT_RTS_THRESHOLD; static p_u16 PARM_RTS_THRESHOLD3 = PARM_DEFAULT_RTS_THRESHOLD; static p_u16 PARM_RTS_THRESHOLD4 = PARM_DEFAULT_RTS_THRESHOLD; static p_u16 PARM_RTS_THRESHOLD5 = PARM_DEFAULT_RTS_THRESHOLD; static p_u16 PARM_RTS_THRESHOLD6 = PARM_DEFAULT_RTS_THRESHOLD; #endif // USE_WDS static p_u16 PARM_RTS_THRESHOLD = PARM_DEFAULT_RTS_THRESHOLD; static p_u16 PARM_SRSC_2GHZ = PARM_DEFAULT_SRSC_2GHZ; static p_u16 PARM_SRSC_5GHZ = PARM_DEFAULT_SRSC_5GHZ; static p_u8 PARM_SYSTEM_SCALE = PARM_DEFAULT_SYSTEM_SCALE; static p_u8 PARM_TX_KEY = PARM_DEFAULT_TX_KEY; static p_u16 PARM_TX_POW_LEVEL = PARM_DEFAULT_TX_POW_LEVEL; #ifdef USE_WDS static p_u16 PARM_TX_RATE1 = PARM_DEFAULT_TX_RATE_2GHZ; static p_u16 PARM_TX_RATE2 = PARM_DEFAULT_TX_RATE_2GHZ; static p_u16 PARM_TX_RATE3 = PARM_DEFAULT_TX_RATE_2GHZ; static p_u16 PARM_TX_RATE4 = PARM_DEFAULT_TX_RATE_2GHZ; static p_u16 PARM_TX_RATE5 = PARM_DEFAULT_TX_RATE_2GHZ; static p_u16 PARM_TX_RATE6 = PARM_DEFAULT_TX_RATE_2GHZ; #endif // USE_WDS static p_u16 PARM_TX_RATE = PARM_DEFAULT_TX_RATE_2GHZ; #ifdef USE_WDS static p_u8 PARM_WDS_ADDRESS1[ETH_ALEN] = PARM_DEFAULT_NETWORK_ADDR; static p_u8 PARM_WDS_ADDRESS2[ETH_ALEN] = PARM_DEFAULT_NETWORK_ADDR; static p_u8 PARM_WDS_ADDRESS3[ETH_ALEN] = PARM_DEFAULT_NETWORK_ADDR; static p_u8 PARM_WDS_ADDRESS4[ETH_ALEN] = PARM_DEFAULT_NETWORK_ADDR; static p_u8 PARM_WDS_ADDRESS5[ETH_ALEN] = PARM_DEFAULT_NETWORK_ADDR; static p_u8 PARM_WDS_ADDRESS6[ETH_ALEN] = PARM_DEFAULT_NETWORK_ADDR; #endif // USE_WDS #if 0 MODULE_PARM(PARM_DESIRED_SSID, "s"); MODULE_PARM_DESC(PARM_DESIRED_SSID, "Network Name (<string>) [ANY]"); MODULE_PARM(PARM_OWN_SSID, "s"); MODULE_PARM_DESC(PARM_OWN_SSID, "Network Name (<string>) [ANY]"); MODULE_PARM(PARM_OWN_CHANNEL, "b"); MODULE_PARM_DESC(PARM_OWN_CHANNEL, "Channel (0 - 14) [0]"); MODULE_PARM(PARM_SYSTEM_SCALE, "b"); MODULE_PARM_DESC(PARM_SYSTEM_SCALE, "Distance Between APs (1 - 3) [1]"); MODULE_PARM(PARM_TX_RATE, "b"); MODULE_PARM_DESC(PARM_TX_RATE, "Transmit Rate Control"); MODULE_PARM(PARM_RTS_THRESHOLD, "h"); MODULE_PARM_DESC(PARM_RTS_THRESHOLD, "Medium Reservation (RTS/CTS Fragment Length) (256 - 2347) [2347]"); MODULE_PARM(PARM_MICROWAVE_ROBUSTNESS, "s"); MODULE_PARM_DESC(PARM_MICROWAVE_ROBUSTNESS, "Microwave Oven Robustness Enabled (<string> N or Y) [N]"); MODULE_PARM(PARM_OWN_NAME, "s"); MODULE_PARM_DESC(PARM_OWN_NAME, "Station Name (<string>) [Linux]"); MODULE_PARM(PARM_ENABLE_ENCRYPTION, "b"); MODULE_PARM_DESC(PARM_ENABLE_ENCRYPTION, "Encryption Mode (0 - 7) [0]"); MODULE_PARM(PARM_KEY1, "s"); MODULE_PARM_DESC(PARM_KEY1, "Data Encryption Key 1 (<string>) []"); MODULE_PARM(PARM_KEY2, "s"); MODULE_PARM_DESC(PARM_KEY2, "Data Encryption Key 2 (<string>) []"); MODULE_PARM(PARM_KEY3, "s"); MODULE_PARM_DESC(PARM_KEY3, "Data Encryption Key 3 (<string>) []"); MODULE_PARM(PARM_KEY4, "s"); MODULE_PARM_DESC(PARM_KEY4, "Data Encryption Key 4 (<string>) []"); MODULE_PARM(PARM_TX_KEY, "b"); MODULE_PARM_DESC(PARM_TX_KEY, "Transmit Key ID (1 - 4) [1]"); MODULE_PARM(PARM_MULTICAST_RATE, "b"); MODULE_PARM_DESC(PARM_MULTICAST_RATE, "Multicast Rate"); MODULE_PARM(PARM_DOWNLOAD_FIRMWARE, "s"); MODULE_PARM_DESC(PARM_DOWNLOAD_FIRMWARE, "filename of firmware image"); MODULE_PARM(PARM_AUTH_KEY_MGMT_SUITE, "b"); MODULE_PARM_DESC(PARM_AUTH_KEY_MGMT_SUITE, "Authentication Key Management suite (0-4) [0]"); MODULE_PARM(PARM_LOAD_BALANCING, "s"); MODULE_PARM_DESC(PARM_LOAD_BALANCING, "Load Balancing Enabled (<string> N or Y) [Y]"); MODULE_PARM(PARM_MEDIUM_DISTRIBUTION, "s"); MODULE_PARM_DESC(PARM_MEDIUM_DISTRIBUTION, "Medium Distribution Enabled (<string> N or Y) [Y]"); MODULE_PARM(PARM_TX_POW_LEVEL, "b"); MODULE_PARM_DESC(PARM_TX_POW_LEVEL, "Transmit Power (0 - 6) [3]"); MODULE_PARM(PARM_SRSC_2GHZ, "b"); MODULE_PARM_DESC(PARM_SRSC_2GHZ, "Supported Rate Set Control 2.4 GHz"); MODULE_PARM(PARM_SRSC_5GHZ, "b"); MODULE_PARM_DESC(PARM_SRSC_5GHZ, "Supported Rate Set Control 5.0 GHz"); MODULE_PARM(PARM_BRSC_2GHZ, "b"); MODULE_PARM_DESC(PARM_BRSC_2GHZ, "Basic Rate Set Control 2.4 GHz"); MODULE_PARM(PARM_BRSC_5GHZ, "b"); MODULE_PARM_DESC(PARM_BRSC_5GHZ, "Basic Rate Set Control 5.0 GHz"); #if 1 //;? (HCF_TYPE) & HCF_TYPE_STA //;?seems reasonable that even an AP-only driver could afford this small additional footprint MODULE_PARM(PARM_PM_ENABLED, "h"); MODULE_PARM_DESC(PARM_PM_ENABLED, "Power Management State (0 - 2, 8001 - 8002) [0]"); MODULE_PARM(PARM_PORT_TYPE, "b"); MODULE_PARM_DESC(PARM_PORT_TYPE, "Port Type (1 - 3) [1]"); //;?MODULE_PARM(PARM_CREATE_IBSS, "s"); //;?MODULE_PARM_DESC(PARM_CREATE_IBSS, "Create IBSS (<string> N or Y) [N]"); //;?MODULE_PARM(PARM_MULTICAST_RX, "s"); //;?MODULE_PARM_DESC(PARM_MULTICAST_RX, "Multicast Receive Enable (<string> N or Y) [Y]"); //;?MODULE_PARM(PARM_MAX_SLEEP, "h"); //;?MODULE_PARM_DESC(PARM_MAX_SLEEP, "Maximum Power Management Sleep Duration (0 - 65535) [100]"); //;?MODULE_PARM(PARM_NETWORK_ADDR, "6b"); //;?MODULE_PARM_DESC(PARM_NETWORK_ADDR, "Hardware Ethernet Address ([0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff]) [<factory value>]"); //;?MODULE_PARM(PARM_AUTHENTICATION, "b"); // //tracker 12448 //;?MODULE_PARM_DESC(PARM_AUTHENTICATION, "Authentication Type (0-2) [0] 0=Open 1=SharedKey 2=LEAP"); //;?MODULE_PARM_DESC(authentication, "Authentication Type (1-2) [1] 1=Open 2=SharedKey"); //tracker 12448 // //;?MODULE_PARM(PARM_OWN_ATIM_WINDOW, "b"); //;?MODULE_PARM_DESC(PARM_OWN_ATIM_WINDOW, "ATIM Window time in TU for IBSS creation (0-100) [0]"); //;?MODULE_PARM(PARM_PM_HOLDOVER_DURATION, "b"); //;?MODULE_PARM_DESC(PARM_PM_HOLDOVER_DURATION, "Time station remains awake after MAC frame transfer when PM is on (0-65535) [100]"); //;?MODULE_PARM(PARM_PROMISCUOUS_MODE, "s"); //;?MODULE_PARM_DESC(PARM_PROMISCUOUS_MODE, "Promiscuous Mode Enable (<string> Y or N ) [N]" ); //;? MODULE_PARM(PARM_CONNECTION_CONTROL, "b"); MODULE_PARM_DESC(PARM_CONNECTION_CONTROL, "Connection Control (0 - 3) [2]"); #endif /* HCF_STA */ #if 1 //;? (HCF_TYPE) & HCF_TYPE_AP //;?should we restore this to allow smaller memory footprint MODULE_PARM(PARM_OWN_DTIM_PERIOD, "b"); MODULE_PARM_DESC(PARM_OWN_DTIM_PERIOD, "DTIM Period (0 - 255) [1]"); MODULE_PARM(PARM_REJECT_ANY, "s"); MODULE_PARM_DESC(PARM_REJECT_ANY, "Closed System (<string> N or Y) [N]"); MODULE_PARM(PARM_EXCLUDE_UNENCRYPTED, "s"); MODULE_PARM_DESC(PARM_EXCLUDE_UNENCRYPTED, "Deny non-encrypted (<string> N or Y) [Y]"); MODULE_PARM(PARM_MULTICAST_PM_BUFFERING,"s"); MODULE_PARM_DESC(PARM_MULTICAST_PM_BUFFERING, "Buffer MAC frames for Tx after DTIM (<string> Y or N) [Y]"); MODULE_PARM(PARM_INTRA_BSS_RELAY, "s"); MODULE_PARM_DESC(PARM_INTRA_BSS_RELAY, "IntraBSS Relay (<string> N or Y) [Y]"); MODULE_PARM(PARM_RTS_THRESHOLD1, "h"); MODULE_PARM_DESC(PARM_RTS_THRESHOLD1, "RTS Threshold, WDS Port 1 (256 - 2347) [2347]"); MODULE_PARM(PARM_RTS_THRESHOLD2, "h"); MODULE_PARM_DESC(PARM_RTS_THRESHOLD2, "RTS Threshold, WDS Port 2 (256 - 2347) [2347]"); MODULE_PARM(PARM_RTS_THRESHOLD3, "h"); MODULE_PARM_DESC(PARM_RTS_THRESHOLD3, "RTS Threshold, WDS Port 3 (256 - 2347) [2347]"); MODULE_PARM(PARM_RTS_THRESHOLD4, "h"); MODULE_PARM_DESC(PARM_RTS_THRESHOLD4, "RTS Threshold, WDS Port 4 (256 - 2347) [2347]"); MODULE_PARM(PARM_RTS_THRESHOLD5, "h"); MODULE_PARM_DESC(PARM_RTS_THRESHOLD5, "RTS Threshold, WDS Port 5 (256 - 2347) [2347]"); MODULE_PARM(PARM_RTS_THRESHOLD6, "h"); MODULE_PARM_DESC(PARM_RTS_THRESHOLD6, "RTS Threshold, WDS Port 6 (256 - 2347) [2347]"); MODULE_PARM(PARM_TX_RATE1, "b"); MODULE_PARM_DESC(PARM_TX_RATE1, "Transmit Rate Control, WDS Port 1 (1 - 7) [3]"); MODULE_PARM(PARM_TX_RATE2, "b"); MODULE_PARM_DESC(PARM_TX_RATE2, "Transmit Rate Control, WDS Port 2 (1 - 7) [3]"); MODULE_PARM(PARM_TX_RATE3, "b"); MODULE_PARM_DESC(PARM_TX_RATE3, "Transmit Rate Control, WDS Port 3 (1 - 7) [3]"); MODULE_PARM(PARM_TX_RATE4, "b"); MODULE_PARM_DESC(PARM_TX_RATE4, "Transmit Rate Control, WDS Port 4 (1 - 7) [3]"); MODULE_PARM(PARM_TX_RATE5, "b"); MODULE_PARM_DESC(PARM_TX_RATE5, "Transmit Rate Control, WDS Port 5 (1 - 7) [3]"); MODULE_PARM(PARM_TX_RATE6, "b"); MODULE_PARM_DESC(PARM_TX_RATE6, "Transmit Rate Control, WDS Port 6 (1 - 7) [3]"); MODULE_PARM(PARM_WDS_ADDRESS1, "6b"); MODULE_PARM_DESC(PARM_WDS_ADDRESS1, "MAC Address, WDS Port 1 ([0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff]) [{0}]"); MODULE_PARM(PARM_WDS_ADDRESS2, "6b"); MODULE_PARM_DESC(PARM_WDS_ADDRESS2, "MAC Address, WDS Port 2 ([0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff]) [{0}]"); MODULE_PARM(PARM_WDS_ADDRESS3, "6b"); MODULE_PARM_DESC(PARM_WDS_ADDRESS3, "MAC Address, WDS Port 3 ([0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff]) [{0}]"); MODULE_PARM(PARM_WDS_ADDRESS4, "6b"); MODULE_PARM_DESC(PARM_WDS_ADDRESS4, "MAC Address, WDS Port 4 ([0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff]) [{0}]"); MODULE_PARM(PARM_WDS_ADDRESS5, "6b"); MODULE_PARM_DESC(PARM_WDS_ADDRESS5, "MAC Address, WDS Port 5 ([0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff]) [{0}]"); MODULE_PARM(PARM_WDS_ADDRESS6, "6b"); MODULE_PARM_DESC(PARM_WDS_ADDRESS6, "MAC Address, WDS Port 6 ([0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff],[0x00-0xff]) [{0}]"); MODULE_PARM(PARM_OWN_BEACON_INTERVAL, "b"); MODULE_PARM_DESC(PARM_OWN_BEACON_INTERVAL, "Own Beacon Interval (20 - 200) [100]"); MODULE_PARM(PARM_COEXISTENCE, "b"); MODULE_PARM_DESC(PARM_COEXISTENCE, "Coexistence (0-7) [0]"); #endif /* HCF_AP */ #endif /* END NEW PARAMETERS */ /******************************************************************************* * debugging specifics ******************************************************************************/ #if DBG static p_u32 pc_debug = DBG_LVL; //MODULE_PARM(pc_debug, "i"); /*static ;?conflicts with my understanding of CL parameters and breaks now I moved * the correspondig logic to wl_profile */ p_u32 DebugFlag = ~0; //recognizable "undefined value" rather then DBG_DEFAULTS; //MODULE_PARM(DebugFlag, "l"); dbg_info_t wl_info = { DBG_MOD_NAME, 0, 0 }; dbg_info_t *DbgInfo = &wl_info; #endif /* DBG */ #ifdef USE_RTS static p_char *useRTS = "N"; MODULE_PARM( useRTS, "s" ); MODULE_PARM_DESC( useRTS, "Use RTS test interface (<string> N or Y) [N]" ); #endif /* USE_RTS */ /******************************************************************************* * firmware download specifics ******************************************************************************/ extern struct CFG_RANGE2_STRCT BASED cfg_drv_act_ranges_pri; // describes primary-actor range of HCF #if 0 //;? (HCF_TYPE) & HCF_TYPE_AP extern memimage ap; // AP firmware image to be downloaded #endif /* HCF_AP */ #if 1 //;? (HCF_TYPE) & HCF_TYPE_STA //extern memimage station; // STA firmware image to be downloaded extern memimage fw_image; // firmware image to be downloaded #endif /* HCF_STA */ int wl_insert( struct net_device *dev ) { int result = 0; int hcf_status = HCF_SUCCESS; int i; unsigned long flags = 0; struct wl_private *lp = wl_priv(dev); /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_insert" ); DBG_ENTER( DbgInfo ); /* Initialize the adapter hardware. */ memset( &( lp->hcfCtx ), 0, sizeof( IFB_STRCT )); /* Initialize the adapter parameters. */ spin_lock_init( &( lp->slock )); /* Initialize states */ //lp->lockcount = 0; //PE1DNN lp->is_handling_int = WL_NOT_HANDLING_INT; lp->firmware_present = WL_FRIMWARE_NOT_PRESENT; lp->dev = dev; DBG_PARAM( DbgInfo, "irq_mask", "0x%04x", irq_mask & 0x0FFFF ); DBG_PARAM( DbgInfo, "irq_list", "0x%02x 0x%02x 0x%02x 0x%02x", irq_list[0] & 0x0FF, irq_list[1] & 0x0FF, irq_list[2] & 0x0FF, irq_list[3] & 0x0FF ); DBG_PARAM( DbgInfo, PARM_NAME_DESIRED_SSID, "\"%s\"", PARM_DESIRED_SSID ); DBG_PARAM( DbgInfo, PARM_NAME_OWN_SSID, "\"%s\"", PARM_OWN_SSID ); DBG_PARAM( DbgInfo, PARM_NAME_OWN_CHANNEL, "%d", PARM_OWN_CHANNEL); DBG_PARAM( DbgInfo, PARM_NAME_SYSTEM_SCALE, "%d", PARM_SYSTEM_SCALE ); DBG_PARAM( DbgInfo, PARM_NAME_TX_RATE, "%d", PARM_TX_RATE ); DBG_PARAM( DbgInfo, PARM_NAME_RTS_THRESHOLD, "%d", PARM_RTS_THRESHOLD ); DBG_PARAM( DbgInfo, PARM_NAME_MICROWAVE_ROBUSTNESS, "\"%s\"", PARM_MICROWAVE_ROBUSTNESS ); DBG_PARAM( DbgInfo, PARM_NAME_OWN_NAME, "\"%s\"", PARM_OWN_NAME ); //;? DBG_PARAM( DbgInfo, PARM_NAME_ENABLE_ENCRYPTION, "\"%s\"", PARM_ENABLE_ENCRYPTION ); DBG_PARAM( DbgInfo, PARM_NAME_KEY1, "\"%s\"", PARM_KEY1 ); DBG_PARAM( DbgInfo, PARM_NAME_KEY2, "\"%s\"", PARM_KEY2 ); DBG_PARAM( DbgInfo, PARM_NAME_KEY3, "\"%s\"", PARM_KEY3 ); DBG_PARAM( DbgInfo, PARM_NAME_KEY4, "\"%s\"", PARM_KEY4 ); DBG_PARAM( DbgInfo, PARM_NAME_TX_KEY, "%d", PARM_TX_KEY ); DBG_PARAM( DbgInfo, PARM_NAME_MULTICAST_RATE, "%d", PARM_MULTICAST_RATE ); DBG_PARAM( DbgInfo, PARM_NAME_DOWNLOAD_FIRMWARE, "\"%s\"", PARM_DOWNLOAD_FIRMWARE ); DBG_PARAM( DbgInfo, PARM_NAME_AUTH_KEY_MGMT_SUITE, "%d", PARM_AUTH_KEY_MGMT_SUITE ); //;?#if (HCF_TYPE) & HCF_TYPE_STA //;?should we make this code conditional depending on in STA mode //;? DBG_PARAM( DbgInfo, PARM_NAME_PORT_TYPE, "%d", PARM_PORT_TYPE ); DBG_PARAM( DbgInfo, PARM_NAME_PM_ENABLED, "%04x", PARM_PM_ENABLED ); //;? DBG_PARAM( DbgInfo, PARM_NAME_CREATE_IBSS, "\"%s\"", PARM_CREATE_IBSS ); //;? DBG_PARAM( DbgInfo, PARM_NAME_MULTICAST_RX, "\"%s\"", PARM_MULTICAST_RX ); //;? DBG_PARAM( DbgInfo, PARM_NAME_MAX_SLEEP, "%d", PARM_MAX_SLEEP ); /* DBG_PARAM(DbgInfo, PARM_NAME_NETWORK_ADDR, "\"%pM\"", PARM_NETWORK_ADDR); */ //;? DBG_PARAM( DbgInfo, PARM_NAME_AUTHENTICATION, "%d", PARM_AUTHENTICATION ); //;? DBG_PARAM( DbgInfo, PARM_NAME_OWN_ATIM_WINDOW, "%d", PARM_OWN_ATIM_WINDOW ); //;? DBG_PARAM( DbgInfo, PARM_NAME_PM_HOLDOVER_DURATION, "%d", PARM_PM_HOLDOVER_DURATION ); //;? DBG_PARAM( DbgInfo, PARM_NAME_PROMISCUOUS_MODE, "\"%s\"", PARM_PROMISCUOUS_MODE ); //;?#endif /* HCF_STA */ #if 1 //;? (HCF_TYPE) & HCF_TYPE_AP //;?should we restore this to allow smaller memory footprint //;?I guess: no, since this is Debug mode only DBG_PARAM( DbgInfo, PARM_NAME_OWN_DTIM_PERIOD, "%d", PARM_OWN_DTIM_PERIOD ); DBG_PARAM( DbgInfo, PARM_NAME_REJECT_ANY, "\"%s\"", PARM_REJECT_ANY ); DBG_PARAM( DbgInfo, PARM_NAME_EXCLUDE_UNENCRYPTED, "\"%s\"", PARM_EXCLUDE_UNENCRYPTED ); DBG_PARAM( DbgInfo, PARM_NAME_MULTICAST_PM_BUFFERING, "\"%s\"", PARM_MULTICAST_PM_BUFFERING ); DBG_PARAM( DbgInfo, PARM_NAME_INTRA_BSS_RELAY, "\"%s\"", PARM_INTRA_BSS_RELAY ); #ifdef USE_WDS DBG_PARAM( DbgInfo, PARM_NAME_RTS_THRESHOLD1, "%d", PARM_RTS_THRESHOLD1 ); DBG_PARAM( DbgInfo, PARM_NAME_RTS_THRESHOLD2, "%d", PARM_RTS_THRESHOLD2 ); DBG_PARAM( DbgInfo, PARM_NAME_RTS_THRESHOLD3, "%d", PARM_RTS_THRESHOLD3 ); DBG_PARAM( DbgInfo, PARM_NAME_RTS_THRESHOLD4, "%d", PARM_RTS_THRESHOLD4 ); DBG_PARAM( DbgInfo, PARM_NAME_RTS_THRESHOLD5, "%d", PARM_RTS_THRESHOLD5 ); DBG_PARAM( DbgInfo, PARM_NAME_RTS_THRESHOLD6, "%d", PARM_RTS_THRESHOLD6 ); DBG_PARAM( DbgInfo, PARM_NAME_TX_RATE1, "%d", PARM_TX_RATE1 ); DBG_PARAM( DbgInfo, PARM_NAME_TX_RATE2, "%d", PARM_TX_RATE2 ); DBG_PARAM( DbgInfo, PARM_NAME_TX_RATE3, "%d", PARM_TX_RATE3 ); DBG_PARAM( DbgInfo, PARM_NAME_TX_RATE4, "%d", PARM_TX_RATE4 ); DBG_PARAM( DbgInfo, PARM_NAME_TX_RATE5, "%d", PARM_TX_RATE5 ); DBG_PARAM( DbgInfo, PARM_NAME_TX_RATE6, "%d", PARM_TX_RATE6 ); DBG_PARAM(DbgInfo, PARM_NAME_WDS_ADDRESS1, "\"%pM\"", PARM_WDS_ADDRESS1); DBG_PARAM(DbgInfo, PARM_NAME_WDS_ADDRESS2, "\"%pM\"", PARM_WDS_ADDRESS2); DBG_PARAM(DbgInfo, PARM_NAME_WDS_ADDRESS3, "\"%pM\"", PARM_WDS_ADDRESS3); DBG_PARAM(DbgInfo, PARM_NAME_WDS_ADDRESS4, "\"%pM\"", PARM_WDS_ADDRESS4); DBG_PARAM(DbgInfo, PARM_NAME_WDS_ADDRESS5, "\"%pM\"", PARM_WDS_ADDRESS5); DBG_PARAM(DbgInfo, PARM_NAME_WDS_ADDRESS6, "\"%pM\"", PARM_WDS_ADDRESS6); #endif /* USE_WDS */ #endif /* HCF_AP */ VALID_PARAM( !PARM_DESIRED_SSID || ( strlen( PARM_DESIRED_SSID ) <= PARM_MAX_NAME_LEN )); VALID_PARAM( !PARM_OWN_SSID || ( strlen( PARM_OWN_SSID ) <= PARM_MAX_NAME_LEN )); VALID_PARAM(( PARM_OWN_CHANNEL <= PARM_MAX_OWN_CHANNEL )); VALID_PARAM(( PARM_SYSTEM_SCALE >= PARM_MIN_SYSTEM_SCALE ) && ( PARM_SYSTEM_SCALE <= PARM_MAX_SYSTEM_SCALE )); VALID_PARAM(( PARM_TX_RATE >= PARM_MIN_TX_RATE ) && ( PARM_TX_RATE <= PARM_MAX_TX_RATE )); VALID_PARAM(( PARM_RTS_THRESHOLD <= PARM_MAX_RTS_THRESHOLD )); VALID_PARAM( !PARM_MICROWAVE_ROBUSTNESS || strchr( "NnYy", PARM_MICROWAVE_ROBUSTNESS[0] ) != NULL ); VALID_PARAM( !PARM_OWN_NAME || ( strlen( PARM_NAME_OWN_NAME ) <= PARM_MAX_NAME_LEN )); VALID_PARAM(( PARM_ENABLE_ENCRYPTION <= PARM_MAX_ENABLE_ENCRYPTION )); VALID_PARAM( is_valid_key_string( PARM_KEY1 )); VALID_PARAM( is_valid_key_string( PARM_KEY2 )); VALID_PARAM( is_valid_key_string( PARM_KEY3 )); VALID_PARAM( is_valid_key_string( PARM_KEY4 )); VALID_PARAM(( PARM_TX_KEY >= PARM_MIN_TX_KEY ) && ( PARM_TX_KEY <= PARM_MAX_TX_KEY )); VALID_PARAM(( PARM_MULTICAST_RATE >= PARM_MIN_MULTICAST_RATE ) && ( PARM_MULTICAST_RATE <= PARM_MAX_MULTICAST_RATE )); VALID_PARAM( !PARM_DOWNLOAD_FIRMWARE || ( strlen( PARM_DOWNLOAD_FIRMWARE ) <= 255 /*;?*/ )); VALID_PARAM(( PARM_AUTH_KEY_MGMT_SUITE < PARM_MAX_AUTH_KEY_MGMT_SUITE )); VALID_PARAM( !PARM_LOAD_BALANCING || strchr( "NnYy", PARM_LOAD_BALANCING[0] ) != NULL ); VALID_PARAM( !PARM_MEDIUM_DISTRIBUTION || strchr( "NnYy", PARM_MEDIUM_DISTRIBUTION[0] ) != NULL ); VALID_PARAM(( PARM_TX_POW_LEVEL <= PARM_MAX_TX_POW_LEVEL )); VALID_PARAM(( PARM_PORT_TYPE >= PARM_MIN_PORT_TYPE ) && ( PARM_PORT_TYPE <= PARM_MAX_PORT_TYPE )); VALID_PARAM( PARM_PM_ENABLED <= WVLAN_PM_STATE_STANDARD || ( PARM_PM_ENABLED & 0x7FFF ) <= WVLAN_PM_STATE_STANDARD ); VALID_PARAM( !PARM_CREATE_IBSS || strchr( "NnYy", PARM_CREATE_IBSS[0] ) != NULL ); VALID_PARAM( !PARM_MULTICAST_RX || strchr( "NnYy", PARM_MULTICAST_RX[0] ) != NULL ); VALID_PARAM(( PARM_MAX_SLEEP <= PARM_MAX_MAX_PM_SLEEP )); VALID_PARAM(( PARM_AUTHENTICATION <= PARM_MAX_AUTHENTICATION )); VALID_PARAM(( PARM_OWN_ATIM_WINDOW <= PARM_MAX_OWN_ATIM_WINDOW )); VALID_PARAM(( PARM_PM_HOLDOVER_DURATION <= PARM_MAX_PM_HOLDOVER_DURATION )); VALID_PARAM( !PARM_PROMISCUOUS_MODE || strchr( "NnYy", PARM_PROMISCUOUS_MODE[0] ) != NULL ); VALID_PARAM(( PARM_CONNECTION_CONTROL <= PARM_MAX_CONNECTION_CONTROL )); VALID_PARAM(( PARM_OWN_DTIM_PERIOD >= PARM_MIN_OWN_DTIM_PERIOD )); VALID_PARAM( !PARM_REJECT_ANY || strchr( "NnYy", PARM_REJECT_ANY[0] ) != NULL ); VALID_PARAM( !PARM_EXCLUDE_UNENCRYPTED || strchr( "NnYy", PARM_EXCLUDE_UNENCRYPTED[0] ) != NULL ); VALID_PARAM( !PARM_MULTICAST_PM_BUFFERING || strchr( "NnYy", PARM_MULTICAST_PM_BUFFERING[0] ) != NULL ); VALID_PARAM( !PARM_INTRA_BSS_RELAY || strchr( "NnYy", PARM_INTRA_BSS_RELAY[0] ) != NULL ); #ifdef USE_WDS VALID_PARAM(( PARM_RTS_THRESHOLD1 <= PARM_MAX_RTS_THRESHOLD )); VALID_PARAM(( PARM_RTS_THRESHOLD2 <= PARM_MAX_RTS_THRESHOLD )); VALID_PARAM(( PARM_RTS_THRESHOLD3 <= PARM_MAX_RTS_THRESHOLD )); VALID_PARAM(( PARM_RTS_THRESHOLD4 <= PARM_MAX_RTS_THRESHOLD )); VALID_PARAM(( PARM_RTS_THRESHOLD5 <= PARM_MAX_RTS_THRESHOLD )); VALID_PARAM(( PARM_RTS_THRESHOLD6 <= PARM_MAX_RTS_THRESHOLD )); VALID_PARAM(( PARM_TX_RATE1 >= PARM_MIN_TX_RATE ) && (PARM_TX_RATE1 <= PARM_MAX_TX_RATE )); VALID_PARAM(( PARM_TX_RATE2 >= PARM_MIN_TX_RATE ) && (PARM_TX_RATE2 <= PARM_MAX_TX_RATE )); VALID_PARAM(( PARM_TX_RATE3 >= PARM_MIN_TX_RATE ) && (PARM_TX_RATE3 <= PARM_MAX_TX_RATE )); VALID_PARAM(( PARM_TX_RATE4 >= PARM_MIN_TX_RATE ) && (PARM_TX_RATE4 <= PARM_MAX_TX_RATE )); VALID_PARAM(( PARM_TX_RATE5 >= PARM_MIN_TX_RATE ) && (PARM_TX_RATE5 <= PARM_MAX_TX_RATE )); VALID_PARAM(( PARM_TX_RATE6 >= PARM_MIN_TX_RATE ) && (PARM_TX_RATE6 <= PARM_MAX_TX_RATE )); #endif /* USE_WDS */ VALID_PARAM(( PARM_OWN_BEACON_INTERVAL >= PARM_MIN_OWN_BEACON_INTERVAL ) && ( PARM_OWN_BEACON_INTERVAL <= PARM_MAX_OWN_BEACON_INTERVAL )); VALID_PARAM(( PARM_COEXISTENCE <= PARM_COEXISTENCE )); /* Set the driver parameters from the passed in parameters. */ /* THESE MODULE PARAMETERS ARE TO BE DEPRECATED IN FAVOR OF A NAMING CONVENTION WHICH IS INLINE WITH THE FORTHCOMING WAVELAN API */ /* START NEW PARAMETERS */ lp->Channel = PARM_OWN_CHANNEL; lp->DistanceBetweenAPs = PARM_SYSTEM_SCALE; /* Need to determine how to handle the new bands for 5GHz */ lp->TxRateControl[0] = PARM_DEFAULT_TX_RATE_2GHZ; lp->TxRateControl[1] = PARM_DEFAULT_TX_RATE_5GHZ; lp->RTSThreshold = PARM_RTS_THRESHOLD; /* Need to determine how to handle the new bands for 5GHz */ lp->MulticastRate[0] = PARM_DEFAULT_MULTICAST_RATE_2GHZ; lp->MulticastRate[1] = PARM_DEFAULT_MULTICAST_RATE_5GHZ; if ( strchr( "Yy", PARM_MICROWAVE_ROBUSTNESS[0] ) != NULL ) { lp->MicrowaveRobustness = 1; } else { lp->MicrowaveRobustness = 0; } if ( PARM_DESIRED_SSID && ( strlen( PARM_DESIRED_SSID ) <= HCF_MAX_NAME_LEN )) { strcpy( lp->NetworkName, PARM_DESIRED_SSID ); } if ( PARM_OWN_SSID && ( strlen( PARM_OWN_SSID ) <= HCF_MAX_NAME_LEN )) { strcpy( lp->NetworkName, PARM_OWN_SSID ); } if ( PARM_OWN_NAME && ( strlen( PARM_OWN_NAME ) <= HCF_MAX_NAME_LEN )) { strcpy( lp->StationName, PARM_OWN_NAME ); } lp->EnableEncryption = PARM_ENABLE_ENCRYPTION; if ( PARM_KEY1 && ( strlen( PARM_KEY1 ) <= MAX_KEY_LEN )) { strcpy( lp->Key1, PARM_KEY1 ); } if ( PARM_KEY2 && ( strlen( PARM_KEY2 ) <= MAX_KEY_LEN )) { strcpy( lp->Key2, PARM_KEY2 ); } if ( PARM_KEY3 && ( strlen( PARM_KEY3 ) <= MAX_KEY_LEN )) { strcpy( lp->Key3, PARM_KEY3 ); } if ( PARM_KEY4 && ( strlen( PARM_KEY4 ) <= MAX_KEY_LEN )) { strcpy( lp->Key4, PARM_KEY4 ); } lp->TransmitKeyID = PARM_TX_KEY; key_string2key( lp->Key1, &(lp->DefaultKeys.key[0] )); key_string2key( lp->Key2, &(lp->DefaultKeys.key[1] )); key_string2key( lp->Key3, &(lp->DefaultKeys.key[2] )); key_string2key( lp->Key4, &(lp->DefaultKeys.key[3] )); lp->DownloadFirmware = 1 ; //;?to be upgraded PARM_DOWNLOAD_FIRMWARE; lp->AuthKeyMgmtSuite = PARM_AUTH_KEY_MGMT_SUITE; if ( strchr( "Yy", PARM_LOAD_BALANCING[0] ) != NULL ) { lp->loadBalancing = 1; } else { lp->loadBalancing = 0; } if ( strchr( "Yy", PARM_MEDIUM_DISTRIBUTION[0] ) != NULL ) { lp->mediumDistribution = 1; } else { lp->mediumDistribution = 0; } lp->txPowLevel = PARM_TX_POW_LEVEL; lp->srsc[0] = PARM_SRSC_2GHZ; lp->srsc[1] = PARM_SRSC_5GHZ; lp->brsc[0] = PARM_BRSC_2GHZ; lp->brsc[1] = PARM_BRSC_5GHZ; #if 1 //;? (HCF_TYPE) & HCF_TYPE_STA //;?seems reasonable that even an AP-only driver could afford this small additional footprint lp->PortType = PARM_PORT_TYPE; lp->MaxSleepDuration = PARM_MAX_SLEEP; lp->authentication = PARM_AUTHENTICATION; lp->atimWindow = PARM_OWN_ATIM_WINDOW; lp->holdoverDuration = PARM_PM_HOLDOVER_DURATION; lp->PMEnabled = PARM_PM_ENABLED; //;? if ( strchr( "Yy", PARM_CREATE_IBSS[0] ) != NULL ) { lp->CreateIBSS = 1; } else { lp->CreateIBSS = 0; } if ( strchr( "Nn", PARM_MULTICAST_RX[0] ) != NULL ) { lp->MulticastReceive = 0; } else { lp->MulticastReceive = 1; } if ( strchr( "Yy", PARM_PROMISCUOUS_MODE[0] ) != NULL ) { lp->promiscuousMode = 1; } else { lp->promiscuousMode = 0; } for( i = 0; i < ETH_ALEN; i++ ) { lp->MACAddress[i] = PARM_NETWORK_ADDR[i]; } lp->connectionControl = PARM_CONNECTION_CONTROL; #endif /* HCF_STA */ #if 1 //;? (HCF_TYPE) & HCF_TYPE_AP //;?should we restore this to allow smaller memory footprint lp->DTIMPeriod = PARM_OWN_DTIM_PERIOD; if ( strchr( "Yy", PARM_REJECT_ANY[0] ) != NULL ) { lp->RejectAny = 1; } else { lp->RejectAny = 0; } if ( strchr( "Nn", PARM_EXCLUDE_UNENCRYPTED[0] ) != NULL ) { lp->ExcludeUnencrypted = 0; } else { lp->ExcludeUnencrypted = 1; } if ( strchr( "Yy", PARM_MULTICAST_PM_BUFFERING[0] ) != NULL ) { lp->multicastPMBuffering = 1; } else { lp->multicastPMBuffering = 0; } if ( strchr( "Yy", PARM_INTRA_BSS_RELAY[0] ) != NULL ) { lp->intraBSSRelay = 1; } else { lp->intraBSSRelay = 0; } lp->ownBeaconInterval = PARM_OWN_BEACON_INTERVAL; lp->coexistence = PARM_COEXISTENCE; #ifdef USE_WDS lp->wds_port[0].rtsThreshold = PARM_RTS_THRESHOLD1; lp->wds_port[1].rtsThreshold = PARM_RTS_THRESHOLD2; lp->wds_port[2].rtsThreshold = PARM_RTS_THRESHOLD3; lp->wds_port[3].rtsThreshold = PARM_RTS_THRESHOLD4; lp->wds_port[4].rtsThreshold = PARM_RTS_THRESHOLD5; lp->wds_port[5].rtsThreshold = PARM_RTS_THRESHOLD6; lp->wds_port[0].txRateCntl = PARM_TX_RATE1; lp->wds_port[1].txRateCntl = PARM_TX_RATE2; lp->wds_port[2].txRateCntl = PARM_TX_RATE3; lp->wds_port[3].txRateCntl = PARM_TX_RATE4; lp->wds_port[4].txRateCntl = PARM_TX_RATE5; lp->wds_port[5].txRateCntl = PARM_TX_RATE6; for( i = 0; i < ETH_ALEN; i++ ) { lp->wds_port[0].wdsAddress[i] = PARM_WDS_ADDRESS1[i]; } for( i = 0; i < ETH_ALEN; i++ ) { lp->wds_port[1].wdsAddress[i] = PARM_WDS_ADDRESS2[i]; } for( i = 0; i < ETH_ALEN; i++ ) { lp->wds_port[2].wdsAddress[i] = PARM_WDS_ADDRESS3[i]; } for( i = 0; i < ETH_ALEN; i++ ) { lp->wds_port[3].wdsAddress[i] = PARM_WDS_ADDRESS4[i]; } for( i = 0; i < ETH_ALEN; i++ ) { lp->wds_port[4].wdsAddress[i] = PARM_WDS_ADDRESS5[i]; } for( i = 0; i < ETH_ALEN; i++ ) { lp->wds_port[5].wdsAddress[i] = PARM_WDS_ADDRESS6[i]; } #endif /* USE_WDS */ #endif /* HCF_AP */ #ifdef USE_RTS if ( strchr( "Yy", useRTS[0] ) != NULL ) { lp->useRTS = 1; } else { lp->useRTS = 0; } #endif /* USE_RTS */ /* END NEW PARAMETERS */ wl_lock( lp, &flags ); /* Initialize the portState variable */ lp->portState = WVLAN_PORT_STATE_DISABLED; /* Initialize the ScanResult struct */ memset( &( lp->scan_results ), 0, sizeof( lp->scan_results )); lp->scan_results.scan_complete = FALSE; /* Initialize the ProbeResult struct */ memset( &( lp->probe_results ), 0, sizeof( lp->probe_results )); lp->probe_results.scan_complete = FALSE; lp->probe_num_aps = 0; /* Initialize Tx queue stuff */ memset( lp->txList, 0, sizeof( lp->txList )); INIT_LIST_HEAD( &( lp->txFree )); lp->txF.skb = NULL; lp->txF.port = 0; for( i = 0; i < DEFAULT_NUM_TX_FRAMES; i++ ) { list_add_tail( &( lp->txList[i].node ), &( lp->txFree )); } for( i = 0; i < WVLAN_MAX_TX_QUEUES; i++ ) { INIT_LIST_HEAD( &( lp->txQ[i] )); } lp->netif_queue_on = TRUE; lp->txQ_count = 0; /* Initialize the use_dma element in the adapter structure. Not sure if this should be a compile-time or run-time configurable. So for now, implement as run-time and just define here */ #ifdef WARP #ifdef ENABLE_DMA DBG_TRACE( DbgInfo, "HERMES 2.5 BUSMASTER DMA MODE\n" ); lp->use_dma = 1; #else DBG_TRACE( DbgInfo, "HERMES 2.5 PORT I/O MODE\n" ); lp->use_dma = 0; #endif // ENABLE_DMA #endif // WARP /* Register the ISR handler information here, so that it's not done repeatedly in the ISR */ tasklet_init(&lp->task, wl_isr_handler, (unsigned long)lp); /* Connect to the adapter */ DBG_TRACE( DbgInfo, "Calling hcf_connect()...\n" ); hcf_status = hcf_connect( &lp->hcfCtx, dev->base_addr ); //HCF_ERR_INCOMP_FW is acceptable, because download must still take place //HCF_ERR_INCOMP_PRI is not acceptable if ( hcf_status != HCF_SUCCESS && hcf_status != HCF_ERR_INCOMP_FW ) { DBG_ERROR( DbgInfo, "hcf_connect() failed, status: 0x%x\n", hcf_status ); wl_unlock( lp, &flags ); goto hcf_failed; } //;?should set HCF_version and how about driver_stat lp->driverInfo.IO_address = dev->base_addr; lp->driverInfo.IO_range = HCF_NUM_IO_PORTS; //;?conditionally 0x40 or 0x80 seems better lp->driverInfo.IRQ_number = dev->irq; lp->driverInfo.card_stat = lp->hcfCtx.IFB_CardStat; //;? what happened to frame_type /* Fill in the driver identity structure */ lp->driverIdentity.len = ( sizeof( lp->driverIdentity ) / sizeof( hcf_16 )) - 1; lp->driverIdentity.typ = CFG_DRV_IDENTITY; lp->driverIdentity.comp_id = DRV_IDENTITY; lp->driverIdentity.variant = DRV_VARIANT; lp->driverIdentity.version_major = DRV_MAJOR_VERSION; lp->driverIdentity.version_minor = DRV_MINOR_VERSION; /* Start the card here - This needs to be done in order to get the MAC address for the network layer */ DBG_TRACE( DbgInfo, "Calling wvlan_go() to perform a card reset...\n" ); hcf_status = wl_go( lp ); if ( hcf_status != HCF_SUCCESS ) { DBG_ERROR( DbgInfo, "wl_go() failed\n" ); wl_unlock( lp, &flags ); goto hcf_failed; } /* Certain RIDs must be set before enabling the ports */ wl_put_ltv_init( lp ); #if 0 //;?why was this already commented out in wl_lkm_720 /* Enable the ports */ if ( wl_adapter_is_open( lp->dev )) { /* Enable the ports */ DBG_TRACE( DbgInfo, "Enabling Port 0\n" ); hcf_status = wl_enable( lp ); if ( hcf_status != HCF_SUCCESS ) { DBG_TRACE( DbgInfo, "Enable port 0 failed: 0x%x\n", hcf_status ); } #if (HCF_TYPE) & HCF_TYPE_AP DBG_TRACE( DbgInfo, "Enabling WDS Ports\n" ); //wl_enable_wds_ports( lp ); #endif /* (HCF_TYPE) & HCF_TYPE_AP */ } #endif /* Fill out the MAC address information in the net_device struct */ memcpy( lp->dev->dev_addr, lp->MACAddress, ETH_ALEN ); dev->addr_len = ETH_ALEN; lp->is_registered = TRUE; #ifdef USE_PROFILE /* Parse the config file for the sake of creating WDS ports if WDS is configured there but not in the module options */ parse_config( dev ); #endif /* USE_PROFILE */ /* If we're going into AP Mode, register the "virtual" ethernet devices needed for WDS */ WL_WDS_NETDEV_REGISTER( lp ); /* Reset the DownloadFirmware variable in the private struct. If the config file is not used, this will not matter; if it is used, it will be reparsed in wl_open(). This is done because logic in wl_open used to check if a firmware download is needed is broken by parsing the file here; however, this parsing is needed to register WDS ports in AP mode, if they are configured */ lp->DownloadFirmware = WVLAN_DRV_MODE_STA; //;?download_firmware; #ifdef USE_RTS if ( lp->useRTS == 1 ) { DBG_TRACE( DbgInfo, "ENTERING RTS MODE...\n" ); wl_act_int_off( lp ); lp->is_handling_int = WL_NOT_HANDLING_INT; // Not handling interrupts anymore wl_disable( lp ); hcf_connect( &lp->hcfCtx, HCF_DISCONNECT); } #endif /* USE_RTS */ wl_unlock( lp, &flags ); DBG_TRACE( DbgInfo, "%s: Wireless, io_addr %#03lx, irq %d, ""mac_address ", dev->name, dev->base_addr, dev->irq ); for( i = 0; i < ETH_ALEN; i++ ) { printk( "%02X%c", dev->dev_addr[i], (( i < ( ETH_ALEN-1 )) ? ':' : '\n' )); } #if 0 //SCULL_USE_PROC /* don't waste space if unused */ create_proc_read_entry( "wlags", 0, NULL, scull_read_procmem, dev ); proc_mkdir("driver/wlags49", 0); proc_write("driver/wlags49/wlags49_type", write_int, &lp->wlags49_type); #endif /* SCULL_USE_PROC */ DBG_LEAVE( DbgInfo ); return result; hcf_failed: wl_hcf_error( dev, hcf_status ); failed: DBG_ERROR( DbgInfo, "wl_insert() FAILED\n" ); if ( lp->is_registered == TRUE ) { lp->is_registered = FALSE; } WL_WDS_NETDEV_DEREGISTER( lp ); result = -EFAULT; DBG_LEAVE( DbgInfo ); return result; } // wl_insert /*============================================================================*/ /******************************************************************************* * wl_reset() ******************************************************************************* * * DESCRIPTION: * * Reset the adapter. * * PARAMETERS: * * dev - a pointer to the net_device struct of the wireless device * * RETURNS: * * an HCF status code * ******************************************************************************/ int wl_reset(struct net_device *dev) { struct wl_private *lp = wl_priv(dev); int hcf_status = HCF_SUCCESS; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_reset" ); DBG_ENTER( DbgInfo ); DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev ); DBG_PARAM( DbgInfo, "dev->base_addr", "(%#03lx)", dev->base_addr ); /* * The caller should already have a lock and * disable the interrupts, we do not lock here, * nor do we enable/disable interrupts! */ DBG_TRACE( DbgInfo, "Device Base Address: %#03lx\n", dev->base_addr ); if ( dev->base_addr ) { /* Shutdown the adapter. */ hcf_connect( &lp->hcfCtx, HCF_DISCONNECT ); /* Reset the driver information. */ lp->txBytes = 0; /* Connect to the adapter. */ hcf_status = hcf_connect( &lp->hcfCtx, dev->base_addr ); if ( hcf_status != HCF_SUCCESS && hcf_status != HCF_ERR_INCOMP_FW ) { DBG_ERROR( DbgInfo, "hcf_connect() failed, status: 0x%x\n", hcf_status ); goto out; } /* Check if firmware is present, if not change state */ if ( hcf_status == HCF_ERR_INCOMP_FW ) { lp->firmware_present = WL_FRIMWARE_NOT_PRESENT; } /* Initialize the portState variable */ lp->portState = WVLAN_PORT_STATE_DISABLED; /* Restart the adapter. */ hcf_status = wl_go( lp ); if ( hcf_status != HCF_SUCCESS ) { DBG_ERROR( DbgInfo, "wl_go() failed, status: 0x%x\n", hcf_status ); goto out; } /* Certain RIDs must be set before enabling the ports */ wl_put_ltv_init( lp ); } else { DBG_ERROR( DbgInfo, "Device Base Address INVALID!!!\n" ); } out: DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_reset /*============================================================================*/ /******************************************************************************* * wl_go() ******************************************************************************* * * DESCRIPTION: * * Reset the adapter. * * PARAMETERS: * * dev - a pointer to the net_device struct of the wireless device * * RETURNS: * * an HCF status code * ******************************************************************************/ int wl_go( struct wl_private *lp ) { int hcf_status = HCF_SUCCESS; char *cp = NULL; //fw_image int retries = 0; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_go" ); DBG_ENTER( DbgInfo ); hcf_status = wl_disable( lp ); if ( hcf_status != HCF_SUCCESS ) { DBG_TRACE( DbgInfo, "Disable port 0 failed: 0x%x\n", hcf_status ); while (( hcf_status != HCF_SUCCESS ) && (retries < 10)) { retries++; hcf_status = wl_disable( lp ); } if ( hcf_status == HCF_SUCCESS ) { DBG_TRACE( DbgInfo, "Disable port 0 succes : %d retries\n", retries ); } else { DBG_TRACE( DbgInfo, "Disable port 0 failed after: %d retries\n", retries ); } } #if 1 //;? (HCF_TYPE) & HCF_TYPE_AP //DBG_TRACE( DbgInfo, "Disabling WDS Ports\n" ); //wl_disable_wds_ports( lp ); #endif /* (HCF_TYPE) & HCF_TYPE_AP */ //;?what was the purpose of this // /* load the appropriate firmware image, depending on driver mode */ // lp->ltvRecord.len = ( sizeof( CFG_RANGE20_STRCT ) / sizeof( hcf_16 )) - 1; // lp->ltvRecord.typ = CFG_DRV_ACT_RANGES_PRI; // hcf_get_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); #if BIN_DL if ( strlen( lp->fw_image_filename ) ) { mm_segment_t fs; int file_desc; int rc; DBG_TRACE( DbgInfo, "F/W image:%s:\n", lp->fw_image_filename ); /* Obtain a user-space process context, storing the original context */ fs = get_fs( ); set_fs( get_ds( )); file_desc = open( lp->fw_image_filename, O_RDONLY, 0 ); if ( file_desc == -1 ) { DBG_ERROR( DbgInfo, "No image file found\n" ); } else { DBG_TRACE( DbgInfo, "F/W image file found\n" ); #define DHF_ALLOC_SIZE 96000 //just below 96K, let's hope it suffices for now and for the future cp = (char*)vmalloc( DHF_ALLOC_SIZE ); if ( cp == NULL ) { DBG_ERROR( DbgInfo, "error in vmalloc\n" ); } else { rc = read( file_desc, cp, DHF_ALLOC_SIZE ); if ( rc == DHF_ALLOC_SIZE ) { DBG_ERROR( DbgInfo, "buffer too small, %d\n", DHF_ALLOC_SIZE ); } else if ( rc > 0 ) { DBG_TRACE( DbgInfo, "read O.K.: %d bytes %.12s\n", rc, cp ); rc = read( file_desc, &cp[rc], 1 ); if ( rc == 0 ) { //;/change to an until-loop at rc<=0 DBG_TRACE( DbgInfo, "no more to read\n" ); } } if ( rc != 0 ) { DBG_ERROR( DbgInfo, "file not read in one swoop or other error"\ ", give up, too complicated, rc = %0X\n", rc ); DBG_ERROR( DbgInfo, "still have to change code to get a real download now !!!!!!!!\n" ); } else { DBG_TRACE( DbgInfo, "before dhf_download_binary\n" ); hcf_status = dhf_download_binary( (memimage *)cp ); DBG_TRACE( DbgInfo, "after dhf_download_binary, before dhf_download_fw\n" ); //;?improve error flow/handling hcf_status = dhf_download_fw( &lp->hcfCtx, (memimage *)cp ); DBG_TRACE( DbgInfo, "after dhf_download_fw\n" ); } vfree( cp ); } close( file_desc ); } set_fs( fs ); /* Return to the original context */ } #endif // BIN_DL /* If firmware is present but the type is unknown then download anyway */ if ( (lp->firmware_present == WL_FRIMWARE_PRESENT) && ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) != COMP_ID_FW_STA ) && ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) != COMP_ID_FW_AP ) ) { /* Unknown type, download needed. */ lp->firmware_present = WL_FRIMWARE_NOT_PRESENT; } if(lp->firmware_present == WL_FRIMWARE_NOT_PRESENT) { if ( cp == NULL ) { DBG_TRACE( DbgInfo, "Downloading STA firmware...\n" ); // hcf_status = dhf_download_fw( &lp->hcfCtx, &station ); hcf_status = dhf_download_fw( &lp->hcfCtx, &fw_image ); } if ( hcf_status != HCF_SUCCESS ) { DBG_ERROR( DbgInfo, "Firmware Download failed\n" ); DBG_LEAVE( DbgInfo ); return hcf_status; } } /* Report the FW versions */ //;?obsolete, use the available IFB info:: wl_get_pri_records( lp ); if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_STA ) { DBG_TRACE( DbgInfo, "downloaded station F/W\n" ); } else if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) { DBG_TRACE( DbgInfo, "downloaded AP F/W\n" ); } else { DBG_ERROR( DbgInfo, "unknown F/W type\n" ); } /* * Downloaded, no need to repeat this next time, assume the * contents stays in the card until it is powered off. Note we * do not switch firmware on the fly, the firmware is fixed in * the driver for now. */ lp->firmware_present = WL_FRIMWARE_PRESENT; DBG_TRACE( DbgInfo, "ComponentID:%04x variant:%04x major:%04x minor:%04x\n", CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ), CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.variant ), CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.version_major ), CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.version_minor )); /* now we wil get the MAC address of the card */ lp->ltvRecord.len = 4; if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) { lp->ltvRecord.typ = CFG_NIC_MAC_ADDR; } else { lp->ltvRecord.typ = CFG_CNF_OWN_MAC_ADDR; } hcf_status = hcf_get_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); if ( hcf_status != HCF_SUCCESS ) { DBG_ERROR( DbgInfo, "Could not retrieve MAC address\n" ); DBG_LEAVE( DbgInfo ); return hcf_status; } memcpy( lp->MACAddress, &lp->ltvRecord.u.u8[0], ETH_ALEN ); DBG_TRACE(DbgInfo, "Card MAC Address: %pM\n", lp->MACAddress); /* Write out configuration to the device, enable, and reconnect. However, only reconnect if in AP mode. For STA mode, need to wait for passive scan completion before a connect can be issued */ wl_put_ltv( lp ); /* Enable the ports */ hcf_status = wl_enable( lp ); if ( lp->DownloadFirmware == WVLAN_DRV_MODE_AP ) { #ifdef USE_WDS wl_enable_wds_ports( lp ); #endif // USE_WDS hcf_status = wl_connect( lp ); } DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_go /*============================================================================*/ /******************************************************************************* * wl_set_wep_keys() ******************************************************************************* * * DESCRIPTION: * * Write TxKeyID and WEP keys to the adapter. This is separated from * wl_apply() to allow dynamic WEP key updates through the wireless * extensions. * * PARAMETERS: * * lp - a pointer to the wireless adapter's private structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_set_wep_keys( struct wl_private *lp ) { int count = 0; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_set_wep_keys" ); DBG_ENTER( DbgInfo ); DBG_PARAM( DbgInfo, "lp", "%s (0x%p)", lp->dev->name, lp ); if ( lp->EnableEncryption ) { /* NOTE: CFG_CNF_ENCRYPTION is set in wl_put_ltv() as it's a static RID */ /* set TxKeyID */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_KEY_ID; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE(lp->TransmitKeyID - 1); hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); DBG_TRACE( DbgInfo, "Key 1 len: %d\n", lp->DefaultKeys.key[0].len ); DBG_TRACE( DbgInfo, "Key 2 len: %d\n", lp->DefaultKeys.key[1].len ); DBG_TRACE( DbgInfo, "Key 3 len: %d\n", lp->DefaultKeys.key[2].len ); DBG_TRACE( DbgInfo, "Key 4 len: %d\n", lp->DefaultKeys.key[3].len ); /* write keys */ lp->DefaultKeys.len = sizeof( lp->DefaultKeys ) / sizeof( hcf_16 ) - 1; lp->DefaultKeys.typ = CFG_DEFAULT_KEYS; /* endian translate the appropriate key information */ for( count = 0; count < MAX_KEYS; count++ ) { lp->DefaultKeys.key[count].len = CNV_INT_TO_LITTLE( lp->DefaultKeys.key[count].len ); } hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->DefaultKeys )); /* Reverse the above endian translation, since these keys are accessed elsewhere */ for( count = 0; count < MAX_KEYS; count++ ) { lp->DefaultKeys.key[count].len = CNV_INT_TO_LITTLE( lp->DefaultKeys.key[count].len ); } DBG_NOTICE( DbgInfo, "encrypt: %d, ID: %d\n", lp->EnableEncryption, lp->TransmitKeyID ); DBG_NOTICE( DbgInfo, "set key: %s(%d) [%d]\n", lp->DefaultKeys.key[lp->TransmitKeyID-1].key, lp->DefaultKeys.key[lp->TransmitKeyID-1].len, lp->TransmitKeyID-1 ); } DBG_LEAVE( DbgInfo ); } // wl_set_wep_keys /*============================================================================*/ /******************************************************************************* * wl_apply() ******************************************************************************* * * DESCRIPTION: * * Write the parameters to the adapter. (re-)enables the card if device is * open. Returns hcf_status of hcf_enable(). * * PARAMETERS: * * lp - a pointer to the wireless adapter's private structure * * RETURNS: * * an HCF status code * ******************************************************************************/ int wl_apply(struct wl_private *lp) { int hcf_status = HCF_SUCCESS; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_apply" ); DBG_ENTER( DbgInfo ); DBG_ASSERT( lp != NULL); DBG_PARAM( DbgInfo, "lp", "%s (0x%p)", lp->dev->name, lp ); if ( !( lp->flags & WVLAN2_UIL_BUSY )) { /* The adapter parameters have changed: disable card reload parameters enable card */ if ( wl_adapter_is_open( lp->dev )) { /* Disconnect and disable if necessary */ hcf_status = wl_disconnect( lp ); if ( hcf_status != HCF_SUCCESS ) { DBG_ERROR( DbgInfo, "Disconnect failed\n" ); DBG_LEAVE( DbgInfo ); return -1; } hcf_status = wl_disable( lp ); if ( hcf_status != HCF_SUCCESS ) { DBG_ERROR( DbgInfo, "Disable failed\n" ); DBG_LEAVE( DbgInfo ); return -1; } else { /* Write out configuration to the device, enable, and reconnect. However, only reconnect if in AP mode. For STA mode, need to wait for passive scan completion before a connect can be issued */ hcf_status = wl_put_ltv( lp ); if ( hcf_status == HCF_SUCCESS ) { hcf_status = wl_enable( lp ); if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) { hcf_status = wl_connect( lp ); } } else { DBG_WARNING( DbgInfo, "wl_put_ltv() failed\n" ); } } } } DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_apply /*============================================================================*/ /******************************************************************************* * wl_put_ltv_init() ******************************************************************************* * * DESCRIPTION: * * Used to set basic parameters for card initialization. * * PARAMETERS: * * lp - a pointer to the wireless adapter's private structure * * RETURNS: * * an HCF status code * ******************************************************************************/ int wl_put_ltv_init( struct wl_private *lp ) { int i; int hcf_status; CFG_RID_LOG_STRCT *RidLog; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_put_ltv_init" ); DBG_ENTER( DbgInfo ); if ( lp == NULL ) { DBG_ERROR( DbgInfo, "lp pointer is NULL\n" ); DBG_LEAVE( DbgInfo ); return -1; } /* DMA/IO */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNTL_OPT; /* The Card Services build must ALWAYS configure for 16-bit I/O. PCI or CardBus can be set to either 16/32 bit I/O, or Bus Master DMA, but only for Hermes-2.5 */ #ifdef BUS_PCMCIA lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( USE_16BIT ); #else if ( lp->use_dma ) { lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( USE_DMA ); } else { lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0 ); } #endif hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); DBG_TRACE( DbgInfo, "CFG_CNTL_OPT : 0x%04x\n", lp->ltvRecord.u.u16[0] ); DBG_TRACE( DbgInfo, "CFG_CNTL_OPT result : 0x%04x\n", hcf_status ); /* Register the list of RIDs on which asynchronous notification is required. Note that this mechanism replaces the mailbox, so the mailbox can be queried by the host (if desired) without contention from us */ i=0; lp->RidList[i].len = sizeof( lp->ProbeResp ); lp->RidList[i].typ = CFG_ACS_SCAN; lp->RidList[i].bufp = (wci_recordp)&lp->ProbeResp; //lp->ProbeResp.infoType = 0xFFFF; i++; lp->RidList[i].len = sizeof( lp->assoc_stat ); lp->RidList[i].typ = CFG_ASSOC_STAT; lp->RidList[i].bufp = (wci_recordp)&lp->assoc_stat; lp->assoc_stat.len = 0xFFFF; i++; lp->RidList[i].len = 4; lp->RidList[i].typ = CFG_UPDATED_INFO_RECORD; lp->RidList[i].bufp = (wci_recordp)&lp->updatedRecord; lp->updatedRecord.len = 0xFFFF; i++; lp->RidList[i].len = sizeof( lp->sec_stat ); lp->RidList[i].typ = CFG_SECURITY_STAT; lp->RidList[i].bufp = (wci_recordp)&lp->sec_stat; lp->sec_stat.len = 0xFFFF; i++; lp->RidList[i].typ = 0; // Terminate List RidLog = (CFG_RID_LOG_STRCT *)&lp->ltvRecord; RidLog->len = 3; RidLog->typ = CFG_REG_INFO_LOG; RidLog->recordp = (RID_LOGP)&lp->RidList[0]; hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); DBG_TRACE( DbgInfo, "CFG_REG_INFO_LOG\n" ); DBG_TRACE( DbgInfo, "CFG_REG_INFO_LOG result : 0x%04x\n", hcf_status ); DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_put_ltv_init /*============================================================================*/ /******************************************************************************* * wl_put_ltv() ******************************************************************************* * * DESCRIPTION: * * Used by wvlan_apply() and wvlan_go to set the card's configuration. * * PARAMETERS: * * lp - a pointer to the wireless adapter's private structure * * RETURNS: * * an HCF status code * ******************************************************************************/ int wl_put_ltv( struct wl_private *lp ) { int len; int hcf_status; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_put_ltv" ); DBG_ENTER( DbgInfo ); if ( lp == NULL ) { DBG_ERROR( DbgInfo, "lp pointer is NULL\n" ); return -1; } if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) { lp->maxPort = 6; //;?why set this here and not as part of download process } else { lp->maxPort = 0; } /* Send our configuration to the card. Perform any endian translation necessary */ /* Register the Mailbox; VxWorks does this elsewhere; why;? */ lp->ltvRecord.len = 4; lp->ltvRecord.typ = CFG_REG_MB; lp->ltvRecord.u.u32[0] = (u_long)&( lp->mailbox ); lp->ltvRecord.u.u16[2] = ( MB_SIZE / sizeof( hcf_16 )); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Max Data Length */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_MAX_DATA_LEN; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( HCF_MAX_PACKET_SIZE ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* System Scale / Distance between APs */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_SYSTEM_SCALE; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->DistanceBetweenAPs ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Channel */ if ( lp->CreateIBSS && ( lp->Channel == 0 )) { DBG_TRACE( DbgInfo, "Create IBSS" ); lp->Channel = 10; } lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_OWN_CHANNEL; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->Channel ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Microwave Robustness */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_MICRO_WAVE; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->MicrowaveRobustness ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Load Balancing */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_LOAD_BALANCING; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->loadBalancing ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Medium Distribution */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_MEDIUM_DISTRIBUTION; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->mediumDistribution ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Country Code */ #ifdef WARP /* Tx Power Level (for supported cards) */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_TX_POW_LVL; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->txPowLevel ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Short Retry Limit */ /*lp->ltvRecord.len = 2; lp->ltvRecord.typ = 0xFC32; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->shortRetryLimit ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); */ /* Long Retry Limit */ /*lp->ltvRecord.len = 2; lp->ltvRecord.typ = 0xFC33; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->longRetryLimit ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); */ /* Supported Rate Set Control */ lp->ltvRecord.len = 3; lp->ltvRecord.typ = CFG_SUPPORTED_RATE_SET_CNTL; //0xFC88; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->srsc[0] ); lp->ltvRecord.u.u16[1] = CNV_INT_TO_LITTLE( lp->srsc[1] ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Basic Rate Set Control */ lp->ltvRecord.len = 3; lp->ltvRecord.typ = CFG_BASIC_RATE_SET_CNTL; //0xFC89; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->brsc[0] ); lp->ltvRecord.u.u16[1] = CNV_INT_TO_LITTLE( lp->brsc[1] ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Frame Burst Limit */ /* Defined, but not currently available in Firmware */ #endif // WARP #ifdef WARP /* Multicast Rate */ lp->ltvRecord.len = 3; lp->ltvRecord.typ = CFG_CNF_MCAST_RATE; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->MulticastRate[0] ); lp->ltvRecord.u.u16[1] = CNV_INT_TO_LITTLE( lp->MulticastRate[1] ); #else lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_MCAST_RATE; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->MulticastRate[0] ); #endif // WARP hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Own Name (Station Nickname) */ if (( len = ( strlen( lp->StationName ) + 1 ) & ~0x01 ) != 0 ) { //DBG_TRACE( DbgInfo, "CFG_CNF_OWN_NAME : %s\n", // lp->StationName ); lp->ltvRecord.len = 2 + ( len / sizeof( hcf_16 )); lp->ltvRecord.typ = CFG_CNF_OWN_NAME; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( strlen( lp->StationName )); memcpy( &( lp->ltvRecord.u.u8[2] ), lp->StationName, len ); } else { //DBG_TRACE( DbgInfo, "CFG_CNF_OWN_NAME : EMPTY\n" ); lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_OWN_NAME; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0 ); } hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); //DBG_TRACE( DbgInfo, "CFG_CNF_OWN_NAME result : 0x%04x\n", // hcf_status ); /* The following are set in STA mode only */ if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_STA ) { /* RTS Threshold */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_RTS_THRH; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->RTSThreshold ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Port Type */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_PORT_TYPE; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->PortType ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Tx Rate Control */ #ifdef WARP lp->ltvRecord.len = 3; lp->ltvRecord.typ = CFG_TX_RATE_CNTL; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->TxRateControl[0] ); lp->ltvRecord.u.u16[1] = CNV_INT_TO_LITTLE( lp->TxRateControl[1] ); #else lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_RATE_CNTL; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->TxRateControl[0] ); #endif // WARP //;?skip temporarily to see whether the RID or something else is the probelm hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); DBG_TRACE( DbgInfo, "CFG_TX_RATE_CNTL 2.4GHz : 0x%04x\n", lp->TxRateControl[0] ); DBG_TRACE( DbgInfo, "CFG_TX_RATE_CNTL 5.0GHz : 0x%04x\n", lp->TxRateControl[1] ); DBG_TRACE( DbgInfo, "CFG_TX_RATE_CNTL result : 0x%04x\n", hcf_status ); /* Power Management */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_PM_ENABLED; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->PMEnabled ); // lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0x8001 ); DBG_TRACE( DbgInfo, "CFG_CNF_PM_ENABLED : 0x%04x\n", lp->PMEnabled ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Multicast Receive */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_MCAST_RX; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->MulticastReceive ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Max Sleep Duration */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_MAX_SLEEP_DURATION; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->MaxSleepDuration ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Create IBSS */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CREATE_IBSS; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->CreateIBSS ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Desired SSID */ if ((( len = ( strlen( lp->NetworkName ) + 1 ) & ~0x01 ) != 0 ) && ( strcmp( lp->NetworkName, "ANY" ) != 0 ) && ( strcmp( lp->NetworkName, "any" ) != 0 )) { //DBG_TRACE( DbgInfo, "CFG_DESIRED_SSID : %s\n", // lp->NetworkName ); lp->ltvRecord.len = 2 + (len / sizeof(hcf_16)); lp->ltvRecord.typ = CFG_DESIRED_SSID; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( strlen( lp->NetworkName )); memcpy( &( lp->ltvRecord.u.u8[2] ), lp->NetworkName, len ); } else { //DBG_TRACE( DbgInfo, "CFG_DESIRED_SSID : ANY\n" ); lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_DESIRED_SSID; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0 ); } hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); //DBG_TRACE( DbgInfo, "CFG_DESIRED_SSID result : 0x%04x\n", // hcf_status ); /* Own ATIM window */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_OWN_ATIM_WINDOW; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->atimWindow ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Holdover Duration */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_HOLDOVER_DURATION; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->holdoverDuration ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Promiscuous Mode */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_PROMISCUOUS_MODE; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->promiscuousMode ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Authentication */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_AUTHENTICATION; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->authentication ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); #ifdef WARP /* Connection Control */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_CONNECTION_CNTL; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->connectionControl ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Probe data rate */ /*lp->ltvRecord.len = 3; lp->ltvRecord.typ = CFG_PROBE_DATA_RATE; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->probeDataRates[0] ); lp->ltvRecord.u.u16[1] = CNV_INT_TO_LITTLE( lp->probeDataRates[1] ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); DBG_TRACE( DbgInfo, "CFG_PROBE_DATA_RATE 2.4GHz : 0x%04x\n", lp->probeDataRates[0] ); DBG_TRACE( DbgInfo, "CFG_PROBE_DATA_RATE 5.0GHz : 0x%04x\n", lp->probeDataRates[1] ); DBG_TRACE( DbgInfo, "CFG_PROBE_DATA_RATE result : 0x%04x\n", hcf_status );*/ #endif // WARP } else { /* The following are set in AP mode only */ #if 0 //;? (HCF_TYPE) & HCF_TYPE_AP //;?should we restore this to allow smaller memory footprint /* DTIM Period */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_OWN_DTIM_PERIOD; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->DTIMPeriod ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Multicast PM Buffering */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_MCAST_PM_BUF; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->multicastPMBuffering ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Reject ANY - Closed System */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_REJECT_ANY; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->RejectAny ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Exclude Unencrypted */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_EXCL_UNENCRYPTED; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->ExcludeUnencrypted ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* IntraBSS Relay */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_INTRA_BSS_RELAY; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->intraBSSRelay ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* RTS Threshold 0 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_RTS_THRH0; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->RTSThreshold ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Tx Rate Control 0 */ #ifdef WARP lp->ltvRecord.len = 3; lp->ltvRecord.typ = CFG_TX_RATE_CNTL0; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->TxRateControl[0] ); lp->ltvRecord.u.u16[1] = CNV_INT_TO_LITTLE( lp->TxRateControl[1] ); #else lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_RATE_CNTL0; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->TxRateControl[0] ); #endif // WARP hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Own Beacon Interval */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = 0xFC31; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->ownBeaconInterval ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Co-Existence Behavior */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = 0xFCC7; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->coexistence ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); #ifdef USE_WDS /* RTS Threshold 1 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_RTS_THRH1; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[0].rtsThreshold ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* RTS Threshold 2 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_RTS_THRH2; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[1].rtsThreshold ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* RTS Threshold 3 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_RTS_THRH3; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[2].rtsThreshold ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* RTS Threshold 4 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_RTS_THRH4; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[3].rtsThreshold ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* RTS Threshold 5 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_RTS_THRH5; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[4].rtsThreshold ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* RTS Threshold 6 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_RTS_THRH6; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[5].rtsThreshold ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); #if 0 /* TX Rate Control 1 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_RATE_CNTL1; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[0].txRateCntl ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* TX Rate Control 2 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_RATE_CNTL2; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[1].txRateCntl ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* TX Rate Control 3 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_RATE_CNTL3; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[2].txRateCntl ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* TX Rate Control 4 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_RATE_CNTL4; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[3].txRateCntl ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* TX Rate Control 5 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_RATE_CNTL5; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[4].txRateCntl ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* TX Rate Control 6 */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_TX_RATE_CNTL6; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->wds_port[5].txRateCntl ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); #endif /* WDS addresses. It's okay to blindly send these parameters, because the port needs to be enabled, before anything is done with it. */ /* WDS Address 1 */ lp->ltvRecord.len = 4; lp->ltvRecord.typ = CFG_CNF_WDS_ADDR1; memcpy( &lp->ltvRecord.u.u8[0], lp->wds_port[0].wdsAddress, ETH_ALEN ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* WDS Address 2 */ lp->ltvRecord.len = 4; lp->ltvRecord.typ = CFG_CNF_WDS_ADDR2; memcpy( &lp->ltvRecord.u.u8[0], lp->wds_port[1].wdsAddress, ETH_ALEN ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* WDS Address 3 */ lp->ltvRecord.len = 4; lp->ltvRecord.typ = CFG_CNF_WDS_ADDR3; memcpy( &lp->ltvRecord.u.u8[0], lp->wds_port[2].wdsAddress, ETH_ALEN ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* WDS Address 4 */ lp->ltvRecord.len = 4; lp->ltvRecord.typ = CFG_CNF_WDS_ADDR4; memcpy( &lp->ltvRecord.u.u8[0], lp->wds_port[3].wdsAddress, ETH_ALEN ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* WDS Address 5 */ lp->ltvRecord.len = 4; lp->ltvRecord.typ = CFG_CNF_WDS_ADDR5; memcpy( &lp->ltvRecord.u.u8[0], lp->wds_port[4].wdsAddress, ETH_ALEN ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* WDS Address 6 */ lp->ltvRecord.len = 4; lp->ltvRecord.typ = CFG_CNF_WDS_ADDR6; memcpy( &lp->ltvRecord.u.u8[0], lp->wds_port[5].wdsAddress, ETH_ALEN ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); #endif /* USE_WDS */ #endif /* (HCF_TYPE) & HCF_TYPE_AP */ } /* Own MAC Address */ /* DBG_TRACE(DbgInfo, "MAC Address : %pM\n", lp->MACAddress); */ if ( WVLAN_VALID_MAC_ADDRESS( lp->MACAddress )) { /* Make the MAC address valid by: Clearing the multicast bit Setting the local MAC address bit */ //lp->MACAddress[0] &= ~0x03; //;?why is this commented out already in 720 //lp->MACAddress[0] |= 0x02; lp->ltvRecord.len = 1 + ( ETH_ALEN / sizeof( hcf_16 )); if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) { //DBG_TRACE( DbgInfo, "CFG_NIC_MAC_ADDR\n" ); lp->ltvRecord.typ = CFG_NIC_MAC_ADDR; } else { //DBG_TRACE( DbgInfo, "CFG_CNF_OWN_MAC_ADDR\n" ); lp->ltvRecord.typ = CFG_CNF_OWN_MAC_ADDR; } /* MAC address is byte aligned, no endian conversion needed */ memcpy( &( lp->ltvRecord.u.u8[0] ), lp->MACAddress, ETH_ALEN ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); //DBG_TRACE( DbgInfo, "CFG_XXX_MAC_ADDR result : 0x%04x\n", // hcf_status ); /* Update the MAC address in the netdevice struct */ memcpy( lp->dev->dev_addr, lp->MACAddress, ETH_ALEN ); //;?what is the purpose of this seemingly complex logic } /* Own SSID */ if ((( len = ( strlen( lp->NetworkName ) + 1 ) & ~0x01 ) != 0 ) && ( strcmp( lp->NetworkName, "ANY" ) != 0 ) && ( strcmp( lp->NetworkName, "any" ) != 0 )) { //DBG_TRACE( DbgInfo, "CFG_CNF_OWN_SSID : %s\n", // lp->NetworkName ); lp->ltvRecord.len = 2 + (len / sizeof(hcf_16)); lp->ltvRecord.typ = CFG_CNF_OWN_SSID; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( strlen( lp->NetworkName )); memcpy( &( lp->ltvRecord.u.u8[2] ), lp->NetworkName, len ); } else { //DBG_TRACE( DbgInfo, "CFG_CNF_OWN_SSID : ANY\n" ); lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_OWN_SSID; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0 ); } hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); //DBG_TRACE( DbgInfo, "CFG_CNF_OWN_SSID result : 0x%04x\n", // hcf_status ); /* enable/disable encryption */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_CNF_ENCRYPTION; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->EnableEncryption ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* Set the Authentication Key Management Suite */ lp->ltvRecord.len = 2; lp->ltvRecord.typ = CFG_SET_WPA_AUTH_KEY_MGMT_SUITE; lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( lp->AuthKeyMgmtSuite ); hcf_status = hcf_put_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); /* If WEP (or no) keys are being used, write (or clear) them */ if (lp->wext_enc != IW_ENCODE_ALG_TKIP) wl_set_wep_keys(lp); /* Country Code */ /* countryInfo, ltvCountryInfo, CFG_CNF_COUNTRY_INFO */ DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_put_ltv /*============================================================================*/ /******************************************************************************* * init_module() ******************************************************************************* * * DESCRIPTION: * * Load the kernel module. * * PARAMETERS: * * N/A * * RETURNS: * * 0 on success * an errno value otherwise * ******************************************************************************/ static int __init wl_module_init( void ) { int result; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_module_init" ); #if DBG /* Convert "standard" PCMCIA parameter pc_debug to a reasonable DebugFlag value. * NOTE: The values all fall through to the lower values. */ DbgInfo->DebugFlag = 0; DbgInfo->DebugFlag = DBG_TRACE_ON; //;?get this mess resolved one day if ( pc_debug ) switch( pc_debug ) { case 8: DbgInfo->DebugFlag |= DBG_DS_ON; case 7: DbgInfo->DebugFlag |= DBG_RX_ON | DBG_TX_ON; case 6: DbgInfo->DebugFlag |= DBG_PARAM_ON; case 5: DbgInfo->DebugFlag |= DBG_TRACE_ON; case 4: DbgInfo->DebugFlag |= DBG_VERBOSE_ON; case 1: DbgInfo->DebugFlag |= DBG_DEFAULTS; default: break; } #endif /* DBG */ DBG_ENTER( DbgInfo ); printk(KERN_INFO "%s\n", VERSION_INFO); printk(KERN_INFO "*** Modified for kernel 2.6 by Henk de Groot <[email protected]>\n"); printk(KERN_INFO "*** Based on 7.18 version by Andrey Borzenkov <[email protected]> $Revision: 39 $\n"); // ;?#if (HCF_TYPE) & HCF_TYPE_AP // DBG_PRINT( "Access Point Mode (AP) Support: YES\n" ); // #else // DBG_PRINT( "Access Point Mode (AP) Support: NO\n" ); // #endif /* (HCF_TYPE) & HCF_TYPE_AP */ result = wl_adapter_init_module( ); DBG_LEAVE( DbgInfo ); return result; } // init_module /*============================================================================*/ /******************************************************************************* * cleanup_module() ******************************************************************************* * * DESCRIPTION: * * Unload the kernel module. * * PARAMETERS: * * N/A * * RETURNS: * * N/A * ******************************************************************************/ static void __exit wl_module_exit( void ) { DBG_FUNC( "wl_module_exit" ); DBG_ENTER(DbgInfo); wl_adapter_cleanup_module( ); #if 0 //SCULL_USE_PROC /* don't waste space if unused */ remove_proc_entry( "wlags", NULL ); //;?why so a-symmetric compared to location of create_proc_read_entry #endif DBG_LEAVE( DbgInfo ); return; } // cleanup_module /*============================================================================*/ module_init(wl_module_init); module_exit(wl_module_exit); /******************************************************************************* * wl_isr() ******************************************************************************* * * DESCRIPTION: * * The Interrupt Service Routine for the driver. * * PARAMETERS: * * irq - the irq the interrupt came in on * dev_id - a buffer containing information about the request * regs - * * RETURNS: * * N/A * ******************************************************************************/ irqreturn_t wl_isr( int irq, void *dev_id, struct pt_regs *regs ) { int events; struct net_device *dev = (struct net_device *) dev_id; struct wl_private *lp = NULL; /*------------------------------------------------------------------------*/ if (( dev == NULL ) || ( !netif_device_present( dev ))) { return IRQ_NONE; } /* Set the wl_private pointer (lp), now that we know that dev is non-null */ lp = wl_priv(dev); #ifdef USE_RTS if ( lp->useRTS == 1 ) { DBG_PRINT( "EXITING ISR, IN RTS MODE...\n" ); return; } #endif /* USE_RTS */ /* If we have interrupts pending, then put them on a system task queue. Otherwise turn interrupts back on */ events = hcf_action( &lp->hcfCtx, HCF_ACT_INT_OFF ); if ( events == HCF_INT_PENDING ) { /* Schedule the ISR handler as a bottom-half task in the tq_immediate queue */ tasklet_schedule(&lp->task); } else { //DBG_PRINT( "NOT OUR INTERRUPT\n" ); hcf_action( &lp->hcfCtx, HCF_ACT_INT_ON ); } return IRQ_RETVAL(events == HCF_INT_PENDING); } // wl_isr /*============================================================================*/ /******************************************************************************* * wl_isr_handler() ******************************************************************************* * * DESCRIPTION: * * The ISR handler, scheduled to run in a deferred context by the ISR. This * is where the ISR's work actually gets done. * * PARAMETERS: * * lp - a pointer to the device's private adapter structure * * RETURNS: * * N/A * ******************************************************************************/ #define WVLAN_MAX_INT_SERVICES 50 void wl_isr_handler( unsigned long p ) { struct net_device *dev; unsigned long flags; bool_t stop = TRUE; int count; int result; struct wl_private *lp = (struct wl_private *)p; /*------------------------------------------------------------------------*/ if ( lp == NULL ) { DBG_PRINT( "wl_isr_handler lp adapter pointer is NULL!!!\n" ); } else { wl_lock( lp, &flags ); dev = (struct net_device *)lp->dev; if ( dev != NULL && netif_device_present( dev ) ) stop = FALSE; for( count = 0; stop == FALSE && count < WVLAN_MAX_INT_SERVICES; count++ ) { stop = TRUE; result = hcf_service_nic( &lp->hcfCtx, (wci_bufp)lp->lookAheadBuf, sizeof( lp->lookAheadBuf )); if ( result == HCF_ERR_MIC ) { wl_wext_event_mic_failed( dev ); /* Send an event that MIC failed */ //;?this seems wrong if HCF_ERR_MIC coincides with another event, stop gets FALSE //so why not do it always ;? } #ifndef USE_MBOX_SYNC if ( lp->hcfCtx.IFB_MBInfoLen != 0 ) { /* anything in the mailbox */ wl_mbx( lp ); stop = FALSE; } #endif /* Check for a Link status event */ if ( ( lp->hcfCtx.IFB_LinkStat & CFG_LINK_STAT_FW ) != 0 ) { wl_process_link_status( lp ); stop = FALSE; } /* Check for probe response events */ if ( lp->ProbeResp.infoType != 0 && lp->ProbeResp.infoType != 0xFFFF ) { wl_process_probe_response( lp ); memset( &lp->ProbeResp, 0, sizeof( lp->ProbeResp )); lp->ProbeResp.infoType = 0xFFFF; stop = FALSE; } /* Check for updated record events */ if ( lp->updatedRecord.len != 0xFFFF ) { wl_process_updated_record( lp ); lp->updatedRecord.len = 0xFFFF; stop = FALSE; } /* Check for association status events */ if ( lp->assoc_stat.len != 0xFFFF ) { wl_process_assoc_status( lp ); lp->assoc_stat.len = 0xFFFF; stop = FALSE; } /* Check for security status events */ if ( lp->sec_stat.len != 0xFFFF ) { wl_process_security_status( lp ); lp->sec_stat.len = 0xFFFF; stop = FALSE; } #ifdef ENABLE_DMA if ( lp->use_dma ) { /* Check for DMA Rx packets */ if ( lp->hcfCtx.IFB_DmaPackets & HREG_EV_RDMAD ) { wl_rx_dma( dev ); stop = FALSE; } /* Return Tx DMA descriptors to host */ if ( lp->hcfCtx.IFB_DmaPackets & HREG_EV_TDMAD ) { wl_pci_dma_hcf_reclaim_tx( lp ); stop = FALSE; } } else #endif // ENABLE_DMA { /* Check for Rx packets */ if ( lp->hcfCtx.IFB_RxLen != 0 ) { wl_rx( dev ); stop = FALSE; } /* Make sure that queued frames get sent */ if ( wl_send( lp )) { stop = FALSE; } } } /* We're done, so turn interrupts which were turned off in wl_isr, back on */ hcf_action( &lp->hcfCtx, HCF_ACT_INT_ON ); wl_unlock( lp, &flags ); } return; } // wl_isr_handler /*============================================================================*/ /******************************************************************************* * wl_remove() ******************************************************************************* * * DESCRIPTION: * * Notify the adapter that it has been removed. Since the adapter is gone, * we should no longer try to talk to it. * * PARAMETERS: * * dev - a pointer to the device's net_device structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_remove( struct net_device *dev ) { struct wl_private *lp = wl_priv(dev); unsigned long flags; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_remove" ); DBG_ENTER( DbgInfo ); DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev ); wl_lock( lp, &flags ); /* stop handling interrupts */ wl_act_int_off( lp ); lp->is_handling_int = WL_NOT_HANDLING_INT; /* * Disable the ports: just change state: since the * card is gone it is useless to talk to it and at * disconnect all state information is lost anyway. */ /* Reset portState */ lp->portState = WVLAN_PORT_STATE_DISABLED; #if 0 //;? (HCF_TYPE) & HCF_TYPE_AP #ifdef USE_WDS //wl_disable_wds_ports( lp ); #endif // USE_WDS #endif /* (HCF_TYPE) & HCF_TYPE_AP */ /* Mark the device as unregistered */ lp->is_registered = FALSE; /* Deregister the WDS ports as well */ WL_WDS_NETDEV_DEREGISTER( lp ); #ifdef USE_RTS if ( lp->useRTS == 1 ) { wl_unlock( lp, &flags ); DBG_LEAVE( DbgInfo ); return; } #endif /* USE_RTS */ /* Inform the HCF that the card has been removed */ hcf_connect( &lp->hcfCtx, HCF_DISCONNECT ); wl_unlock( lp, &flags ); DBG_LEAVE( DbgInfo ); return; } // wl_remove /*============================================================================*/ /******************************************************************************* * wl_suspend() ******************************************************************************* * * DESCRIPTION: * * Power-down and halt the adapter. * * PARAMETERS: * * dev - a pointer to the device's net_device structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_suspend( struct net_device *dev ) { struct wl_private *lp = wl_priv(dev); unsigned long flags; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_suspend" ); DBG_ENTER( DbgInfo ); DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev ); /* The adapter is suspended: Stop the adapter Power down */ wl_lock( lp, &flags ); /* Disable interrupt handling */ wl_act_int_off( lp ); /* Disconnect */ wl_disconnect( lp ); /* Disable */ wl_disable( lp ); /* Disconnect from the adapter */ hcf_connect( &lp->hcfCtx, HCF_DISCONNECT ); /* Reset portState to be sure (should have been done by wl_disable */ lp->portState = WVLAN_PORT_STATE_DISABLED; wl_unlock( lp, &flags ); DBG_LEAVE( DbgInfo ); return; } // wl_suspend /*============================================================================*/ /******************************************************************************* * wl_resume() ******************************************************************************* * * DESCRIPTION: * * Resume a previously suspended adapter. * * PARAMETERS: * * dev - a pointer to the device's net_device structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_resume(struct net_device *dev) { struct wl_private *lp = wl_priv(dev); unsigned long flags; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_resume" ); DBG_ENTER( DbgInfo ); DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev ); wl_lock( lp, &flags ); /* Connect to the adapter */ hcf_connect( &lp->hcfCtx, dev->base_addr ); /* Reset portState */ lp->portState = WVLAN_PORT_STATE_DISABLED; /* Power might have been off, assume the card lost the firmware*/ lp->firmware_present = WL_FRIMWARE_NOT_PRESENT; /* Reload the firmware and restart */ wl_reset( dev ); /* Resume interrupt handling */ wl_act_int_on( lp ); wl_unlock( lp, &flags ); DBG_LEAVE( DbgInfo ); return; } // wl_resume /*============================================================================*/ /******************************************************************************* * wl_release() ******************************************************************************* * * DESCRIPTION: * * This function perfroms a check on the device and calls wl_remove() if * necessary. This function can be used for all bus types, but exists mostly * for the benefit of the Card Services driver, as there are times when * wl_remove() does not get called. * * PARAMETERS: * * dev - a pointer to the device's net_device structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_release( struct net_device *dev ) { struct wl_private *lp = wl_priv(dev); /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_release" ); DBG_ENTER( DbgInfo ); DBG_PARAM( DbgInfo, "dev", "%s (0x%p)", dev->name, dev ); /* If wl_remove() hasn't been called (i.e. when Card Services is shut down with the card in the slot), then call it */ if ( lp->is_registered == TRUE ) { DBG_TRACE( DbgInfo, "Calling unregister_netdev(), as it wasn't called yet\n" ); wl_remove( dev ); lp->is_registered = FALSE; } DBG_LEAVE( DbgInfo ); return; } // wl_release /*============================================================================*/ /******************************************************************************* * wl_get_irq_mask() ******************************************************************************* * * DESCRIPTION: * * Accessor function to retrieve the irq_mask module parameter * * PARAMETERS: * * N/A * * RETURNS: * * The irq_mask module parameter * ******************************************************************************/ p_u16 wl_get_irq_mask( void ) { return irq_mask; } // wl_get_irq_mask /*============================================================================*/ /******************************************************************************* * wl_get_irq_list() ******************************************************************************* * * DESCRIPTION: * * Accessor function to retrieve the irq_list module parameter * * PARAMETERS: * * N/A * * RETURNS: * * The irq_list module parameter * ******************************************************************************/ p_s8 * wl_get_irq_list( void ) { return irq_list; } // wl_get_irq_list /*============================================================================*/ /******************************************************************************* * wl_enable() ******************************************************************************* * * DESCRIPTION: * * Used to enable MAC ports * * PARAMETERS: * * lp - pointer to the device's private adapter structure * * RETURNS: * * N/A * ******************************************************************************/ int wl_enable( struct wl_private *lp ) { int hcf_status = HCF_SUCCESS; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_enable" ); DBG_ENTER( DbgInfo ); if ( lp->portState == WVLAN_PORT_STATE_ENABLED ) { DBG_TRACE( DbgInfo, "No action: Card already enabled\n" ); } else if ( lp->portState == WVLAN_PORT_STATE_CONNECTED ) { //;?suspicuous logic, how can you be connected without being enabled so this is probably dead code DBG_TRACE( DbgInfo, "No action: Card already connected\n" ); } else { hcf_status = hcf_cntl( &lp->hcfCtx, HCF_CNTL_ENABLE ); if ( hcf_status == HCF_SUCCESS ) { /* Set the status of the NIC to enabled */ lp->portState = WVLAN_PORT_STATE_ENABLED; //;?bad mnemonic, NIC iso PORT #ifdef ENABLE_DMA if ( lp->use_dma ) { wl_pci_dma_hcf_supply( lp ); //;?always succes? } #endif } } if ( hcf_status != HCF_SUCCESS ) { //;?make this an assert DBG_TRACE( DbgInfo, "failed: 0x%x\n", hcf_status ); } DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_enable /*============================================================================*/ #ifdef USE_WDS /******************************************************************************* * wl_enable_wds_ports() ******************************************************************************* * * DESCRIPTION: * * Used to enable the WDS MAC ports 1-6 * * PARAMETERS: * * lp - pointer to the device's private adapter structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_enable_wds_ports( struct wl_private * lp ) { DBG_FUNC( "wl_enable_wds_ports" ); DBG_ENTER( DbgInfo ); if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ){ DBG_ERROR( DbgInfo, "!!!!;? someone misunderstood something !!!!!\n" ); } DBG_LEAVE( DbgInfo ); return; } // wl_enable_wds_ports #endif /* USE_WDS */ /*============================================================================*/ /******************************************************************************* * wl_connect() ******************************************************************************* * * DESCRIPTION: * * Used to connect a MAC port * * PARAMETERS: * * lp - pointer to the device's private adapter structure * * RETURNS: * * N/A * ******************************************************************************/ int wl_connect( struct wl_private *lp ) { int hcf_status; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_connect" ); DBG_ENTER( DbgInfo ); if ( lp->portState != WVLAN_PORT_STATE_ENABLED ) { DBG_TRACE( DbgInfo, "No action: Not in enabled state\n" ); DBG_LEAVE( DbgInfo ); return HCF_SUCCESS; } hcf_status = hcf_cntl( &lp->hcfCtx, HCF_CNTL_CONNECT ); if ( hcf_status == HCF_SUCCESS ) { lp->portState = WVLAN_PORT_STATE_CONNECTED; } DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_connect /*============================================================================*/ /******************************************************************************* * wl_disconnect() ******************************************************************************* * * DESCRIPTION: * * Used to disconnect a MAC port * * PARAMETERS: * * lp - pointer to the device's private adapter structure * * RETURNS: * * N/A * ******************************************************************************/ int wl_disconnect( struct wl_private *lp ) { int hcf_status; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_disconnect" ); DBG_ENTER( DbgInfo ); if ( lp->portState != WVLAN_PORT_STATE_CONNECTED ) { DBG_TRACE( DbgInfo, "No action: Not in connected state\n" ); DBG_LEAVE( DbgInfo ); return HCF_SUCCESS; } hcf_status = hcf_cntl( &lp->hcfCtx, HCF_CNTL_DISCONNECT ); if ( hcf_status == HCF_SUCCESS ) { lp->portState = WVLAN_PORT_STATE_ENABLED; } DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_disconnect /*============================================================================*/ /******************************************************************************* * wl_disable() ******************************************************************************* * * DESCRIPTION: * * Used to disable MAC ports * * PARAMETERS: * * lp - pointer to the device's private adapter structure * port - the MAC port to disable * * RETURNS: * * N/A * ******************************************************************************/ int wl_disable( struct wl_private *lp ) { int hcf_status = HCF_SUCCESS; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_disable" ); DBG_ENTER( DbgInfo ); if ( lp->portState == WVLAN_PORT_STATE_DISABLED ) { DBG_TRACE( DbgInfo, "No action: Port state is disabled\n" ); } else { hcf_status = hcf_cntl( &lp->hcfCtx, HCF_CNTL_DISABLE ); if ( hcf_status == HCF_SUCCESS ) { /* Set the status of the port to disabled */ //;?bad mnemonic use NIC iso PORT lp->portState = WVLAN_PORT_STATE_DISABLED; #ifdef ENABLE_DMA if ( lp->use_dma ) { wl_pci_dma_hcf_reclaim( lp ); } #endif } } if ( hcf_status != HCF_SUCCESS ) { DBG_TRACE( DbgInfo, "failed: 0x%x\n", hcf_status ); } DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_disable /*============================================================================*/ #ifdef USE_WDS /******************************************************************************* * wl_disable_wds_ports() ******************************************************************************* * * DESCRIPTION: * * Used to disable the WDS MAC ports 1-6 * * PARAMETERS: * * lp - pointer to the device's private adapter structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_disable_wds_ports( struct wl_private * lp ) { DBG_FUNC( "wl_disable_wds_ports" ); DBG_ENTER( DbgInfo ); if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ){ DBG_ERROR( DbgInfo, "!!!!;? someone misunderstood something !!!!!\n" ); } // if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) { // wl_disable( lp, HCF_PORT_1 ); // wl_disable( lp, HCF_PORT_2 ); // wl_disable( lp, HCF_PORT_3 ); // wl_disable( lp, HCF_PORT_4 ); // wl_disable( lp, HCF_PORT_5 ); // wl_disable( lp, HCF_PORT_6 ); // } DBG_LEAVE( DbgInfo ); return; } // wl_disable_wds_ports #endif // USE_WDS /*============================================================================*/ #ifndef USE_MBOX_SYNC /******************************************************************************* * wl_mbx() ******************************************************************************* * * DESCRIPTION: * This function is used to read and process a mailbox message. * * * PARAMETERS: * * lp - pointer to the device's private adapter structure * * RETURNS: * * an HCF status code * ******************************************************************************/ int wl_mbx( struct wl_private *lp ) { int hcf_status = HCF_SUCCESS; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_mbx" ); DBG_ENTER( DbgInfo ); DBG_TRACE( DbgInfo, "Mailbox Info: IFB_MBInfoLen: %d\n", lp->hcfCtx.IFB_MBInfoLen ); memset( &( lp->ltvRecord ), 0, sizeof( ltv_t )); lp->ltvRecord.len = MB_SIZE; lp->ltvRecord.typ = CFG_MB_INFO; hcf_status = hcf_get_info( &lp->hcfCtx, (LTVP)&( lp->ltvRecord )); if ( hcf_status != HCF_SUCCESS ) { DBG_ERROR( DbgInfo, "hcf_get_info returned 0x%x\n", hcf_status ); DBG_LEAVE( DbgInfo ); return hcf_status; } if ( lp->ltvRecord.typ == CFG_MB_INFO ) { DBG_LEAVE( DbgInfo ); return hcf_status; } /* Endian translate the mailbox data, then process the message */ wl_endian_translate_mailbox( &( lp->ltvRecord )); wl_process_mailbox( lp ); DBG_LEAVE( DbgInfo ); return hcf_status; } // wl_mbx /*============================================================================*/ /******************************************************************************* * wl_endian_translate_mailbox() ******************************************************************************* * * DESCRIPTION: * * This function will perform the tedious task of endian translating all * fields withtin a mailbox message which need translating. * * PARAMETERS: * * ltv - pointer to the LTV to endian translate * * RETURNS: * * none * ******************************************************************************/ void wl_endian_translate_mailbox( ltv_t *ltv ) { DBG_FUNC( "wl_endian_translate_mailbox" ); DBG_ENTER( DbgInfo ); switch( ltv->typ ) { case CFG_TALLIES: break; case CFG_SCAN: { int num_aps; SCAN_RS_STRCT *aps = (SCAN_RS_STRCT *)&ltv->u.u8[0]; num_aps = (hcf_16)(( (size_t)(ltv->len - 1 ) * 2 ) / ( sizeof( SCAN_RS_STRCT ))); while( num_aps >= 1 ) { num_aps--; aps[num_aps].channel_id = CNV_LITTLE_TO_INT( aps[num_aps].channel_id ); aps[num_aps].noise_level = CNV_LITTLE_TO_INT( aps[num_aps].noise_level ); aps[num_aps].signal_level = CNV_LITTLE_TO_INT( aps[num_aps].signal_level ); aps[num_aps].beacon_interval_time = CNV_LITTLE_TO_INT( aps[num_aps].beacon_interval_time ); aps[num_aps].capability = CNV_LITTLE_TO_INT( aps[num_aps].capability ); aps[num_aps].ssid_len = CNV_LITTLE_TO_INT( aps[num_aps].ssid_len ); aps[num_aps].ssid_val[aps[num_aps].ssid_len] = 0; } } break; case CFG_ACS_SCAN: { PROBE_RESP *probe_resp = (PROBE_RESP *)ltv; probe_resp->frameControl = CNV_LITTLE_TO_INT( probe_resp->frameControl ); probe_resp->durID = CNV_LITTLE_TO_INT( probe_resp->durID ); probe_resp->sequence = CNV_LITTLE_TO_INT( probe_resp->sequence ); probe_resp->dataLength = CNV_LITTLE_TO_INT( probe_resp->dataLength ); #ifndef WARP probe_resp->lenType = CNV_LITTLE_TO_INT( probe_resp->lenType ); #endif // WARP probe_resp->beaconInterval = CNV_LITTLE_TO_INT( probe_resp->beaconInterval ); probe_resp->capability = CNV_LITTLE_TO_INT( probe_resp->capability ); probe_resp->flags = CNV_LITTLE_TO_INT( probe_resp->flags ); } break; case CFG_LINK_STAT: #define ls ((LINK_STATUS_STRCT *)ltv) ls->linkStatus = CNV_LITTLE_TO_INT( ls->linkStatus ); break; #undef ls case CFG_ASSOC_STAT: { ASSOC_STATUS_STRCT *as = (ASSOC_STATUS_STRCT *)ltv; as->assocStatus = CNV_LITTLE_TO_INT( as->assocStatus ); } break; case CFG_SECURITY_STAT: { SECURITY_STATUS_STRCT *ss = (SECURITY_STATUS_STRCT *)ltv; ss->securityStatus = CNV_LITTLE_TO_INT( ss->securityStatus ); ss->reason = CNV_LITTLE_TO_INT( ss->reason ); } break; case CFG_WMP: break; case CFG_NULL: break; default: break; } DBG_LEAVE( DbgInfo ); return; } // wl_endian_translate_mailbox /*============================================================================*/ /******************************************************************************* * wl_process_mailbox() ******************************************************************************* * * DESCRIPTION: * * This function will process the mailbox data. * * PARAMETERS: * * ltv - pointer to the LTV to be processed. * * RETURNS: * * none * ******************************************************************************/ void wl_process_mailbox( struct wl_private *lp ) { ltv_t *ltv; hcf_16 ltv_val = 0xFFFF; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_process_mailbox" ); DBG_ENTER( DbgInfo ); ltv = &( lp->ltvRecord ); switch( ltv->typ ) { case CFG_TALLIES: DBG_TRACE( DbgInfo, "CFG_TALLIES\n" ); break; case CFG_SCAN: DBG_TRACE( DbgInfo, "CFG_SCAN\n" ); { int num_aps; SCAN_RS_STRCT *aps = (SCAN_RS_STRCT *)&ltv->u.u8[0]; num_aps = (hcf_16)(( (size_t)(ltv->len - 1 ) * 2 ) / ( sizeof( SCAN_RS_STRCT ))); lp->scan_results.num_aps = num_aps; DBG_TRACE( DbgInfo, "Number of APs: %d\n", num_aps ); while( num_aps >= 1 ) { num_aps--; DBG_TRACE( DbgInfo, "AP : %d\n", num_aps ); DBG_TRACE( DbgInfo, "=========================\n" ); DBG_TRACE( DbgInfo, "Channel ID : 0x%04x\n", aps[num_aps].channel_id ); DBG_TRACE( DbgInfo, "Noise Level : 0x%04x\n", aps[num_aps].noise_level ); DBG_TRACE( DbgInfo, "Signal Level : 0x%04x\n", aps[num_aps].signal_level ); DBG_TRACE( DbgInfo, "Beacon Interval : 0x%04x\n", aps[num_aps].beacon_interval_time ); DBG_TRACE( DbgInfo, "Capability : 0x%04x\n", aps[num_aps].capability ); DBG_TRACE( DbgInfo, "SSID Length : 0x%04x\n", aps[num_aps].ssid_len ); DBG_TRACE(DbgInfo, "BSSID : %pM\n", aps[num_aps].bssid); if ( aps[num_aps].ssid_len != 0 ) { DBG_TRACE( DbgInfo, "SSID : %s.\n", aps[num_aps].ssid_val ); } else { DBG_TRACE( DbgInfo, "SSID : %s.\n", "ANY" ); } DBG_TRACE( DbgInfo, "\n" ); /* Copy the info to the ScanResult structure in the private adapter struct */ memcpy( &( lp->scan_results.APTable[num_aps]), &( aps[num_aps] ), sizeof( SCAN_RS_STRCT )); } /* Set scan result to true so that any scan requests will complete */ lp->scan_results.scan_complete = TRUE; } break; case CFG_ACS_SCAN: DBG_TRACE( DbgInfo, "CFG_ACS_SCAN\n" ); { PROBE_RESP *probe_rsp = (PROBE_RESP *)ltv; hcf_8 *wpa_ie = NULL; hcf_16 wpa_ie_len = 0; DBG_TRACE( DbgInfo, "(%s) =========================\n", lp->dev->name ); DBG_TRACE( DbgInfo, "(%s) length : 0x%04x.\n", lp->dev->name, probe_rsp->length ); if ( probe_rsp->length > 1 ) { DBG_TRACE( DbgInfo, "(%s) infoType : 0x%04x.\n", lp->dev->name, probe_rsp->infoType ); DBG_TRACE( DbgInfo, "(%s) signal : 0x%02x.\n", lp->dev->name, probe_rsp->signal ); DBG_TRACE( DbgInfo, "(%s) silence : 0x%02x.\n", lp->dev->name, probe_rsp->silence ); DBG_TRACE( DbgInfo, "(%s) rxFlow : 0x%02x.\n", lp->dev->name, probe_rsp->rxFlow ); DBG_TRACE( DbgInfo, "(%s) rate : 0x%02x.\n", lp->dev->name, probe_rsp->rate ); DBG_TRACE( DbgInfo, "(%s) frame cntl : 0x%04x.\n", lp->dev->name, probe_rsp->frameControl ); DBG_TRACE( DbgInfo, "(%s) durID : 0x%04x.\n", lp->dev->name, probe_rsp->durID ); DBG_TRACE(DbgInfo, "(%s) address1 : %pM\n", lp->dev->name, probe_rsp->address1); DBG_TRACE(DbgInfo, "(%s) address2 : %pM\n", lp->dev->name, probe_rsp->address2); DBG_TRACE(DbgInfo, "(%s) BSSID : %pM\n", lp->dev->name, probe_rsp->BSSID); DBG_TRACE( DbgInfo, "(%s) sequence : 0x%04x.\n", lp->dev->name, probe_rsp->sequence ); DBG_TRACE(DbgInfo, "(%s) address4 : %pM\n", lp->dev->name, probe_rsp->address4); DBG_TRACE( DbgInfo, "(%s) datalength : 0x%04x.\n", lp->dev->name, probe_rsp->dataLength ); DBG_TRACE(DbgInfo, "(%s) DA : %pM\n", lp->dev->name, probe_rsp->DA); DBG_TRACE(DbgInfo, "(%s) SA : %pM\n", lp->dev->name, probe_rsp->SA); //DBG_TRACE( DbgInfo, "(%s) lenType : 0x%04x.\n", // lp->dev->name, probe_rsp->lenType ); DBG_TRACE(DbgInfo, "(%s) timeStamp : " "%d.%d.%d.%d.%d.%d.%d.%d\n", lp->dev->name, probe_rsp->timeStamp[0], probe_rsp->timeStamp[1], probe_rsp->timeStamp[2], probe_rsp->timeStamp[3], probe_rsp->timeStamp[4], probe_rsp->timeStamp[5], probe_rsp->timeStamp[6], probe_rsp->timeStamp[7]); DBG_TRACE( DbgInfo, "(%s) beaconInt : 0x%04x.\n", lp->dev->name, probe_rsp->beaconInterval ); DBG_TRACE( DbgInfo, "(%s) capability : 0x%04x.\n", lp->dev->name, probe_rsp->capability ); DBG_TRACE( DbgInfo, "(%s) SSID len : 0x%04x.\n", lp->dev->name, probe_rsp->rawData[1] ); if ( probe_rsp->rawData[1] > 0 ) { char ssid[HCF_MAX_NAME_LEN]; memset( ssid, 0, sizeof( ssid )); strncpy( ssid, &probe_rsp->rawData[2], probe_rsp->rawData[1] ); DBG_TRACE( DbgInfo, "(%s) SSID : %s\n", lp->dev->name, ssid ); } /* Parse out the WPA-IE, if one exists */ wpa_ie = wl_parse_wpa_ie( probe_rsp, &wpa_ie_len ); if ( wpa_ie != NULL ) { DBG_TRACE( DbgInfo, "(%s) WPA-IE : %s\n", lp->dev->name, wl_print_wpa_ie( wpa_ie, wpa_ie_len )); } DBG_TRACE( DbgInfo, "(%s) flags : 0x%04x.\n", lp->dev->name, probe_rsp->flags ); } DBG_TRACE( DbgInfo, "\n\n" ); /* If probe response length is 1, then the scan is complete */ if ( probe_rsp->length == 1 ) { DBG_TRACE( DbgInfo, "SCAN COMPLETE\n" ); lp->probe_results.num_aps = lp->probe_num_aps; lp->probe_results.scan_complete = TRUE; /* Reset the counter for the next scan request */ lp->probe_num_aps = 0; /* Send a wireless extensions event that the scan completed */ wl_wext_event_scan_complete( lp->dev ); } else { /* Only copy to the table if the entry is unique; APs sometimes respond more than once to a probe */ if ( lp->probe_num_aps == 0 ) { /* Copy the info to the ScanResult structure in the private adapter struct */ memcpy( &( lp->probe_results.ProbeTable[lp->probe_num_aps] ), probe_rsp, sizeof( PROBE_RESP )); /* Increment the number of APs detected */ lp->probe_num_aps++; } else { int count; int unique = 1; for( count = 0; count < lp->probe_num_aps; count++ ) { if ( memcmp( &( probe_rsp->BSSID ), lp->probe_results.ProbeTable[count].BSSID, ETH_ALEN ) == 0 ) { unique = 0; } } if ( unique ) { /* Copy the info to the ScanResult structure in the private adapter struct. Only copy if there's room in the table */ if ( lp->probe_num_aps < MAX_NAPS ) { memcpy( &( lp->probe_results.ProbeTable[lp->probe_num_aps] ), probe_rsp, sizeof( PROBE_RESP )); } else { DBG_WARNING( DbgInfo, "Num of scan results exceeds storage, truncating\n" ); } /* Increment the number of APs detected. Note I do this here even when I don't copy the probe response to the buffer in order to detect the overflow condition */ lp->probe_num_aps++; } } } } break; case CFG_LINK_STAT: #define ls ((LINK_STATUS_STRCT *)ltv) DBG_TRACE( DbgInfo, "CFG_LINK_STAT\n" ); switch( ls->linkStatus ) { case 1: DBG_TRACE( DbgInfo, "Link Status : Connected\n" ); wl_wext_event_ap( lp->dev ); break; case 2: DBG_TRACE( DbgInfo, "Link Status : Disconnected\n" ); break; case 3: DBG_TRACE( DbgInfo, "Link Status : Access Point Change\n" ); break; case 4: DBG_TRACE( DbgInfo, "Link Status : Access Point Out of Range\n" ); break; case 5: DBG_TRACE( DbgInfo, "Link Status : Access Point In Range\n" ); break; default: DBG_TRACE( DbgInfo, "Link Status : UNKNOWN (0x%04x)\n", ls->linkStatus ); break; } break; #undef ls case CFG_ASSOC_STAT: DBG_TRACE( DbgInfo, "CFG_ASSOC_STAT\n" ); { ASSOC_STATUS_STRCT *as = (ASSOC_STATUS_STRCT *)ltv; switch( as->assocStatus ) { case 1: DBG_TRACE( DbgInfo, "Association Status : STA Associated\n" ); break; case 2: DBG_TRACE( DbgInfo, "Association Status : STA Reassociated\n" ); break; case 3: DBG_TRACE( DbgInfo, "Association Status : STA Disassociated\n" ); break; default: DBG_TRACE( DbgInfo, "Association Status : UNKNOWN (0x%04x)\n", as->assocStatus ); break; } DBG_TRACE(DbgInfo, "STA Address : %pM\n", as->staAddr); if (( as->assocStatus == 2 ) && ( as->len == 8 )) { DBG_TRACE(DbgInfo, "Old AP Address : %pM\n", as->oldApAddr); } } break; case CFG_SECURITY_STAT: DBG_TRACE( DbgInfo, "CFG_SECURITY_STAT\n" ); { SECURITY_STATUS_STRCT *ss = (SECURITY_STATUS_STRCT *)ltv; switch( ss->securityStatus ) { case 1: DBG_TRACE( DbgInfo, "Security Status : Dissassociate [AP]\n" ); break; case 2: DBG_TRACE( DbgInfo, "Security Status : Deauthenticate [AP]\n" ); break; case 3: DBG_TRACE( DbgInfo, "Security Status : Authenticate Fail [STA] or [AP]\n" ); break; case 4: DBG_TRACE( DbgInfo, "Security Status : MIC Fail\n" ); break; case 5: DBG_TRACE( DbgInfo, "Security Status : Associate Fail\n" ); break; default: DBG_TRACE( DbgInfo, "Security Status : UNKNOWN %d\n", ss->securityStatus ); break; } DBG_TRACE(DbgInfo, "STA Address : %pM\n", ss->staAddr); DBG_TRACE(DbgInfo, "Reason : 0x%04x\n", ss->reason); } break; case CFG_WMP: DBG_TRACE( DbgInfo, "CFG_WMP, size is %d bytes\n", ltv->len ); { WMP_RSP_STRCT *wmp_rsp = (WMP_RSP_STRCT *)ltv; DBG_TRACE( DbgInfo, "CFG_WMP, pdu type is 0x%x\n", wmp_rsp->wmpRsp.wmpHdr.type ); switch( wmp_rsp->wmpRsp.wmpHdr.type ) { case WVLAN_WMP_PDU_TYPE_LT_RSP: { #if DBG LINKTEST_RSP_STRCT *lt_rsp = (LINKTEST_RSP_STRCT *)ltv; #endif // DBG DBG_TRACE( DbgInfo, "LINK TEST RESULT\n" ); DBG_TRACE( DbgInfo, "================\n" ); DBG_TRACE( DbgInfo, "Length : %d.\n", lt_rsp->len ); DBG_TRACE( DbgInfo, "Name : %s.\n", lt_rsp->ltRsp.ltRsp.name ); DBG_TRACE( DbgInfo, "Signal Level : 0x%02x.\n", lt_rsp->ltRsp.ltRsp.signal ); DBG_TRACE( DbgInfo, "Noise Level : 0x%02x.\n", lt_rsp->ltRsp.ltRsp.noise ); DBG_TRACE( DbgInfo, "Receive Flow : 0x%02x.\n", lt_rsp->ltRsp.ltRsp.rxFlow ); DBG_TRACE( DbgInfo, "Data Rate : 0x%02x.\n", lt_rsp->ltRsp.ltRsp.dataRate ); DBG_TRACE( DbgInfo, "Protocol : 0x%04x.\n", lt_rsp->ltRsp.ltRsp.protocol ); DBG_TRACE( DbgInfo, "Station : 0x%02x.\n", lt_rsp->ltRsp.ltRsp.station ); DBG_TRACE( DbgInfo, "Data Rate Cap : 0x%02x.\n", lt_rsp->ltRsp.ltRsp.dataRateCap ); DBG_TRACE( DbgInfo, "Power Mgmt : 0x%02x 0x%02x 0x%02x 0x%02x.\n", lt_rsp->ltRsp.ltRsp.powerMgmt[0], lt_rsp->ltRsp.ltRsp.powerMgmt[1], lt_rsp->ltRsp.ltRsp.powerMgmt[2], lt_rsp->ltRsp.ltRsp.powerMgmt[3] ); DBG_TRACE( DbgInfo, "Robustness : 0x%02x 0x%02x 0x%02x 0x%02x.\n", lt_rsp->ltRsp.ltRsp.robustness[0], lt_rsp->ltRsp.ltRsp.robustness[1], lt_rsp->ltRsp.ltRsp.robustness[2], lt_rsp->ltRsp.ltRsp.robustness[3] ); DBG_TRACE( DbgInfo, "Scaling : 0x%02x.\n", lt_rsp->ltRsp.ltRsp.scaling ); } break; default: break; } } break; case CFG_NULL: DBG_TRACE( DbgInfo, "CFG_NULL\n" ); break; case CFG_UPDATED_INFO_RECORD: // Updated Information Record DBG_TRACE( DbgInfo, "UPDATED INFORMATION RECORD\n" ); ltv_val = CNV_INT_TO_LITTLE( ltv->u.u16[0] ); /* Check and see which RID was updated */ switch( ltv_val ) { case CFG_CUR_COUNTRY_INFO: // Indicate Passive Scan Completion DBG_TRACE( DbgInfo, "Updated country info\n" ); /* Do I need to hold off on updating RIDs until the process is complete? */ wl_connect( lp ); break; case CFG_PORT_STAT: // Wait for Connect Event //wl_connect( lp ); break; default: DBG_WARNING( DbgInfo, "Unknown RID: 0x%04x\n", ltv_val ); } break; default: DBG_TRACE( DbgInfo, "UNKNOWN MESSAGE: 0x%04x\n", ltv->typ ); break; } DBG_LEAVE( DbgInfo ); return; } // wl_process_mailbox /*============================================================================*/ #endif /* ifndef USE_MBOX_SYNC */ #ifdef USE_WDS /******************************************************************************* * wl_wds_netdev_register() ******************************************************************************* * * DESCRIPTION: * * This function registers net_device structures with the system's network * layer for use with the WDS ports. * * * PARAMETERS: * * lp - pointer to the device's private adapter structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_wds_netdev_register( struct wl_private *lp ) { int count; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_wds_netdev_register" ); DBG_ENTER( DbgInfo ); //;?why is there no USE_WDS clause like in wl_enable_wds_ports if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) { for( count = 0; count < NUM_WDS_PORTS; count++ ) { if ( WVLAN_VALID_MAC_ADDRESS( lp->wds_port[count].wdsAddress )) { if ( register_netdev( lp->wds_port[count].dev ) != 0 ) { DBG_WARNING( DbgInfo, "net device for WDS port %d could not be registered\n", ( count + 1 )); } lp->wds_port[count].is_registered = TRUE; /* Fill out the net_device structs with the MAC addr */ memcpy( lp->wds_port[count].dev->dev_addr, lp->MACAddress, ETH_ALEN ); lp->wds_port[count].dev->addr_len = ETH_ALEN; } } } DBG_LEAVE( DbgInfo ); return; } // wl_wds_netdev_register /*============================================================================*/ /******************************************************************************* * wl_wds_netdev_deregister() ******************************************************************************* * * DESCRIPTION: * * This function deregisters the WDS net_device structures used by the * system's network layer. * * * PARAMETERS: * * lp - pointer to the device's private adapter structure * * RETURNS: * * N/A * ******************************************************************************/ void wl_wds_netdev_deregister( struct wl_private *lp ) { int count; /*------------------------------------------------------------------------*/ DBG_FUNC( "wl_wds_netdev_deregister" ); DBG_ENTER( DbgInfo ); if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) { for( count = 0; count < NUM_WDS_PORTS; count++ ) { if ( WVLAN_VALID_MAC_ADDRESS( lp->wds_port[count].wdsAddress )) { unregister_netdev( lp->wds_port[count].dev ); } lp->wds_port[count].is_registered = FALSE; } } DBG_LEAVE( DbgInfo ); return; } // wl_wds_netdev_deregister /*============================================================================*/ #endif /* USE_WDS */ #if 0 //SCULL_USE_PROC /* don't waste space if unused */ /* * The proc filesystem: function to read and entry */ int printf_hcf_16( char *s, char *buf, hcf_16* p, int n ); int printf_hcf_16( char *s, char *buf, hcf_16* p, int n ) { int i, len; len = sprintf(buf, "%s", s ); while ( len < 20 ) len += sprintf(buf+len, " " ); len += sprintf(buf+len,": " ); for ( i = 0; i < n; i++ ) { if ( len % 80 > 75 ) { len += sprintf(buf+len,"\n" ); } len += sprintf(buf+len,"%04X ", p[i] ); } len += sprintf(buf+len,"\n" ); return len; } // printf_hcf_16 int printf_hcf_8( char *s, char *buf, hcf_8* p, int n ); int printf_hcf_8( char *s, char *buf, hcf_8* p, int n ) { int i, len; len = sprintf(buf, "%s", s ); while ( len < 20 ) len += sprintf(buf+len, " " ); len += sprintf(buf+len,": " ); for ( i = 0; i <= n; i++ ) { if ( len % 80 > 77 ) { len += sprintf(buf+len,"\n" ); } len += sprintf(buf+len,"%02X ", p[i] ); } len += sprintf(buf+len,"\n" ); return len; } // printf_hcf8 int printf_strct( char *s, char *buf, hcf_16* p ); int printf_strct( char *s, char *buf, hcf_16* p ) { int i, len; len = sprintf(buf, "%s", s ); while ( len < 20 ) len += sprintf(buf+len, " " ); len += sprintf(buf+len,": " ); for ( i = 0; i <= *p; i++ ) { if ( len % 80 > 75 ) { len += sprintf(buf+len,"\n" ); } len += sprintf(buf+len,"%04X ", p[i] ); } len += sprintf(buf+len,"\n" ); return len; } // printf_strct int scull_read_procmem(char *buf, char **start, off_t offset, int len, int *eof, void *data ) { struct wl_private *lp = NULL; IFBP ifbp; CFG_HERMES_TALLIES_STRCT *p; #define LIMIT (PAGE_SIZE-80) /* don't print any more after this size */ len=0; lp = ((struct net_device *)data)->priv; if (lp == NULL) { len += sprintf(buf+len,"No wl_private in scull_read_procmem\n" ); } else if ( lp->wlags49_type == 0 ){ ifbp = &lp->hcfCtx; len += sprintf(buf+len,"Magic: 0x%04X\n", ifbp->IFB_Magic ); len += sprintf(buf+len,"IOBase: 0x%04X\n", ifbp->IFB_IOBase ); len += sprintf(buf+len,"LinkStat: 0x%04X\n", ifbp->IFB_LinkStat ); len += sprintf(buf+len,"DSLinkStat: 0x%04X\n", ifbp->IFB_DSLinkStat ); len += sprintf(buf+len,"TickIni: 0x%08lX\n", ifbp->IFB_TickIni ); len += sprintf(buf+len,"TickCnt: 0x%04X\n", ifbp->IFB_TickCnt ); len += sprintf(buf+len,"IntOffCnt: 0x%04X\n", ifbp->IFB_IntOffCnt ); len += printf_hcf_16( "IFB_FWIdentity", &buf[len], &ifbp->IFB_FWIdentity.len, ifbp->IFB_FWIdentity.len + 1 ); } else if ( lp->wlags49_type == 1 ) { len += sprintf(buf+len,"Channel: 0x%04X\n", lp->Channel ); /****** len += sprintf(buf+len,"slock: %d\n", lp->slock ); */ //x struct tq_struct "task: 0x%04X\n", lp->task ); //x struct net_device_stats "stats: 0x%04X\n", lp->stats ); #ifdef WIRELESS_EXT //x struct iw_statistics "wstats: 0x%04X\n", lp->wstats ); //x len += sprintf(buf+len,"spy_number: 0x%04X\n", lp->spy_number ); //x u_char spy_address[IW_MAX_SPY][ETH_ALEN]; //x struct iw_quality spy_stat[IW_MAX_SPY]; #endif // WIRELESS_EXT len += sprintf(buf+len,"IFB: 0x%p\n", &lp->hcfCtx ); len += sprintf(buf+len,"flags: %#.8lX\n", lp->flags ); //;?use this format from now on len += sprintf(buf+len,"DebugFlag(wl_private) 0x%04X\n", lp->DebugFlag ); #if DBG len += sprintf(buf+len,"DebugFlag (DbgInfo): 0x%08lX\n", DbgInfo->DebugFlag ); #endif // DBG len += sprintf(buf+len,"is_registered: 0x%04X\n", lp->is_registered ); //x CFG_DRV_INFO_STRCT "driverInfo: 0x%04X\n", lp->driverInfo ); len += printf_strct( "driverInfo", &buf[len], (hcf_16*)&lp->driverInfo ); //x CFG_IDENTITY_STRCT "driverIdentity: 0x%04X\n", lp->driverIdentity ); len += printf_strct( "driverIdentity", &buf[len], (hcf_16*)&lp->driverIdentity ); //x CFG_FW_IDENTITY_STRCT "StationIdentity: 0x%04X\n", lp->StationIdentity ); len += printf_strct( "StationIdentity", &buf[len], (hcf_16*)&lp->StationIdentity ); //x CFG_PRI_IDENTITY_STRCT "PrimaryIdentity: 0x%04X\n", lp->PrimaryIdentity ); len += printf_strct( "PrimaryIdentity", &buf[len], (hcf_16*)&lp->hcfCtx.IFB_PRIIdentity ); len += printf_strct( "PrimarySupplier", &buf[len], (hcf_16*)&lp->hcfCtx.IFB_PRISup ); //x CFG_PRI_IDENTITY_STRCT "NICIdentity: 0x%04X\n", lp->NICIdentity ); len += printf_strct( "NICIdentity", &buf[len], (hcf_16*)&lp->NICIdentity ); //x ltv_t "ltvRecord: 0x%04X\n", lp->ltvRecord ); len += sprintf(buf+len,"txBytes: 0x%08lX\n", lp->txBytes ); len += sprintf(buf+len,"maxPort: 0x%04X\n", lp->maxPort ); /* 0 for STA, 6 for AP */ /* Elements used for async notification from hardware */ //x RID_LOG_STRCT RidList[10]; //x ltv_t "updatedRecord: 0x%04X\n", lp->updatedRecord ); //x PROBE_RESP "ProbeResp: 0x%04X\n", lp->ProbeResp ); //x ASSOC_STATUS_STRCT "assoc_stat: 0x%04X\n", lp->assoc_stat ); //x SECURITY_STATUS_STRCT "sec_stat: 0x%04X\n", lp->sec_stat ); //x u_char lookAheadBuf[WVLAN_MAX_LOOKAHEAD]; len += sprintf(buf+len,"PortType: 0x%04X\n", lp->PortType ); // 1 - 3 (1 [Normal] | 3 [AdHoc]) len += sprintf(buf+len,"Channel: 0x%04X\n", lp->Channel ); // 0 - 14 (0) //x hcf_16 TxRateControl[2]; len += sprintf(buf+len,"TxRateControl[2]: 0x%04X 0x%04X\n", lp->TxRateControl[0], lp->TxRateControl[1] ); len += sprintf(buf+len,"DistanceBetweenAPs: 0x%04X\n", lp->DistanceBetweenAPs ); // 1 - 3 (1) len += sprintf(buf+len,"RTSThreshold: 0x%04X\n", lp->RTSThreshold ); // 0 - 2347 (2347) len += sprintf(buf+len,"PMEnabled: 0x%04X\n", lp->PMEnabled ); // 0 - 2, 8001 - 8002 (0) len += sprintf(buf+len,"MicrowaveRobustness: 0x%04X\n", lp->MicrowaveRobustness );// 0 - 1 (0) len += sprintf(buf+len,"CreateIBSS: 0x%04X\n", lp->CreateIBSS ); // 0 - 1 (0) len += sprintf(buf+len,"MulticastReceive: 0x%04X\n", lp->MulticastReceive ); // 0 - 1 (1) len += sprintf(buf+len,"MaxSleepDuration: 0x%04X\n", lp->MaxSleepDuration ); // 0 - 65535 (100) //x hcf_8 MACAddress[ETH_ALEN]; len += printf_hcf_8( "MACAddress", &buf[len], lp->MACAddress, ETH_ALEN ); //x char NetworkName[HCF_MAX_NAME_LEN+1]; len += sprintf(buf+len,"NetworkName: %.32s\n", lp->NetworkName ); //x char StationName[HCF_MAX_NAME_LEN+1]; len += sprintf(buf+len,"EnableEncryption: 0x%04X\n", lp->EnableEncryption ); // 0 - 1 (0) //x char Key1[MAX_KEY_LEN+1]; len += printf_hcf_8( "Key1", &buf[len], lp->Key1, MAX_KEY_LEN ); //x char Key2[MAX_KEY_LEN+1]; //x char Key3[MAX_KEY_LEN+1]; //x char Key4[MAX_KEY_LEN+1]; len += sprintf(buf+len,"TransmitKeyID: 0x%04X\n", lp->TransmitKeyID ); // 1 - 4 (1) //x CFG_DEFAULT_KEYS_STRCT "DefaultKeys: 0x%04X\n", lp->DefaultKeys ); //x u_char mailbox[MB_SIZE]; //x char szEncryption[MAX_ENC_LEN]; len += sprintf(buf+len,"driverEnable: 0x%04X\n", lp->driverEnable ); len += sprintf(buf+len,"wolasEnable: 0x%04X\n", lp->wolasEnable ); len += sprintf(buf+len,"atimWindow: 0x%04X\n", lp->atimWindow ); len += sprintf(buf+len,"holdoverDuration: 0x%04X\n", lp->holdoverDuration ); //x hcf_16 MulticastRate[2]; len += sprintf(buf+len,"authentication: 0x%04X\n", lp->authentication ); // is this AP specific? len += sprintf(buf+len,"promiscuousMode: 0x%04X\n", lp->promiscuousMode ); len += sprintf(buf+len,"DownloadFirmware: 0x%04X\n", lp->DownloadFirmware ); // 0 - 2 (0 [None] | 1 [STA] | 2 [AP]) len += sprintf(buf+len,"AuthKeyMgmtSuite: 0x%04X\n", lp->AuthKeyMgmtSuite ); len += sprintf(buf+len,"loadBalancing: 0x%04X\n", lp->loadBalancing ); len += sprintf(buf+len,"mediumDistribution: 0x%04X\n", lp->mediumDistribution ); len += sprintf(buf+len,"txPowLevel: 0x%04X\n", lp->txPowLevel ); // len += sprintf(buf+len,"shortRetryLimit: 0x%04X\n", lp->shortRetryLimit ); // len += sprintf(buf+len,"longRetryLimit: 0x%04X\n", lp->longRetryLimit ); //x hcf_16 srsc[2]; //x hcf_16 brsc[2]; len += sprintf(buf+len,"connectionControl: 0x%04X\n", lp->connectionControl ); //x //hcf_16 probeDataRates[2]; len += sprintf(buf+len,"ownBeaconInterval: 0x%04X\n", lp->ownBeaconInterval ); len += sprintf(buf+len,"coexistence: 0x%04X\n", lp->coexistence ); //x WVLAN_FRAME "txF: 0x%04X\n", lp->txF ); //x WVLAN_LFRAME txList[DEFAULT_NUM_TX_FRAMES]; //x struct list_head "txFree: 0x%04X\n", lp->txFree ); //x struct list_head txQ[WVLAN_MAX_TX_QUEUES]; len += sprintf(buf+len,"netif_queue_on: 0x%04X\n", lp->netif_queue_on ); len += sprintf(buf+len,"txQ_count: 0x%04X\n", lp->txQ_count ); //x DESC_STRCT "desc_rx: 0x%04X\n", lp->desc_rx ); //x DESC_STRCT "desc_tx: 0x%04X\n", lp->desc_tx ); //x WVLAN_PORT_STATE "portState: 0x%04X\n", lp->portState ); //x ScanResult "scan_results: 0x%04X\n", lp->scan_results ); //x ProbeResult "probe_results: 0x%04X\n", lp->probe_results ); len += sprintf(buf+len,"probe_num_aps: 0x%04X\n", lp->probe_num_aps ); len += sprintf(buf+len,"use_dma: 0x%04X\n", lp->use_dma ); //x DMA_STRCT "dma: 0x%04X\n", lp->dma ); #ifdef USE_RTS len += sprintf(buf+len,"useRTS: 0x%04X\n", lp->useRTS ); #endif // USE_RTS #if 1 //;? (HCF_TYPE) & HCF_TYPE_AP //;?should we restore this to allow smaller memory footprint //;?I guess not. This should be brought under Debug mode only len += sprintf(buf+len,"DTIMPeriod: 0x%04X\n", lp->DTIMPeriod ); // 1 - 255 (1) len += sprintf(buf+len,"multicastPMBuffering: 0x%04X\n", lp->multicastPMBuffering ); len += sprintf(buf+len,"RejectAny: 0x%04X\n", lp->RejectAny ); // 0 - 1 (0) len += sprintf(buf+len,"ExcludeUnencrypted: 0x%04X\n", lp->ExcludeUnencrypted ); // 0 - 1 (1) len += sprintf(buf+len,"intraBSSRelay: 0x%04X\n", lp->intraBSSRelay ); len += sprintf(buf+len,"wlags49_type: 0x%08lX\n", lp->wlags49_type ); #ifdef USE_WDS //x WVLAN_WDS_IF wds_port[NUM_WDS_PORTS]; #endif // USE_WDS #endif // HCF_AP } else if ( lp->wlags49_type == 2 ){ len += sprintf(buf+len,"tallies to be added\n" ); //Hermes Tallies (IFB substructure) { p = &lp->hcfCtx.IFB_NIC_Tallies; len += sprintf(buf+len,"TxUnicastFrames: %08lX\n", p->TxUnicastFrames ); len += sprintf(buf+len,"TxMulticastFrames: %08lX\n", p->TxMulticastFrames ); len += sprintf(buf+len,"TxFragments: %08lX\n", p->TxFragments ); len += sprintf(buf+len,"TxUnicastOctets: %08lX\n", p->TxUnicastOctets ); len += sprintf(buf+len,"TxMulticastOctets: %08lX\n", p->TxMulticastOctets ); len += sprintf(buf+len,"TxDeferredTransmissions: %08lX\n", p->TxDeferredTransmissions ); len += sprintf(buf+len,"TxSingleRetryFrames: %08lX\n", p->TxSingleRetryFrames ); len += sprintf(buf+len,"TxMultipleRetryFrames: %08lX\n", p->TxMultipleRetryFrames ); len += sprintf(buf+len,"TxRetryLimitExceeded: %08lX\n", p->TxRetryLimitExceeded ); len += sprintf(buf+len,"TxDiscards: %08lX\n", p->TxDiscards ); len += sprintf(buf+len,"RxUnicastFrames: %08lX\n", p->RxUnicastFrames ); len += sprintf(buf+len,"RxMulticastFrames: %08lX\n", p->RxMulticastFrames ); len += sprintf(buf+len,"RxFragments: %08lX\n", p->RxFragments ); len += sprintf(buf+len,"RxUnicastOctets: %08lX\n", p->RxUnicastOctets ); len += sprintf(buf+len,"RxMulticastOctets: %08lX\n", p->RxMulticastOctets ); len += sprintf(buf+len,"RxFCSErrors: %08lX\n", p->RxFCSErrors ); len += sprintf(buf+len,"RxDiscardsNoBuffer: %08lX\n", p->RxDiscardsNoBuffer ); len += sprintf(buf+len,"TxDiscardsWrongSA: %08lX\n", p->TxDiscardsWrongSA ); len += sprintf(buf+len,"RxWEPUndecryptable: %08lX\n", p->RxWEPUndecryptable ); len += sprintf(buf+len,"RxMsgInMsgFragments: %08lX\n", p->RxMsgInMsgFragments ); len += sprintf(buf+len,"RxMsgInBadMsgFragments: %08lX\n", p->RxMsgInBadMsgFragments ); len += sprintf(buf+len,"RxDiscardsWEPICVError: %08lX\n", p->RxDiscardsWEPICVError ); len += sprintf(buf+len,"RxDiscardsWEPExcluded: %08lX\n", p->RxDiscardsWEPExcluded ); #if (HCF_EXT) & HCF_EXT_TALLIES_FW //to be added ;? #endif // HCF_EXT_TALLIES_FW } else if ( lp->wlags49_type & 0x8000 ) { //;?kludgy but it is unclear to me were else to place this #if DBG DbgInfo->DebugFlag = lp->wlags49_type & 0x7FFF; #endif // DBG lp->wlags49_type = 0; //default to IFB again ;? } else { len += sprintf(buf+len,"unknown value for wlags49_type: 0x%08lX\n", lp->wlags49_type ); len += sprintf(buf+len,"0x0000 - IFB\n" ); len += sprintf(buf+len,"0x0001 - wl_private\n" ); len += sprintf(buf+len,"0x0002 - Tallies\n" ); len += sprintf(buf+len,"0x8xxx - Change debufflag\n" ); len += sprintf(buf+len,"ERROR 0001\nWARNING 0002\nNOTICE 0004\nTRACE 0008\n" ); len += sprintf(buf+len,"VERBOSE 0010\nPARAM 0020\nBREAK 0040\nRX 0100\n" ); len += sprintf(buf+len,"TX 0200\nDS 0400\n" ); } return len; } // scull_read_procmem static void proc_write(const char *name, write_proc_t *w, void *data) { struct proc_dir_entry * entry = create_proc_entry(name, S_IFREG | S_IWUSR, NULL); if (entry) { entry->write_proc = w; entry->data = data; } } // proc_write static int write_int(struct file *file, const char *buffer, unsigned long count, void *data) { static char proc_number[11]; unsigned int nr = 0; DBG_FUNC( "write_int" ); DBG_ENTER( DbgInfo ); if (count > 9) { count = -EINVAL; } else if ( copy_from_user(proc_number, buffer, count) ) { count = -EFAULT; } if (count > 0 ) { proc_number[count] = 0; nr = simple_strtoul(proc_number , NULL, 0); *(unsigned int *)data = nr; if ( nr & 0x8000 ) { //;?kludgy but it is unclear to me were else to place this #if DBG DbgInfo->DebugFlag = nr & 0x7FFF; #endif // DBG } } DBG_PRINT( "value: %08X\n", nr ); DBG_LEAVE( DbgInfo ); return count; } // write_int #endif /* SCULL_USE_PROC */ #ifdef DN554 #define RUN_AT(x) (jiffies+(x)) //"borrowed" from include/pcmcia/k_compat.h #define DS_OOR 0x8000 //Deepsleep OutOfRange Status lp->timer_oor_cnt = DS_OOR; init_timer( &lp->timer_oor ); lp->timer_oor.function = timer_oor; lp->timer_oor.data = (unsigned long)lp; lp->timer_oor.expires = RUN_AT( 3 * HZ ); add_timer( &lp->timer_oor ); printk( "<5>wl_enable: %ld\n", jiffies ); //;?remove me 1 day #endif //DN554 #ifdef DN554 /******************************************************************************* * timer_oor() ******************************************************************************* * * DESCRIPTION: * * * PARAMETERS: * * arg - a u_long representing a pointer to a dev_link_t structure for the * device to be released. * * RETURNS: * * N/A * ******************************************************************************/ void timer_oor( u_long arg ) { struct wl_private *lp = (struct wl_private *)arg; /*------------------------------------------------------------------------*/ DBG_FUNC( "timer_oor" ); DBG_ENTER( DbgInfo ); DBG_PARAM( DbgInfo, "arg", "0x%08lx", arg ); printk( "<5>timer_oor: %ld 0x%04X\n", jiffies, lp->timer_oor_cnt ); //;?remove me 1 day lp->timer_oor_cnt += 10; if ( (lp->timer_oor_cnt & ~DS_OOR) > 300 ) { lp->timer_oor_cnt = 300; } lp->timer_oor_cnt |= DS_OOR; init_timer( &lp->timer_oor ); lp->timer_oor.function = timer_oor; lp->timer_oor.data = (unsigned long)lp; lp->timer_oor.expires = RUN_AT( (lp->timer_oor_cnt & ~DS_OOR) * HZ ); add_timer( &lp->timer_oor ); DBG_LEAVE( DbgInfo ); } // timer_oor #endif //DN554 MODULE_LICENSE("Dual BSD/GPL");
957270.c
/*************************************************************************************** * FILE NAME: Blind Sorting-11714.c * * PURPOSE: Solve of Uva problem. * * @author: Md. Arafat Hasan Jenin * EMAIL: [email protected] * * DEVELOPMENT HISTORY: * Date Change Version Description * ------------------------------------------------------------------------ * 30 Sep 16 New 1.0 Accepted **************************************************************************************/ #include <stdio.h> #include <math.h> int main() { long long n; while(scanf("%lli",&n)==1) printf("%lli\n",(n-1)+(int)log2(n-1)); return 0; }
663294.c
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <criterion/criterion.h> #include "alloc.h" #include "config.h" #include "extensions.h" static void setup(void) { #ifdef USE_RPMALLOC rpmalloc_initialize(); #endif } static void teardown(void) { #ifdef USE_RPMALLOC rpmalloc_finalize(); #endif } #define WSS_EXTENSION_NO_FILE "resources/test-ext-no-file.so" #define WSS_EXTENSION_NO_ALLOC "resources/test-ext-no-set-allocators.so" #define WSS_EXTENSION_NO_INIT "resources/test-ext-no-init.so" #define WSS_EXTENSION_NO_OPEN "resources/test-ext-no-open.so" #define WSS_EXTENSION_NO_IN_FRAME "resources/test-ext-no-in-frame.so" #define WSS_EXTENSION_NO_IN_FRAMES "resources/test-ext-no-in-frames.so" #define WSS_EXTENSION_NO_OUT_FRAME "resources/test-ext-no-out-frame.so" #define WSS_EXTENSION_NO_OUT_FRAMES "resources/test-ext-no-out-frames.so" #define WSS_EXTENSION_NO_CLOSE "resources/test-ext-no-close.so" #define WSS_EXTENSION_NO_DESTROY "resources/test-ext-no-destroy.so" TestSuite(WSS_load_extensions, .init = setup, .fini = teardown); Test(WSS_load_extensions, no_config) { WSS_load_extensions(NULL); cr_assert(NULL == WSS_find_extension(NULL)); WSS_destroy_extensions(); } Test(WSS_load_extensions, no_file) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_FILE)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_FILE); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-file")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_set_allocators) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_ALLOC)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_ALLOC); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-set-allocators")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_init) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_INIT)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_INIT); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-init")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_open) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_OPEN)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_OPEN); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-open")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_in_frame) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_IN_FRAME)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_IN_FRAME); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-in-frame")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_in_frames) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_IN_FRAMES)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_IN_FRAMES); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-in-frames")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_out_frame) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_OUT_FRAME)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_OUT_FRAME); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-out-frame")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_out_frames) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_OUT_FRAMES)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_OUT_FRAMES); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-out-frames")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_close) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_CLOSE)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_CLOSE); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-close")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, no_destroy) { size_t length = 1; wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); conf->extensions_length = 1; conf->extensions = WSS_calloc(length, sizeof(char *)); conf->extensions[0] = WSS_malloc(sizeof(char)*(strlen(WSS_EXTENSION_NO_DESTROY)+1)); sprintf(conf->extensions[0], "%s", WSS_EXTENSION_NO_DESTROY); conf->extensions_config = WSS_calloc(length, sizeof(char *)); conf->extensions_config[0] = NULL; WSS_load_extensions(conf); cr_assert(NULL == WSS_find_extension("test-ext-no-destroy")); WSS_destroy_extensions(); WSS_free((void**) &conf->extensions[0]); WSS_config_free(conf); WSS_free((void**) &conf); } Test(WSS_load_extensions, successful) { wss_config_t *conf = (wss_config_t *) WSS_malloc(sizeof(wss_config_t)); cr_assert(WSS_SUCCESS == WSS_config_load(conf, "resources/test_wss.json")); WSS_load_extensions(conf); cr_assert(NULL != WSS_find_extension("permessage-deflate")); WSS_destroy_extensions(); WSS_config_free(conf); WSS_free((void**) &conf); }
970536.c
/* * libwebsockets - small server side websockets and web server implementation * * Copyright (C) 2010 - 2019 Andy Green <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "private-lib-core.h" static const unsigned char lextable[] = { #include "lextable.h" }; #define FAIL_CHAR 0x08 #if defined(LWS_WITH_CUSTOM_HEADERS) #define UHO_NLEN 0 #define UHO_VLEN 2 #define UHO_LL 4 #define UHO_NAME 8 #endif static struct allocated_headers * _lws_create_ah(struct lws_context_per_thread *pt, ah_data_idx_t data_size) { struct allocated_headers *ah = lws_zalloc(sizeof(*ah), "ah struct"); if (!ah) return NULL; ah->data = lws_malloc(data_size, "ah data"); if (!ah->data) { lws_free(ah); return NULL; } ah->next = pt->http.ah_list; pt->http.ah_list = ah; ah->data_length = data_size; pt->http.ah_pool_length++; lwsl_info("%s: created ah %p (size %d): pool length %ld\n", __func__, ah, (int)data_size, (unsigned long)pt->http.ah_pool_length); return ah; } int _lws_destroy_ah(struct lws_context_per_thread *pt, struct allocated_headers *ah) { lws_start_foreach_llp(struct allocated_headers **, a, pt->http.ah_list) { if ((*a) == ah) { *a = ah->next; pt->http.ah_pool_length--; lwsl_info("%s: freed ah %p : pool length %ld\n", __func__, ah, (unsigned long)pt->http.ah_pool_length); if (ah->data) lws_free(ah->data); lws_free(ah); return 0; } } lws_end_foreach_llp(a, next); return 1; } void _lws_header_table_reset(struct allocated_headers *ah) { /* init the ah to reflect no headers or data have appeared yet */ memset(ah->frag_index, 0, sizeof(ah->frag_index)); memset(ah->frags, 0, sizeof(ah->frags)); ah->nfrag = 0; ah->pos = 0; ah->http_response = 0; ah->parser_state = WSI_TOKEN_NAME_PART; ah->lextable_pos = 0; #if defined(LWS_WITH_CUSTOM_HEADERS) ah->unk_pos = 0; ah->unk_ll_head = 0; ah->unk_ll_tail = 0; #endif } // doesn't scrub the ah rxbuffer by default, parent must do if needed void __lws_header_table_reset(struct lws *wsi, int autoservice) { struct allocated_headers *ah = wsi->http.ah; struct lws_context_per_thread *pt; struct lws_pollfd *pfd; /* if we have the idea we're resetting 'our' ah, must be bound to one */ assert(ah); /* ah also concurs with ownership */ assert(ah->wsi == wsi); _lws_header_table_reset(ah); /* since we will restart the ah, our new headers are not completed */ wsi->hdr_parsing_completed = 0; /* while we hold the ah, keep a timeout on the wsi */ __lws_set_timeout(wsi, PENDING_TIMEOUT_HOLDING_AH, wsi->vhost->timeout_secs_ah_idle); time(&ah->assigned); if (wsi->position_in_fds_table != LWS_NO_FDS_POS && lws_buflist_next_segment_len(&wsi->buflist, NULL) && autoservice) { lwsl_debug("%s: service on readbuf ah\n", __func__); pt = &wsi->context->pt[(int)wsi->tsi]; /* * Unlike a normal connect, we have the headers already * (or the first part of them anyway) */ pfd = &pt->fds[wsi->position_in_fds_table]; pfd->revents |= LWS_POLLIN; lwsl_err("%s: calling service\n", __func__); lws_service_fd_tsi(wsi->context, pfd, wsi->tsi); } } void lws_header_table_reset(struct lws *wsi, int autoservice) { struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; lws_pt_lock(pt, __func__); __lws_header_table_reset(wsi, autoservice); lws_pt_unlock(pt); } static void _lws_header_ensure_we_are_on_waiting_list(struct lws *wsi) { struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; struct lws_pollargs pa; struct lws **pwsi = &pt->http.ah_wait_list; while (*pwsi) { if (*pwsi == wsi) return; pwsi = &(*pwsi)->http.ah_wait_list; } lwsl_info("%s: wsi: %p\n", __func__, wsi); wsi->http.ah_wait_list = pt->http.ah_wait_list; pt->http.ah_wait_list = wsi; pt->http.ah_wait_list_length++; /* we cannot accept input then */ _lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa); } static int __lws_remove_from_ah_waiting_list(struct lws *wsi) { struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; struct lws **pwsi =&pt->http.ah_wait_list; while (*pwsi) { if (*pwsi == wsi) { lwsl_info("%s: wsi %p\n", __func__, wsi); /* point prev guy to our next */ *pwsi = wsi->http.ah_wait_list; /* we shouldn't point anywhere now */ wsi->http.ah_wait_list = NULL; pt->http.ah_wait_list_length--; return 1; } pwsi = &(*pwsi)->http.ah_wait_list; } return 0; } int LWS_WARN_UNUSED_RESULT lws_header_table_attach(struct lws *wsi, int autoservice) { struct lws_context *context = wsi->context; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; struct lws_pollargs pa; int n; lwsl_info("%s: wsi %p: ah %p (tsi %d, count = %d) in\n", __func__, (void *)wsi, (void *)wsi->http.ah, wsi->tsi, pt->http.ah_count_in_use); if (!lwsi_role_http(wsi)) { lwsl_err("%s: bad role %s\n", __func__, wsi->role_ops->name); assert(0); return -1; } lws_pt_lock(pt, __func__); /* if we are already bound to one, just clear it down */ if (wsi->http.ah) { lwsl_info("%s: cleardown\n", __func__); goto reset; } n = pt->http.ah_count_in_use == context->max_http_header_pool; #if defined(LWS_WITH_PEER_LIMITS) if (!n) { n = lws_peer_confirm_ah_attach_ok(context, wsi->peer); if (n) lws_stats_bump(pt, LWSSTATS_C_PEER_LIMIT_AH_DENIED, 1); } #endif if (n) { /* * Pool is either all busy, or we don't want to give this * particular guy an ah right now... * * Make sure we are on the waiting list, and return that we * weren't able to provide the ah */ _lws_header_ensure_we_are_on_waiting_list(wsi); goto bail; } __lws_remove_from_ah_waiting_list(wsi); wsi->http.ah = _lws_create_ah(pt, context->max_http_header_data); if (!wsi->http.ah) { /* we could not create an ah */ _lws_header_ensure_we_are_on_waiting_list(wsi); goto bail; } wsi->http.ah->in_use = 1; wsi->http.ah->wsi = wsi; /* mark our owner */ pt->http.ah_count_in_use++; #if defined(LWS_WITH_PEER_LIMITS) && (defined(LWS_ROLE_H1) || \ defined(LWS_ROLE_H2)) lws_context_lock(context, "ah attach"); /* <========================= */ if (wsi->peer) wsi->peer->http.count_ah++; lws_context_unlock(context); /* ====================================> */ #endif _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa); lwsl_info("%s: did attach wsi %p: ah %p: count %d (on exit)\n", __func__, (void *)wsi, (void *)wsi->http.ah, pt->http.ah_count_in_use); reset: __lws_header_table_reset(wsi, autoservice); lws_pt_unlock(pt); #if defined(LWS_WITH_CLIENT) if (lwsi_role_client(wsi) && lwsi_state(wsi) == LRS_UNCONNECTED) if (!lws_http_client_connect_via_info2(wsi)) /* our client connect has failed, the wsi * has been closed */ return -1; #endif return 0; bail: lws_pt_unlock(pt); return 1; } int __lws_header_table_detach(struct lws *wsi, int autoservice) { struct lws_context *context = wsi->context; struct allocated_headers *ah = wsi->http.ah; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; struct lws_pollargs pa; struct lws **pwsi, **pwsi_eligible; time_t now; __lws_remove_from_ah_waiting_list(wsi); if (!ah) return 0; lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__, (void *)wsi, (void *)ah, wsi->tsi, pt->http.ah_count_in_use); /* we did have an ah attached */ time(&now); if (ah->assigned && now - ah->assigned > 3) { /* * we're detaching the ah, but it was held an * unreasonably long time */ lwsl_debug("%s: wsi %p: ah held %ds, role/state 0x%lx 0x%x," "\n", __func__, wsi, (int)(now - ah->assigned), (unsigned long)lwsi_role(wsi), lwsi_state(wsi)); } ah->assigned = 0; /* if we think we're detaching one, there should be one in use */ assert(pt->http.ah_count_in_use > 0); /* and this specific one should have been in use */ assert(ah->in_use); memset(&wsi->http.ah, 0, sizeof(wsi->http.ah)); #if defined(LWS_WITH_PEER_LIMITS) if (ah->wsi) lws_peer_track_ah_detach(context, wsi->peer); #endif ah->wsi = NULL; /* no owner */ pwsi = &pt->http.ah_wait_list; /* oh there is nobody on the waiting list... leave the ah unattached */ if (!*pwsi) goto nobody_usable_waiting; /* * at least one wsi on the same tsi is waiting, give it to oldest guy * who is allowed to take it (if any) */ lwsl_info("pt wait list %p\n", *pwsi); wsi = NULL; pwsi_eligible = NULL; while (*pwsi) { #if defined(LWS_WITH_PEER_LIMITS) /* are we willing to give this guy an ah? */ if (!lws_peer_confirm_ah_attach_ok(context, (*pwsi)->peer)) #endif { wsi = *pwsi; pwsi_eligible = pwsi; } #if defined(LWS_WITH_PEER_LIMITS) else if (!(*pwsi)->http.ah_wait_list) lws_stats_bump(pt, LWSSTATS_C_PEER_LIMIT_AH_DENIED, 1); #endif pwsi = &(*pwsi)->http.ah_wait_list; } if (!wsi) /* everybody waiting already has too many ah... */ goto nobody_usable_waiting; lwsl_info("%s: transferring ah to last eligible wsi in wait list " "%p (wsistate 0x%lx)\n", __func__, wsi, (unsigned long)wsi->wsistate); wsi->http.ah = ah; ah->wsi = wsi; /* new owner */ __lws_header_table_reset(wsi, autoservice); #if defined(LWS_WITH_PEER_LIMITS) && (defined(LWS_ROLE_H1) || \ defined(LWS_ROLE_H2)) lws_context_lock(context, "ah detach"); /* <========================= */ if (wsi->peer) wsi->peer->http.count_ah++; lws_context_unlock(context); /* ====================================> */ #endif /* clients acquire the ah and then insert themselves in fds table... */ if (wsi->position_in_fds_table != LWS_NO_FDS_POS) { lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi); /* he has been stuck waiting for an ah, but now his wait is * over, let him progress */ _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa); } /* point prev guy to next guy in list instead */ *pwsi_eligible = wsi->http.ah_wait_list; /* the guy who got one is out of the list */ wsi->http.ah_wait_list = NULL; pt->http.ah_wait_list_length--; #if defined(LWS_WITH_CLIENT) if (lwsi_role_client(wsi) && lwsi_state(wsi) == LRS_UNCONNECTED) { lws_pt_unlock(pt); if (!lws_http_client_connect_via_info2(wsi)) { /* our client connect has failed, the wsi * has been closed */ return -1; } return 0; } #endif assert(!!pt->http.ah_wait_list_length == !!(lws_intptr_t)pt->http.ah_wait_list); bail: lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__, (void *)wsi, (void *)ah, pt->tid, pt->http.ah_count_in_use); return 0; nobody_usable_waiting: lwsl_info("%s: nobody usable waiting\n", __func__); _lws_destroy_ah(pt, ah); pt->http.ah_count_in_use--; goto bail; } int lws_header_table_detach(struct lws *wsi, int autoservice) { struct lws_context *context = wsi->context; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; int n; lws_pt_lock(pt, __func__); n = __lws_header_table_detach(wsi, autoservice); lws_pt_unlock(pt); return n; } LWS_VISIBLE int lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx) { int n; if (!wsi->http.ah) return 0; n = wsi->http.ah->frag_index[h]; if (!n) return 0; do { if (!frag_idx) return wsi->http.ah->frags[n].len; n = wsi->http.ah->frags[n].nfrag; } while (frag_idx-- && n); return 0; } LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h) { int n; int len = 0; if (!wsi->http.ah) return 0; n = wsi->http.ah->frag_index[h]; if (!n) return 0; do { len += wsi->http.ah->frags[n].len; n = wsi->http.ah->frags[n].nfrag; if (n && h != WSI_TOKEN_HTTP_COOKIE) ++len; } while (n); return len; } LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len, enum lws_token_indexes h, int frag_idx) { int n = 0; int f; if (!wsi->http.ah) return -1; f = wsi->http.ah->frag_index[h]; if (!f) return -1; while (n < frag_idx) { f = wsi->http.ah->frags[f].nfrag; if (!f) return -1; n++; } if (wsi->http.ah->frags[f].len >= len) return -1; memcpy(dst, wsi->http.ah->data + wsi->http.ah->frags[f].offset, wsi->http.ah->frags[f].len); dst[wsi->http.ah->frags[f].len] = '\0'; return wsi->http.ah->frags[f].len; } LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len, enum lws_token_indexes h) { int toklen = lws_hdr_total_length(wsi, h); int n; int comma; *dst = '\0'; if (!toklen) return 0; if (toklen >= len) return -1; if (!wsi->http.ah) return -1; n = wsi->http.ah->frag_index[h]; if (!n) return 0; do { comma = (wsi->http.ah->frags[n].nfrag && h != WSI_TOKEN_HTTP_COOKIE) ? 1 : 0; if (wsi->http.ah->frags[n].len + comma >= len) return -1; strncpy(dst, &wsi->http.ah->data[wsi->http.ah->frags[n].offset], wsi->http.ah->frags[n].len); dst += wsi->http.ah->frags[n].len; len -= wsi->http.ah->frags[n].len; n = wsi->http.ah->frags[n].nfrag; if (comma) *dst++ = ','; } while (n); *dst = '\0'; return toklen; } #if defined(LWS_WITH_CUSTOM_HEADERS) LWS_VISIBLE int lws_hdr_custom_length(struct lws *wsi, const char *name, int nlen) { ah_data_idx_t ll; if (!wsi->http.ah || wsi->http2_substream) return -1; ll = wsi->http.ah->unk_ll_head; while (ll) { if (ll >= wsi->http.ah->data_length) return -1; if (nlen == lws_ser_ru16be( (uint8_t *)&wsi->http.ah->data[ll + UHO_NLEN]) && !strncmp(name, &wsi->http.ah->data[ll + UHO_NAME], nlen)) return lws_ser_ru16be( (uint8_t *)&wsi->http.ah->data[ll + UHO_VLEN]); ll = lws_ser_ru32be((uint8_t *)&wsi->http.ah->data[ll + UHO_LL]); } return -1; } LWS_VISIBLE int lws_hdr_custom_copy(struct lws *wsi, char *dst, int len, const char *name, int nlen) { ah_data_idx_t ll; int n; if (!wsi->http.ah || wsi->http2_substream) return -1; *dst = '\0'; ll = wsi->http.ah->unk_ll_head; while (ll) { if (ll >= wsi->http.ah->data_length) return -1; if (nlen == lws_ser_ru16be( (uint8_t *)&wsi->http.ah->data[ll + UHO_NLEN]) && !strncmp(name, &wsi->http.ah->data[ll + UHO_NAME], nlen)) { n = lws_ser_ru16be( (uint8_t *)&wsi->http.ah->data[ll + UHO_VLEN]); if (n + 1 > len) return -1; strncpy(dst, &wsi->http.ah->data[ll + UHO_NAME + nlen], n); dst[n] = '\0'; return n; } ll = lws_ser_ru32be((uint8_t *)&wsi->http.ah->data[ll + UHO_LL]); } return -1; } #endif char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h) { int n; if (!wsi->http.ah) return NULL; n = wsi->http.ah->frag_index[h]; if (!n) return NULL; return wsi->http.ah->data + wsi->http.ah->frags[n].offset; } static int LWS_WARN_UNUSED_RESULT lws_pos_in_bounds(struct lws *wsi) { if (!wsi->http.ah) return -1; if (wsi->http.ah->pos < (unsigned int)wsi->context->max_http_header_data) return 0; if ((int)wsi->http.ah->pos >= wsi->context->max_http_header_data - 1) { lwsl_err("Ran out of header data space\n"); return 1; } /* * with these tests everywhere, it should never be able to exceed * the limit, only meet it */ lwsl_err("%s: pos %ld, limit %ld\n", __func__, (unsigned long)wsi->http.ah->pos, (unsigned long)wsi->context->max_http_header_data); assert(0); return 1; } int LWS_WARN_UNUSED_RESULT lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s) { wsi->http.ah->nfrag++; if (wsi->http.ah->nfrag == LWS_ARRAY_SIZE(wsi->http.ah->frags)) { lwsl_warn("More hdr frags than we can deal with, dropping\n"); return -1; } wsi->http.ah->frag_index[h] = wsi->http.ah->nfrag; wsi->http.ah->frags[wsi->http.ah->nfrag].offset = wsi->http.ah->pos; wsi->http.ah->frags[wsi->http.ah->nfrag].len = 0; wsi->http.ah->frags[wsi->http.ah->nfrag].nfrag = 0; do { if (lws_pos_in_bounds(wsi)) return -1; wsi->http.ah->data[wsi->http.ah->pos++] = *s; if (*s) wsi->http.ah->frags[wsi->http.ah->nfrag].len++; } while (*s++); return 0; } static int LWS_WARN_UNUSED_RESULT issue_char(struct lws *wsi, unsigned char c) { unsigned short frag_len; if (lws_pos_in_bounds(wsi)) return -1; frag_len = wsi->http.ah->frags[wsi->http.ah->nfrag].len; /* * If we haven't hit the token limit, just copy the character into * the header */ if (!wsi->http.ah->current_token_limit || frag_len < wsi->http.ah->current_token_limit) { wsi->http.ah->data[wsi->http.ah->pos++] = c; if (c) wsi->http.ah->frags[wsi->http.ah->nfrag].len++; return 0; } /* Insert a null character when we *hit* the limit: */ if (frag_len == wsi->http.ah->current_token_limit) { if (lws_pos_in_bounds(wsi)) return -1; wsi->http.ah->data[wsi->http.ah->pos++] = '\0'; lwsl_warn("header %li exceeds limit %ld\n", (long)wsi->http.ah->parser_state, (long)wsi->http.ah->current_token_limit); } return 1; } int lws_parse_urldecode(struct lws *wsi, uint8_t *_c) { struct allocated_headers *ah = wsi->http.ah; unsigned int enc = 0; uint8_t c = *_c; // lwsl_notice("ah->ups %d\n", ah->ups); /* * PRIORITY 1 * special URI processing... convert %xx */ switch (ah->ues) { case URIES_IDLE: if (c == '%') { ah->ues = URIES_SEEN_PERCENT; goto swallow; } break; case URIES_SEEN_PERCENT: if (char_to_hex(c) < 0) /* illegal post-% char */ goto forbid; ah->esc_stash = c; ah->ues = URIES_SEEN_PERCENT_H1; goto swallow; case URIES_SEEN_PERCENT_H1: if (char_to_hex(c) < 0) /* illegal post-% char */ goto forbid; *_c = (char_to_hex(ah->esc_stash) << 4) | char_to_hex(c); c = *_c; enc = 1; ah->ues = URIES_IDLE; break; } /* * PRIORITY 2 * special URI processing... * convert /.. or /... or /../ etc to / * convert /./ to / * convert // or /// etc to / * leave /.dir or whatever alone */ switch (ah->ups) { case URIPS_IDLE: if (!c) return -1; /* genuine delimiter */ if ((c == '&' || c == ';') && !enc) { if (issue_char(wsi, '\0') < 0) return -1; /* link to next fragment */ ah->frags[ah->nfrag].nfrag = ah->nfrag + 1; ah->nfrag++; if (ah->nfrag >= LWS_ARRAY_SIZE(ah->frags)) goto excessive; /* start next fragment after the & */ ah->post_literal_equal = 0; ah->frags[ah->nfrag].offset = ++ah->pos; ah->frags[ah->nfrag].len = 0; ah->frags[ah->nfrag].nfrag = 0; goto swallow; } /* uriencoded = in the name part, disallow */ if (c == '=' && enc && ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] && !ah->post_literal_equal) { c = '_'; *_c =c; } /* after the real =, we don't care how many = */ if (c == '=' && !enc) ah->post_literal_equal = 1; /* + to space */ if (c == '+' && !enc) { c = ' '; *_c = c; } /* issue the first / always */ if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) ah->ups = URIPS_SEEN_SLASH; break; case URIPS_SEEN_SLASH: /* swallow subsequent slashes */ if (c == '/') goto swallow; /* track and swallow the first . after / */ if (c == '.') { ah->ups = URIPS_SEEN_SLASH_DOT; goto swallow; } ah->ups = URIPS_IDLE; break; case URIPS_SEEN_SLASH_DOT: /* swallow second . */ if (c == '.') { ah->ups = URIPS_SEEN_SLASH_DOT_DOT; goto swallow; } /* change /./ to / */ if (c == '/') { ah->ups = URIPS_SEEN_SLASH; goto swallow; } /* it was like /.dir ... regurgitate the . */ ah->ups = URIPS_IDLE; if (issue_char(wsi, '.') < 0) return -1; break; case URIPS_SEEN_SLASH_DOT_DOT: /* /../ or /..[End of URI] --> backup to last / */ if (c == '/' || c == '?') { /* * back up one dir level if possible * safe against header fragmentation because * the method URI can only be in 1 fragment */ if (ah->frags[ah->nfrag].len > 2) { ah->pos--; ah->frags[ah->nfrag].len--; do { ah->pos--; ah->frags[ah->nfrag].len--; } while (ah->frags[ah->nfrag].len > 1 && ah->data[ah->pos] != '/'); } ah->ups = URIPS_SEEN_SLASH; if (ah->frags[ah->nfrag].len > 1) break; goto swallow; } /* /..[^/] ... regurgitate and allow */ if (issue_char(wsi, '.') < 0) return -1; if (issue_char(wsi, '.') < 0) return -1; ah->ups = URIPS_IDLE; break; } if (c == '?' && !enc && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI args */ if (ah->ues != URIES_IDLE) goto forbid; /* seal off uri header */ if (issue_char(wsi, '\0') < 0) return -1; /* move to using WSI_TOKEN_HTTP_URI_ARGS */ ah->nfrag++; if (ah->nfrag >= LWS_ARRAY_SIZE(ah->frags)) goto excessive; ah->frags[ah->nfrag].offset = ++ah->pos; ah->frags[ah->nfrag].len = 0; ah->frags[ah->nfrag].nfrag = 0; ah->post_literal_equal = 0; ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag; ah->ups = URIPS_IDLE; goto swallow; } return LPUR_CONTINUE; swallow: return LPUR_SWALLOW; forbid: return LPUR_FORBID; excessive: return LPUR_EXCESSIVE; } static const unsigned char methods[] = { WSI_TOKEN_GET_URI, WSI_TOKEN_POST_URI, WSI_TOKEN_OPTIONS_URI, WSI_TOKEN_PUT_URI, WSI_TOKEN_PATCH_URI, WSI_TOKEN_DELETE_URI, WSI_TOKEN_CONNECT, WSI_TOKEN_HEAD_URI, }; /* * possible returns:, -1 fail, 0 ok or 2, transition to raw */ lws_parser_return_t LWS_WARN_UNUSED_RESULT lws_parse(struct lws *wsi, unsigned char *buf, int *len) { struct allocated_headers *ah = wsi->http.ah; struct lws_context *context = wsi->context; unsigned int n, m; unsigned char c; int r, pos; assert(wsi->http.ah); do { (*len)--; c = *buf++; switch (ah->parser_state) { #if defined(LWS_WITH_CUSTOM_HEADERS) case WSI_TOKEN_UNKNOWN_VALUE_PART: if (c == '\r') break; if (c == '\n') { lws_ser_wu16be((uint8_t *)&ah->data[ah->unk_pos + 2], ah->pos - ah->unk_value_pos); ah->parser_state = WSI_TOKEN_NAME_PART; ah->unk_pos = 0; ah->lextable_pos = 0; break; } /* trim leading whitespace */ if (ah->pos != ah->unk_value_pos || (c != ' ' && c != '\t')) { if (lws_pos_in_bounds(wsi)) return LPR_FAIL; ah->data[ah->pos++] = c; } pos = ah->lextable_pos; break; #endif default: lwsl_parser("WSI_TOK_(%d) '%c'\n", ah->parser_state, c); /* collect into malloc'd buffers */ /* optional initial space swallow */ if (!ah->frags[ah->frag_index[ah->parser_state]].len && c == ' ') break; for (m = 0; m < LWS_ARRAY_SIZE(methods); m++) if (ah->parser_state == methods[m]) break; if (m == LWS_ARRAY_SIZE(methods)) /* it was not any of the methods */ goto check_eol; /* special URI processing... end at space */ if (c == ' ') { /* enforce starting with / */ if (!ah->frags[ah->nfrag].len) if (issue_char(wsi, '/') < 0) return LPR_FAIL; if (ah->ups == URIPS_SEEN_SLASH_DOT_DOT) { /* * back up one dir level if possible * safe against header fragmentation * because the method URI can only be * in 1 fragment */ if (ah->frags[ah->nfrag].len > 2) { ah->pos--; ah->frags[ah->nfrag].len--; do { ah->pos--; ah->frags[ah->nfrag].len--; } while (ah->frags[ah->nfrag].len > 1 && ah->data[ah->pos] != '/'); } } /* begin parsing HTTP version: */ if (issue_char(wsi, '\0') < 0) return LPR_FAIL; ah->parser_state = WSI_TOKEN_HTTP; goto start_fragment; } r = lws_parse_urldecode(wsi, &c); switch (r) { case LPUR_CONTINUE: break; case LPUR_SWALLOW: goto swallow; case LPUR_FORBID: goto forbid; case LPUR_EXCESSIVE: goto excessive; default: return LPR_FAIL; } check_eol: /* bail at EOL */ if (ah->parser_state != WSI_TOKEN_CHALLENGE && c == '\x0d') { if (ah->ues != URIES_IDLE) goto forbid; c = '\0'; ah->parser_state = WSI_TOKEN_SKIPPING_SAW_CR; lwsl_parser("*\n"); } n = issue_char(wsi, c); if ((int)n < 0) return LPR_FAIL; if (n > 0) ah->parser_state = WSI_TOKEN_SKIPPING; swallow: /* per-protocol end of headers management */ if (ah->parser_state == WSI_TOKEN_CHALLENGE) goto set_parsing_complete; break; /* collecting and checking a name part */ case WSI_TOKEN_NAME_PART: lwsl_parser("WSI_TOKEN_NAME_PART '%c' 0x%02X " "(role=0x%lx) " "wsi->lextable_pos=%d\n", c, c, (unsigned long)lwsi_role(wsi), ah->lextable_pos); if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; #if defined(LWS_WITH_CUSTOM_HEADERS) /* * ...in case it's an unknown header, speculatively * store it as the name comes in. If we recognize it as * a known header, we'll snip this. */ if (!ah->unk_pos) { ah->unk_pos = ah->pos; /* * Prepare new unknown header linked-list entry * * - 16-bit BE: name part length * - 16-bit BE: value part length * - 32-bit BE: data offset of next, or 0 */ for (n = 0; n < 8; n++) if (!lws_pos_in_bounds(wsi)) ah->data[ah->pos++] = 0; } #endif if (lws_pos_in_bounds(wsi)) return LPR_FAIL; ah->data[ah->pos++] = c; pos = ah->lextable_pos; #if defined(LWS_WITH_CUSTOM_HEADERS) if (pos < 0 && c == ':') { /* * process unknown headers * * register us in the unknown hdr ll */ if (!ah->unk_ll_head) ah->unk_ll_head = ah->unk_pos; if (ah->unk_ll_tail) lws_ser_wu32be( (uint8_t *)&ah->data[ah->unk_ll_tail + UHO_LL], ah->unk_pos); ah->unk_ll_tail = ah->unk_pos; lwsl_debug("%s: unk header %d '%.*s'\n", __func__, ah->pos - (ah->unk_pos + UHO_NAME), ah->pos - (ah->unk_pos + UHO_NAME), &ah->data[ah->unk_pos + UHO_NAME]); /* set the unknown header name part length */ lws_ser_wu16be((uint8_t *)&ah->data[ah->unk_pos], (ah->pos - ah->unk_pos) - UHO_NAME); ah->unk_value_pos = ah->pos; /* * collect whatever's coming for the unknown header * argument until the next CRLF */ ah->parser_state = WSI_TOKEN_UNKNOWN_VALUE_PART; break; } #endif if (pos < 0) break; while (1) { if (lextable[pos] & (1 << 7)) { /* 1-byte, fail on mismatch */ if ((lextable[pos] & 0x7f) != c) { nope: ah->lextable_pos = -1; break; } /* fall thru */ pos++; if (lextable[pos] == FAIL_CHAR) goto nope; ah->lextable_pos = pos; break; } if (lextable[pos] == FAIL_CHAR) goto nope; /* b7 = 0, end or 3-byte */ if (lextable[pos] < FAIL_CHAR) { #if defined(LWS_WITH_CUSTOM_HEADERS) /* * We hit a terminal marker, so we * recognized this header... drop the * speculative name part storage */ ah->pos = ah->unk_pos; ah->unk_pos = 0; #endif ah->lextable_pos = pos; break; } if (lextable[pos] == c) { /* goto */ ah->lextable_pos = pos + (lextable[pos + 1]) + (lextable[pos + 2] << 8); break; } /* fall thru goto */ pos += 3; /* continue */ } /* * If it's h1, server needs to be on the look out for * unknown methods... */ if (ah->lextable_pos < 0 && lwsi_role_h1(wsi) && lwsi_role_server(wsi)) { /* * this is not a header we know about... did * we get a valid method (GET, POST etc) * already, or is this the bogus method? */ for (m = 0; m < LWS_ARRAY_SIZE(methods); m++) if (ah->frag_index[methods[m]]) { /* * already had the method */ #if !defined(LWS_WITH_CUSTOM_HEADERS) ah->parser_state = WSI_TOKEN_SKIPPING; #endif break; } if (m != LWS_ARRAY_SIZE(methods)) #if defined(LWS_WITH_CUSTOM_HEADERS) /* * We have the method, this is just an * unknown header then */ goto unknown_hdr; #else break; #endif /* * ...it's an unknown http method from a client * in fact, it cannot be valid http. * * Are we set up to transition to another role * in these cases? */ if (lws_check_opt(wsi->vhost->options, LWS_SERVER_OPTION_FALLBACK_TO_APPLY_LISTEN_ACCEPT_CONFIG)) { lwsl_notice("%s: http fail fallback\n", __func__); /* transition to other role */ return LPR_DO_FALLBACK; } lwsl_info("Unknown method - dropping\n"); goto forbid; } if (ah->lextable_pos < 0) { #if defined(LWS_WITH_CUSTOM_HEADERS) goto unknown_hdr; #else /* * ...otherwise for a client, let him ignore * unknown headers coming from the server */ ah->parser_state = WSI_TOKEN_SKIPPING; break; #endif } if (lextable[ah->lextable_pos] < FAIL_CHAR) { /* terminal state */ n = ((unsigned int)lextable[ah->lextable_pos] << 8) | lextable[ah->lextable_pos + 1]; lwsl_parser("known hdr %d\n", n); for (m = 0; m < LWS_ARRAY_SIZE(methods); m++) if (n == methods[m] && ah->frag_index[methods[m]]) { lwsl_warn("Duplicated method\n"); return LPR_FAIL; } /* * WSORIGIN is protocol equiv to ORIGIN, * JWebSocket likes to send it, map to ORIGIN */ if (n == WSI_TOKEN_SWORIGIN) n = WSI_TOKEN_ORIGIN; ah->parser_state = (enum lws_token_indexes) (WSI_TOKEN_GET_URI + n); ah->ups = URIPS_IDLE; if (context->token_limits) ah->current_token_limit = context-> token_limits->token_limit[ ah->parser_state]; else ah->current_token_limit = wsi->context->max_http_header_data; if (ah->parser_state == WSI_TOKEN_CHALLENGE) goto set_parsing_complete; goto start_fragment; } break; #if defined(LWS_WITH_CUSTOM_HEADERS) unknown_hdr: //ah->parser_state = WSI_TOKEN_SKIPPING; //break; break; #endif start_fragment: ah->nfrag++; excessive: if (ah->nfrag == LWS_ARRAY_SIZE(ah->frags)) { lwsl_warn("More hdr frags than we can deal with\n"); return LPR_FAIL; } ah->frags[ah->nfrag].offset = ah->pos; ah->frags[ah->nfrag].len = 0; ah->frags[ah->nfrag].nfrag = 0; ah->frags[ah->nfrag].flags = 2; n = ah->frag_index[ah->parser_state]; if (!n) { /* first fragment */ ah->frag_index[ah->parser_state] = ah->nfrag; ah->hdr_token_idx = ah->parser_state; break; } /* continuation */ while (ah->frags[n].nfrag) n = ah->frags[n].nfrag; ah->frags[n].nfrag = ah->nfrag; if (issue_char(wsi, ' ') < 0) return LPR_FAIL; break; /* skipping arg part of a name we didn't recognize */ case WSI_TOKEN_SKIPPING: lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c); if (c == '\x0d') ah->parser_state = WSI_TOKEN_SKIPPING_SAW_CR; break; case WSI_TOKEN_SKIPPING_SAW_CR: lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c); if (ah->ues != URIES_IDLE) goto forbid; if (c == '\x0a') { ah->parser_state = WSI_TOKEN_NAME_PART; #if defined(LWS_WITH_CUSTOM_HEADERS) ah->unk_pos = 0; #endif ah->lextable_pos = 0; } else ah->parser_state = WSI_TOKEN_SKIPPING; break; /* we're done, ignore anything else */ case WSI_PARSING_COMPLETE: lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c); break; } } while (*len); return LPR_OK; set_parsing_complete: if (ah->ues != URIES_IDLE) goto forbid; if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) { if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION)) wsi->rx_frame_type = /* temp for ws version index */ atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION)); lwsl_parser("v%02d hdrs done\n", wsi->rx_frame_type); } ah->parser_state = WSI_PARSING_COMPLETE; wsi->hdr_parsing_completed = 1; return LPR_OK; forbid: lwsl_notice(" forbidding on uri sanitation\n"); #if defined(LWS_WITH_SERVER) lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL); #endif return LPR_FORBIDDEN; }
380154.c
/** ***************************************************************************************** * Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved. ***************************************************************************************** * @file datatrans_server.c * @brief Source file for data transmission server * @details * @author hector_huang * @date 2018-10-31 * @version v1.0 * ************************************************************************************* */ #define MM_ID MM_SERVICE #include "platform_misc.h" #include "platform_diagnose.h" #include "gap.h" #include "profile_server.h" #include "datatrans_service.h" #include "datatrans_server.h" /** application callback function */ static P_FUN_SERVER_GENERAL_CB datatrans_cb = NULL; /** @brief Index of each characteristic in service database. */ #define DATATRANS_DATA_IN_INDEX 0x02 #define DATATRANS_DATA_OUT_INDEX 0x04 #define DATATRANS_DATA_OUT_CCCD_INDEX (DATATRANS_DATA_OUT_INDEX + 1) /******************************************************************************************************** * local static variables defined here, only used in this source file. ********************************************************************************************************/ uint8_t datatrans_server_id = SERVICE_PROFILE_GENERAL_ID; //static uint8_t datatrans_data_out_cccd = GATT_CLIENT_CHAR_CONFIG_DEFAULT; /** @brief profile/service definition. */ const T_ATTRIB_APPL datatrans_server_table[] = { /* <<Primary Service>>, Data transmission service */ { (ATTRIB_FLAG_VOID | ATTRIB_FLAG_LE), /* wFlags */ { /* bTypeValue */ LO_WORD(GATT_UUID_PRIMARY_SERVICE), HI_WORD(GATT_UUID_PRIMARY_SERVICE), }, UUID_128BIT_SIZE, /* bValueLen */ (void *)GATT_UUID_DATATRANS_SERVICE, /* pValueContext */ GATT_PERM_READ /* wPermissions */ }, /* <<Characteristic>>, Data transmission in */ { ATTRIB_FLAG_VALUE_INCL, /* wFlags */ { /* bTypeValue */ LO_WORD(GATT_UUID_CHARACTERISTIC), HI_WORD(GATT_UUID_CHARACTERISTIC), GATT_CHAR_PROP_WRITE_NO_RSP /* characteristic properties */ /* characteristic UUID not needed here, is UUID of next attrib. */ }, 1, /* bValueLen */ NULL, GATT_PERM_READ /* wPermissions */ }, /* Data transmission data value */ { ATTRIB_FLAG_VALUE_APPL, /* wFlags */ { /* bTypeValue */ LO_WORD(DATATRANS_DATA_IN_UUID), HI_WORD(DATATRANS_DATA_IN_UUID) }, 0, /* bValueLen, 0 : variable length */ NULL, GATT_PERM_WRITE /* wPermissions */ }, /* <<Characteristic>>, Data transmission out */ { ATTRIB_FLAG_VALUE_INCL, /* wFlags */ { /* bTypeValue */ LO_WORD(GATT_UUID_CHARACTERISTIC), HI_WORD(GATT_UUID_CHARACTERISTIC), GATT_CHAR_PROP_NOTIFY | GATT_CHAR_PROP_READ /* characteristic properties */ /* characteristic UUID not needed here, is UUID of next attrib. */ }, 1, /* bValueLen */ NULL, GATT_PERM_READ /* wPermissions */ }, /* Data transmission data value */ { ATTRIB_FLAG_VALUE_APPL, /* wFlags */ { /* bTypeValue */ LO_WORD(DATATRANS_DATA_OUT_UUID), HI_WORD(DATATRANS_DATA_OUT_UUID) }, 0, /* bValueLen, 0 : variable length */ NULL, GATT_PERM_READ /* wPermissions */ }, /* Client characteristic configuration */ { (ATTRIB_FLAG_VALUE_INCL | /* wFlags */ ATTRIB_FLAG_CCCD_APPL), { /* bTypeValue */ LO_WORD(GATT_UUID_CHAR_CLIENT_CONFIG), HI_WORD(GATT_UUID_CHAR_CLIENT_CONFIG), /* NOTE: this value has an instantiation for each client, a write to */ /* this attribute does not modify this default value: */ LO_WORD(GATT_CLIENT_CHAR_CONFIG_DEFAULT), /* client char. config. bit field */ HI_WORD(GATT_CLIENT_CHAR_CONFIG_DEFAULT) }, 2, /* bValueLen */ NULL, (GATT_PERM_READ | GATT_PERM_WRITE) /* wPermissions */ } }; /** * @brief data transmission server read data callback function * @param conn_id[in]: connection link id * @param service_id[in]: service id to be read * @param attrib_index[in]: attribute index in service * @param offset[in]: value read offset from pp_value * @param p_length[out]: output value length * @param pp_value[out]: output value pointer * @return status */ static T_APP_RESULT datatrans_server_read_cb(uint8_t conn_id, T_SERVER_ID service_id, uint16_t attrib_index, uint16_t offset, uint16_t *p_length, uint8_t **pp_value) { T_APP_RESULT ret = APP_RESULT_SUCCESS; switch (attrib_index) { case DATATRANS_DATA_OUT_INDEX: if (NULL != datatrans_cb) { /** get data from specified app */ datatrans_server_data_t cb_data; cb_data.type = SERVICE_CALLBACK_TYPE_READ_CHAR_VALUE; datatrans_cb(service_id, &cb_data); *p_length = cb_data.len; *pp_value = cb_data.data; } break; default: printe("datatrans_server_read_cb: attribute not fount, index %d", attrib_index); ret = APP_RESULT_ATTR_NOT_FOUND; break; } return ret; } /** * @brief data transmission server write data callback function * @param conn_id[in]: connection link id * @param service_id[in]: serivce id to be write to * @param attrib_index[in]: attribute index in service * @param wtire_type[in]: wtite type * @param len[in]: data length * @param pvalue[in]: data value * @param ppost_proc[in]: write done callback * @return status */ static T_APP_RESULT datatrans_server_write_cb(uint8_t conn_id, T_SERVER_ID service_id, uint16_t attrib_index, T_WRITE_TYPE write_type, uint16_t len, uint8_t *pvalue, P_FUN_WRITE_IND_POST_PROC *ppost_proc) { T_APP_RESULT ret = APP_RESULT_SUCCESS; switch (attrib_index) { case DATATRANS_DATA_IN_INDEX: if (NULL != datatrans_cb) { /** write data to specified app */ datatrans_server_data_t cb_data; cb_data.type = SERVICE_CALLBACK_TYPE_WRITE_CHAR_VALUE; cb_data.len = len; cb_data.data = pvalue; datatrans_cb(service_id, &cb_data); } break; default: printe("datatrans_server_write_cb: attribute not fount, index %d", attrib_index); ret = APP_RESULT_ATTR_NOT_FOUND; break; } return ret; } bool datatrans_server_notify(uint8_t conn_id, uint8_t *pvalue, uint16_t len) { return server_send_data(conn_id, datatrans_server_id, DATATRANS_DATA_OUT_INDEX, pvalue, len, GATT_PDU_TYPE_NOTIFICATION); } /** * @brief update cccd bits from stack. * @param conn_id[in]: connection link id * @param server_id[in]: service id * @param attrib_index[in]: attribute index of characteristic data * @param cccd_bits[in]: cccd bits from stack. */ static void datatrans_server_cccd_update_cb(uint8_t conn_id, T_SERVER_ID server_id, uint16_t attrib_index, uint16_t cccd_bits) { printi("datatrans_server_cccd_update_cb: index = %d, cccd_bits = 0x%x", attrib_index, cccd_bits); switch (attrib_index) { case DATATRANS_DATA_OUT_CCCD_INDEX: { if (cccd_bits & GATT_CLIENT_CHAR_CONFIG_NOTIFY) { /** enable notification */ //datatrans_data_out_cccd = GATT_CLIENT_CHAR_CONFIG_NOTIFY; } else { /** disable Notification */ //datatrans_data_out_cccd = GATT_CLIENT_CHAR_CONFIG_DEFAULT; } } break; default: break; } } /** * @brief service callbacks. */ const T_FUN_GATT_SERVICE_CBS datatrans_server_cbs = { .read_attr_cb = datatrans_server_read_cb, /** read callback function pointer */ .write_attr_cb = datatrans_server_write_cb, /** write callback function pointer */ .cccd_update_cb = datatrans_server_cccd_update_cb /** cccd update callback function pointer */ }; uint8_t datatrans_server_add(void *pcb) { uint8_t server_id; if (FALSE == server_add_service(&server_id, (uint8_t *)datatrans_server_table, sizeof(datatrans_server_table), datatrans_server_cbs)) { printe("datatrans_server_add: add service id(%d) failed!", datatrans_server_id); server_id = SERVICE_PROFILE_GENERAL_ID; return server_id; } datatrans_server_id = server_id; datatrans_cb = (P_FUN_SERVER_GENERAL_CB)pcb; return datatrans_server_id; }
609585.c
//#include "stddefs.h" #include <stdint.h> #include "murax.h" #include "main.h" #define DEBUG 0 uint32_t gcd(uint32_t a, uint32_t b){ GCD->A = a; GCD->B = b; GCD->VALID = 0x00000001; uint32_t rdyFlag = 0; do{ rdyFlag = GCD->READY; }while(!rdyFlag); return GCD->RES; } void calcPrintGCD(uint32_t a, uint32_t b){ uint32_t myGCD = 0; char buf[5] = { 0x00 }; char aBuf[11] = { 0x00 }; char bBuf[11] = { 0x00 }; itoa(a, aBuf, 10); itoa(b, bBuf, 10); print("gcd(");print(aBuf);print(",");print(bBuf);println("):"); myGCD = gcd(a,b); itoa(myGCD, buf, 10); println(buf); } void main() { GPIO_A->OUTPUT_ENABLE = 0x0000000F; GPIO_A->OUTPUT = 0x00000001; println("hello gcd world"); const int nleds = 4; const int nloops = 2000000; GCD->VALID = 0x00000000; while(GCD->READY); calcPrintGCD(1, 123913); calcPrintGCD(461952, 116298); calcPrintGCD(461952, 116298); calcPrintGCD(461952, 116298); while(1){ for(unsigned int i=0;i<nleds-1;i++){ GPIO_A->OUTPUT = 1<<i; delay(nloops); } for(unsigned int i=0;i<nleds-1;i++){ GPIO_A->OUTPUT = (1<<(nleds-1))>>i; delay(nloops); } } } void irqCallback(){ }