ASM Long
Collection
Neural Long Context Assembly Transpilation
•
19 items
•
Updated
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(©_path, ©_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 */
|