text
stringlengths 2
100k
| meta
dict |
---|---|
// (C) Copyright Edward Diener 2011-2015
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#if !defined(BOOST_VMD_DETAIL_EQUAL_9_HPP)
#define BOOST_VMD_DETAIL_EQUAL_9_HPP
#include <boost/vmd/detail/recurse/equal/equal_headers.hpp>
#define BOOST_VMD_DETAIL_EQUAL_9_CNI_CHK(vseq1,vseq2,vtype) \
BOOST_PP_IIF \
( \
BOOST_PP_BITOR \
( \
BOOST_PP_BITOR \
( \
BOOST_VMD_DETAIL_EQUAL_TYPE(vtype,BOOST_VMD_TYPE_ARRAY), \
BOOST_VMD_DETAIL_EQUAL_TYPE(vtype,BOOST_VMD_TYPE_LIST) \
), \
BOOST_PP_BITOR \
( \
BOOST_VMD_DETAIL_EQUAL_TYPE(vtype,BOOST_VMD_TYPE_SEQ), \
BOOST_VMD_DETAIL_EQUAL_TYPE(vtype,BOOST_VMD_TYPE_TUPLE) \
) \
), \
BOOST_VMD_DETAIL_DATA_EQUAL_9, \
BOOST_VMD_DETAIL_EQUAL_CNI_SMP \
) \
(vseq1,vseq2,vtype) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_CNI_CHK_D(d,vseq1,vseq2,vtype) \
BOOST_PP_IIF \
( \
BOOST_PP_BITOR \
( \
BOOST_PP_BITOR \
( \
BOOST_VMD_DETAIL_EQUAL_TYPE_D(d,vtype,BOOST_VMD_TYPE_ARRAY), \
BOOST_VMD_DETAIL_EQUAL_TYPE_D(d,vtype,BOOST_VMD_TYPE_LIST) \
), \
BOOST_PP_BITOR \
( \
BOOST_VMD_DETAIL_EQUAL_TYPE_D(d,vtype,BOOST_VMD_TYPE_SEQ), \
BOOST_VMD_DETAIL_EQUAL_TYPE_D(d,vtype,BOOST_VMD_TYPE_TUPLE) \
) \
), \
BOOST_VMD_DETAIL_DATA_EQUAL_9_D, \
BOOST_VMD_DETAIL_EQUAL_CNI_SMP_D \
) \
(d,vseq1,vseq2,vtype) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_VSEQ(vseq1,vseq2,vtype) \
BOOST_VMD_DETAIL_DATA_EQUAL_9 \
( \
BOOST_VMD_TO_SEQ(vseq1), \
BOOST_VMD_TO_SEQ(vseq2), \
BOOST_VMD_TYPE_SEQ \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_VSEQ_D(d,vseq1,vseq2,vtype) \
BOOST_VMD_DETAIL_DATA_EQUAL_9_D \
( \
d, \
BOOST_VMD_TO_SEQ_D(d,vseq1), \
BOOST_VMD_TO_SEQ_D(d,vseq2), \
BOOST_VMD_TYPE_SEQ \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_CNI(vseq1,vseq2,vtype) \
BOOST_PP_IIF \
( \
BOOST_VMD_DETAIL_EQUAL_TYPE \
( \
vtype, \
BOOST_VMD_TYPE_SEQUENCE \
), \
BOOST_VMD_DETAIL_EQUAL_9_VSEQ, \
BOOST_VMD_DETAIL_EQUAL_9_CNI_CHK \
) \
(vseq1,vseq2,vtype) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_CNI_D(d,vseq1,vseq2,vtype) \
BOOST_PP_IIF \
( \
BOOST_VMD_DETAIL_EQUAL_TYPE_D \
( \
d, \
vtype, \
BOOST_VMD_TYPE_SEQUENCE \
), \
BOOST_VMD_DETAIL_EQUAL_9_VSEQ_D, \
BOOST_VMD_DETAIL_EQUAL_9_CNI_CHK_D \
) \
(d,vseq1,vseq2,vtype) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_WT_CHECK(vseq1,vseq2,vtype1,vtype2) \
BOOST_VMD_IDENTITY_RESULT \
( \
BOOST_PP_IIF \
( \
BOOST_VMD_DETAIL_EQUAL_TYPE \
( \
vtype1, \
vtype2 \
), \
BOOST_VMD_DETAIL_EQUAL_9_CNI, \
BOOST_VMD_IDENTITY(0) \
) \
(vseq1,vseq2,vtype1) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_WT_CHECK_D(d,vseq1,vseq2,vtype1,vtype2) \
BOOST_VMD_IDENTITY_RESULT \
( \
BOOST_PP_IIF \
( \
BOOST_VMD_DETAIL_EQUAL_TYPE_D \
( \
d, \
vtype1, \
vtype2 \
), \
BOOST_VMD_DETAIL_EQUAL_9_CNI_D, \
BOOST_VMD_IDENTITY(0) \
) \
(d,vseq1,vseq2,vtype1) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_WT_CONVERT(vseq1,vseq2,vtype1,vtype2) \
BOOST_VMD_DETAIL_EQUAL_9_WT_CHECK \
( \
vseq1, \
vseq2, \
BOOST_VMD_DETAIL_ADJUST_TUPLE_TYPE(vseq1,vtype1), \
BOOST_VMD_DETAIL_ADJUST_TUPLE_TYPE(vseq2,vtype2) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_WT_CONVERT_D(d,vseq1,vseq2,vtype1,vtype2) \
BOOST_VMD_DETAIL_EQUAL_9_WT_CHECK_D \
( \
d, \
vseq1, \
vseq2, \
BOOST_VMD_DETAIL_ADJUST_TUPLE_TYPE_D(d,vseq1,vtype1), \
BOOST_VMD_DETAIL_ADJUST_TUPLE_TYPE_D(d,vseq2,vtype2) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_WT(vseq1,vseq2,vtype1,vtype2) \
BOOST_VMD_IDENTITY_RESULT \
( \
BOOST_PP_IIF \
( \
BOOST_VMD_DETAIL_EQUAL_IS_TUPLE_MISMATCH(vseq1,vseq2,vtype1,vtype2), \
BOOST_VMD_IDENTITY(0), \
BOOST_VMD_DETAIL_EQUAL_9_WT_CONVERT \
) \
(vseq1,vseq2,vtype1,vtype2) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_WT_D(d,vseq1,vseq2,vtype1,vtype2) \
BOOST_VMD_IDENTITY_RESULT \
( \
BOOST_PP_IIF \
( \
BOOST_VMD_DETAIL_EQUAL_IS_TUPLE_MISMATCH_D(d,vseq1,vseq2,vtype1,vtype2), \
BOOST_VMD_IDENTITY(0), \
BOOST_VMD_DETAIL_EQUAL_9_WT_CONVERT_D \
) \
(d,vseq1,vseq2,vtype1,vtype2) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_GTYPE(vseq1,vseq2) \
BOOST_VMD_DETAIL_EQUAL_9_WT \
( \
vseq1, \
vseq2, \
BOOST_VMD_GET_TYPE(vseq1,BOOST_VMD_RETURN_TYPE_TUPLE), \
BOOST_VMD_GET_TYPE(vseq2,BOOST_VMD_RETURN_TYPE_TUPLE) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_GTYPE_D(d,vseq1,vseq2) \
BOOST_VMD_DETAIL_EQUAL_9_WT_D \
( \
d, \
vseq1, \
vseq2, \
BOOST_VMD_GET_TYPE_D(d,vseq1,BOOST_VMD_RETURN_TYPE_TUPLE), \
BOOST_VMD_GET_TYPE_D(d,vseq2,BOOST_VMD_RETURN_TYPE_TUPLE) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_EBP(vseq1,vseq2,be1,be2) \
BOOST_VMD_IDENTITY_RESULT \
( \
BOOST_PP_IIF \
( \
BOOST_PP_BITAND \
( \
BOOST_VMD_DETAIL_EQUAL_CHK_MATCH(be1,be2), \
BOOST_VMD_DETAIL_EQUAL_CHK_PARENS_MATCH(vseq1,vseq2) \
), \
BOOST_VMD_DETAIL_EQUAL_9_GTYPE, \
BOOST_VMD_IDENTITY(0) \
) \
(vseq1,vseq2) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_EBP_D(d,vseq1,vseq2,be1,be2) \
BOOST_VMD_IDENTITY_RESULT \
( \
BOOST_PP_IIF \
( \
BOOST_PP_BITAND \
( \
BOOST_VMD_DETAIL_EQUAL_CHK_MATCH(be1,be2), \
BOOST_VMD_DETAIL_EQUAL_CHK_PARENS_MATCH(vseq1,vseq2) \
), \
BOOST_VMD_DETAIL_EQUAL_9_GTYPE_D, \
BOOST_VMD_IDENTITY(0) \
) \
(d,vseq1,vseq2) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_EMPTY(vseq1,vseq2,be1,be2) \
BOOST_PP_IIF \
( \
BOOST_PP_BITAND(be1,be2), \
BOOST_VMD_DETAIL_EQUAL_BOTH_EMPTY, \
BOOST_VMD_DETAIL_EQUAL_9_EBP \
) \
(vseq1,vseq2,be1,be2) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_EMPTY_D(d,vseq1,vseq2,be1,be2) \
BOOST_PP_IIF \
( \
BOOST_PP_BITAND(be1,be2), \
BOOST_VMD_DETAIL_EQUAL_BOTH_EMPTY, \
BOOST_VMD_DETAIL_EQUAL_9_EBP_D \
) \
(d,vseq1,vseq2,be1,be2) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9(vseq1,vseq2) \
BOOST_VMD_DETAIL_EQUAL_9_EMPTY \
( \
vseq1, \
vseq2, \
BOOST_VMD_IS_EMPTY(vseq1), \
BOOST_VMD_IS_EMPTY(vseq2) \
) \
/**/
#define BOOST_VMD_DETAIL_EQUAL_9_D(d,vseq1,vseq2) \
BOOST_VMD_DETAIL_EQUAL_9_EMPTY_D \
( \
d, \
vseq1, \
vseq2, \
BOOST_VMD_IS_EMPTY(vseq1), \
BOOST_VMD_IS_EMPTY(vseq2) \
) \
/**/
#endif /* BOOST_VMD_DETAIL_EQUAL_9_HPP */
| {
"language": "C"
} |
#ifndef WXCUSTOMCONTROLS_HPP
#define WXCUSTOMCONTROLS_HPP
#ifdef __WXGTK__
// GTK2 & 3
#define wxUSE_NATIVE_CHOICE 1
#define wxUSE_NATIVE_BUTTON 1
#define wxUSE_NATIVE_SCROLLBAR 0
#elif defined(__WXOSX__)
// macOS
#define wxUSE_NATIVE_CHOICE 1
#define wxUSE_NATIVE_BUTTON 1
#define wxUSE_NATIVE_SCROLLBAR 1
#else
// Windows
#define wxUSE_NATIVE_CHOICE 0
#define wxUSE_NATIVE_BUTTON 0
#define wxUSE_NATIVE_SCROLLBAR 1
#endif
#endif // WXCUSTOMCONTROLS_HPP
| {
"language": "C"
} |
/*
* gcinode.c - dummy inodes to buffer blocks for garbage collection
*
* Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by Seiji Kihara <kihara@osrg.net>, Amagai Yoshiji <amagai@osrg.net>,
* and Ryusuke Konishi <ryusuke@osrg.net>.
* Revised by Ryusuke Konishi <ryusuke@osrg.net>.
*
*/
/*
* This file adds the cache of on-disk blocks to be moved in garbage
* collection. The disk blocks are held with dummy inodes (called
* gcinodes), and this file provides lookup function of the dummy
* inodes and their buffer read function.
*
* Buffers and pages held by the dummy inodes will be released each
* time after they are copied to a new log. Dirty blocks made on the
* current generation and the blocks to be moved by GC never overlap
* because the dirty blocks make a new generation; they rather must be
* written individually.
*/
#include <linux/buffer_head.h>
#include <linux/mpage.h>
#include <linux/hash.h>
#include <linux/slab.h>
#include <linux/swap.h>
#include "nilfs.h"
#include "btree.h"
#include "btnode.h"
#include "page.h"
#include "mdt.h"
#include "dat.h"
#include "ifile.h"
/*
* nilfs_gccache_submit_read_data() - add data buffer and submit read request
* @inode - gc inode
* @blkoff - dummy offset treated as the key for the page cache
* @pbn - physical block number of the block
* @vbn - virtual block number of the block, 0 for non-virtual block
* @out_bh - indirect pointer to a buffer_head struct to receive the results
*
* Description: nilfs_gccache_submit_read_data() registers the data buffer
* specified by @pbn to the GC pagecache with the key @blkoff.
* This function sets @vbn (@pbn if @vbn is zero) in b_blocknr of the buffer.
*
* Return Value: On success, 0 is returned. On Error, one of the following
* negative error code is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-ENOENT - The block specified with @pbn does not exist.
*/
int nilfs_gccache_submit_read_data(struct inode *inode, sector_t blkoff,
sector_t pbn, __u64 vbn,
struct buffer_head **out_bh)
{
struct buffer_head *bh;
int err;
bh = nilfs_grab_buffer(inode, inode->i_mapping, blkoff, 0);
if (unlikely(!bh))
return -ENOMEM;
if (buffer_uptodate(bh))
goto out;
if (pbn == 0) {
struct the_nilfs *nilfs = inode->i_sb->s_fs_info;
err = nilfs_dat_translate(nilfs->ns_dat, vbn, &pbn);
if (unlikely(err)) { /* -EIO, -ENOMEM, -ENOENT */
brelse(bh);
goto failed;
}
}
lock_buffer(bh);
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
goto out;
}
if (!buffer_mapped(bh)) {
bh->b_bdev = inode->i_sb->s_bdev;
set_buffer_mapped(bh);
}
bh->b_blocknr = pbn;
bh->b_end_io = end_buffer_read_sync;
get_bh(bh);
submit_bh(READ, bh);
if (vbn)
bh->b_blocknr = vbn;
out:
err = 0;
*out_bh = bh;
failed:
unlock_page(bh->b_page);
page_cache_release(bh->b_page);
return err;
}
/*
* nilfs_gccache_submit_read_node() - add node buffer and submit read request
* @inode - gc inode
* @pbn - physical block number for the block
* @vbn - virtual block number for the block
* @out_bh - indirect pointer to a buffer_head struct to receive the results
*
* Description: nilfs_gccache_submit_read_node() registers the node buffer
* specified by @vbn to the GC pagecache. @pbn can be supplied by the
* caller to avoid translation of the disk block address.
*
* Return Value: On success, 0 is returned. On Error, one of the following
* negative error code is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*/
int nilfs_gccache_submit_read_node(struct inode *inode, sector_t pbn,
__u64 vbn, struct buffer_head **out_bh)
{
int ret;
ret = nilfs_btnode_submit_block(&NILFS_I(inode)->i_btnode_cache,
vbn ? : pbn, pbn, READ, out_bh, &pbn);
if (ret == -EEXIST) /* internal code (cache hit) */
ret = 0;
return ret;
}
int nilfs_gccache_wait_and_mark_dirty(struct buffer_head *bh)
{
wait_on_buffer(bh);
if (!buffer_uptodate(bh))
return -EIO;
if (buffer_dirty(bh))
return -EEXIST;
if (buffer_nilfs_node(bh) && nilfs_btree_broken_node_block(bh)) {
clear_buffer_uptodate(bh);
return -EIO;
}
mark_buffer_dirty(bh);
return 0;
}
int nilfs_init_gcinode(struct inode *inode)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
inode->i_mode = S_IFREG;
mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
inode->i_mapping->a_ops = &empty_aops;
inode->i_mapping->backing_dev_info = inode->i_sb->s_bdi;
ii->i_flags = 0;
nilfs_bmap_init_gc(ii->i_bmap);
return 0;
}
/**
* nilfs_remove_all_gcinodes() - remove all unprocessed gc inodes
*/
void nilfs_remove_all_gcinodes(struct the_nilfs *nilfs)
{
struct list_head *head = &nilfs->ns_gc_inodes;
struct nilfs_inode_info *ii;
while (!list_empty(head)) {
ii = list_first_entry(head, struct nilfs_inode_info, i_dirty);
list_del_init(&ii->i_dirty);
truncate_inode_pages(&ii->vfs_inode.i_data, 0);
nilfs_btnode_cache_clear(&ii->i_btnode_cache);
iput(&ii->vfs_inode);
}
}
| {
"language": "C"
} |
/*
* crc32.c - simple CRC32 code
*
* This file is part of the SSH Library
*
* Copyright (c) 2005 by Aris Adamantiadis
*
* The SSH 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.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include "libssh/priv.h"
#include "libssh/crc32.h"
static uint32_t crc_table[] = {
0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
0x2d02ef8dUL
};
uint32_t ssh_crc32(const char *buf, uint32_t len) {
uint32_t ret = 0;
while(len > 0) {
ret = crc_table[(ret ^ *buf) & 0xff] ^ (ret >> 8);
--len;
++buf;
}
return ret;
}
/* vim: set ts=2 sw=2 et cindent: */
| {
"language": "C"
} |
/*
* Copyright (c) 1997, 1998, 1999, 2000
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Computer Systems
* Engineering Group at Lawrence Berkeley Laboratory.
* 4. Neither the name of the University nor of the Laboratory 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.
*/
#ifndef lint
static const char rcsid[] =
"@(#) $Id: ifaddrlist.c,v 1.9 2000/11/23 20:01:55 leres Exp $ (LBL)";
#endif
#include <sys/param.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#ifdef HAVE_SYS_SOCKIO_H
#include <sys/sockio.h>
#endif
#include <sys/time.h> /* concession to AIX */
#if __STDC__
struct mbuf;
struct rtentry;
#endif
#include <net/if.h>
#include <netinet/in.h>
#include <ctype.h>
#include <errno.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "ifaddrlist.h"
/*
* Return the interface list
*/
int
ifaddrlist(register struct ifaddrlist **ipaddrp, register char *errbuf)
{
register int fd, nipaddr;
#ifdef HAVE_SOCKADDR_SA_LEN
size_t n;
#endif
register struct ifreq *ifrp, *ifend, *ifnext, *mp;
register struct sockaddr_in *sin;
register struct ifaddrlist *al;
struct ifconf ifc;
struct ifreq ibuf[(32 * 1024) / sizeof(struct ifreq)], ifr;
#define MAX_IPADDR ((int)(sizeof(ibuf) / sizeof(ibuf[0])))
static struct ifaddrlist ifaddrlist[MAX_IPADDR];
char device[sizeof(ifr.ifr_name) + 1];
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
(void)sprintf(errbuf, "socket: %s", strerror(errno));
return (-1);
}
ifc.ifc_len = sizeof(ibuf);
ifc.ifc_buf = (caddr_t)ibuf;
if (ioctl(fd, SIOCGIFCONF, (char *)&ifc) < 0 ||
ifc.ifc_len < (int)sizeof(struct ifreq)) {
if (errno == EINVAL)
(void)sprintf(errbuf,
"SIOCGIFCONF: ifreq struct too small (%zu bytes)",
sizeof(ibuf));
else
(void)sprintf(errbuf, "SIOCGIFCONF: %s",
strerror(errno));
(void)close(fd);
return (-1);
}
ifrp = ibuf;
ifend = (struct ifreq *)((char *)ibuf + ifc.ifc_len);
al = ifaddrlist;
mp = NULL;
nipaddr = 0;
for (; ifrp < ifend; ifrp = ifnext) {
#ifdef HAVE_SOCKADDR_SA_LEN
n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
if (n < sizeof(*ifrp))
ifnext = ifrp + 1;
else
ifnext = (struct ifreq *)((char *)ifrp + n);
if (ifrp->ifr_addr.sa_family != AF_INET)
continue;
#else
ifnext = ifrp + 1;
#endif
/*
* Need a template to preserve address info that is
* used below to locate the next entry. (Otherwise,
* SIOCGIFFLAGS stomps over it because the requests
* are returned in a union.)
*/
strncpy(ifr.ifr_name, ifrp->ifr_name, sizeof(ifr.ifr_name));
if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
if (errno == ENXIO)
continue;
(void)sprintf(errbuf, "SIOCGIFFLAGS: %.*s: %s",
(int)sizeof(ifr.ifr_name), ifr.ifr_name,
strerror(errno));
(void)close(fd);
return (-1);
}
/* Must be up */
if ((ifr.ifr_flags & IFF_UP) == 0)
continue;
(void)strncpy(device, ifr.ifr_name, sizeof(ifr.ifr_name));
device[sizeof(device) - 1] = '\0';
#ifdef sun
/* Ignore sun virtual interfaces */
if (strchr(device, ':') != NULL)
continue;
#endif
if (ioctl(fd, SIOCGIFADDR, (char *)&ifr) < 0) {
(void)sprintf(errbuf, "SIOCGIFADDR: %s: %s",
device, strerror(errno));
(void)close(fd);
return (-1);
}
if (nipaddr >= MAX_IPADDR) {
(void)sprintf(errbuf, "Too many interfaces (%d)",
MAX_IPADDR);
(void)close(fd);
return (-1);
}
sin = (struct sockaddr_in *)&ifr.ifr_addr;
al->addr = sin->sin_addr.s_addr;
al->device = strdup(device);
++al;
++nipaddr;
}
(void)close(fd);
*ipaddrp = ifaddrlist;
return (nipaddr);
}
| {
"language": "C"
} |
/*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2001, 2002, 2004 Ralf Baechle
*/
#include <linux/init.h>
#include <linux/console.h>
#include <linux/kdev_t.h>
#include <linux/major.h>
#include <linux/termios.h>
#include <linux/sched.h>
#include <linux/tty.h>
#include <linux/serial.h>
#include <linux/serial_core.h>
#include <asm/serial.h>
#include <asm/io.h>
/* SUPERIO uart register map */
struct yo_uartregs {
union {
volatile u8 rbr; /* read only, DLAB == 0 */
volatile u8 thr; /* write only, DLAB == 0 */
volatile u8 dll; /* DLAB == 1 */
} u1;
union {
volatile u8 ier; /* DLAB == 0 */
volatile u8 dlm; /* DLAB == 1 */
} u2;
union {
volatile u8 iir; /* read only */
volatile u8 fcr; /* write only */
} u3;
volatile u8 iu_lcr;
volatile u8 iu_mcr;
volatile u8 iu_lsr;
volatile u8 iu_msr;
volatile u8 iu_scr;
} yo_uregs_t;
#define iu_rbr u1.rbr
#define iu_thr u1.thr
#define iu_dll u1.dll
#define iu_ier u2.ier
#define iu_dlm u2.dlm
#define iu_iir u3.iir
#define iu_fcr u3.fcr
#define ssnop() __asm__ __volatile__("sll $0, $0, 1\n");
#define ssnop_4() do { ssnop(); ssnop(); ssnop(); ssnop(); } while (0)
#define IO_BASE_64 0x9000000000000000ULL
static unsigned char readb_outer_space(unsigned long long phys)
{
unsigned long long vaddr = IO_BASE_64 | phys;
unsigned char res;
unsigned int sr;
sr = read_c0_status();
write_c0_status((sr | ST0_KX) & ~ ST0_IE);
ssnop_4();
__asm__ __volatile__ (
" .set mips3 \n"
" ld %0, %1 \n"
" lbu %0, (%0) \n"
" .set mips0 \n"
: "=r" (res)
: "m" (vaddr));
write_c0_status(sr);
ssnop_4();
return res;
}
static void writeb_outer_space(unsigned long long phys, unsigned char c)
{
unsigned long long vaddr = IO_BASE_64 | phys;
unsigned long tmp;
unsigned int sr;
sr = read_c0_status();
write_c0_status((sr | ST0_KX) & ~ ST0_IE);
ssnop_4();
__asm__ __volatile__ (
" .set mips3 \n"
" ld %0, %1 \n"
" sb %2, (%0) \n"
" .set mips0 \n"
: "=&r" (tmp)
: "m" (vaddr), "r" (c));
write_c0_status(sr);
ssnop_4();
}
void prom_putchar(char c)
{
unsigned long lsr = 0xfd000008ULL + offsetof(struct yo_uartregs, iu_lsr);
unsigned long thr = 0xfd000008ULL + offsetof(struct yo_uartregs, iu_thr);
while ((readb_outer_space(lsr) & 0x20) == 0);
writeb_outer_space(thr, c);
}
| {
"language": "C"
} |
/*************************************************************************
* GLFW 3.2 - www.glfw.org
* A library for OpenGL, window and input
*------------------------------------------------------------------------
* Copyright (c) 2002-2006 Marcus Geelnard
* Copyright (c) 2006-2016 Camilla Berglund <elmindreda@glfw.org>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*************************************************************************/
#ifndef _glfw3_native_h_
#define _glfw3_native_h_
#ifdef __cplusplus
extern "C" {
#endif
/*************************************************************************
* Doxygen documentation
*************************************************************************/
/*! @file glfw3native.h
* @brief The header of the native access functions.
*
* This is the header file of the native access functions. See @ref native for
* more information.
*/
/*! @defgroup native Native access
*
* **By using the native access functions you assert that you know what you're
* doing and how to fix problems caused by using them. If you don't, you
* shouldn't be using them.**
*
* Before the inclusion of @ref glfw3native.h, you may define exactly one
* window system API macro and zero or more context creation API macros.
*
* The chosen backends must match those the library was compiled for. Failure
* to do this will cause a link-time error.
*
* The available window API macros are:
* * `GLFW_EXPOSE_NATIVE_WIN32`
* * `GLFW_EXPOSE_NATIVE_COCOA`
* * `GLFW_EXPOSE_NATIVE_X11`
* * `GLFW_EXPOSE_NATIVE_WAYLAND`
* * `GLFW_EXPOSE_NATIVE_MIR`
*
* The available context API macros are:
* * `GLFW_EXPOSE_NATIVE_WGL`
* * `GLFW_EXPOSE_NATIVE_NSGL`
* * `GLFW_EXPOSE_NATIVE_GLX`
* * `GLFW_EXPOSE_NATIVE_EGL`
*
* These macros select which of the native access functions that are declared
* and which platform-specific headers to include. It is then up your (by
* definition platform-specific) code to handle which of these should be
* defined.
*/
/*************************************************************************
* System headers and types
*************************************************************************/
#if defined(GLFW_EXPOSE_NATIVE_WIN32)
// This is a workaround for the fact that glfw3.h needs to export APIENTRY (for
// example to allow applications to correctly declare a GL_ARB_debug_output
// callback) but windows.h assumes no one will define APIENTRY before it does
#undef APIENTRY
#include <windows.h>
#elif defined(GLFW_EXPOSE_NATIVE_COCOA)
#include <ApplicationServices/ApplicationServices.h>
#if defined(__OBJC__)
#import <Cocoa/Cocoa.h>
#else
typedef void* id;
#endif
#elif defined(GLFW_EXPOSE_NATIVE_X11)
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
#elif defined(GLFW_EXPOSE_NATIVE_WAYLAND)
#include <wayland-client.h>
#elif defined(GLFW_EXPOSE_NATIVE_MIR)
#include <mir_toolkit/mir_client_library.h>
#endif
#if defined(GLFW_EXPOSE_NATIVE_WGL)
/* WGL is declared by windows.h */
#endif
#if defined(GLFW_EXPOSE_NATIVE_NSGL)
/* NSGL is declared by Cocoa.h */
#endif
#if defined(GLFW_EXPOSE_NATIVE_GLX)
#include <GL/glx.h>
#endif
#if defined(GLFW_EXPOSE_NATIVE_EGL)
#include <EGL/egl.h>
#endif
/*************************************************************************
* Functions
*************************************************************************/
#if defined(GLFW_EXPOSE_NATIVE_WIN32)
/*! @brief Returns the adapter device name of the specified monitor.
*
* @return The UTF-8 encoded adapter device name (for example `\\.\DISPLAY1`)
* of the specified monitor, or `NULL` if an [error](@ref error_handling)
* occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI const char* glfwGetWin32Adapter(GLFWmonitor* monitor);
/*! @brief Returns the display device name of the specified monitor.
*
* @return The UTF-8 encoded display device name (for example
* `\\.\DISPLAY1\Monitor0`) of the specified monitor, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI const char* glfwGetWin32Monitor(GLFWmonitor* monitor);
/*! @brief Returns the `HWND` of the specified window.
*
* @return The `HWND` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI HWND glfwGetWin32Window(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_WGL)
/*! @brief Returns the `HGLRC` of the specified window.
*
* @return The `HGLRC` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI HGLRC glfwGetWGLContext(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_COCOA)
/*! @brief Returns the `CGDirectDisplayID` of the specified monitor.
*
* @return The `CGDirectDisplayID` of the specified monitor, or
* `kCGNullDirectDisplay` if an [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI CGDirectDisplayID glfwGetCocoaMonitor(GLFWmonitor* monitor);
/*! @brief Returns the `NSWindow` of the specified window.
*
* @return The `NSWindow` of the specified window, or `nil` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI id glfwGetCocoaWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_NSGL)
/*! @brief Returns the `NSOpenGLContext` of the specified window.
*
* @return The `NSOpenGLContext` of the specified window, or `nil` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI id glfwGetNSGLContext(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_X11)
/*! @brief Returns the `Display` used by GLFW.
*
* @return The `Display` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI Display* glfwGetX11Display(void);
/*! @brief Returns the `RRCrtc` of the specified monitor.
*
* @return The `RRCrtc` of the specified monitor, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI RRCrtc glfwGetX11Adapter(GLFWmonitor* monitor);
/*! @brief Returns the `RROutput` of the specified monitor.
*
* @return The `RROutput` of the specified monitor, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI RROutput glfwGetX11Monitor(GLFWmonitor* monitor);
/*! @brief Returns the `Window` of the specified window.
*
* @return The `Window` of the specified window, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI Window glfwGetX11Window(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_GLX)
/*! @brief Returns the `GLXContext` of the specified window.
*
* @return The `GLXContext` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI GLXContext glfwGetGLXContext(GLFWwindow* window);
/*! @brief Returns the `GLXWindow` of the specified window.
*
* @return The `GLXWindow` of the specified window, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI GLXWindow glfwGetGLXWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_WAYLAND)
/*! @brief Returns the `struct wl_display*` used by GLFW.
*
* @return The `struct wl_display*` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_display* glfwGetWaylandDisplay(void);
/*! @brief Returns the `struct wl_output*` of the specified monitor.
*
* @return The `struct wl_output*` of the specified monitor, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_output* glfwGetWaylandMonitor(GLFWmonitor* monitor);
/*! @brief Returns the main `struct wl_surface*` of the specified window.
*
* @return The main `struct wl_surface*` of the specified window, or `NULL` if
* an [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_surface* glfwGetWaylandWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_MIR)
/*! @brief Returns the `MirConnection*` used by GLFW.
*
* @return The `MirConnection*` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI MirConnection* glfwGetMirDisplay(void);
/*! @brief Returns the Mir output ID of the specified monitor.
*
* @return The Mir output ID of the specified monitor, or zero if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI int glfwGetMirMonitor(GLFWmonitor* monitor);
/*! @brief Returns the `MirSurface*` of the specified window.
*
* @return The `MirSurface*` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI MirSurface* glfwGetMirWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_EGL)
/*! @brief Returns the `EGLDisplay` used by GLFW.
*
* @return The `EGLDisplay` used by GLFW, or `EGL_NO_DISPLAY` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLDisplay glfwGetEGLDisplay(void);
/*! @brief Returns the `EGLContext` of the specified window.
*
* @return The `EGLContext` of the specified window, or `EGL_NO_CONTEXT` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLContext glfwGetEGLContext(GLFWwindow* window);
/*! @brief Returns the `EGLSurface` of the specified window.
*
* @return The `EGLSurface` of the specified window, or `EGL_NO_SURFACE` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLSurface glfwGetEGLSurface(GLFWwindow* window);
#endif
#ifdef __cplusplus
}
#endif
#endif /* _glfw3_native_h_ */
| {
"language": "C"
} |
/*
* This file was generated by mib2c and is intended for use as a mib module
* for the ucd-snmp snmpd agent.
*/
#ifndef _MIBGROUP_MTETRIGGERBOOLEANTABLE_H
#define _MIBGROUP_MTETRIGGERBOOLEANTABLE_H
/*
* we may use header_complex from the header_complex module
*/
config_require(header_complex)
/*
* enum definitions from the covered mib sections
*/
#define MTETRIGGERBOOLEANCOMPARISON_UNEQUAL 1
#define MTETRIGGERBOOLEANCOMPARISON_EQUAL 2
#define MTETRIGGERBOOLEANCOMPARISON_LESS 3
#define MTETRIGGERBOOLEANCOMPARISON_LESSOREQUAL 4
#define MTETRIGGERBOOLEANCOMPARISON_GREATER 5
#define MTETRIGGERBOOLEANCOMPARISON_GREATEROREQUAL 6
#define MTETRIGGERBOOLEANSTARTUP_TRUE 1
#define MTETRIGGERBOOLEANSTARTUP_FALSE 2
/*
* function prototypes
*/
void init_mteTriggerBooleanTable(void);
FindVarMethod var_mteTriggerBooleanTable;
WriteMethod write_mteTriggerBooleanComparison;
WriteMethod write_mteTriggerBooleanValue;
WriteMethod write_mteTriggerBooleanStartup;
WriteMethod write_mteTriggerBooleanObjectsOwner;
WriteMethod write_mteTriggerBooleanObjects;
WriteMethod write_mteTriggerBooleanEventOwner;
WriteMethod write_mteTriggerBooleanEvent;
#endif /* _MIBGROUP_MTETRIGGERBOOLEANTABLE_H */
| {
"language": "C"
} |
/*
* VTI CMA3000_D0x Accelerometer driver
*
* Copyright (C) 2010 Texas Instruments
* Author: Hemanth V <hemanthv@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _INPUT_CMA3000_H
#define _INPUT_CMA3000_H
#include <linux/types.h>
#include <linux/input.h>
struct device;
struct cma3000_accl_data;
struct cma3000_bus_ops {
u16 bustype;
u8 ctrl_mod;
int (*read)(struct device *, u8, char *);
int (*write)(struct device *, u8, u8, char *);
};
struct cma3000_accl_data *cma3000_init(struct device *dev, int irq,
const struct cma3000_bus_ops *bops);
void cma3000_exit(struct cma3000_accl_data *);
void cma3000_suspend(struct cma3000_accl_data *);
void cma3000_resume(struct cma3000_accl_data *);
#endif
| {
"language": "C"
} |
/*****
* util.h
* Andy Hammerlindl 2004/05/10
*
* A place for useful utility functions.
*****/
#ifndef UTIL_H
#define UTIL_H
#include <sys/types.h>
#include <iostream>
#include <cstdlib>
#ifdef __CYGWIN__
extern "C" int sigaddset(sigset_t *set, int signum);
extern "C" int sigemptyset(sigset_t *set);
extern "C" int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
#endif
#include <csignal>
#include "common.h"
#include <strings.h>
// Demangle a typeid name (if the proper library is installed.
string demangle(const char *s);
// Duplicate a string.
char *Strdup(string s);
char *StrdupNoGC(string s);
char *StrdupMalloc(string s);
// Strip the directory from a filename.
string stripDir(string name);
// Strip the file from a filename, returning the directory.
string stripFile(string name);
// Strip the extension from a filename.
string stripExt(string name, const string& suffix="");
void writeDisabled();
// Replace spaces in file part of name with underscores.
string cleanpath(string name);
// Construct the full output path.
string outpath(string name);
// Construct a filename from the original, adding aux at the end, and
// changing the suffix.
string buildname(string filename, string suffix="", string aux="");
// Construct an alternate filename for a temporary file in the current
// directory.
string auxname(string filename, string suffix="");
// Cast argument to a string.
template<class T>
string String(T x)
{
ostringstream buf;
buf << x;
return buf.str();
}
typedef void (*sighandler_t)(int);
// Portable signal (sigaction wrapper).
sighandler_t Signal(int signum, sighandler_t handler);
// Split string S and push the pieces onto vector a.
void push_split(mem::vector<string>& a, const string& S);
// Wrapper to append /c start "" to MSDOS cmd.
void push_command(mem::vector<string>& a, const string& s);
// Return an argv array corresponding to the fields in command delimited
// by spaces not within matching single quotes.
char **args(const mem::vector<string> &args, bool quiet=false);
// Similar to the standard system call except allows interrupts and does
// not invoke a shell.
int System(const mem::vector<string> &command, int quiet=0, bool wait=true,
const char *hint=NULL, const char *application="",
int *pid=NULL);
#if defined(__DECCXX_LIBCXX_RH70)
extern "C" char *strsignal(int sig);
extern "C" double asinh(double x);
extern "C" double acosh(double x);
extern "C" double atanh(double x);
extern "C" double cbrt(double x);
extern "C" double erf(double x);
extern "C" double erfc(double x);
extern "C" double lgamma(double x);
extern "C" double remainder(double x, double y);
extern "C" double hypot(double x, double y) throw();
extern "C" double jn(Int n, double x);
extern "C" double yn(Int n, double x);
extern "C" int isnan(double);
#endif
#if defined(__DECCXX_LIBCXX_RH70) || defined(__CYGWIN__)
extern "C" int usleep(useconds_t);
extern "C" int kill(pid_t pid, int sig) throw();
extern "C" int snprintf(char *str, size_t size, const char *format,...);
#include <stdio.h>
extern "C" FILE *fdopen(int fd, const char *mode);
extern "C" int fileno(FILE *);
extern "C" char *strptime(const char *s, const char *format, struct tm *tm);
extern "C" int setenv(const char *name, const char *value, int overwrite);
extern "C" int unsetenv(const char *name);
#endif
extern bool False;
// Strip blank lines (which would break the bidirectional TeX pipe)
string stripblanklines(const string& s);
const char *startPath();
const char* setPath(const char *s, bool quiet=false);
const char *changeDirectory(const char *s);
extern char *startpath;
void backslashToSlash(string& s);
void spaceToUnderscore(string& s);
string Getenv(const char *name, bool msdos);
char *getPath(char *p=NULL);
void execError(const char *command, const char *hint, const char *application);
// This invokes a viewer to display the manual. Subsequent calls will only
// pop-up a new viewer if the old one has been closed.
void popupHelp();
#ifdef __CYGWIN__
inline long long llabs(long long x) {return x >= 0 ? x : -x;}
extern "C" char *initstate (unsigned seed, char *state, size_t size);
extern "C" long random (void);
#endif
inline Int Abs(Int x) {
#ifdef HAVE_LONG_LONG
return llabs(x);
#else
#ifdef HAVE_LONG
return labs(x);
#else
return abs(x);
#endif
#endif
}
unsigned unsignedcast(Int n);
unsignedInt unsignedIntcast(Int n);
int intcast(Int n);
Int Intcast(unsignedInt n);
#endif
| {
"language": "C"
} |
/*
* Copyright (C) 2017 Broadcom
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation version 2.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/*
* Broadcom FlexRM Mailbox Driver
*
* Each Broadcom FlexSparx4 offload engine is implemented as an
* extension to Broadcom FlexRM ring manager. The FlexRM ring
* manager provides a set of rings which can be used to submit
* work to a FlexSparx4 offload engine.
*
* This driver creates a mailbox controller using a set of FlexRM
* rings where each mailbox channel represents a separate FlexRM ring.
*/
#include <asm/barrier.h>
#include <asm/byteorder.h>
#include <linux/atomic.h>
#include <linux/bitmap.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/mailbox_controller.h>
#include <linux/mailbox_client.h>
#include <linux/mailbox/brcm-message.h>
#include <linux/module.h>
#include <linux/msi.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
/* ====== FlexRM register defines ===== */
/* FlexRM configuration */
#define RING_REGS_SIZE 0x10000
#define RING_DESC_SIZE 8
#define RING_DESC_INDEX(offset) \
((offset) / RING_DESC_SIZE)
#define RING_DESC_OFFSET(index) \
((index) * RING_DESC_SIZE)
#define RING_MAX_REQ_COUNT 1024
#define RING_BD_ALIGN_ORDER 12
#define RING_BD_ALIGN_CHECK(addr) \
(!((addr) & ((0x1 << RING_BD_ALIGN_ORDER) - 1)))
#define RING_BD_TOGGLE_INVALID(offset) \
(((offset) >> RING_BD_ALIGN_ORDER) & 0x1)
#define RING_BD_TOGGLE_VALID(offset) \
(!RING_BD_TOGGLE_INVALID(offset))
#define RING_BD_DESC_PER_REQ 32
#define RING_BD_DESC_COUNT \
(RING_MAX_REQ_COUNT * RING_BD_DESC_PER_REQ)
#define RING_BD_SIZE \
(RING_BD_DESC_COUNT * RING_DESC_SIZE)
#define RING_CMPL_ALIGN_ORDER 13
#define RING_CMPL_DESC_COUNT RING_MAX_REQ_COUNT
#define RING_CMPL_SIZE \
(RING_CMPL_DESC_COUNT * RING_DESC_SIZE)
#define RING_VER_MAGIC 0x76303031
/* Per-Ring register offsets */
#define RING_VER 0x000
#define RING_BD_START_ADDR 0x004
#define RING_BD_READ_PTR 0x008
#define RING_BD_WRITE_PTR 0x00c
#define RING_BD_READ_PTR_DDR_LS 0x010
#define RING_BD_READ_PTR_DDR_MS 0x014
#define RING_CMPL_START_ADDR 0x018
#define RING_CMPL_WRITE_PTR 0x01c
#define RING_NUM_REQ_RECV_LS 0x020
#define RING_NUM_REQ_RECV_MS 0x024
#define RING_NUM_REQ_TRANS_LS 0x028
#define RING_NUM_REQ_TRANS_MS 0x02c
#define RING_NUM_REQ_OUTSTAND 0x030
#define RING_CONTROL 0x034
#define RING_FLUSH_DONE 0x038
#define RING_MSI_ADDR_LS 0x03c
#define RING_MSI_ADDR_MS 0x040
#define RING_MSI_CONTROL 0x048
#define RING_BD_READ_PTR_DDR_CONTROL 0x04c
#define RING_MSI_DATA_VALUE 0x064
/* Register RING_BD_START_ADDR fields */
#define BD_LAST_UPDATE_HW_SHIFT 28
#define BD_LAST_UPDATE_HW_MASK 0x1
#define BD_START_ADDR_VALUE(pa) \
((u32)((((dma_addr_t)(pa)) >> RING_BD_ALIGN_ORDER) & 0x0fffffff))
#define BD_START_ADDR_DECODE(val) \
((dma_addr_t)((val) & 0x0fffffff) << RING_BD_ALIGN_ORDER)
/* Register RING_CMPL_START_ADDR fields */
#define CMPL_START_ADDR_VALUE(pa) \
((u32)((((u64)(pa)) >> RING_CMPL_ALIGN_ORDER) & 0x07ffffff))
/* Register RING_CONTROL fields */
#define CONTROL_MASK_DISABLE_CONTROL 12
#define CONTROL_FLUSH_SHIFT 5
#define CONTROL_ACTIVE_SHIFT 4
#define CONTROL_RATE_ADAPT_MASK 0xf
#define CONTROL_RATE_DYNAMIC 0x0
#define CONTROL_RATE_FAST 0x8
#define CONTROL_RATE_MEDIUM 0x9
#define CONTROL_RATE_SLOW 0xa
#define CONTROL_RATE_IDLE 0xb
/* Register RING_FLUSH_DONE fields */
#define FLUSH_DONE_MASK 0x1
/* Register RING_MSI_CONTROL fields */
#define MSI_TIMER_VAL_SHIFT 16
#define MSI_TIMER_VAL_MASK 0xffff
#define MSI_ENABLE_SHIFT 15
#define MSI_ENABLE_MASK 0x1
#define MSI_COUNT_SHIFT 0
#define MSI_COUNT_MASK 0x3ff
/* Register RING_BD_READ_PTR_DDR_CONTROL fields */
#define BD_READ_PTR_DDR_TIMER_VAL_SHIFT 16
#define BD_READ_PTR_DDR_TIMER_VAL_MASK 0xffff
#define BD_READ_PTR_DDR_ENABLE_SHIFT 15
#define BD_READ_PTR_DDR_ENABLE_MASK 0x1
/* ====== FlexRM ring descriptor defines ===== */
/* Completion descriptor format */
#define CMPL_OPAQUE_SHIFT 0
#define CMPL_OPAQUE_MASK 0xffff
#define CMPL_ENGINE_STATUS_SHIFT 16
#define CMPL_ENGINE_STATUS_MASK 0xffff
#define CMPL_DME_STATUS_SHIFT 32
#define CMPL_DME_STATUS_MASK 0xffff
#define CMPL_RM_STATUS_SHIFT 48
#define CMPL_RM_STATUS_MASK 0xffff
/* Completion DME status code */
#define DME_STATUS_MEM_COR_ERR BIT(0)
#define DME_STATUS_MEM_UCOR_ERR BIT(1)
#define DME_STATUS_FIFO_UNDERFLOW BIT(2)
#define DME_STATUS_FIFO_OVERFLOW BIT(3)
#define DME_STATUS_RRESP_ERR BIT(4)
#define DME_STATUS_BRESP_ERR BIT(5)
#define DME_STATUS_ERROR_MASK (DME_STATUS_MEM_COR_ERR | \
DME_STATUS_MEM_UCOR_ERR | \
DME_STATUS_FIFO_UNDERFLOW | \
DME_STATUS_FIFO_OVERFLOW | \
DME_STATUS_RRESP_ERR | \
DME_STATUS_BRESP_ERR)
/* Completion RM status code */
#define RM_STATUS_CODE_SHIFT 0
#define RM_STATUS_CODE_MASK 0x3ff
#define RM_STATUS_CODE_GOOD 0x0
#define RM_STATUS_CODE_AE_TIMEOUT 0x3ff
/* General descriptor format */
#define DESC_TYPE_SHIFT 60
#define DESC_TYPE_MASK 0xf
#define DESC_PAYLOAD_SHIFT 0
#define DESC_PAYLOAD_MASK 0x0fffffffffffffff
/* Null descriptor format */
#define NULL_TYPE 0
#define NULL_TOGGLE_SHIFT 58
#define NULL_TOGGLE_MASK 0x1
/* Header descriptor format */
#define HEADER_TYPE 1
#define HEADER_TOGGLE_SHIFT 58
#define HEADER_TOGGLE_MASK 0x1
#define HEADER_ENDPKT_SHIFT 57
#define HEADER_ENDPKT_MASK 0x1
#define HEADER_STARTPKT_SHIFT 56
#define HEADER_STARTPKT_MASK 0x1
#define HEADER_BDCOUNT_SHIFT 36
#define HEADER_BDCOUNT_MASK 0x1f
#define HEADER_BDCOUNT_MAX HEADER_BDCOUNT_MASK
#define HEADER_FLAGS_SHIFT 16
#define HEADER_FLAGS_MASK 0xffff
#define HEADER_OPAQUE_SHIFT 0
#define HEADER_OPAQUE_MASK 0xffff
/* Source (SRC) descriptor format */
#define SRC_TYPE 2
#define SRC_LENGTH_SHIFT 44
#define SRC_LENGTH_MASK 0xffff
#define SRC_ADDR_SHIFT 0
#define SRC_ADDR_MASK 0x00000fffffffffff
/* Destination (DST) descriptor format */
#define DST_TYPE 3
#define DST_LENGTH_SHIFT 44
#define DST_LENGTH_MASK 0xffff
#define DST_ADDR_SHIFT 0
#define DST_ADDR_MASK 0x00000fffffffffff
/* Immediate (IMM) descriptor format */
#define IMM_TYPE 4
#define IMM_DATA_SHIFT 0
#define IMM_DATA_MASK 0x0fffffffffffffff
/* Next pointer (NPTR) descriptor format */
#define NPTR_TYPE 5
#define NPTR_TOGGLE_SHIFT 58
#define NPTR_TOGGLE_MASK 0x1
#define NPTR_ADDR_SHIFT 0
#define NPTR_ADDR_MASK 0x00000fffffffffff
/* Mega source (MSRC) descriptor format */
#define MSRC_TYPE 6
#define MSRC_LENGTH_SHIFT 44
#define MSRC_LENGTH_MASK 0xffff
#define MSRC_ADDR_SHIFT 0
#define MSRC_ADDR_MASK 0x00000fffffffffff
/* Mega destination (MDST) descriptor format */
#define MDST_TYPE 7
#define MDST_LENGTH_SHIFT 44
#define MDST_LENGTH_MASK 0xffff
#define MDST_ADDR_SHIFT 0
#define MDST_ADDR_MASK 0x00000fffffffffff
/* Source with tlast (SRCT) descriptor format */
#define SRCT_TYPE 8
#define SRCT_LENGTH_SHIFT 44
#define SRCT_LENGTH_MASK 0xffff
#define SRCT_ADDR_SHIFT 0
#define SRCT_ADDR_MASK 0x00000fffffffffff
/* Destination with tlast (DSTT) descriptor format */
#define DSTT_TYPE 9
#define DSTT_LENGTH_SHIFT 44
#define DSTT_LENGTH_MASK 0xffff
#define DSTT_ADDR_SHIFT 0
#define DSTT_ADDR_MASK 0x00000fffffffffff
/* Immediate with tlast (IMMT) descriptor format */
#define IMMT_TYPE 10
#define IMMT_DATA_SHIFT 0
#define IMMT_DATA_MASK 0x0fffffffffffffff
/* Descriptor helper macros */
#define DESC_DEC(_d, _s, _m) (((_d) >> (_s)) & (_m))
#define DESC_ENC(_d, _v, _s, _m) \
do { \
(_d) &= ~((u64)(_m) << (_s)); \
(_d) |= (((u64)(_v) & (_m)) << (_s)); \
} while (0)
/* ====== FlexRM data structures ===== */
struct flexrm_ring {
/* Unprotected members */
int num;
struct flexrm_mbox *mbox;
void __iomem *regs;
bool irq_requested;
unsigned int irq;
cpumask_t irq_aff_hint;
unsigned int msi_timer_val;
unsigned int msi_count_threshold;
struct brcm_message *requests[RING_MAX_REQ_COUNT];
void *bd_base;
dma_addr_t bd_dma_base;
u32 bd_write_offset;
void *cmpl_base;
dma_addr_t cmpl_dma_base;
/* Atomic stats */
atomic_t msg_send_count;
atomic_t msg_cmpl_count;
/* Protected members */
spinlock_t lock;
DECLARE_BITMAP(requests_bmap, RING_MAX_REQ_COUNT);
u32 cmpl_read_offset;
};
struct flexrm_mbox {
struct device *dev;
void __iomem *regs;
u32 num_rings;
struct flexrm_ring *rings;
struct dma_pool *bd_pool;
struct dma_pool *cmpl_pool;
struct dentry *root;
struct dentry *config;
struct dentry *stats;
struct mbox_controller controller;
};
/* ====== FlexRM ring descriptor helper routines ===== */
static u64 flexrm_read_desc(void *desc_ptr)
{
return le64_to_cpu(*((u64 *)desc_ptr));
}
static void flexrm_write_desc(void *desc_ptr, u64 desc)
{
*((u64 *)desc_ptr) = cpu_to_le64(desc);
}
static u32 flexrm_cmpl_desc_to_reqid(u64 cmpl_desc)
{
return (u32)(cmpl_desc & CMPL_OPAQUE_MASK);
}
static int flexrm_cmpl_desc_to_error(u64 cmpl_desc)
{
u32 status;
status = DESC_DEC(cmpl_desc, CMPL_DME_STATUS_SHIFT,
CMPL_DME_STATUS_MASK);
if (status & DME_STATUS_ERROR_MASK)
return -EIO;
status = DESC_DEC(cmpl_desc, CMPL_RM_STATUS_SHIFT,
CMPL_RM_STATUS_MASK);
status &= RM_STATUS_CODE_MASK;
if (status == RM_STATUS_CODE_AE_TIMEOUT)
return -ETIMEDOUT;
return 0;
}
static bool flexrm_is_next_table_desc(void *desc_ptr)
{
u64 desc = flexrm_read_desc(desc_ptr);
u32 type = DESC_DEC(desc, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
return (type == NPTR_TYPE) ? true : false;
}
static u64 flexrm_next_table_desc(u32 toggle, dma_addr_t next_addr)
{
u64 desc = 0;
DESC_ENC(desc, NPTR_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, toggle, NPTR_TOGGLE_SHIFT, NPTR_TOGGLE_MASK);
DESC_ENC(desc, next_addr, NPTR_ADDR_SHIFT, NPTR_ADDR_MASK);
return desc;
}
static u64 flexrm_null_desc(u32 toggle)
{
u64 desc = 0;
DESC_ENC(desc, NULL_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, toggle, NULL_TOGGLE_SHIFT, NULL_TOGGLE_MASK);
return desc;
}
static u32 flexrm_estimate_header_desc_count(u32 nhcnt)
{
u32 hcnt = nhcnt / HEADER_BDCOUNT_MAX;
if (!(nhcnt % HEADER_BDCOUNT_MAX))
hcnt += 1;
return hcnt;
}
static void flexrm_flip_header_toogle(void *desc_ptr)
{
u64 desc = flexrm_read_desc(desc_ptr);
if (desc & ((u64)0x1 << HEADER_TOGGLE_SHIFT))
desc &= ~((u64)0x1 << HEADER_TOGGLE_SHIFT);
else
desc |= ((u64)0x1 << HEADER_TOGGLE_SHIFT);
flexrm_write_desc(desc_ptr, desc);
}
static u64 flexrm_header_desc(u32 toggle, u32 startpkt, u32 endpkt,
u32 bdcount, u32 flags, u32 opaque)
{
u64 desc = 0;
DESC_ENC(desc, HEADER_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, toggle, HEADER_TOGGLE_SHIFT, HEADER_TOGGLE_MASK);
DESC_ENC(desc, startpkt, HEADER_STARTPKT_SHIFT, HEADER_STARTPKT_MASK);
DESC_ENC(desc, endpkt, HEADER_ENDPKT_SHIFT, HEADER_ENDPKT_MASK);
DESC_ENC(desc, bdcount, HEADER_BDCOUNT_SHIFT, HEADER_BDCOUNT_MASK);
DESC_ENC(desc, flags, HEADER_FLAGS_SHIFT, HEADER_FLAGS_MASK);
DESC_ENC(desc, opaque, HEADER_OPAQUE_SHIFT, HEADER_OPAQUE_MASK);
return desc;
}
static void flexrm_enqueue_desc(u32 nhpos, u32 nhcnt, u32 reqid,
u64 desc, void **desc_ptr, u32 *toggle,
void *start_desc, void *end_desc)
{
u64 d;
u32 nhavail, _toggle, _startpkt, _endpkt, _bdcount;
/* Sanity check */
if (nhcnt <= nhpos)
return;
/*
* Each request or packet start with a HEADER descriptor followed
* by one or more non-HEADER descriptors (SRC, SRCT, MSRC, DST,
* DSTT, MDST, IMM, and IMMT). The number of non-HEADER descriptors
* following a HEADER descriptor is represented by BDCOUNT field
* of HEADER descriptor. The max value of BDCOUNT field is 31 which
* means we can only have 31 non-HEADER descriptors following one
* HEADER descriptor.
*
* In general use, number of non-HEADER descriptors can easily go
* beyond 31. To tackle this situation, we have packet (or request)
* extenstion bits (STARTPKT and ENDPKT) in the HEADER descriptor.
*
* To use packet extension, the first HEADER descriptor of request
* (or packet) will have STARTPKT=1 and ENDPKT=0. The intermediate
* HEADER descriptors will have STARTPKT=0 and ENDPKT=0. The last
* HEADER descriptor will have STARTPKT=0 and ENDPKT=1. Also, the
* TOGGLE bit of the first HEADER will be set to invalid state to
* ensure that FlexRM does not start fetching descriptors till all
* descriptors are enqueued. The user of this function will flip
* the TOGGLE bit of first HEADER after all descriptors are
* enqueued.
*/
if ((nhpos % HEADER_BDCOUNT_MAX == 0) && (nhcnt - nhpos)) {
/* Prepare the header descriptor */
nhavail = (nhcnt - nhpos);
_toggle = (nhpos == 0) ? !(*toggle) : (*toggle);
_startpkt = (nhpos == 0) ? 0x1 : 0x0;
_endpkt = (nhavail <= HEADER_BDCOUNT_MAX) ? 0x1 : 0x0;
_bdcount = (nhavail <= HEADER_BDCOUNT_MAX) ?
nhavail : HEADER_BDCOUNT_MAX;
if (nhavail <= HEADER_BDCOUNT_MAX)
_bdcount = nhavail;
else
_bdcount = HEADER_BDCOUNT_MAX;
d = flexrm_header_desc(_toggle, _startpkt, _endpkt,
_bdcount, 0x0, reqid);
/* Write header descriptor */
flexrm_write_desc(*desc_ptr, d);
/* Point to next descriptor */
*desc_ptr += sizeof(desc);
if (*desc_ptr == end_desc)
*desc_ptr = start_desc;
/* Skip next pointer descriptors */
while (flexrm_is_next_table_desc(*desc_ptr)) {
*toggle = (*toggle) ? 0 : 1;
*desc_ptr += sizeof(desc);
if (*desc_ptr == end_desc)
*desc_ptr = start_desc;
}
}
/* Write desired descriptor */
flexrm_write_desc(*desc_ptr, desc);
/* Point to next descriptor */
*desc_ptr += sizeof(desc);
if (*desc_ptr == end_desc)
*desc_ptr = start_desc;
/* Skip next pointer descriptors */
while (flexrm_is_next_table_desc(*desc_ptr)) {
*toggle = (*toggle) ? 0 : 1;
*desc_ptr += sizeof(desc);
if (*desc_ptr == end_desc)
*desc_ptr = start_desc;
}
}
static u64 flexrm_src_desc(dma_addr_t addr, unsigned int length)
{
u64 desc = 0;
DESC_ENC(desc, SRC_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, length, SRC_LENGTH_SHIFT, SRC_LENGTH_MASK);
DESC_ENC(desc, addr, SRC_ADDR_SHIFT, SRC_ADDR_MASK);
return desc;
}
static u64 flexrm_msrc_desc(dma_addr_t addr, unsigned int length_div_16)
{
u64 desc = 0;
DESC_ENC(desc, MSRC_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, length_div_16, MSRC_LENGTH_SHIFT, MSRC_LENGTH_MASK);
DESC_ENC(desc, addr, MSRC_ADDR_SHIFT, MSRC_ADDR_MASK);
return desc;
}
static u64 flexrm_dst_desc(dma_addr_t addr, unsigned int length)
{
u64 desc = 0;
DESC_ENC(desc, DST_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, length, DST_LENGTH_SHIFT, DST_LENGTH_MASK);
DESC_ENC(desc, addr, DST_ADDR_SHIFT, DST_ADDR_MASK);
return desc;
}
static u64 flexrm_mdst_desc(dma_addr_t addr, unsigned int length_div_16)
{
u64 desc = 0;
DESC_ENC(desc, MDST_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, length_div_16, MDST_LENGTH_SHIFT, MDST_LENGTH_MASK);
DESC_ENC(desc, addr, MDST_ADDR_SHIFT, MDST_ADDR_MASK);
return desc;
}
static u64 flexrm_imm_desc(u64 data)
{
u64 desc = 0;
DESC_ENC(desc, IMM_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, data, IMM_DATA_SHIFT, IMM_DATA_MASK);
return desc;
}
static u64 flexrm_srct_desc(dma_addr_t addr, unsigned int length)
{
u64 desc = 0;
DESC_ENC(desc, SRCT_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, length, SRCT_LENGTH_SHIFT, SRCT_LENGTH_MASK);
DESC_ENC(desc, addr, SRCT_ADDR_SHIFT, SRCT_ADDR_MASK);
return desc;
}
static u64 flexrm_dstt_desc(dma_addr_t addr, unsigned int length)
{
u64 desc = 0;
DESC_ENC(desc, DSTT_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, length, DSTT_LENGTH_SHIFT, DSTT_LENGTH_MASK);
DESC_ENC(desc, addr, DSTT_ADDR_SHIFT, DSTT_ADDR_MASK);
return desc;
}
static u64 flexrm_immt_desc(u64 data)
{
u64 desc = 0;
DESC_ENC(desc, IMMT_TYPE, DESC_TYPE_SHIFT, DESC_TYPE_MASK);
DESC_ENC(desc, data, IMMT_DATA_SHIFT, IMMT_DATA_MASK);
return desc;
}
static bool flexrm_spu_sanity_check(struct brcm_message *msg)
{
struct scatterlist *sg;
if (!msg->spu.src || !msg->spu.dst)
return false;
for (sg = msg->spu.src; sg; sg = sg_next(sg)) {
if (sg->length & 0xf) {
if (sg->length > SRC_LENGTH_MASK)
return false;
} else {
if (sg->length > (MSRC_LENGTH_MASK * 16))
return false;
}
}
for (sg = msg->spu.dst; sg; sg = sg_next(sg)) {
if (sg->length & 0xf) {
if (sg->length > DST_LENGTH_MASK)
return false;
} else {
if (sg->length > (MDST_LENGTH_MASK * 16))
return false;
}
}
return true;
}
static u32 flexrm_spu_estimate_nonheader_desc_count(struct brcm_message *msg)
{
u32 cnt = 0;
unsigned int dst_target = 0;
struct scatterlist *src_sg = msg->spu.src, *dst_sg = msg->spu.dst;
while (src_sg || dst_sg) {
if (src_sg) {
cnt++;
dst_target = src_sg->length;
src_sg = sg_next(src_sg);
} else
dst_target = UINT_MAX;
while (dst_target && dst_sg) {
cnt++;
if (dst_sg->length < dst_target)
dst_target -= dst_sg->length;
else
dst_target = 0;
dst_sg = sg_next(dst_sg);
}
}
return cnt;
}
static int flexrm_spu_dma_map(struct device *dev, struct brcm_message *msg)
{
int rc;
rc = dma_map_sg(dev, msg->spu.src, sg_nents(msg->spu.src),
DMA_TO_DEVICE);
if (rc < 0)
return rc;
rc = dma_map_sg(dev, msg->spu.dst, sg_nents(msg->spu.dst),
DMA_FROM_DEVICE);
if (rc < 0) {
dma_unmap_sg(dev, msg->spu.src, sg_nents(msg->spu.src),
DMA_TO_DEVICE);
return rc;
}
return 0;
}
static void flexrm_spu_dma_unmap(struct device *dev, struct brcm_message *msg)
{
dma_unmap_sg(dev, msg->spu.dst, sg_nents(msg->spu.dst),
DMA_FROM_DEVICE);
dma_unmap_sg(dev, msg->spu.src, sg_nents(msg->spu.src),
DMA_TO_DEVICE);
}
static void *flexrm_spu_write_descs(struct brcm_message *msg, u32 nhcnt,
u32 reqid, void *desc_ptr, u32 toggle,
void *start_desc, void *end_desc)
{
u64 d;
u32 nhpos = 0;
void *orig_desc_ptr = desc_ptr;
unsigned int dst_target = 0;
struct scatterlist *src_sg = msg->spu.src, *dst_sg = msg->spu.dst;
while (src_sg || dst_sg) {
if (src_sg) {
if (sg_dma_len(src_sg) & 0xf)
d = flexrm_src_desc(sg_dma_address(src_sg),
sg_dma_len(src_sg));
else
d = flexrm_msrc_desc(sg_dma_address(src_sg),
sg_dma_len(src_sg)/16);
flexrm_enqueue_desc(nhpos, nhcnt, reqid,
d, &desc_ptr, &toggle,
start_desc, end_desc);
nhpos++;
dst_target = sg_dma_len(src_sg);
src_sg = sg_next(src_sg);
} else
dst_target = UINT_MAX;
while (dst_target && dst_sg) {
if (sg_dma_len(dst_sg) & 0xf)
d = flexrm_dst_desc(sg_dma_address(dst_sg),
sg_dma_len(dst_sg));
else
d = flexrm_mdst_desc(sg_dma_address(dst_sg),
sg_dma_len(dst_sg)/16);
flexrm_enqueue_desc(nhpos, nhcnt, reqid,
d, &desc_ptr, &toggle,
start_desc, end_desc);
nhpos++;
if (sg_dma_len(dst_sg) < dst_target)
dst_target -= sg_dma_len(dst_sg);
else
dst_target = 0;
dst_sg = sg_next(dst_sg);
}
}
/* Null descriptor with invalid toggle bit */
flexrm_write_desc(desc_ptr, flexrm_null_desc(!toggle));
/* Ensure that descriptors have been written to memory */
wmb();
/* Flip toggle bit in header */
flexrm_flip_header_toogle(orig_desc_ptr);
return desc_ptr;
}
static bool flexrm_sba_sanity_check(struct brcm_message *msg)
{
u32 i;
if (!msg->sba.cmds || !msg->sba.cmds_count)
return false;
for (i = 0; i < msg->sba.cmds_count; i++) {
if (((msg->sba.cmds[i].flags & BRCM_SBA_CMD_TYPE_B) ||
(msg->sba.cmds[i].flags & BRCM_SBA_CMD_TYPE_C)) &&
(msg->sba.cmds[i].flags & BRCM_SBA_CMD_HAS_OUTPUT))
return false;
if ((msg->sba.cmds[i].flags & BRCM_SBA_CMD_TYPE_B) &&
(msg->sba.cmds[i].data_len > SRCT_LENGTH_MASK))
return false;
if ((msg->sba.cmds[i].flags & BRCM_SBA_CMD_TYPE_C) &&
(msg->sba.cmds[i].data_len > SRCT_LENGTH_MASK))
return false;
if ((msg->sba.cmds[i].flags & BRCM_SBA_CMD_HAS_RESP) &&
(msg->sba.cmds[i].resp_len > DSTT_LENGTH_MASK))
return false;
if ((msg->sba.cmds[i].flags & BRCM_SBA_CMD_HAS_OUTPUT) &&
(msg->sba.cmds[i].data_len > DSTT_LENGTH_MASK))
return false;
}
return true;
}
static u32 flexrm_sba_estimate_nonheader_desc_count(struct brcm_message *msg)
{
u32 i, cnt;
cnt = 0;
for (i = 0; i < msg->sba.cmds_count; i++) {
cnt++;
if ((msg->sba.cmds[i].flags & BRCM_SBA_CMD_TYPE_B) ||
(msg->sba.cmds[i].flags & BRCM_SBA_CMD_TYPE_C))
cnt++;
if (msg->sba.cmds[i].flags & BRCM_SBA_CMD_HAS_RESP)
cnt++;
if (msg->sba.cmds[i].flags & BRCM_SBA_CMD_HAS_OUTPUT)
cnt++;
}
return cnt;
}
static void *flexrm_sba_write_descs(struct brcm_message *msg, u32 nhcnt,
u32 reqid, void *desc_ptr, u32 toggle,
void *start_desc, void *end_desc)
{
u64 d;
u32 i, nhpos = 0;
struct brcm_sba_command *c;
void *orig_desc_ptr = desc_ptr;
/* Convert SBA commands into descriptors */
for (i = 0; i < msg->sba.cmds_count; i++) {
c = &msg->sba.cmds[i];
if ((c->flags & BRCM_SBA_CMD_HAS_RESP) &&
(c->flags & BRCM_SBA_CMD_HAS_OUTPUT)) {
/* Destination response descriptor */
d = flexrm_dst_desc(c->resp, c->resp_len);
flexrm_enqueue_desc(nhpos, nhcnt, reqid,
d, &desc_ptr, &toggle,
start_desc, end_desc);
nhpos++;
} else if (c->flags & BRCM_SBA_CMD_HAS_RESP) {
/* Destination response with tlast descriptor */
d = flexrm_dstt_desc(c->resp, c->resp_len);
flexrm_enqueue_desc(nhpos, nhcnt, reqid,
d, &desc_ptr, &toggle,
start_desc, end_desc);
nhpos++;
}
if (c->flags & BRCM_SBA_CMD_HAS_OUTPUT) {
/* Destination with tlast descriptor */
d = flexrm_dstt_desc(c->data, c->data_len);
flexrm_enqueue_desc(nhpos, nhcnt, reqid,
d, &desc_ptr, &toggle,
start_desc, end_desc);
nhpos++;
}
if (c->flags & BRCM_SBA_CMD_TYPE_B) {
/* Command as immediate descriptor */
d = flexrm_imm_desc(c->cmd);
flexrm_enqueue_desc(nhpos, nhcnt, reqid,
d, &desc_ptr, &toggle,
start_desc, end_desc);
nhpos++;
} else {
/* Command as immediate descriptor with tlast */
d = flexrm_immt_desc(c->cmd);
flexrm_enqueue_desc(nhpos, nhcnt, reqid,
d, &desc_ptr, &toggle,
start_desc, end_desc);
nhpos++;
}
if ((c->flags & BRCM_SBA_CMD_TYPE_B) ||
(c->flags & BRCM_SBA_CMD_TYPE_C)) {
/* Source with tlast descriptor */
d = flexrm_srct_desc(c->data, c->data_len);
flexrm_enqueue_desc(nhpos, nhcnt, reqid,
d, &desc_ptr, &toggle,
start_desc, end_desc);
nhpos++;
}
}
/* Null descriptor with invalid toggle bit */
flexrm_write_desc(desc_ptr, flexrm_null_desc(!toggle));
/* Ensure that descriptors have been written to memory */
wmb();
/* Flip toggle bit in header */
flexrm_flip_header_toogle(orig_desc_ptr);
return desc_ptr;
}
static bool flexrm_sanity_check(struct brcm_message *msg)
{
if (!msg)
return false;
switch (msg->type) {
case BRCM_MESSAGE_SPU:
return flexrm_spu_sanity_check(msg);
case BRCM_MESSAGE_SBA:
return flexrm_sba_sanity_check(msg);
default:
return false;
};
}
static u32 flexrm_estimate_nonheader_desc_count(struct brcm_message *msg)
{
if (!msg)
return 0;
switch (msg->type) {
case BRCM_MESSAGE_SPU:
return flexrm_spu_estimate_nonheader_desc_count(msg);
case BRCM_MESSAGE_SBA:
return flexrm_sba_estimate_nonheader_desc_count(msg);
default:
return 0;
};
}
static int flexrm_dma_map(struct device *dev, struct brcm_message *msg)
{
if (!dev || !msg)
return -EINVAL;
switch (msg->type) {
case BRCM_MESSAGE_SPU:
return flexrm_spu_dma_map(dev, msg);
default:
break;
}
return 0;
}
static void flexrm_dma_unmap(struct device *dev, struct brcm_message *msg)
{
if (!dev || !msg)
return;
switch (msg->type) {
case BRCM_MESSAGE_SPU:
flexrm_spu_dma_unmap(dev, msg);
break;
default:
break;
}
}
static void *flexrm_write_descs(struct brcm_message *msg, u32 nhcnt,
u32 reqid, void *desc_ptr, u32 toggle,
void *start_desc, void *end_desc)
{
if (!msg || !desc_ptr || !start_desc || !end_desc)
return ERR_PTR(-ENOTSUPP);
if ((desc_ptr < start_desc) || (end_desc <= desc_ptr))
return ERR_PTR(-ERANGE);
switch (msg->type) {
case BRCM_MESSAGE_SPU:
return flexrm_spu_write_descs(msg, nhcnt, reqid,
desc_ptr, toggle,
start_desc, end_desc);
case BRCM_MESSAGE_SBA:
return flexrm_sba_write_descs(msg, nhcnt, reqid,
desc_ptr, toggle,
start_desc, end_desc);
default:
return ERR_PTR(-ENOTSUPP);
};
}
/* ====== FlexRM driver helper routines ===== */
static void flexrm_write_config_in_seqfile(struct flexrm_mbox *mbox,
struct seq_file *file)
{
int i;
const char *state;
struct flexrm_ring *ring;
seq_printf(file, "%-5s %-9s %-18s %-10s %-18s %-10s\n",
"Ring#", "State", "BD_Addr", "BD_Size",
"Cmpl_Addr", "Cmpl_Size");
for (i = 0; i < mbox->num_rings; i++) {
ring = &mbox->rings[i];
if (readl(ring->regs + RING_CONTROL) &
BIT(CONTROL_ACTIVE_SHIFT))
state = "active";
else
state = "inactive";
seq_printf(file,
"%-5d %-9s 0x%016llx 0x%08x 0x%016llx 0x%08x\n",
ring->num, state,
(unsigned long long)ring->bd_dma_base,
(u32)RING_BD_SIZE,
(unsigned long long)ring->cmpl_dma_base,
(u32)RING_CMPL_SIZE);
}
}
static void flexrm_write_stats_in_seqfile(struct flexrm_mbox *mbox,
struct seq_file *file)
{
int i;
u32 val, bd_read_offset;
struct flexrm_ring *ring;
seq_printf(file, "%-5s %-10s %-10s %-10s %-11s %-11s\n",
"Ring#", "BD_Read", "BD_Write",
"Cmpl_Read", "Submitted", "Completed");
for (i = 0; i < mbox->num_rings; i++) {
ring = &mbox->rings[i];
bd_read_offset = readl_relaxed(ring->regs + RING_BD_READ_PTR);
val = readl_relaxed(ring->regs + RING_BD_START_ADDR);
bd_read_offset *= RING_DESC_SIZE;
bd_read_offset += (u32)(BD_START_ADDR_DECODE(val) -
ring->bd_dma_base);
seq_printf(file, "%-5d 0x%08x 0x%08x 0x%08x %-11d %-11d\n",
ring->num,
(u32)bd_read_offset,
(u32)ring->bd_write_offset,
(u32)ring->cmpl_read_offset,
(u32)atomic_read(&ring->msg_send_count),
(u32)atomic_read(&ring->msg_cmpl_count));
}
}
static int flexrm_new_request(struct flexrm_ring *ring,
struct brcm_message *batch_msg,
struct brcm_message *msg)
{
void *next;
unsigned long flags;
u32 val, count, nhcnt;
u32 read_offset, write_offset;
bool exit_cleanup = false;
int ret = 0, reqid;
/* Do sanity check on message */
if (!flexrm_sanity_check(msg))
return -EIO;
msg->error = 0;
/* If no requests possible then save data pointer and goto done. */
spin_lock_irqsave(&ring->lock, flags);
reqid = bitmap_find_free_region(ring->requests_bmap,
RING_MAX_REQ_COUNT, 0);
spin_unlock_irqrestore(&ring->lock, flags);
if (reqid < 0)
return -ENOSPC;
ring->requests[reqid] = msg;
/* Do DMA mappings for the message */
ret = flexrm_dma_map(ring->mbox->dev, msg);
if (ret < 0) {
ring->requests[reqid] = NULL;
spin_lock_irqsave(&ring->lock, flags);
bitmap_release_region(ring->requests_bmap, reqid, 0);
spin_unlock_irqrestore(&ring->lock, flags);
return ret;
}
/* Determine current HW BD read offset */
read_offset = readl_relaxed(ring->regs + RING_BD_READ_PTR);
val = readl_relaxed(ring->regs + RING_BD_START_ADDR);
read_offset *= RING_DESC_SIZE;
read_offset += (u32)(BD_START_ADDR_DECODE(val) - ring->bd_dma_base);
/*
* Number required descriptors = number of non-header descriptors +
* number of header descriptors +
* 1x null descriptor
*/
nhcnt = flexrm_estimate_nonheader_desc_count(msg);
count = flexrm_estimate_header_desc_count(nhcnt) + nhcnt + 1;
/* Check for available descriptor space. */
write_offset = ring->bd_write_offset;
while (count) {
if (!flexrm_is_next_table_desc(ring->bd_base + write_offset))
count--;
write_offset += RING_DESC_SIZE;
if (write_offset == RING_BD_SIZE)
write_offset = 0x0;
if (write_offset == read_offset)
break;
}
if (count) {
ret = -ENOSPC;
exit_cleanup = true;
goto exit;
}
/* Write descriptors to ring */
next = flexrm_write_descs(msg, nhcnt, reqid,
ring->bd_base + ring->bd_write_offset,
RING_BD_TOGGLE_VALID(ring->bd_write_offset),
ring->bd_base, ring->bd_base + RING_BD_SIZE);
if (IS_ERR(next)) {
ret = PTR_ERR(next);
exit_cleanup = true;
goto exit;
}
/* Save ring BD write offset */
ring->bd_write_offset = (unsigned long)(next - ring->bd_base);
/* Increment number of messages sent */
atomic_inc_return(&ring->msg_send_count);
exit:
/* Update error status in message */
msg->error = ret;
/* Cleanup if we failed */
if (exit_cleanup) {
flexrm_dma_unmap(ring->mbox->dev, msg);
ring->requests[reqid] = NULL;
spin_lock_irqsave(&ring->lock, flags);
bitmap_release_region(ring->requests_bmap, reqid, 0);
spin_unlock_irqrestore(&ring->lock, flags);
}
return ret;
}
static int flexrm_process_completions(struct flexrm_ring *ring)
{
u64 desc;
int err, count = 0;
unsigned long flags;
struct brcm_message *msg = NULL;
u32 reqid, cmpl_read_offset, cmpl_write_offset;
struct mbox_chan *chan = &ring->mbox->controller.chans[ring->num];
spin_lock_irqsave(&ring->lock, flags);
/*
* Get current completion read and write offset
*
* Note: We should read completion write pointer atleast once
* after we get a MSI interrupt because HW maintains internal
* MSI status which will allow next MSI interrupt only after
* completion write pointer is read.
*/
cmpl_write_offset = readl_relaxed(ring->regs + RING_CMPL_WRITE_PTR);
cmpl_write_offset *= RING_DESC_SIZE;
cmpl_read_offset = ring->cmpl_read_offset;
ring->cmpl_read_offset = cmpl_write_offset;
spin_unlock_irqrestore(&ring->lock, flags);
/* For each completed request notify mailbox clients */
reqid = 0;
while (cmpl_read_offset != cmpl_write_offset) {
/* Dequeue next completion descriptor */
desc = *((u64 *)(ring->cmpl_base + cmpl_read_offset));
/* Next read offset */
cmpl_read_offset += RING_DESC_SIZE;
if (cmpl_read_offset == RING_CMPL_SIZE)
cmpl_read_offset = 0;
/* Decode error from completion descriptor */
err = flexrm_cmpl_desc_to_error(desc);
if (err < 0) {
dev_warn(ring->mbox->dev,
"ring%d got completion desc=0x%lx with error %d\n",
ring->num, (unsigned long)desc, err);
}
/* Determine request id from completion descriptor */
reqid = flexrm_cmpl_desc_to_reqid(desc);
/* Determine message pointer based on reqid */
msg = ring->requests[reqid];
if (!msg) {
dev_warn(ring->mbox->dev,
"ring%d null msg pointer for completion desc=0x%lx\n",
ring->num, (unsigned long)desc);
continue;
}
/* Release reqid for recycling */
ring->requests[reqid] = NULL;
spin_lock_irqsave(&ring->lock, flags);
bitmap_release_region(ring->requests_bmap, reqid, 0);
spin_unlock_irqrestore(&ring->lock, flags);
/* Unmap DMA mappings */
flexrm_dma_unmap(ring->mbox->dev, msg);
/* Give-back message to mailbox client */
msg->error = err;
mbox_chan_received_data(chan, msg);
/* Increment number of completions processed */
atomic_inc_return(&ring->msg_cmpl_count);
count++;
}
return count;
}
/* ====== FlexRM Debugfs callbacks ====== */
static int flexrm_debugfs_conf_show(struct seq_file *file, void *offset)
{
struct platform_device *pdev = to_platform_device(file->private);
struct flexrm_mbox *mbox = platform_get_drvdata(pdev);
/* Write config in file */
flexrm_write_config_in_seqfile(mbox, file);
return 0;
}
static int flexrm_debugfs_stats_show(struct seq_file *file, void *offset)
{
struct platform_device *pdev = to_platform_device(file->private);
struct flexrm_mbox *mbox = platform_get_drvdata(pdev);
/* Write stats in file */
flexrm_write_stats_in_seqfile(mbox, file);
return 0;
}
/* ====== FlexRM interrupt handler ===== */
static irqreturn_t flexrm_irq_event(int irq, void *dev_id)
{
/* We only have MSI for completions so just wakeup IRQ thread */
/* Ring related errors will be informed via completion descriptors */
return IRQ_WAKE_THREAD;
}
static irqreturn_t flexrm_irq_thread(int irq, void *dev_id)
{
flexrm_process_completions(dev_id);
return IRQ_HANDLED;
}
/* ====== FlexRM mailbox callbacks ===== */
static int flexrm_send_data(struct mbox_chan *chan, void *data)
{
int i, rc;
struct flexrm_ring *ring = chan->con_priv;
struct brcm_message *msg = data;
if (msg->type == BRCM_MESSAGE_BATCH) {
for (i = msg->batch.msgs_queued;
i < msg->batch.msgs_count; i++) {
rc = flexrm_new_request(ring, msg,
&msg->batch.msgs[i]);
if (rc) {
msg->error = rc;
return rc;
}
msg->batch.msgs_queued++;
}
return 0;
}
return flexrm_new_request(ring, NULL, data);
}
static bool flexrm_peek_data(struct mbox_chan *chan)
{
int cnt = flexrm_process_completions(chan->con_priv);
return (cnt > 0) ? true : false;
}
static int flexrm_startup(struct mbox_chan *chan)
{
u64 d;
u32 val, off;
int ret = 0;
dma_addr_t next_addr;
struct flexrm_ring *ring = chan->con_priv;
/* Allocate BD memory */
ring->bd_base = dma_pool_alloc(ring->mbox->bd_pool,
GFP_KERNEL, &ring->bd_dma_base);
if (!ring->bd_base) {
dev_err(ring->mbox->dev,
"can't allocate BD memory for ring%d\n",
ring->num);
ret = -ENOMEM;
goto fail;
}
/* Configure next table pointer entries in BD memory */
for (off = 0; off < RING_BD_SIZE; off += RING_DESC_SIZE) {
next_addr = off + RING_DESC_SIZE;
if (next_addr == RING_BD_SIZE)
next_addr = 0;
next_addr += ring->bd_dma_base;
if (RING_BD_ALIGN_CHECK(next_addr))
d = flexrm_next_table_desc(RING_BD_TOGGLE_VALID(off),
next_addr);
else
d = flexrm_null_desc(RING_BD_TOGGLE_INVALID(off));
flexrm_write_desc(ring->bd_base + off, d);
}
/* Allocate completion memory */
ring->cmpl_base = dma_pool_zalloc(ring->mbox->cmpl_pool,
GFP_KERNEL, &ring->cmpl_dma_base);
if (!ring->cmpl_base) {
dev_err(ring->mbox->dev,
"can't allocate completion memory for ring%d\n",
ring->num);
ret = -ENOMEM;
goto fail_free_bd_memory;
}
/* Request IRQ */
if (ring->irq == UINT_MAX) {
dev_err(ring->mbox->dev,
"ring%d IRQ not available\n", ring->num);
ret = -ENODEV;
goto fail_free_cmpl_memory;
}
ret = request_threaded_irq(ring->irq,
flexrm_irq_event,
flexrm_irq_thread,
0, dev_name(ring->mbox->dev), ring);
if (ret) {
dev_err(ring->mbox->dev,
"failed to request ring%d IRQ\n", ring->num);
goto fail_free_cmpl_memory;
}
ring->irq_requested = true;
/* Set IRQ affinity hint */
ring->irq_aff_hint = CPU_MASK_NONE;
val = ring->mbox->num_rings;
val = (num_online_cpus() < val) ? val / num_online_cpus() : 1;
cpumask_set_cpu((ring->num / val) % num_online_cpus(),
&ring->irq_aff_hint);
ret = irq_set_affinity_hint(ring->irq, &ring->irq_aff_hint);
if (ret) {
dev_err(ring->mbox->dev,
"failed to set IRQ affinity hint for ring%d\n",
ring->num);
goto fail_free_irq;
}
/* Disable/inactivate ring */
writel_relaxed(0x0, ring->regs + RING_CONTROL);
/* Program BD start address */
val = BD_START_ADDR_VALUE(ring->bd_dma_base);
writel_relaxed(val, ring->regs + RING_BD_START_ADDR);
/* BD write pointer will be same as HW write pointer */
ring->bd_write_offset =
readl_relaxed(ring->regs + RING_BD_WRITE_PTR);
ring->bd_write_offset *= RING_DESC_SIZE;
/* Program completion start address */
val = CMPL_START_ADDR_VALUE(ring->cmpl_dma_base);
writel_relaxed(val, ring->regs + RING_CMPL_START_ADDR);
/* Completion read pointer will be same as HW write pointer */
ring->cmpl_read_offset =
readl_relaxed(ring->regs + RING_CMPL_WRITE_PTR);
ring->cmpl_read_offset *= RING_DESC_SIZE;
/* Read ring Tx, Rx, and Outstanding counts to clear */
readl_relaxed(ring->regs + RING_NUM_REQ_RECV_LS);
readl_relaxed(ring->regs + RING_NUM_REQ_RECV_MS);
readl_relaxed(ring->regs + RING_NUM_REQ_TRANS_LS);
readl_relaxed(ring->regs + RING_NUM_REQ_TRANS_MS);
readl_relaxed(ring->regs + RING_NUM_REQ_OUTSTAND);
/* Configure RING_MSI_CONTROL */
val = 0;
val |= (ring->msi_timer_val << MSI_TIMER_VAL_SHIFT);
val |= BIT(MSI_ENABLE_SHIFT);
val |= (ring->msi_count_threshold & MSI_COUNT_MASK) << MSI_COUNT_SHIFT;
writel_relaxed(val, ring->regs + RING_MSI_CONTROL);
/* Enable/activate ring */
val = BIT(CONTROL_ACTIVE_SHIFT);
writel_relaxed(val, ring->regs + RING_CONTROL);
/* Reset stats to zero */
atomic_set(&ring->msg_send_count, 0);
atomic_set(&ring->msg_cmpl_count, 0);
return 0;
fail_free_irq:
free_irq(ring->irq, ring);
ring->irq_requested = false;
fail_free_cmpl_memory:
dma_pool_free(ring->mbox->cmpl_pool,
ring->cmpl_base, ring->cmpl_dma_base);
ring->cmpl_base = NULL;
fail_free_bd_memory:
dma_pool_free(ring->mbox->bd_pool,
ring->bd_base, ring->bd_dma_base);
ring->bd_base = NULL;
fail:
return ret;
}
static void flexrm_shutdown(struct mbox_chan *chan)
{
u32 reqid;
unsigned int timeout;
struct brcm_message *msg;
struct flexrm_ring *ring = chan->con_priv;
/* Disable/inactivate ring */
writel_relaxed(0x0, ring->regs + RING_CONTROL);
/* Set ring flush state */
timeout = 1000; /* timeout of 1s */
writel_relaxed(BIT(CONTROL_FLUSH_SHIFT),
ring->regs + RING_CONTROL);
do {
if (readl_relaxed(ring->regs + RING_FLUSH_DONE) &
FLUSH_DONE_MASK)
break;
mdelay(1);
} while (--timeout);
if (!timeout)
dev_err(ring->mbox->dev,
"setting ring%d flush state timedout\n", ring->num);
/* Clear ring flush state */
timeout = 1000; /* timeout of 1s */
writel_relaxed(0x0, ring + RING_CONTROL);
do {
if (!(readl_relaxed(ring + RING_FLUSH_DONE) &
FLUSH_DONE_MASK))
break;
mdelay(1);
} while (--timeout);
if (!timeout)
dev_err(ring->mbox->dev,
"clearing ring%d flush state timedout\n", ring->num);
/* Abort all in-flight requests */
for (reqid = 0; reqid < RING_MAX_REQ_COUNT; reqid++) {
msg = ring->requests[reqid];
if (!msg)
continue;
/* Release reqid for recycling */
ring->requests[reqid] = NULL;
/* Unmap DMA mappings */
flexrm_dma_unmap(ring->mbox->dev, msg);
/* Give-back message to mailbox client */
msg->error = -EIO;
mbox_chan_received_data(chan, msg);
}
/* Clear requests bitmap */
bitmap_zero(ring->requests_bmap, RING_MAX_REQ_COUNT);
/* Release IRQ */
if (ring->irq_requested) {
irq_set_affinity_hint(ring->irq, NULL);
free_irq(ring->irq, ring);
ring->irq_requested = false;
}
/* Free-up completion descriptor ring */
if (ring->cmpl_base) {
dma_pool_free(ring->mbox->cmpl_pool,
ring->cmpl_base, ring->cmpl_dma_base);
ring->cmpl_base = NULL;
}
/* Free-up BD descriptor ring */
if (ring->bd_base) {
dma_pool_free(ring->mbox->bd_pool,
ring->bd_base, ring->bd_dma_base);
ring->bd_base = NULL;
}
}
static const struct mbox_chan_ops flexrm_mbox_chan_ops = {
.send_data = flexrm_send_data,
.startup = flexrm_startup,
.shutdown = flexrm_shutdown,
.peek_data = flexrm_peek_data,
};
static struct mbox_chan *flexrm_mbox_of_xlate(struct mbox_controller *cntlr,
const struct of_phandle_args *pa)
{
struct mbox_chan *chan;
struct flexrm_ring *ring;
if (pa->args_count < 3)
return ERR_PTR(-EINVAL);
if (pa->args[0] >= cntlr->num_chans)
return ERR_PTR(-ENOENT);
if (pa->args[1] > MSI_COUNT_MASK)
return ERR_PTR(-EINVAL);
if (pa->args[2] > MSI_TIMER_VAL_MASK)
return ERR_PTR(-EINVAL);
chan = &cntlr->chans[pa->args[0]];
ring = chan->con_priv;
ring->msi_count_threshold = pa->args[1];
ring->msi_timer_val = pa->args[2];
return chan;
}
/* ====== FlexRM platform driver ===== */
static void flexrm_mbox_msi_write(struct msi_desc *desc, struct msi_msg *msg)
{
struct device *dev = msi_desc_to_dev(desc);
struct flexrm_mbox *mbox = dev_get_drvdata(dev);
struct flexrm_ring *ring = &mbox->rings[desc->platform.msi_index];
/* Configure per-Ring MSI registers */
writel_relaxed(msg->address_lo, ring->regs + RING_MSI_ADDR_LS);
writel_relaxed(msg->address_hi, ring->regs + RING_MSI_ADDR_MS);
writel_relaxed(msg->data, ring->regs + RING_MSI_DATA_VALUE);
}
static int flexrm_mbox_probe(struct platform_device *pdev)
{
int index, ret = 0;
void __iomem *regs;
void __iomem *regs_end;
struct msi_desc *desc;
struct resource *iomem;
struct flexrm_ring *ring;
struct flexrm_mbox *mbox;
struct device *dev = &pdev->dev;
/* Allocate driver mailbox struct */
mbox = devm_kzalloc(dev, sizeof(*mbox), GFP_KERNEL);
if (!mbox) {
ret = -ENOMEM;
goto fail;
}
mbox->dev = dev;
platform_set_drvdata(pdev, mbox);
/* Get resource for registers */
iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!iomem || (resource_size(iomem) < RING_REGS_SIZE)) {
ret = -ENODEV;
goto fail;
}
/* Map registers of all rings */
mbox->regs = devm_ioremap_resource(&pdev->dev, iomem);
if (IS_ERR(mbox->regs)) {
ret = PTR_ERR(mbox->regs);
dev_err(&pdev->dev, "Failed to remap mailbox regs: %d\n", ret);
goto fail;
}
regs_end = mbox->regs + resource_size(iomem);
/* Scan and count available rings */
mbox->num_rings = 0;
for (regs = mbox->regs; regs < regs_end; regs += RING_REGS_SIZE) {
if (readl_relaxed(regs + RING_VER) == RING_VER_MAGIC)
mbox->num_rings++;
}
if (!mbox->num_rings) {
ret = -ENODEV;
goto fail;
}
/* Allocate driver ring structs */
ring = devm_kcalloc(dev, mbox->num_rings, sizeof(*ring), GFP_KERNEL);
if (!ring) {
ret = -ENOMEM;
goto fail;
}
mbox->rings = ring;
/* Initialize members of driver ring structs */
regs = mbox->regs;
for (index = 0; index < mbox->num_rings; index++) {
ring = &mbox->rings[index];
ring->num = index;
ring->mbox = mbox;
while ((regs < regs_end) &&
(readl_relaxed(regs + RING_VER) != RING_VER_MAGIC))
regs += RING_REGS_SIZE;
if (regs_end <= regs) {
ret = -ENODEV;
goto fail;
}
ring->regs = regs;
regs += RING_REGS_SIZE;
ring->irq = UINT_MAX;
ring->irq_requested = false;
ring->msi_timer_val = MSI_TIMER_VAL_MASK;
ring->msi_count_threshold = 0x1;
memset(ring->requests, 0, sizeof(ring->requests));
ring->bd_base = NULL;
ring->bd_dma_base = 0;
ring->cmpl_base = NULL;
ring->cmpl_dma_base = 0;
atomic_set(&ring->msg_send_count, 0);
atomic_set(&ring->msg_cmpl_count, 0);
spin_lock_init(&ring->lock);
bitmap_zero(ring->requests_bmap, RING_MAX_REQ_COUNT);
ring->cmpl_read_offset = 0;
}
/* FlexRM is capable of 40-bit physical addresses only */
ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(40));
if (ret) {
ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32));
if (ret)
goto fail;
}
/* Create DMA pool for ring BD memory */
mbox->bd_pool = dma_pool_create("bd", dev, RING_BD_SIZE,
1 << RING_BD_ALIGN_ORDER, 0);
if (!mbox->bd_pool) {
ret = -ENOMEM;
goto fail;
}
/* Create DMA pool for ring completion memory */
mbox->cmpl_pool = dma_pool_create("cmpl", dev, RING_CMPL_SIZE,
1 << RING_CMPL_ALIGN_ORDER, 0);
if (!mbox->cmpl_pool) {
ret = -ENOMEM;
goto fail_destroy_bd_pool;
}
/* Allocate platform MSIs for each ring */
ret = platform_msi_domain_alloc_irqs(dev, mbox->num_rings,
flexrm_mbox_msi_write);
if (ret)
goto fail_destroy_cmpl_pool;
/* Save alloced IRQ numbers for each ring */
for_each_msi_entry(desc, dev) {
ring = &mbox->rings[desc->platform.msi_index];
ring->irq = desc->irq;
}
/* Check availability of debugfs */
if (!debugfs_initialized())
goto skip_debugfs;
/* Create debugfs root entry */
mbox->root = debugfs_create_dir(dev_name(mbox->dev), NULL);
if (IS_ERR_OR_NULL(mbox->root)) {
ret = PTR_ERR_OR_ZERO(mbox->root);
goto fail_free_msis;
}
/* Create debugfs config entry */
mbox->config = debugfs_create_devm_seqfile(mbox->dev,
"config", mbox->root,
flexrm_debugfs_conf_show);
if (IS_ERR_OR_NULL(mbox->config)) {
ret = PTR_ERR_OR_ZERO(mbox->config);
goto fail_free_debugfs_root;
}
/* Create debugfs stats entry */
mbox->stats = debugfs_create_devm_seqfile(mbox->dev,
"stats", mbox->root,
flexrm_debugfs_stats_show);
if (IS_ERR_OR_NULL(mbox->stats)) {
ret = PTR_ERR_OR_ZERO(mbox->stats);
goto fail_free_debugfs_root;
}
skip_debugfs:
/* Initialize mailbox controller */
mbox->controller.txdone_irq = false;
mbox->controller.txdone_poll = false;
mbox->controller.ops = &flexrm_mbox_chan_ops;
mbox->controller.dev = dev;
mbox->controller.num_chans = mbox->num_rings;
mbox->controller.of_xlate = flexrm_mbox_of_xlate;
mbox->controller.chans = devm_kcalloc(dev, mbox->num_rings,
sizeof(*mbox->controller.chans), GFP_KERNEL);
if (!mbox->controller.chans) {
ret = -ENOMEM;
goto fail_free_debugfs_root;
}
for (index = 0; index < mbox->num_rings; index++)
mbox->controller.chans[index].con_priv = &mbox->rings[index];
/* Register mailbox controller */
ret = mbox_controller_register(&mbox->controller);
if (ret)
goto fail_free_debugfs_root;
dev_info(dev, "registered flexrm mailbox with %d channels\n",
mbox->controller.num_chans);
return 0;
fail_free_debugfs_root:
debugfs_remove_recursive(mbox->root);
fail_free_msis:
platform_msi_domain_free_irqs(dev);
fail_destroy_cmpl_pool:
dma_pool_destroy(mbox->cmpl_pool);
fail_destroy_bd_pool:
dma_pool_destroy(mbox->bd_pool);
fail:
return ret;
}
static int flexrm_mbox_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct flexrm_mbox *mbox = platform_get_drvdata(pdev);
mbox_controller_unregister(&mbox->controller);
debugfs_remove_recursive(mbox->root);
platform_msi_domain_free_irqs(dev);
dma_pool_destroy(mbox->cmpl_pool);
dma_pool_destroy(mbox->bd_pool);
return 0;
}
static const struct of_device_id flexrm_mbox_of_match[] = {
{ .compatible = "brcm,iproc-flexrm-mbox", },
{},
};
MODULE_DEVICE_TABLE(of, flexrm_mbox_of_match);
static struct platform_driver flexrm_mbox_driver = {
.driver = {
.name = "brcm-flexrm-mbox",
.of_match_table = flexrm_mbox_of_match,
},
.probe = flexrm_mbox_probe,
.remove = flexrm_mbox_remove,
};
module_platform_driver(flexrm_mbox_driver);
MODULE_AUTHOR("Anup Patel <anup.patel@broadcom.com>");
MODULE_DESCRIPTION("Broadcom FlexRM mailbox driver");
MODULE_LICENSE("GPL v2");
| {
"language": "C"
} |
/*
* SpanDSP - a series of DSP components for telephony
*
* echo.c - A line echo canceller. This code is being developed
* against and partially complies with G168.
*
* Written by Steve Underwood <steveu@coppice.org>
* and David Rowe <david_at_rowetel_dot_com>
*
* Copyright (C) 2001 Steve Underwood and 2007 David Rowe
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __ECHO_H
#define __ECHO_H
/*
Line echo cancellation for voice
What does it do?
This module aims to provide G.168-2002 compliant echo cancellation, to remove
electrical echoes (e.g. from 2-4 wire hybrids) from voice calls.
How does it work?
The heart of the echo cancellor is FIR filter. This is adapted to match the
echo impulse response of the telephone line. It must be long enough to
adequately cover the duration of that impulse response. The signal transmitted
to the telephone line is passed through the FIR filter. Once the FIR is
properly adapted, the resulting output is an estimate of the echo signal
received from the line. This is subtracted from the received signal. The result
is an estimate of the signal which originated at the far end of the line, free
from echos of our own transmitted signal.
The least mean squares (LMS) algorithm is attributed to Widrow and Hoff, and
was introduced in 1960. It is the commonest form of filter adaption used in
things like modem line equalisers and line echo cancellers. There it works very
well. However, it only works well for signals of constant amplitude. It works
very poorly for things like speech echo cancellation, where the signal level
varies widely. This is quite easy to fix. If the signal level is normalised -
similar to applying AGC - LMS can work as well for a signal of varying
amplitude as it does for a modem signal. This normalised least mean squares
(NLMS) algorithm is the commonest one used for speech echo cancellation. Many
other algorithms exist - e.g. RLS (essentially the same as Kalman filtering),
FAP, etc. Some perform significantly better than NLMS. However, factors such
as computational complexity and patents favour the use of NLMS.
A simple refinement to NLMS can improve its performance with speech. NLMS tends
to adapt best to the strongest parts of a signal. If the signal is white noise,
the NLMS algorithm works very well. However, speech has more low frequency than
high frequency content. Pre-whitening (i.e. filtering the signal to flatten its
spectrum) the echo signal improves the adapt rate for speech, and ensures the
final residual signal is not heavily biased towards high frequencies. A very
low complexity filter is adequate for this, so pre-whitening adds little to the
compute requirements of the echo canceller.
An FIR filter adapted using pre-whitened NLMS performs well, provided certain
conditions are met:
- The transmitted signal has poor self-correlation.
- There is no signal being generated within the environment being
cancelled.
The difficulty is that neither of these can be guaranteed.
If the adaption is performed while transmitting noise (or something fairly
noise like, such as voice) the adaption works very well. If the adaption is
performed while transmitting something highly correlative (typically narrow
band energy such as signalling tones or DTMF), the adaption can go seriously
wrong. The reason is there is only one solution for the adaption on a near
random signal - the impulse response of the line. For a repetitive signal,
there are any number of solutions which converge the adaption, and nothing
guides the adaption to choose the generalised one. Allowing an untrained
canceller to converge on this kind of narrowband energy probably a good thing,
since at least it cancels the tones. Allowing a well converged canceller to
continue converging on such energy is just a way to ruin its generalised
adaption. A narrowband detector is needed, so adapation can be suspended at
appropriate times.
The adaption process is based on trying to eliminate the received signal. When
there is any signal from within the environment being cancelled it may upset
the adaption process. Similarly, if the signal we are transmitting is small,
noise may dominate and disturb the adaption process. If we can ensure that the
adaption is only performed when we are transmitting a significant signal level,
and the environment is not, things will be OK. Clearly, it is easy to tell when
we are sending a significant signal. Telling, if the environment is generating
a significant signal, and doing it with sufficient speed that the adaption will
not have diverged too much more we stop it, is a little harder.
The key problem in detecting when the environment is sourcing significant
energy is that we must do this very quickly. Given a reasonably long sample of
the received signal, there are a number of strategies which may be used to
assess whether that signal contains a strong far end component. However, by the
time that assessment is complete the far end signal will have already caused
major mis-convergence in the adaption process. An assessment algorithm is
needed which produces a fairly accurate result from a very short burst of far
end energy.
How do I use it?
The echo cancellor processes both the transmit and receive streams sample by
sample. The processing function is not declared inline. Unfortunately,
cancellation requires many operations per sample, so the call overhead is only
a minor burden.
*/
#include "fir.h"
#include "oslec.h"
/*
G.168 echo canceller descriptor. This defines the working state for a line
echo canceller.
*/
struct oslec_state {
int16_t tx, rx;
int16_t clean;
int16_t clean_nlp;
int nonupdate_dwell;
int curr_pos;
int taps;
int log2taps;
int adaption_mode;
int cond_met;
int32_t Pstates;
int16_t adapt;
int32_t factor;
int16_t shift;
/* Average levels and averaging filter states */
int Ltxacc, Lrxacc, Lcleanacc, Lclean_bgacc;
int Ltx, Lrx;
int Lclean;
int Lclean_bg;
int Lbgn, Lbgn_acc, Lbgn_upper, Lbgn_upper_acc;
/* foreground and background filter states */
struct fir16_state_t fir_state;
struct fir16_state_t fir_state_bg;
int16_t *fir_taps16[2];
/* DC blocking filter states */
int tx_1, tx_2, rx_1, rx_2;
/* optional High Pass Filter states */
int32_t xvtx[5], yvtx[5];
int32_t xvrx[5], yvrx[5];
/* Parameters for the optional Hoth noise generator */
int cng_level;
int cng_rndnum;
int cng_filter;
/* snapshot sample of coeffs used for development */
int16_t *snapshot;
};
#endif /* __ECHO_H */
| {
"language": "C"
} |
////////// Copyright © 2011, Goldeneye Source. All rights reserved. ///////////
//
// ge_ammocrate.h
//
// Description:
// An ammo crate that gives a certain amount of ammo of different types
//
// Created On: 6/20/2011
// Created By: Killer Monkey
////////////////////////////////////////////////////////////////////////////////
#ifndef GE_AMMOCRATE_H
#define GE_AMMOCRATE_H
#include "items.h"
#include "player.h"
#include "ge_shareddefs.h"
class CGEAmmoCrate : public CItem
{
public:
DECLARE_CLASS( CGEAmmoCrate, CItem );
DECLARE_DATADESC();
CGEAmmoCrate();
// CBaseEntity functions
virtual void Spawn();
virtual void Precache();
// CItem functions
virtual void ItemTouch( CBaseEntity *pEntity );
virtual bool MyTouch( CBasePlayer *pPlayer );
virtual void Materialize();
virtual CBaseEntity *Respawn();
// Special refill function if we only take partial ammo
void RefillThink();
// Ammo Crate specific functions
void SetAmmoType( int id );
int GetAmmoType();
bool HasAmmo();
void UpdateOnRemove();
void SetWeaponID( int id );
int GetWeaponID() { return m_iWeaponID; }
int GetWeight() { return m_iWeight; }
private:
int m_iAmmoID;
int m_iAmmoAmount;
bool m_bGaveGlobalAmmo;
int m_iWeaponID;
int m_iWeight;
};
#endif
| {
"language": "C"
} |
/*
* Copyright (c) 2006-2016 Kirill Simonov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "yaml_private.h"
/*
* Declarations.
*/
static int
yaml_emitter_set_writer_error(yaml_emitter_t *emitter, const char *problem);
YAML_DECLARE(int)
yaml_emitter_flush(yaml_emitter_t *emitter);
/*
* Set the writer error and return 0.
*/
static int
yaml_emitter_set_writer_error(yaml_emitter_t *emitter, const char *problem)
{
emitter->error = YAML_WRITER_ERROR;
emitter->problem = problem;
return 0;
}
/*
* Flush the output buffer.
*/
YAML_DECLARE(int)
yaml_emitter_flush(yaml_emitter_t *emitter)
{
int low, high;
assert(emitter); /* Non-NULL emitter object is expected. */
assert(emitter->write_handler); /* Write handler must be set. */
assert(emitter->encoding); /* Output encoding must be set. */
emitter->buffer.last = emitter->buffer.pointer;
emitter->buffer.pointer = emitter->buffer.start;
/* Check if the buffer is empty. */
if (emitter->buffer.start == emitter->buffer.last) {
return 1;
}
/* If the output encoding is UTF-8, we don't need to recode the buffer. */
if (emitter->encoding == YAML_UTF8_ENCODING)
{
if (emitter->write_handler(emitter->write_handler_data,
emitter->buffer.start,
emitter->buffer.last - emitter->buffer.start)) {
emitter->buffer.last = emitter->buffer.start;
emitter->buffer.pointer = emitter->buffer.start;
return 1;
}
else {
return yaml_emitter_set_writer_error(emitter, "write error");
}
}
/* Recode the buffer into the raw buffer. */
low = (emitter->encoding == YAML_UTF16LE_ENCODING ? 0 : 1);
high = (emitter->encoding == YAML_UTF16LE_ENCODING ? 1 : 0);
while (emitter->buffer.pointer != emitter->buffer.last)
{
unsigned char octet;
unsigned int width;
unsigned int value;
size_t k;
/*
* See the "reader.c" code for more details on UTF-8 encoding. Note
* that we assume that the buffer contains a valid UTF-8 sequence.
*/
/* Read the next UTF-8 character. */
octet = emitter->buffer.pointer[0];
width = (octet & 0x80) == 0x00 ? 1 :
(octet & 0xE0) == 0xC0 ? 2 :
(octet & 0xF0) == 0xE0 ? 3 :
(octet & 0xF8) == 0xF0 ? 4 : 0;
value = (octet & 0x80) == 0x00 ? octet & 0x7F :
(octet & 0xE0) == 0xC0 ? octet & 0x1F :
(octet & 0xF0) == 0xE0 ? octet & 0x0F :
(octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
for (k = 1; k < width; k ++) {
octet = emitter->buffer.pointer[k];
value = (value << 6) + (octet & 0x3F);
}
emitter->buffer.pointer += width;
/* Write the character. */
if (value < 0x10000)
{
emitter->raw_buffer.last[high] = value >> 8;
emitter->raw_buffer.last[low] = value & 0xFF;
emitter->raw_buffer.last += 2;
}
else
{
/* Write the character using a surrogate pair (check "reader.c"). */
value -= 0x10000;
emitter->raw_buffer.last[high] = 0xD8 + (value >> 18);
emitter->raw_buffer.last[low] = (value >> 10) & 0xFF;
emitter->raw_buffer.last[high+2] = 0xDC + ((value >> 8) & 0xFF);
emitter->raw_buffer.last[low+2] = value & 0xFF;
emitter->raw_buffer.last += 4;
}
}
/* Write the raw buffer. */
if (emitter->write_handler(emitter->write_handler_data,
emitter->raw_buffer.start,
emitter->raw_buffer.last - emitter->raw_buffer.start)) {
emitter->buffer.last = emitter->buffer.start;
emitter->buffer.pointer = emitter->buffer.start;
emitter->raw_buffer.last = emitter->raw_buffer.start;
emitter->raw_buffer.pointer = emitter->raw_buffer.start;
return 1;
}
else {
return yaml_emitter_set_writer_error(emitter, "write error");
}
}
| {
"language": "C"
} |
/*
* Copyright (c) 2014 Genome Research Ltd.
* Author(s): James Bonfield
*
* 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 names Genome Research Ltd and Wellcome Trust Sanger
* Institute 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 GENOME RESEARCH LTD 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 GENOME RESEARCH
* LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RANS_STATIC_H
#define RANS_STATIC_H
#ifdef __cplusplus
extern "C" {
#endif
unsigned char *rans_compress(unsigned char *in, unsigned int in_size,
unsigned int *out_size, int order);
unsigned char *rans_uncompress(unsigned char *in, unsigned int in_size,
unsigned int *out_size);
#ifdef __cplusplus
}
#endif
#endif /* RANS_STATIC_H */
| {
"language": "C"
} |
/*-------------------------------------------------------------------------
*
* common.c
* Catalog routines used by pg_dump; long ago these were shared
* by another dump tool, but not anymore.
*
* Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/bin/pg_dump/common.c
*
*-------------------------------------------------------------------------
*/
#include "postgres_fe.h"
#include "pg_backup_archiver.h"
#include "pg_backup_utils.h"
#include "pg_dump.h"
#include <ctype.h>
#include "catalog/pg_class_d.h"
#include "fe_utils/string_utils.h"
/*
* Variables for mapping DumpId to DumpableObject
*/
static DumpableObject **dumpIdMap = NULL;
static int allocedDumpIds = 0;
static DumpId lastDumpId = 0;
/*
* Variables for mapping CatalogId to DumpableObject
*/
static bool catalogIdMapValid = false;
static DumpableObject **catalogIdMap = NULL;
static int numCatalogIds = 0;
/*
* These variables are static to avoid the notational cruft of having to pass
* them into findTableByOid() and friends. For each of these arrays, we build
* a sorted-by-OID index array immediately after the objects are fetched,
* and then we use binary search in findTableByOid() and friends. (qsort'ing
* the object arrays themselves would be simpler, but it doesn't work because
* pg_dump.c may have already established pointers between items.)
*/
static DumpableObject **tblinfoindex;
static DumpableObject **typinfoindex;
static DumpableObject **funinfoindex;
static DumpableObject **oprinfoindex;
static DumpableObject **collinfoindex;
static DumpableObject **nspinfoindex;
static DumpableObject **extinfoindex;
static int numTables;
static int numTypes;
static int numFuncs;
static int numOperators;
static int numCollations;
static int numNamespaces;
static int numExtensions;
/* This is an array of object identities, not actual DumpableObjects */
static ExtensionMemberId *extmembers;
static int numextmembers;
static void flagInhTables(Archive *fout, TableInfo *tbinfo, int numTables,
InhInfo *inhinfo, int numInherits);
static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int numTables);
static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables);
static DumpableObject **buildIndexArray(void *objArray, int numObjs,
Size objSize);
static int DOCatalogIdCompare(const void *p1, const void *p2);
static int ExtensionMemberIdCompare(const void *p1, const void *p2);
static void findParentsByOid(TableInfo *self,
InhInfo *inhinfo, int numInherits);
static int strInArray(const char *pattern, char **arr, int arr_size);
static IndxInfo *findIndexByOid(Oid oid, DumpableObject **idxinfoindex,
int numIndexes);
/*
* getSchemaData
* Collect information about all potentially dumpable objects
*/
TableInfo *
getSchemaData(Archive *fout, int *numTablesPtr)
{
TableInfo *tblinfo;
TypeInfo *typinfo;
FuncInfo *funinfo;
OprInfo *oprinfo;
CollInfo *collinfo;
NamespaceInfo *nspinfo;
ExtensionInfo *extinfo;
InhInfo *inhinfo;
int numAggregates;
int numInherits;
int numRules;
int numProcLangs;
int numCasts;
int numTransforms;
int numAccessMethods;
int numOpclasses;
int numOpfamilies;
int numConversions;
int numTSParsers;
int numTSTemplates;
int numTSDicts;
int numTSConfigs;
int numForeignDataWrappers;
int numForeignServers;
int numDefaultACLs;
int numEventTriggers;
/*
* We must read extensions and extension membership info first, because
* extension membership needs to be consultable during decisions about
* whether other objects are to be dumped.
*/
pg_log_info("reading extensions");
extinfo = getExtensions(fout, &numExtensions);
extinfoindex = buildIndexArray(extinfo, numExtensions, sizeof(ExtensionInfo));
pg_log_info("identifying extension members");
getExtensionMembership(fout, extinfo, numExtensions);
pg_log_info("reading schemas");
nspinfo = getNamespaces(fout, &numNamespaces);
nspinfoindex = buildIndexArray(nspinfo, numNamespaces, sizeof(NamespaceInfo));
/*
* getTables should be done as soon as possible, so as to minimize the
* window between starting our transaction and acquiring per-table locks.
* However, we have to do getNamespaces first because the tables get
* linked to their containing namespaces during getTables.
*/
pg_log_info("reading user-defined tables");
tblinfo = getTables(fout, &numTables);
tblinfoindex = buildIndexArray(tblinfo, numTables, sizeof(TableInfo));
/* Do this after we've built tblinfoindex */
getOwnedSeqs(fout, tblinfo, numTables);
pg_log_info("reading user-defined functions");
funinfo = getFuncs(fout, &numFuncs);
funinfoindex = buildIndexArray(funinfo, numFuncs, sizeof(FuncInfo));
/* this must be after getTables and getFuncs */
pg_log_info("reading user-defined types");
typinfo = getTypes(fout, &numTypes);
typinfoindex = buildIndexArray(typinfo, numTypes, sizeof(TypeInfo));
/* this must be after getFuncs, too */
pg_log_info("reading procedural languages");
getProcLangs(fout, &numProcLangs);
pg_log_info("reading user-defined aggregate functions");
getAggregates(fout, &numAggregates);
pg_log_info("reading user-defined operators");
oprinfo = getOperators(fout, &numOperators);
oprinfoindex = buildIndexArray(oprinfo, numOperators, sizeof(OprInfo));
pg_log_info("reading user-defined access methods");
getAccessMethods(fout, &numAccessMethods);
pg_log_info("reading user-defined operator classes");
getOpclasses(fout, &numOpclasses);
pg_log_info("reading user-defined operator families");
getOpfamilies(fout, &numOpfamilies);
pg_log_info("reading user-defined text search parsers");
getTSParsers(fout, &numTSParsers);
pg_log_info("reading user-defined text search templates");
getTSTemplates(fout, &numTSTemplates);
pg_log_info("reading user-defined text search dictionaries");
getTSDictionaries(fout, &numTSDicts);
pg_log_info("reading user-defined text search configurations");
getTSConfigurations(fout, &numTSConfigs);
pg_log_info("reading user-defined foreign-data wrappers");
getForeignDataWrappers(fout, &numForeignDataWrappers);
pg_log_info("reading user-defined foreign servers");
getForeignServers(fout, &numForeignServers);
pg_log_info("reading default privileges");
getDefaultACLs(fout, &numDefaultACLs);
pg_log_info("reading user-defined collations");
collinfo = getCollations(fout, &numCollations);
collinfoindex = buildIndexArray(collinfo, numCollations, sizeof(CollInfo));
pg_log_info("reading user-defined conversions");
getConversions(fout, &numConversions);
pg_log_info("reading type casts");
getCasts(fout, &numCasts);
pg_log_info("reading transforms");
getTransforms(fout, &numTransforms);
pg_log_info("reading table inheritance information");
inhinfo = getInherits(fout, &numInherits);
pg_log_info("reading event triggers");
getEventTriggers(fout, &numEventTriggers);
/* Identify extension configuration tables that should be dumped */
pg_log_info("finding extension tables");
processExtensionTables(fout, extinfo, numExtensions);
/* Link tables to parents, mark parents of target tables interesting */
pg_log_info("finding inheritance relationships");
flagInhTables(fout, tblinfo, numTables, inhinfo, numInherits);
pg_log_info("reading column info for interesting tables");
getTableAttrs(fout, tblinfo, numTables);
pg_log_info("flagging inherited columns in subtables");
flagInhAttrs(fout->dopt, tblinfo, numTables);
pg_log_info("reading indexes");
getIndexes(fout, tblinfo, numTables);
pg_log_info("flagging indexes in partitioned tables");
flagInhIndexes(fout, tblinfo, numTables);
pg_log_info("reading extended statistics");
getExtendedStatistics(fout);
pg_log_info("reading constraints");
getConstraints(fout, tblinfo, numTables);
pg_log_info("reading triggers");
getTriggers(fout, tblinfo, numTables);
pg_log_info("reading rewrite rules");
getRules(fout, &numRules);
pg_log_info("reading policies");
getPolicies(fout, tblinfo, numTables);
pg_log_info("reading publications");
getPublications(fout);
pg_log_info("reading publication membership");
getPublicationTables(fout, tblinfo, numTables);
pg_log_info("reading subscriptions");
getSubscriptions(fout);
*numTablesPtr = numTables;
return tblinfo;
}
/* flagInhTables -
* Fill in parent link fields of tables for which we need that information,
* and mark parents of target tables as interesting
*
* Note that only direct ancestors of targets are marked interesting.
* This is sufficient; we don't much care whether they inherited their
* attributes or not.
*
* modifies tblinfo
*/
static void
flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
InhInfo *inhinfo, int numInherits)
{
DumpOptions *dopt = fout->dopt;
int i,
j;
for (i = 0; i < numTables; i++)
{
bool find_parents = true;
bool mark_parents = true;
/* Some kinds never have parents */
if (tblinfo[i].relkind == RELKIND_SEQUENCE ||
tblinfo[i].relkind == RELKIND_VIEW ||
tblinfo[i].relkind == RELKIND_MATVIEW)
continue;
/*
* Normally, we don't bother computing anything for non-target tables,
* but if load-via-partition-root is specified, we gather information
* on every partition in the system so that getRootTableInfo can trace
* from any given to leaf partition all the way up to the root. (We
* don't need to mark them as interesting for getTableAttrs, though.)
*/
if (!tblinfo[i].dobj.dump)
{
mark_parents = false;
if (!dopt->load_via_partition_root ||
!tblinfo[i].ispartition)
find_parents = false;
}
/* If needed, find all the immediate parent tables. */
if (find_parents)
findParentsByOid(&tblinfo[i], inhinfo, numInherits);
/*
* If needed, mark the parents as interesting for getTableAttrs and
* getIndexes.
*/
if (mark_parents)
{
int numParents = tblinfo[i].numParents;
TableInfo **parents = tblinfo[i].parents;
for (j = 0; j < numParents; j++)
parents[j]->interesting = true;
}
}
}
/*
* flagInhIndexes -
* Create AttachIndexInfo objects for partitioned indexes, and add
* appropriate dependency links.
*/
static void
flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
{
int i,
j,
k;
DumpableObject ***parentIndexArray;
parentIndexArray = (DumpableObject ***)
pg_malloc0(getMaxDumpId() * sizeof(DumpableObject **));
for (i = 0; i < numTables; i++)
{
TableInfo *parenttbl;
IndexAttachInfo *attachinfo;
if (!tblinfo[i].ispartition || tblinfo[i].numParents == 0)
continue;
Assert(tblinfo[i].numParents == 1);
parenttbl = tblinfo[i].parents[0];
/*
* We need access to each parent table's index list, but there is no
* index to cover them outside of this function. To avoid having to
* sort every parent table's indexes each time we come across each of
* its partitions, create an indexed array for each parent the first
* time it is required.
*/
if (parentIndexArray[parenttbl->dobj.dumpId] == NULL)
parentIndexArray[parenttbl->dobj.dumpId] =
buildIndexArray(parenttbl->indexes,
parenttbl->numIndexes,
sizeof(IndxInfo));
attachinfo = (IndexAttachInfo *)
pg_malloc0(tblinfo[i].numIndexes * sizeof(IndexAttachInfo));
for (j = 0, k = 0; j < tblinfo[i].numIndexes; j++)
{
IndxInfo *index = &(tblinfo[i].indexes[j]);
IndxInfo *parentidx;
if (index->parentidx == 0)
continue;
parentidx = findIndexByOid(index->parentidx,
parentIndexArray[parenttbl->dobj.dumpId],
parenttbl->numIndexes);
if (parentidx == NULL)
continue;
attachinfo[k].dobj.objType = DO_INDEX_ATTACH;
attachinfo[k].dobj.catId.tableoid = 0;
attachinfo[k].dobj.catId.oid = 0;
AssignDumpId(&attachinfo[k].dobj);
attachinfo[k].dobj.name = pg_strdup(index->dobj.name);
attachinfo[k].dobj.namespace = index->indextable->dobj.namespace;
attachinfo[k].parentIdx = parentidx;
attachinfo[k].partitionIdx = index;
/*
* We must state the DO_INDEX_ATTACH object's dependencies
* explicitly, since it will not match anything in pg_depend.
*
* Give it dependencies on both the partition index and the parent
* index, so that it will not be executed till both of those
* exist. (There's no need to care what order those are created
* in.)
*
* In addition, give it dependencies on the indexes' underlying
* tables. This does nothing of great value so far as serial
* restore ordering goes, but it ensures that a parallel restore
* will not try to run the ATTACH concurrently with other
* operations on those tables.
*/
addObjectDependency(&attachinfo[k].dobj, index->dobj.dumpId);
addObjectDependency(&attachinfo[k].dobj, parentidx->dobj.dumpId);
addObjectDependency(&attachinfo[k].dobj,
index->indextable->dobj.dumpId);
addObjectDependency(&attachinfo[k].dobj,
parentidx->indextable->dobj.dumpId);
k++;
}
}
for (i = 0; i < numTables; i++)
if (parentIndexArray[i])
pg_free(parentIndexArray[i]);
pg_free(parentIndexArray);
}
/* flagInhAttrs -
* for each dumpable table in tblinfo, flag its inherited attributes
*
* What we need to do here is detect child columns that inherit NOT NULL
* bits from their parents (so that we needn't specify that again for the
* child) and child columns that have DEFAULT NULL when their parents had
* some non-null default. In the latter case, we make up a dummy AttrDefInfo
* object so that we'll correctly emit the necessary DEFAULT NULL clause;
* otherwise the backend will apply an inherited default to the column.
*
* modifies tblinfo
*/
static void
flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables)
{
int i,
j,
k;
for (i = 0; i < numTables; i++)
{
TableInfo *tbinfo = &(tblinfo[i]);
int numParents;
TableInfo **parents;
/* Some kinds never have parents */
if (tbinfo->relkind == RELKIND_SEQUENCE ||
tbinfo->relkind == RELKIND_VIEW ||
tbinfo->relkind == RELKIND_MATVIEW)
continue;
/* Don't bother computing anything for non-target tables, either */
if (!tbinfo->dobj.dump)
continue;
numParents = tbinfo->numParents;
parents = tbinfo->parents;
if (numParents == 0)
continue; /* nothing to see here, move along */
/* For each column, search for matching column names in parent(s) */
for (j = 0; j < tbinfo->numatts; j++)
{
bool foundNotNull; /* Attr was NOT NULL in a parent */
bool foundDefault; /* Found a default in a parent */
/* no point in examining dropped columns */
if (tbinfo->attisdropped[j])
continue;
foundNotNull = false;
foundDefault = false;
for (k = 0; k < numParents; k++)
{
TableInfo *parent = parents[k];
int inhAttrInd;
inhAttrInd = strInArray(tbinfo->attnames[j],
parent->attnames,
parent->numatts);
if (inhAttrInd >= 0)
{
foundNotNull |= parent->notnull[inhAttrInd];
foundDefault |= (parent->attrdefs[inhAttrInd] != NULL);
}
}
/* Remember if we found inherited NOT NULL */
tbinfo->inhNotNull[j] = foundNotNull;
/* Manufacture a DEFAULT NULL clause if necessary */
if (foundDefault && tbinfo->attrdefs[j] == NULL)
{
AttrDefInfo *attrDef;
attrDef = (AttrDefInfo *) pg_malloc(sizeof(AttrDefInfo));
attrDef->dobj.objType = DO_ATTRDEF;
attrDef->dobj.catId.tableoid = 0;
attrDef->dobj.catId.oid = 0;
AssignDumpId(&attrDef->dobj);
attrDef->dobj.name = pg_strdup(tbinfo->dobj.name);
attrDef->dobj.namespace = tbinfo->dobj.namespace;
attrDef->dobj.dump = tbinfo->dobj.dump;
attrDef->adtable = tbinfo;
attrDef->adnum = j + 1;
attrDef->adef_expr = pg_strdup("NULL");
/* Will column be dumped explicitly? */
if (shouldPrintColumn(dopt, tbinfo, j))
{
attrDef->separate = false;
/* No dependency needed: NULL cannot have dependencies */
}
else
{
/* column will be suppressed, print default separately */
attrDef->separate = true;
/* ensure it comes out after the table */
addObjectDependency(&attrDef->dobj,
tbinfo->dobj.dumpId);
}
tbinfo->attrdefs[j] = attrDef;
}
}
}
}
/*
* AssignDumpId
* Given a newly-created dumpable object, assign a dump ID,
* and enter the object into the lookup table.
*
* The caller is expected to have filled in objType and catId,
* but not any of the other standard fields of a DumpableObject.
*/
void
AssignDumpId(DumpableObject *dobj)
{
dobj->dumpId = ++lastDumpId;
dobj->name = NULL; /* must be set later */
dobj->namespace = NULL; /* may be set later */
dobj->dump = DUMP_COMPONENT_ALL; /* default assumption */
dobj->ext_member = false; /* default assumption */
dobj->dependencies = NULL;
dobj->nDeps = 0;
dobj->allocDeps = 0;
while (dobj->dumpId >= allocedDumpIds)
{
int newAlloc;
if (allocedDumpIds <= 0)
{
newAlloc = 256;
dumpIdMap = (DumpableObject **)
pg_malloc(newAlloc * sizeof(DumpableObject *));
}
else
{
newAlloc = allocedDumpIds * 2;
dumpIdMap = (DumpableObject **)
pg_realloc(dumpIdMap, newAlloc * sizeof(DumpableObject *));
}
memset(dumpIdMap + allocedDumpIds, 0,
(newAlloc - allocedDumpIds) * sizeof(DumpableObject *));
allocedDumpIds = newAlloc;
}
dumpIdMap[dobj->dumpId] = dobj;
/* mark catalogIdMap invalid, but don't rebuild it yet */
catalogIdMapValid = false;
}
/*
* Assign a DumpId that's not tied to a DumpableObject.
*
* This is used when creating a "fixed" ArchiveEntry that doesn't need to
* participate in the sorting logic.
*/
DumpId
createDumpId(void)
{
return ++lastDumpId;
}
/*
* Return the largest DumpId so far assigned
*/
DumpId
getMaxDumpId(void)
{
return lastDumpId;
}
/*
* Find a DumpableObject by dump ID
*
* Returns NULL for invalid ID
*/
DumpableObject *
findObjectByDumpId(DumpId dumpId)
{
if (dumpId <= 0 || dumpId >= allocedDumpIds)
return NULL; /* out of range? */
return dumpIdMap[dumpId];
}
/*
* Find a DumpableObject by catalog ID
*
* Returns NULL for unknown ID
*
* We use binary search in a sorted list that is built on first call.
* If AssignDumpId() and findObjectByCatalogId() calls were freely intermixed,
* the code would work, but possibly be very slow. In the current usage
* pattern that does not happen, indeed we build the list at most twice.
*/
DumpableObject *
findObjectByCatalogId(CatalogId catalogId)
{
DumpableObject **low;
DumpableObject **high;
if (!catalogIdMapValid)
{
if (catalogIdMap)
free(catalogIdMap);
getDumpableObjects(&catalogIdMap, &numCatalogIds);
if (numCatalogIds > 1)
qsort((void *) catalogIdMap, numCatalogIds,
sizeof(DumpableObject *), DOCatalogIdCompare);
catalogIdMapValid = true;
}
/*
* We could use bsearch() here, but the notational cruft of calling
* bsearch is nearly as bad as doing it ourselves; and the generalized
* bsearch function is noticeably slower as well.
*/
if (numCatalogIds <= 0)
return NULL;
low = catalogIdMap;
high = catalogIdMap + (numCatalogIds - 1);
while (low <= high)
{
DumpableObject **middle;
int difference;
middle = low + (high - low) / 2;
/* comparison must match DOCatalogIdCompare, below */
difference = oidcmp((*middle)->catId.oid, catalogId.oid);
if (difference == 0)
difference = oidcmp((*middle)->catId.tableoid, catalogId.tableoid);
if (difference == 0)
return *middle;
else if (difference < 0)
low = middle + 1;
else
high = middle - 1;
}
return NULL;
}
/*
* Find a DumpableObject by OID, in a pre-sorted array of one type of object
*
* Returns NULL for unknown OID
*/
static DumpableObject *
findObjectByOid(Oid oid, DumpableObject **indexArray, int numObjs)
{
DumpableObject **low;
DumpableObject **high;
/*
* This is the same as findObjectByCatalogId except we assume we need not
* look at table OID because the objects are all the same type.
*
* We could use bsearch() here, but the notational cruft of calling
* bsearch is nearly as bad as doing it ourselves; and the generalized
* bsearch function is noticeably slower as well.
*/
if (numObjs <= 0)
return NULL;
low = indexArray;
high = indexArray + (numObjs - 1);
while (low <= high)
{
DumpableObject **middle;
int difference;
middle = low + (high - low) / 2;
difference = oidcmp((*middle)->catId.oid, oid);
if (difference == 0)
return *middle;
else if (difference < 0)
low = middle + 1;
else
high = middle - 1;
}
return NULL;
}
/*
* Build an index array of DumpableObject pointers, sorted by OID
*/
static DumpableObject **
buildIndexArray(void *objArray, int numObjs, Size objSize)
{
DumpableObject **ptrs;
int i;
ptrs = (DumpableObject **) pg_malloc(numObjs * sizeof(DumpableObject *));
for (i = 0; i < numObjs; i++)
ptrs[i] = (DumpableObject *) ((char *) objArray + i * objSize);
/* We can use DOCatalogIdCompare to sort since its first key is OID */
if (numObjs > 1)
qsort((void *) ptrs, numObjs, sizeof(DumpableObject *),
DOCatalogIdCompare);
return ptrs;
}
/*
* qsort comparator for pointers to DumpableObjects
*/
static int
DOCatalogIdCompare(const void *p1, const void *p2)
{
const DumpableObject *obj1 = *(DumpableObject *const *) p1;
const DumpableObject *obj2 = *(DumpableObject *const *) p2;
int cmpval;
/*
* Compare OID first since it's usually unique, whereas there will only be
* a few distinct values of tableoid.
*/
cmpval = oidcmp(obj1->catId.oid, obj2->catId.oid);
if (cmpval == 0)
cmpval = oidcmp(obj1->catId.tableoid, obj2->catId.tableoid);
return cmpval;
}
/*
* Build an array of pointers to all known dumpable objects
*
* This simply creates a modifiable copy of the internal map.
*/
void
getDumpableObjects(DumpableObject ***objs, int *numObjs)
{
int i,
j;
*objs = (DumpableObject **)
pg_malloc(allocedDumpIds * sizeof(DumpableObject *));
j = 0;
for (i = 1; i < allocedDumpIds; i++)
{
if (dumpIdMap[i])
(*objs)[j++] = dumpIdMap[i];
}
*numObjs = j;
}
/*
* Add a dependency link to a DumpableObject
*
* Note: duplicate dependencies are currently not eliminated
*/
void
addObjectDependency(DumpableObject *dobj, DumpId refId)
{
if (dobj->nDeps >= dobj->allocDeps)
{
if (dobj->allocDeps <= 0)
{
dobj->allocDeps = 16;
dobj->dependencies = (DumpId *)
pg_malloc(dobj->allocDeps * sizeof(DumpId));
}
else
{
dobj->allocDeps *= 2;
dobj->dependencies = (DumpId *)
pg_realloc(dobj->dependencies,
dobj->allocDeps * sizeof(DumpId));
}
}
dobj->dependencies[dobj->nDeps++] = refId;
}
/*
* Remove a dependency link from a DumpableObject
*
* If there are multiple links, all are removed
*/
void
removeObjectDependency(DumpableObject *dobj, DumpId refId)
{
int i;
int j = 0;
for (i = 0; i < dobj->nDeps; i++)
{
if (dobj->dependencies[i] != refId)
dobj->dependencies[j++] = dobj->dependencies[i];
}
dobj->nDeps = j;
}
/*
* findTableByOid
* finds the entry (in tblinfo) of the table with the given oid
* returns NULL if not found
*/
TableInfo *
findTableByOid(Oid oid)
{
return (TableInfo *) findObjectByOid(oid, tblinfoindex, numTables);
}
/*
* findTypeByOid
* finds the entry (in typinfo) of the type with the given oid
* returns NULL if not found
*/
TypeInfo *
findTypeByOid(Oid oid)
{
return (TypeInfo *) findObjectByOid(oid, typinfoindex, numTypes);
}
/*
* findFuncByOid
* finds the entry (in funinfo) of the function with the given oid
* returns NULL if not found
*/
FuncInfo *
findFuncByOid(Oid oid)
{
return (FuncInfo *) findObjectByOid(oid, funinfoindex, numFuncs);
}
/*
* findOprByOid
* finds the entry (in oprinfo) of the operator with the given oid
* returns NULL if not found
*/
OprInfo *
findOprByOid(Oid oid)
{
return (OprInfo *) findObjectByOid(oid, oprinfoindex, numOperators);
}
/*
* findCollationByOid
* finds the entry (in collinfo) of the collation with the given oid
* returns NULL if not found
*/
CollInfo *
findCollationByOid(Oid oid)
{
return (CollInfo *) findObjectByOid(oid, collinfoindex, numCollations);
}
/*
* findNamespaceByOid
* finds the entry (in nspinfo) of the namespace with the given oid
* returns NULL if not found
*/
NamespaceInfo *
findNamespaceByOid(Oid oid)
{
return (NamespaceInfo *) findObjectByOid(oid, nspinfoindex, numNamespaces);
}
/*
* findExtensionByOid
* finds the entry (in extinfo) of the extension with the given oid
* returns NULL if not found
*/
ExtensionInfo *
findExtensionByOid(Oid oid)
{
return (ExtensionInfo *) findObjectByOid(oid, extinfoindex, numExtensions);
}
/*
* findIndexByOid
* find the entry of the index with the given oid
*
* This one's signature is different from the previous ones because we lack a
* global array of all indexes, so caller must pass their array as argument.
*/
static IndxInfo *
findIndexByOid(Oid oid, DumpableObject **idxinfoindex, int numIndexes)
{
return (IndxInfo *) findObjectByOid(oid, idxinfoindex, numIndexes);
}
/*
* setExtensionMembership
* accept and save data about which objects belong to extensions
*/
void
setExtensionMembership(ExtensionMemberId *extmems, int nextmems)
{
/* Sort array in preparation for binary searches */
if (nextmems > 1)
qsort((void *) extmems, nextmems, sizeof(ExtensionMemberId),
ExtensionMemberIdCompare);
/* And save */
extmembers = extmems;
numextmembers = nextmems;
}
/*
* findOwningExtension
* return owning extension for specified catalog ID, or NULL if none
*/
ExtensionInfo *
findOwningExtension(CatalogId catalogId)
{
ExtensionMemberId *low;
ExtensionMemberId *high;
/*
* We could use bsearch() here, but the notational cruft of calling
* bsearch is nearly as bad as doing it ourselves; and the generalized
* bsearch function is noticeably slower as well.
*/
if (numextmembers <= 0)
return NULL;
low = extmembers;
high = extmembers + (numextmembers - 1);
while (low <= high)
{
ExtensionMemberId *middle;
int difference;
middle = low + (high - low) / 2;
/* comparison must match ExtensionMemberIdCompare, below */
difference = oidcmp(middle->catId.oid, catalogId.oid);
if (difference == 0)
difference = oidcmp(middle->catId.tableoid, catalogId.tableoid);
if (difference == 0)
return middle->ext;
else if (difference < 0)
low = middle + 1;
else
high = middle - 1;
}
return NULL;
}
/*
* qsort comparator for ExtensionMemberIds
*/
static int
ExtensionMemberIdCompare(const void *p1, const void *p2)
{
const ExtensionMemberId *obj1 = (const ExtensionMemberId *) p1;
const ExtensionMemberId *obj2 = (const ExtensionMemberId *) p2;
int cmpval;
/*
* Compare OID first since it's usually unique, whereas there will only be
* a few distinct values of tableoid.
*/
cmpval = oidcmp(obj1->catId.oid, obj2->catId.oid);
if (cmpval == 0)
cmpval = oidcmp(obj1->catId.tableoid, obj2->catId.tableoid);
return cmpval;
}
/*
* findParentsByOid
* find a table's parents in tblinfo[]
*/
static void
findParentsByOid(TableInfo *self,
InhInfo *inhinfo, int numInherits)
{
Oid oid = self->dobj.catId.oid;
int i,
j;
int numParents;
numParents = 0;
for (i = 0; i < numInherits; i++)
{
if (inhinfo[i].inhrelid == oid)
numParents++;
}
self->numParents = numParents;
if (numParents > 0)
{
self->parents = (TableInfo **)
pg_malloc(sizeof(TableInfo *) * numParents);
j = 0;
for (i = 0; i < numInherits; i++)
{
if (inhinfo[i].inhrelid == oid)
{
TableInfo *parent;
parent = findTableByOid(inhinfo[i].inhparent);
if (parent == NULL)
{
pg_log_error("failed sanity check, parent OID %u of table \"%s\" (OID %u) not found",
inhinfo[i].inhparent,
self->dobj.name,
oid);
exit_nicely(1);
}
self->parents[j++] = parent;
}
}
}
else
self->parents = NULL;
}
/*
* parseOidArray
* parse a string of numbers delimited by spaces into a character array
*
* Note: actually this is used for both Oids and potentially-signed
* attribute numbers. This should cause no trouble, but we could split
* the function into two functions with different argument types if it does.
*/
void
parseOidArray(const char *str, Oid *array, int arraysize)
{
int j,
argNum;
char temp[100];
char s;
argNum = 0;
j = 0;
for (;;)
{
s = *str++;
if (s == ' ' || s == '\0')
{
if (j > 0)
{
if (argNum >= arraysize)
{
pg_log_error("could not parse numeric array \"%s\": too many numbers", str);
exit_nicely(1);
}
temp[j] = '\0';
array[argNum++] = atooid(temp);
j = 0;
}
if (s == '\0')
break;
}
else
{
if (!(isdigit((unsigned char) s) || s == '-') ||
j >= sizeof(temp) - 1)
{
pg_log_error("could not parse numeric array \"%s\": invalid character in number", str);
exit_nicely(1);
}
temp[j++] = s;
}
}
while (argNum < arraysize)
array[argNum++] = InvalidOid;
}
/*
* strInArray:
* takes in a string and a string array and the number of elements in the
* string array.
* returns the index if the string is somewhere in the array, -1 otherwise
*/
static int
strInArray(const char *pattern, char **arr, int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
{
if (strcmp(pattern, arr[i]) == 0)
return i;
}
return -1;
}
| {
"language": "C"
} |
/*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* File: main_usb.c
*
* Purpose: driver entry for initial, open, close, tx and rx.
*
* Author: Lyndon Chen
*
* Date: Dec 8, 2005
*
* Functions:
*
* vt6656_probe - module initial (insmod) driver entry
* vnt_free_tx_bufs - free tx buffer function
* vnt_init_registers- initial MAC & BBP & RF internal registers.
*
* Revision History:
*/
#undef __NO_VERSION__
#include <linux/etherdevice.h>
#include <linux/file.h>
#include "device.h"
#include "card.h"
#include "baseband.h"
#include "mac.h"
#include "power.h"
#include "wcmd.h"
#include "rxtx.h"
#include "dpc.h"
#include "rf.h"
#include "firmware.h"
#include "usbpipe.h"
#include "channel.h"
#include "int.h"
/*
* define module options
*/
/* version information */
#define DRIVER_AUTHOR \
"VIA Networking Technologies, Inc., <lyndonchen@vntek.com.tw>"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION(DEVICE_FULL_DRV_NAM);
#define RX_DESC_DEF0 64
static int vnt_rx_buffers = RX_DESC_DEF0;
module_param_named(rx_buffers, vnt_rx_buffers, int, 0644);
MODULE_PARM_DESC(rx_buffers, "Number of receive usb rx buffers");
#define TX_DESC_DEF0 64
static int vnt_tx_buffers = TX_DESC_DEF0;
module_param_named(tx_buffers, vnt_tx_buffers, int, 0644);
MODULE_PARM_DESC(tx_buffers, "Number of receive usb tx buffers");
#define RTS_THRESH_DEF 2347
#define FRAG_THRESH_DEF 2346
#define SHORT_RETRY_DEF 8
#define LONG_RETRY_DEF 4
/* BasebandType[] baseband type selected
0: indicate 802.11a type
1: indicate 802.11b type
2: indicate 802.11g type
*/
#define BBP_TYPE_DEF 2
/*
* Static vars definitions
*/
static struct usb_device_id vt6656_table[] = {
{USB_DEVICE(VNT_USB_VENDOR_ID, VNT_USB_PRODUCT_ID)},
{}
};
static void vnt_set_options(struct vnt_private *priv)
{
/* Set number of TX buffers */
if (vnt_tx_buffers < CB_MIN_TX_DESC || vnt_tx_buffers > CB_MAX_TX_DESC)
priv->num_tx_context = TX_DESC_DEF0;
else
priv->num_tx_context = vnt_tx_buffers;
/* Set number of RX buffers */
if (vnt_rx_buffers < CB_MIN_RX_DESC || vnt_rx_buffers > CB_MAX_RX_DESC)
priv->num_rcb = RX_DESC_DEF0;
else
priv->num_rcb = vnt_rx_buffers;
priv->short_retry_limit = SHORT_RETRY_DEF;
priv->long_retry_limit = LONG_RETRY_DEF;
priv->op_mode = NL80211_IFTYPE_UNSPECIFIED;
priv->bb_type = BBP_TYPE_DEF;
priv->packet_type = priv->bb_type;
priv->auto_fb_ctrl = AUTO_FB_0;
priv->preamble_type = 0;
priv->exist_sw_net_addr = false;
}
/*
* initialization of MAC & BBP registers
*/
static int vnt_init_registers(struct vnt_private *priv)
{
struct vnt_cmd_card_init *init_cmd = &priv->init_command;
struct vnt_rsp_card_init *init_rsp = &priv->init_response;
u8 antenna;
int ii;
int status = STATUS_SUCCESS;
u8 tmp;
u8 calib_tx_iq = 0, calib_tx_dc = 0, calib_rx_iq = 0;
dev_dbg(&priv->usb->dev, "---->INIbInitAdapter. [%d][%d]\n",
DEVICE_INIT_COLD, priv->packet_type);
if (!vnt_check_firmware_version(priv)) {
if (vnt_download_firmware(priv) == true) {
if (vnt_firmware_branch_to_sram(priv) == false) {
dev_dbg(&priv->usb->dev,
" vnt_firmware_branch_to_sram fail\n");
return false;
}
} else {
dev_dbg(&priv->usb->dev, "FIRMWAREbDownload fail\n");
return false;
}
}
if (!vnt_vt3184_init(priv)) {
dev_dbg(&priv->usb->dev, "vnt_vt3184_init fail\n");
return false;
}
init_cmd->init_class = DEVICE_INIT_COLD;
init_cmd->exist_sw_net_addr = priv->exist_sw_net_addr;
for (ii = 0; ii < 6; ii++)
init_cmd->sw_net_addr[ii] = priv->current_net_addr[ii];
init_cmd->short_retry_limit = priv->short_retry_limit;
init_cmd->long_retry_limit = priv->long_retry_limit;
/* issue card_init command to device */
status = vnt_control_out(priv,
MESSAGE_TYPE_CARDINIT, 0, 0,
sizeof(struct vnt_cmd_card_init), (u8 *)init_cmd);
if (status != STATUS_SUCCESS) {
dev_dbg(&priv->usb->dev, "Issue Card init fail\n");
return false;
}
status = vnt_control_in(priv, MESSAGE_TYPE_INIT_RSP, 0, 0,
sizeof(struct vnt_rsp_card_init), (u8 *)init_rsp);
if (status != STATUS_SUCCESS) {
dev_dbg(&priv->usb->dev,
"Cardinit request in status fail!\n");
return false;
}
/* local ID for AES functions */
status = vnt_control_in(priv, MESSAGE_TYPE_READ,
MAC_REG_LOCALID, MESSAGE_REQUEST_MACREG, 1,
&priv->local_id);
if (status != STATUS_SUCCESS)
return false;
/* do MACbSoftwareReset in MACvInitialize */
priv->top_ofdm_basic_rate = RATE_24M;
priv->top_cck_basic_rate = RATE_1M;
/* target to IF pin while programming to RF chip */
priv->power = 0xFF;
priv->cck_pwr = priv->eeprom[EEP_OFS_PWR_CCK];
priv->ofdm_pwr_g = priv->eeprom[EEP_OFS_PWR_OFDMG];
/* load power table */
for (ii = 0; ii < 14; ii++) {
priv->cck_pwr_tbl[ii] =
priv->eeprom[ii + EEP_OFS_CCK_PWR_TBL];
if (priv->cck_pwr_tbl[ii] == 0)
priv->cck_pwr_tbl[ii] = priv->cck_pwr;
priv->ofdm_pwr_tbl[ii] =
priv->eeprom[ii + EEP_OFS_OFDM_PWR_TBL];
if (priv->ofdm_pwr_tbl[ii] == 0)
priv->ofdm_pwr_tbl[ii] = priv->ofdm_pwr_g;
}
/*
* original zonetype is USA, but custom zonetype is Europe,
* then need to recover 12, 13, 14 channels with 11 channel
*/
for (ii = 11; ii < 14; ii++) {
priv->cck_pwr_tbl[ii] = priv->cck_pwr_tbl[10];
priv->ofdm_pwr_tbl[ii] = priv->ofdm_pwr_tbl[10];
}
priv->ofdm_pwr_a = 0x34; /* same as RFbMA2829SelectChannel */
/* load OFDM A power table */
for (ii = 0; ii < CB_MAX_CHANNEL_5G; ii++) {
priv->ofdm_a_pwr_tbl[ii] =
priv->eeprom[ii + EEP_OFS_OFDMA_PWR_TBL];
if (priv->ofdm_a_pwr_tbl[ii] == 0)
priv->ofdm_a_pwr_tbl[ii] = priv->ofdm_pwr_a;
}
antenna = priv->eeprom[EEP_OFS_ANTENNA];
if (antenna & EEP_ANTINV)
priv->tx_rx_ant_inv = true;
else
priv->tx_rx_ant_inv = false;
antenna &= (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
if (antenna == 0) /* if not set default is both */
antenna = (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
if (antenna == (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN)) {
priv->tx_antenna_mode = ANT_B;
priv->rx_antenna_sel = 1;
if (priv->tx_rx_ant_inv == true)
priv->rx_antenna_mode = ANT_A;
else
priv->rx_antenna_mode = ANT_B;
} else {
priv->rx_antenna_sel = 0;
if (antenna & EEP_ANTENNA_AUX) {
priv->tx_antenna_mode = ANT_A;
if (priv->tx_rx_ant_inv == true)
priv->rx_antenna_mode = ANT_B;
else
priv->rx_antenna_mode = ANT_A;
} else {
priv->tx_antenna_mode = ANT_B;
if (priv->tx_rx_ant_inv == true)
priv->rx_antenna_mode = ANT_A;
else
priv->rx_antenna_mode = ANT_B;
}
}
/* Set initial antenna mode */
vnt_set_antenna_mode(priv, priv->rx_antenna_mode);
/* get Auto Fall Back type */
priv->auto_fb_ctrl = AUTO_FB_0;
/* default Auto Mode */
priv->bb_type = BB_TYPE_11G;
/* get RFType */
priv->rf_type = init_rsp->rf_type;
/* load vt3266 calibration parameters in EEPROM */
if (priv->rf_type == RF_VT3226D0) {
if ((priv->eeprom[EEP_OFS_MAJOR_VER] == 0x1) &&
(priv->eeprom[EEP_OFS_MINOR_VER] >= 0x4)) {
calib_tx_iq = priv->eeprom[EEP_OFS_CALIB_TX_IQ];
calib_tx_dc = priv->eeprom[EEP_OFS_CALIB_TX_DC];
calib_rx_iq = priv->eeprom[EEP_OFS_CALIB_RX_IQ];
if (calib_tx_iq || calib_tx_dc || calib_rx_iq) {
/* CR255, enable TX/RX IQ and
DC compensation mode */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xff,
0x03);
/* CR251, TX I/Q Imbalance Calibration */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xfb,
calib_tx_iq);
/* CR252, TX DC-Offset Calibration */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xfC,
calib_tx_dc);
/* CR253, RX I/Q Imbalance Calibration */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xfd,
calib_rx_iq);
} else {
/* CR255, turn off
BB Calibration compensation */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xff,
0x0);
}
}
}
/* get permanent network address */
memcpy(priv->permanent_net_addr, init_rsp->net_addr, 6);
ether_addr_copy(priv->current_net_addr, priv->permanent_net_addr);
/* if exist SW network address, use it */
dev_dbg(&priv->usb->dev, "Network address = %pM\n",
priv->current_net_addr);
/*
* set BB and packet type at the same time
* set Short Slot Time, xIFS, and RSPINF
*/
if (priv->bb_type == BB_TYPE_11A)
priv->short_slot_time = true;
else
priv->short_slot_time = false;
vnt_set_short_slot_time(priv);
priv->radio_ctl = priv->eeprom[EEP_OFS_RADIOCTL];
if ((priv->radio_ctl & EEP_RADIOCTL_ENABLE) != 0) {
status = vnt_control_in(priv, MESSAGE_TYPE_READ,
MAC_REG_GPIOCTL1, MESSAGE_REQUEST_MACREG, 1, &tmp);
if (status != STATUS_SUCCESS)
return false;
if ((tmp & GPIO3_DATA) == 0)
vnt_mac_reg_bits_on(priv, MAC_REG_GPIOCTL1,
GPIO3_INTMD);
else
vnt_mac_reg_bits_off(priv, MAC_REG_GPIOCTL1,
GPIO3_INTMD);
}
vnt_mac_set_led(priv, LEDSTS_TMLEN, 0x38);
vnt_mac_set_led(priv, LEDSTS_STS, LEDSTS_SLOW);
vnt_mac_reg_bits_on(priv, MAC_REG_GPIOCTL0, 0x01);
vnt_radio_power_on(priv);
dev_dbg(&priv->usb->dev, "<----INIbInitAdapter Exit\n");
return true;
}
static void vnt_free_tx_bufs(struct vnt_private *priv)
{
struct vnt_usb_send_context *tx_context;
int ii;
for (ii = 0; ii < priv->num_tx_context; ii++) {
tx_context = priv->tx_context[ii];
/* deallocate URBs */
if (tx_context->urb) {
usb_kill_urb(tx_context->urb);
usb_free_urb(tx_context->urb);
}
kfree(tx_context);
}
}
static void vnt_free_rx_bufs(struct vnt_private *priv)
{
struct vnt_rcb *rcb;
int ii;
for (ii = 0; ii < priv->num_rcb; ii++) {
rcb = priv->rcb[ii];
if (!rcb)
continue;
/* deallocate URBs */
if (rcb->urb) {
usb_kill_urb(rcb->urb);
usb_free_urb(rcb->urb);
}
/* deallocate skb */
if (rcb->skb)
dev_kfree_skb(rcb->skb);
kfree(rcb);
}
}
static void usb_device_reset(struct vnt_private *priv)
{
int status;
status = usb_reset_device(priv->usb);
if (status)
dev_warn(&priv->usb->dev,
"usb_device_reset fail status=%d\n", status);
}
static void vnt_free_int_bufs(struct vnt_private *priv)
{
kfree(priv->int_buf.data_buf);
}
static bool vnt_alloc_bufs(struct vnt_private *priv)
{
struct vnt_usb_send_context *tx_context;
struct vnt_rcb *rcb;
int ii;
for (ii = 0; ii < priv->num_tx_context; ii++) {
tx_context = kmalloc(sizeof(struct vnt_usb_send_context),
GFP_KERNEL);
if (tx_context == NULL)
goto free_tx;
priv->tx_context[ii] = tx_context;
tx_context->priv = priv;
tx_context->pkt_no = ii;
/* allocate URBs */
tx_context->urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!tx_context->urb) {
dev_err(&priv->usb->dev, "alloc tx urb failed\n");
goto free_tx;
}
tx_context->in_use = false;
}
for (ii = 0; ii < priv->num_rcb; ii++) {
priv->rcb[ii] = kzalloc(sizeof(struct vnt_rcb), GFP_KERNEL);
if (!priv->rcb[ii]) {
dev_err(&priv->usb->dev,
"failed to allocate rcb no %d\n", ii);
goto free_rx_tx;
}
rcb = priv->rcb[ii];
rcb->priv = priv;
/* allocate URBs */
rcb->urb = usb_alloc_urb(0, GFP_ATOMIC);
if (rcb->urb == NULL) {
dev_err(&priv->usb->dev, "Failed to alloc rx urb\n");
goto free_rx_tx;
}
rcb->skb = dev_alloc_skb(priv->rx_buf_sz);
if (rcb->skb == NULL)
goto free_rx_tx;
rcb->in_use = false;
/* submit rx urb */
if (vnt_submit_rx_urb(priv, rcb))
goto free_rx_tx;
}
priv->interrupt_urb = usb_alloc_urb(0, GFP_ATOMIC);
if (priv->interrupt_urb == NULL) {
dev_err(&priv->usb->dev, "Failed to alloc int urb\n");
goto free_rx_tx;
}
priv->int_buf.data_buf = kmalloc(MAX_INTERRUPT_SIZE, GFP_KERNEL);
if (priv->int_buf.data_buf == NULL) {
usb_free_urb(priv->interrupt_urb);
goto free_rx_tx;
}
return true;
free_rx_tx:
vnt_free_rx_bufs(priv);
free_tx:
vnt_free_tx_bufs(priv);
return false;
}
static void vnt_tx_80211(struct ieee80211_hw *hw,
struct ieee80211_tx_control *control, struct sk_buff *skb)
{
struct vnt_private *priv = hw->priv;
if (vnt_tx_packet(priv, skb))
ieee80211_free_txskb(hw, skb);
}
static int vnt_start(struct ieee80211_hw *hw)
{
struct vnt_private *priv = hw->priv;
priv->rx_buf_sz = MAX_TOTAL_SIZE_WITH_ALL_HEADERS;
if (!vnt_alloc_bufs(priv)) {
dev_dbg(&priv->usb->dev, "vnt_alloc_bufs fail...\n");
return -ENOMEM;
}
clear_bit(DEVICE_FLAGS_DISCONNECTED, &priv->flags);
if (vnt_init_registers(priv) == false) {
dev_dbg(&priv->usb->dev, " init register fail\n");
goto free_all;
}
priv->int_interval = 1; /* bInterval is set to 1 */
vnt_int_start_interrupt(priv);
ieee80211_wake_queues(hw);
return 0;
free_all:
vnt_free_rx_bufs(priv);
vnt_free_tx_bufs(priv);
vnt_free_int_bufs(priv);
usb_kill_urb(priv->interrupt_urb);
usb_free_urb(priv->interrupt_urb);
return -ENOMEM;
}
static void vnt_stop(struct ieee80211_hw *hw)
{
struct vnt_private *priv = hw->priv;
int i;
if (!priv)
return;
for (i = 0; i < MAX_KEY_TABLE; i++)
vnt_mac_disable_keyentry(priv, i);
/* clear all keys */
priv->key_entry_inuse = 0;
if (!test_bit(DEVICE_FLAGS_UNPLUG, &priv->flags))
vnt_mac_shutdown(priv);
ieee80211_stop_queues(hw);
set_bit(DEVICE_FLAGS_DISCONNECTED, &priv->flags);
cancel_delayed_work_sync(&priv->run_command_work);
priv->cmd_running = false;
vnt_free_tx_bufs(priv);
vnt_free_rx_bufs(priv);
vnt_free_int_bufs(priv);
usb_kill_urb(priv->interrupt_urb);
usb_free_urb(priv->interrupt_urb);
}
static int vnt_add_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
priv->vif = vif;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
break;
case NL80211_IFTYPE_ADHOC:
vnt_mac_reg_bits_off(priv, MAC_REG_RCR, RCR_UNICAST);
vnt_mac_reg_bits_on(priv, MAC_REG_HOSTCR, HOSTCR_ADHOC);
break;
case NL80211_IFTYPE_AP:
vnt_mac_reg_bits_off(priv, MAC_REG_RCR, RCR_UNICAST);
vnt_mac_reg_bits_on(priv, MAC_REG_HOSTCR, HOSTCR_AP);
break;
default:
return -EOPNOTSUPP;
}
priv->op_mode = vif->type;
vnt_set_bss_mode(priv);
/* LED blink on TX */
vnt_mac_set_led(priv, LEDSTS_STS, LEDSTS_INTER);
return 0;
}
static void vnt_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
break;
case NL80211_IFTYPE_ADHOC:
vnt_mac_reg_bits_off(priv, MAC_REG_TCR, TCR_AUTOBCNTX);
vnt_mac_reg_bits_off(priv, MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
vnt_mac_reg_bits_off(priv, MAC_REG_HOSTCR, HOSTCR_ADHOC);
break;
case NL80211_IFTYPE_AP:
vnt_mac_reg_bits_off(priv, MAC_REG_TCR, TCR_AUTOBCNTX);
vnt_mac_reg_bits_off(priv, MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
vnt_mac_reg_bits_off(priv, MAC_REG_HOSTCR, HOSTCR_AP);
break;
default:
break;
}
vnt_radio_power_off(priv);
priv->op_mode = NL80211_IFTYPE_UNSPECIFIED;
/* LED slow blink */
vnt_mac_set_led(priv, LEDSTS_STS, LEDSTS_SLOW);
}
static int vnt_config(struct ieee80211_hw *hw, u32 changed)
{
struct vnt_private *priv = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
u8 bb_type;
if (changed & IEEE80211_CONF_CHANGE_PS) {
if (conf->flags & IEEE80211_CONF_PS)
vnt_enable_power_saving(priv, conf->listen_interval);
else
vnt_disable_power_saving(priv);
}
if ((changed & IEEE80211_CONF_CHANGE_CHANNEL) ||
(conf->flags & IEEE80211_CONF_OFFCHANNEL)) {
vnt_set_channel(priv, conf->chandef.chan->hw_value);
if (conf->chandef.chan->band == IEEE80211_BAND_5GHZ)
bb_type = BB_TYPE_11A;
else
bb_type = BB_TYPE_11G;
if (priv->bb_type != bb_type) {
priv->bb_type = bb_type;
vnt_set_bss_mode(priv);
}
}
if (changed & IEEE80211_CONF_CHANGE_POWER) {
if (priv->bb_type == BB_TYPE_11B)
priv->current_rate = RATE_1M;
else
priv->current_rate = RATE_54M;
vnt_rf_setpower(priv, priv->current_rate,
conf->chandef.chan->hw_value);
}
return 0;
}
static void vnt_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, struct ieee80211_bss_conf *conf,
u32 changed)
{
struct vnt_private *priv = hw->priv;
priv->current_aid = conf->aid;
if (changed & BSS_CHANGED_BSSID && conf->bssid)
vnt_mac_set_bssid_addr(priv, (u8 *)conf->bssid);
if (changed & BSS_CHANGED_BASIC_RATES) {
priv->basic_rates = conf->basic_rates;
vnt_update_top_rates(priv);
dev_dbg(&priv->usb->dev, "basic rates %x\n", conf->basic_rates);
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
if (conf->use_short_preamble) {
vnt_mac_enable_barker_preamble_mode(priv);
priv->preamble_type = true;
} else {
vnt_mac_disable_barker_preamble_mode(priv);
priv->preamble_type = false;
}
}
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
if (conf->use_cts_prot)
vnt_mac_enable_protect_mode(priv);
else
vnt_mac_disable_protect_mode(priv);
}
if (changed & BSS_CHANGED_ERP_SLOT) {
if (conf->use_short_slot)
priv->short_slot_time = true;
else
priv->short_slot_time = false;
vnt_set_short_slot_time(priv);
vnt_set_vga_gain_offset(priv, priv->bb_vga[0]);
vnt_update_pre_ed_threshold(priv, false);
}
if (changed & BSS_CHANGED_TXPOWER)
vnt_rf_setpower(priv, priv->current_rate,
conf->chandef.chan->hw_value);
if (changed & BSS_CHANGED_BEACON_ENABLED) {
dev_dbg(&priv->usb->dev,
"Beacon enable %d\n", conf->enable_beacon);
if (conf->enable_beacon) {
vnt_beacon_enable(priv, vif, conf);
vnt_mac_reg_bits_on(priv, MAC_REG_TCR, TCR_AUTOBCNTX);
} else {
vnt_mac_reg_bits_off(priv, MAC_REG_TCR, TCR_AUTOBCNTX);
}
}
if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_BEACON_INFO) &&
priv->op_mode != NL80211_IFTYPE_AP) {
if (conf->assoc && conf->beacon_rate) {
vnt_mac_reg_bits_on(priv, MAC_REG_TFTCTL,
TFTCTL_TSFCNTREN);
vnt_adjust_tsf(priv, conf->beacon_rate->hw_value,
conf->sync_tsf, priv->current_tsf);
vnt_mac_set_beacon_interval(priv, conf->beacon_int);
vnt_reset_next_tbtt(priv, conf->beacon_int);
} else {
vnt_clear_current_tsf(priv);
vnt_mac_reg_bits_off(priv, MAC_REG_TFTCTL,
TFTCTL_TSFCNTREN);
}
}
}
static u64 vnt_prepare_multicast(struct ieee80211_hw *hw,
struct netdev_hw_addr_list *mc_list)
{
struct vnt_private *priv = hw->priv;
struct netdev_hw_addr *ha;
u64 mc_filter = 0;
u32 bit_nr = 0;
netdev_hw_addr_list_for_each(ha, mc_list) {
bit_nr = ether_crc(ETH_ALEN, ha->addr) >> 26;
mc_filter |= 1ULL << (bit_nr & 0x3f);
}
priv->mc_list_count = mc_list->count;
return mc_filter;
}
static void vnt_configure(struct ieee80211_hw *hw,
unsigned int changed_flags, unsigned int *total_flags, u64 multicast)
{
struct vnt_private *priv = hw->priv;
u8 rx_mode = 0;
int rc;
*total_flags &= FIF_ALLMULTI | FIF_OTHER_BSS | FIF_BCN_PRBRESP_PROMISC;
rc = vnt_control_in(priv, MESSAGE_TYPE_READ, MAC_REG_RCR,
MESSAGE_REQUEST_MACREG, sizeof(u8), &rx_mode);
if (!rc)
rx_mode = RCR_MULTICAST | RCR_BROADCAST;
dev_dbg(&priv->usb->dev, "rx mode in = %x\n", rx_mode);
if (changed_flags & FIF_ALLMULTI) {
if (*total_flags & FIF_ALLMULTI) {
if (priv->mc_list_count > 2)
vnt_mac_set_filter(priv, ~0);
else
vnt_mac_set_filter(priv, multicast);
rx_mode |= RCR_MULTICAST | RCR_BROADCAST;
} else {
rx_mode &= ~(RCR_MULTICAST | RCR_BROADCAST);
}
}
if (changed_flags & (FIF_OTHER_BSS | FIF_BCN_PRBRESP_PROMISC)) {
if (*total_flags & (FIF_OTHER_BSS | FIF_BCN_PRBRESP_PROMISC))
rx_mode &= ~RCR_BSSID;
else
rx_mode |= RCR_BSSID;
}
vnt_control_out_u8(priv, MESSAGE_REQUEST_MACREG, MAC_REG_RCR, rx_mode);
dev_dbg(&priv->usb->dev, "rx mode out= %x\n", rx_mode);
}
static int vnt_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct vnt_private *priv = hw->priv;
switch (cmd) {
case SET_KEY:
if (vnt_set_keys(hw, sta, vif, key))
return -EOPNOTSUPP;
break;
case DISABLE_KEY:
if (test_bit(key->hw_key_idx, &priv->key_entry_inuse))
clear_bit(key->hw_key_idx, &priv->key_entry_inuse);
default:
break;
}
return 0;
}
static void vnt_sw_scan_start(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
const u8 *addr)
{
struct vnt_private *priv = hw->priv;
vnt_set_bss_mode(priv);
/* Set max sensitivity*/
vnt_update_pre_ed_threshold(priv, true);
}
static void vnt_sw_scan_complete(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
/* Return sensitivity to channel level*/
vnt_update_pre_ed_threshold(priv, false);
}
static int vnt_get_stats(struct ieee80211_hw *hw,
struct ieee80211_low_level_stats *stats)
{
struct vnt_private *priv = hw->priv;
memcpy(stats, &priv->low_stats, sizeof(*stats));
return 0;
}
static u64 vnt_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
return priv->current_tsf;
}
static void vnt_set_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
u64 tsf)
{
struct vnt_private *priv = hw->priv;
vnt_update_next_tbtt(priv, tsf, vif->bss_conf.beacon_int);
}
static void vnt_reset_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
vnt_mac_reg_bits_off(priv, MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
vnt_clear_current_tsf(priv);
}
static const struct ieee80211_ops vnt_mac_ops = {
.tx = vnt_tx_80211,
.start = vnt_start,
.stop = vnt_stop,
.add_interface = vnt_add_interface,
.remove_interface = vnt_remove_interface,
.config = vnt_config,
.bss_info_changed = vnt_bss_info_changed,
.prepare_multicast = vnt_prepare_multicast,
.configure_filter = vnt_configure,
.set_key = vnt_set_key,
.sw_scan_start = vnt_sw_scan_start,
.sw_scan_complete = vnt_sw_scan_complete,
.get_stats = vnt_get_stats,
.get_tsf = vnt_get_tsf,
.set_tsf = vnt_set_tsf,
.reset_tsf = vnt_reset_tsf,
};
int vnt_init(struct vnt_private *priv)
{
if (!(vnt_init_registers(priv)))
return -EAGAIN;
SET_IEEE80211_PERM_ADDR(priv->hw, priv->permanent_net_addr);
vnt_init_bands(priv);
if (ieee80211_register_hw(priv->hw))
return -ENODEV;
priv->mac_hw = true;
vnt_radio_power_off(priv);
return 0;
}
static int
vt6656_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *udev;
struct vnt_private *priv;
struct ieee80211_hw *hw;
struct wiphy *wiphy;
int rc = 0;
udev = usb_get_dev(interface_to_usbdev(intf));
dev_notice(&udev->dev, "%s Ver. %s\n",
DEVICE_FULL_DRV_NAM, DEVICE_VERSION);
dev_notice(&udev->dev,
"Copyright (c) 2004 VIA Networking Technologies, Inc.\n");
hw = ieee80211_alloc_hw(sizeof(struct vnt_private), &vnt_mac_ops);
if (!hw) {
dev_err(&udev->dev, "could not register ieee80211_hw\n");
rc = -ENOMEM;
goto err_nomem;
}
priv = hw->priv;
priv->hw = hw;
priv->usb = udev;
vnt_set_options(priv);
spin_lock_init(&priv->lock);
mutex_init(&priv->usb_lock);
INIT_DELAYED_WORK(&priv->run_command_work, vnt_run_command);
usb_set_intfdata(intf, priv);
wiphy = priv->hw->wiphy;
wiphy->frag_threshold = FRAG_THRESH_DEF;
wiphy->rts_threshold = RTS_THRESH_DEF;
wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) | BIT(NL80211_IFTYPE_AP);
ieee80211_hw_set(priv->hw, TIMING_BEACON_ONLY);
ieee80211_hw_set(priv->hw, SIGNAL_DBM);
ieee80211_hw_set(priv->hw, RX_INCLUDES_FCS);
ieee80211_hw_set(priv->hw, REPORTS_TX_ACK_STATUS);
ieee80211_hw_set(priv->hw, SUPPORTS_PS);
priv->hw->max_signal = 100;
SET_IEEE80211_DEV(priv->hw, &intf->dev);
usb_device_reset(priv);
clear_bit(DEVICE_FLAGS_DISCONNECTED, &priv->flags);
vnt_reset_command_timer(priv);
vnt_schedule_command(priv, WLAN_CMD_INIT_MAC80211);
return 0;
err_nomem:
usb_put_dev(udev);
return rc;
}
static void vt6656_disconnect(struct usb_interface *intf)
{
struct vnt_private *priv = usb_get_intfdata(intf);
if (!priv)
return;
if (priv->mac_hw)
ieee80211_unregister_hw(priv->hw);
usb_set_intfdata(intf, NULL);
usb_put_dev(interface_to_usbdev(intf));
set_bit(DEVICE_FLAGS_UNPLUG, &priv->flags);
ieee80211_free_hw(priv->hw);
}
#ifdef CONFIG_PM
static int vt6656_suspend(struct usb_interface *intf, pm_message_t message)
{
return 0;
}
static int vt6656_resume(struct usb_interface *intf)
{
return 0;
}
#endif /* CONFIG_PM */
MODULE_DEVICE_TABLE(usb, vt6656_table);
static struct usb_driver vt6656_driver = {
.name = DEVICE_NAME,
.probe = vt6656_probe,
.disconnect = vt6656_disconnect,
.id_table = vt6656_table,
#ifdef CONFIG_PM
.suspend = vt6656_suspend,
.resume = vt6656_resume,
#endif /* CONFIG_PM */
};
module_usb_driver(vt6656_driver);
| {
"language": "C"
} |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* SiRF audio codec driver
*
* Copyright (c) 2011 Cambridge Silicon Radio Limited, a CSR plc group company.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/regmap.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include <sound/soc.h>
#include <sound/dmaengine_pcm.h>
#include "sirf-audio-codec.h"
struct sirf_audio_codec {
struct clk *clk;
struct regmap *regmap;
u32 reg_ctrl0, reg_ctrl1;
};
static const char * const input_mode_mux[] = {"Single-ended",
"Differential"};
static const struct soc_enum input_mode_mux_enum =
SOC_ENUM_SINGLE(AUDIO_IC_CODEC_CTRL1, 4, 2, input_mode_mux);
static const struct snd_kcontrol_new sirf_audio_codec_input_mode_control =
SOC_DAPM_ENUM("Route", input_mode_mux_enum);
static const DECLARE_TLV_DB_SCALE(playback_vol_tlv, -12400, 100, 0);
static const DECLARE_TLV_DB_SCALE(capture_vol_tlv_prima2, 500, 100, 0);
static const DECLARE_TLV_DB_RANGE(capture_vol_tlv_atlas6,
0, 7, TLV_DB_SCALE_ITEM(-100, 100, 0),
0x22, 0x3F, TLV_DB_SCALE_ITEM(700, 100, 0),
);
static struct snd_kcontrol_new volume_controls_atlas6[] = {
SOC_DOUBLE_TLV("Playback Volume", AUDIO_IC_CODEC_CTRL0, 21, 14,
0x7F, 0, playback_vol_tlv),
SOC_DOUBLE_TLV("Capture Volume", AUDIO_IC_CODEC_CTRL1, 16, 10,
0x3F, 0, capture_vol_tlv_atlas6),
};
static struct snd_kcontrol_new volume_controls_prima2[] = {
SOC_DOUBLE_TLV("Speaker Volume", AUDIO_IC_CODEC_CTRL0, 21, 14,
0x7F, 0, playback_vol_tlv),
SOC_DOUBLE_TLV("Capture Volume", AUDIO_IC_CODEC_CTRL1, 15, 10,
0x1F, 0, capture_vol_tlv_prima2),
};
static struct snd_kcontrol_new left_input_path_controls[] = {
SOC_DAPM_SINGLE("Line Left Switch", AUDIO_IC_CODEC_CTRL1, 6, 1, 0),
SOC_DAPM_SINGLE("Mic Left Switch", AUDIO_IC_CODEC_CTRL1, 3, 1, 0),
};
static struct snd_kcontrol_new right_input_path_controls[] = {
SOC_DAPM_SINGLE("Line Right Switch", AUDIO_IC_CODEC_CTRL1, 5, 1, 0),
SOC_DAPM_SINGLE("Mic Right Switch", AUDIO_IC_CODEC_CTRL1, 2, 1, 0),
};
static struct snd_kcontrol_new left_dac_to_hp_left_amp_switch_control =
SOC_DAPM_SINGLE("Switch", AUDIO_IC_CODEC_CTRL0, 9, 1, 0);
static struct snd_kcontrol_new left_dac_to_hp_right_amp_switch_control =
SOC_DAPM_SINGLE("Switch", AUDIO_IC_CODEC_CTRL0, 8, 1, 0);
static struct snd_kcontrol_new right_dac_to_hp_left_amp_switch_control =
SOC_DAPM_SINGLE("Switch", AUDIO_IC_CODEC_CTRL0, 7, 1, 0);
static struct snd_kcontrol_new right_dac_to_hp_right_amp_switch_control =
SOC_DAPM_SINGLE("Switch", AUDIO_IC_CODEC_CTRL0, 6, 1, 0);
static struct snd_kcontrol_new left_dac_to_speaker_lineout_switch_control =
SOC_DAPM_SINGLE("Switch", AUDIO_IC_CODEC_CTRL0, 11, 1, 0);
static struct snd_kcontrol_new right_dac_to_speaker_lineout_switch_control =
SOC_DAPM_SINGLE("Switch", AUDIO_IC_CODEC_CTRL0, 10, 1, 0);
/* After enable adc, Delay 200ms to avoid pop noise */
static int adc_enable_delay_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
switch (event) {
case SND_SOC_DAPM_POST_PMU:
msleep(200);
break;
default:
break;
}
return 0;
}
static void enable_and_reset_codec(struct regmap *regmap,
u32 codec_enable_bits, u32 codec_reset_bits)
{
regmap_update_bits(regmap, AUDIO_IC_CODEC_CTRL1,
codec_enable_bits | codec_reset_bits,
codec_enable_bits);
msleep(20);
regmap_update_bits(regmap, AUDIO_IC_CODEC_CTRL1,
codec_reset_bits, codec_reset_bits);
}
static int atlas6_codec_enable_and_reset_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
#define ATLAS6_CODEC_ENABLE_BITS (1 << 29)
#define ATLAS6_CODEC_RESET_BITS (1 << 28)
struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm);
struct sirf_audio_codec *sirf_audio_codec = snd_soc_component_get_drvdata(component);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
enable_and_reset_codec(sirf_audio_codec->regmap,
ATLAS6_CODEC_ENABLE_BITS, ATLAS6_CODEC_RESET_BITS);
break;
case SND_SOC_DAPM_POST_PMD:
regmap_update_bits(sirf_audio_codec->regmap,
AUDIO_IC_CODEC_CTRL1, ATLAS6_CODEC_ENABLE_BITS, 0);
break;
default:
break;
}
return 0;
}
static int prima2_codec_enable_and_reset_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
#define PRIMA2_CODEC_ENABLE_BITS (1 << 27)
#define PRIMA2_CODEC_RESET_BITS (1 << 26)
struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm);
struct sirf_audio_codec *sirf_audio_codec = snd_soc_component_get_drvdata(component);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
enable_and_reset_codec(sirf_audio_codec->regmap,
PRIMA2_CODEC_ENABLE_BITS, PRIMA2_CODEC_RESET_BITS);
break;
case SND_SOC_DAPM_POST_PMD:
regmap_update_bits(sirf_audio_codec->regmap,
AUDIO_IC_CODEC_CTRL1, PRIMA2_CODEC_ENABLE_BITS, 0);
break;
default:
break;
}
return 0;
}
static const struct snd_soc_dapm_widget atlas6_output_driver_dapm_widgets[] = {
SND_SOC_DAPM_OUT_DRV("HP Left Driver", AUDIO_IC_CODEC_CTRL1,
25, 0, NULL, 0),
SND_SOC_DAPM_OUT_DRV("HP Right Driver", AUDIO_IC_CODEC_CTRL1,
26, 0, NULL, 0),
SND_SOC_DAPM_OUT_DRV("Speaker Driver", AUDIO_IC_CODEC_CTRL1,
27, 0, NULL, 0),
};
static const struct snd_soc_dapm_widget prima2_output_driver_dapm_widgets[] = {
SND_SOC_DAPM_OUT_DRV("HP Left Driver", AUDIO_IC_CODEC_CTRL1,
23, 0, NULL, 0),
SND_SOC_DAPM_OUT_DRV("HP Right Driver", AUDIO_IC_CODEC_CTRL1,
24, 0, NULL, 0),
SND_SOC_DAPM_OUT_DRV("Speaker Driver", AUDIO_IC_CODEC_CTRL1,
25, 0, NULL, 0),
};
static const struct snd_soc_dapm_widget atlas6_codec_clock_dapm_widget =
SND_SOC_DAPM_SUPPLY("codecclk", SND_SOC_NOPM, 0, 0,
atlas6_codec_enable_and_reset_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD);
static const struct snd_soc_dapm_widget prima2_codec_clock_dapm_widget =
SND_SOC_DAPM_SUPPLY("codecclk", SND_SOC_NOPM, 0, 0,
prima2_codec_enable_and_reset_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD);
static const struct snd_soc_dapm_widget sirf_audio_codec_dapm_widgets[] = {
SND_SOC_DAPM_DAC("DAC left", NULL, AUDIO_IC_CODEC_CTRL0, 1, 0),
SND_SOC_DAPM_DAC("DAC right", NULL, AUDIO_IC_CODEC_CTRL0, 0, 0),
SND_SOC_DAPM_SWITCH("Left dac to hp left amp", SND_SOC_NOPM, 0, 0,
&left_dac_to_hp_left_amp_switch_control),
SND_SOC_DAPM_SWITCH("Left dac to hp right amp", SND_SOC_NOPM, 0, 0,
&left_dac_to_hp_right_amp_switch_control),
SND_SOC_DAPM_SWITCH("Right dac to hp left amp", SND_SOC_NOPM, 0, 0,
&right_dac_to_hp_left_amp_switch_control),
SND_SOC_DAPM_SWITCH("Right dac to hp right amp", SND_SOC_NOPM, 0, 0,
&right_dac_to_hp_right_amp_switch_control),
SND_SOC_DAPM_OUT_DRV("HP amp left driver", AUDIO_IC_CODEC_CTRL0, 3, 0,
NULL, 0),
SND_SOC_DAPM_OUT_DRV("HP amp right driver", AUDIO_IC_CODEC_CTRL0, 3, 0,
NULL, 0),
SND_SOC_DAPM_SWITCH("Left dac to speaker lineout", SND_SOC_NOPM, 0, 0,
&left_dac_to_speaker_lineout_switch_control),
SND_SOC_DAPM_SWITCH("Right dac to speaker lineout", SND_SOC_NOPM, 0, 0,
&right_dac_to_speaker_lineout_switch_control),
SND_SOC_DAPM_OUT_DRV("Speaker amp driver", AUDIO_IC_CODEC_CTRL0, 4, 0,
NULL, 0),
SND_SOC_DAPM_OUTPUT("HPOUTL"),
SND_SOC_DAPM_OUTPUT("HPOUTR"),
SND_SOC_DAPM_OUTPUT("SPKOUT"),
SND_SOC_DAPM_ADC_E("ADC left", NULL, AUDIO_IC_CODEC_CTRL1, 8, 0,
adc_enable_delay_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_ADC_E("ADC right", NULL, AUDIO_IC_CODEC_CTRL1, 7, 0,
adc_enable_delay_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER("Left PGA mixer", AUDIO_IC_CODEC_CTRL1, 1, 0,
&left_input_path_controls[0],
ARRAY_SIZE(left_input_path_controls)),
SND_SOC_DAPM_MIXER("Right PGA mixer", AUDIO_IC_CODEC_CTRL1, 0, 0,
&right_input_path_controls[0],
ARRAY_SIZE(right_input_path_controls)),
SND_SOC_DAPM_MUX("Mic input mode mux", SND_SOC_NOPM, 0, 0,
&sirf_audio_codec_input_mode_control),
SND_SOC_DAPM_MICBIAS("Mic Bias", AUDIO_IC_CODEC_PWR, 3, 0),
SND_SOC_DAPM_INPUT("MICIN1"),
SND_SOC_DAPM_INPUT("MICIN2"),
SND_SOC_DAPM_INPUT("LINEIN1"),
SND_SOC_DAPM_INPUT("LINEIN2"),
SND_SOC_DAPM_SUPPLY("HSL Phase Opposite", AUDIO_IC_CODEC_CTRL0,
30, 0, NULL, 0),
};
static const struct snd_soc_dapm_route sirf_audio_codec_map[] = {
{"SPKOUT", NULL, "Speaker Driver"},
{"Speaker Driver", NULL, "Speaker amp driver"},
{"Speaker amp driver", NULL, "Left dac to speaker lineout"},
{"Speaker amp driver", NULL, "Right dac to speaker lineout"},
{"Left dac to speaker lineout", "Switch", "DAC left"},
{"Right dac to speaker lineout", "Switch", "DAC right"},
{"HPOUTL", NULL, "HP Left Driver"},
{"HPOUTR", NULL, "HP Right Driver"},
{"HP Left Driver", NULL, "HP amp left driver"},
{"HP Right Driver", NULL, "HP amp right driver"},
{"HP amp left driver", NULL, "Right dac to hp left amp"},
{"HP amp right driver", NULL , "Right dac to hp right amp"},
{"HP amp left driver", NULL, "Left dac to hp left amp"},
{"HP amp right driver", NULL , "Right dac to hp right amp"},
{"Right dac to hp left amp", "Switch", "DAC left"},
{"Right dac to hp right amp", "Switch", "DAC right"},
{"Left dac to hp left amp", "Switch", "DAC left"},
{"Left dac to hp right amp", "Switch", "DAC right"},
{"DAC left", NULL, "codecclk"},
{"DAC right", NULL, "codecclk"},
{"DAC left", NULL, "Playback"},
{"DAC right", NULL, "Playback"},
{"DAC left", NULL, "HSL Phase Opposite"},
{"DAC right", NULL, "HSL Phase Opposite"},
{"Capture", NULL, "ADC left"},
{"Capture", NULL, "ADC right"},
{"ADC left", NULL, "codecclk"},
{"ADC right", NULL, "codecclk"},
{"ADC left", NULL, "Left PGA mixer"},
{"ADC right", NULL, "Right PGA mixer"},
{"Left PGA mixer", "Line Left Switch", "LINEIN2"},
{"Right PGA mixer", "Line Right Switch", "LINEIN1"},
{"Left PGA mixer", "Mic Left Switch", "MICIN2"},
{"Right PGA mixer", "Mic Right Switch", "Mic input mode mux"},
{"Mic input mode mux", "Single-ended", "MICIN1"},
{"Mic input mode mux", "Differential", "MICIN1"},
};
static void sirf_audio_codec_tx_enable(struct sirf_audio_codec *sirf_audio_codec)
{
regmap_update_bits(sirf_audio_codec->regmap, AUDIO_PORT_IC_TXFIFO_OP,
AUDIO_FIFO_RESET, AUDIO_FIFO_RESET);
regmap_update_bits(sirf_audio_codec->regmap, AUDIO_PORT_IC_TXFIFO_OP,
AUDIO_FIFO_RESET, ~AUDIO_FIFO_RESET);
regmap_write(sirf_audio_codec->regmap, AUDIO_PORT_IC_TXFIFO_INT_MSK, 0);
regmap_write(sirf_audio_codec->regmap, AUDIO_PORT_IC_TXFIFO_OP, 0);
regmap_update_bits(sirf_audio_codec->regmap, AUDIO_PORT_IC_TXFIFO_OP,
AUDIO_FIFO_START, AUDIO_FIFO_START);
regmap_update_bits(sirf_audio_codec->regmap,
AUDIO_PORT_IC_CODEC_TX_CTRL, IC_TX_ENABLE, IC_TX_ENABLE);
}
static void sirf_audio_codec_tx_disable(struct sirf_audio_codec *sirf_audio_codec)
{
regmap_write(sirf_audio_codec->regmap, AUDIO_PORT_IC_TXFIFO_OP, 0);
regmap_update_bits(sirf_audio_codec->regmap,
AUDIO_PORT_IC_CODEC_TX_CTRL, IC_TX_ENABLE, ~IC_TX_ENABLE);
}
static void sirf_audio_codec_rx_enable(struct sirf_audio_codec *sirf_audio_codec,
int channels)
{
regmap_update_bits(sirf_audio_codec->regmap, AUDIO_PORT_IC_RXFIFO_OP,
AUDIO_FIFO_RESET, AUDIO_FIFO_RESET);
regmap_update_bits(sirf_audio_codec->regmap, AUDIO_PORT_IC_RXFIFO_OP,
AUDIO_FIFO_RESET, ~AUDIO_FIFO_RESET);
regmap_write(sirf_audio_codec->regmap,
AUDIO_PORT_IC_RXFIFO_INT_MSK, 0);
regmap_write(sirf_audio_codec->regmap, AUDIO_PORT_IC_RXFIFO_OP, 0);
regmap_update_bits(sirf_audio_codec->regmap, AUDIO_PORT_IC_RXFIFO_OP,
AUDIO_FIFO_START, AUDIO_FIFO_START);
if (channels == 1)
regmap_update_bits(sirf_audio_codec->regmap,
AUDIO_PORT_IC_CODEC_RX_CTRL,
IC_RX_ENABLE_MONO, IC_RX_ENABLE_MONO);
else
regmap_update_bits(sirf_audio_codec->regmap,
AUDIO_PORT_IC_CODEC_RX_CTRL,
IC_RX_ENABLE_STEREO, IC_RX_ENABLE_STEREO);
}
static void sirf_audio_codec_rx_disable(struct sirf_audio_codec *sirf_audio_codec)
{
regmap_update_bits(sirf_audio_codec->regmap,
AUDIO_PORT_IC_CODEC_RX_CTRL,
IC_RX_ENABLE_STEREO, ~IC_RX_ENABLE_STEREO);
}
static int sirf_audio_codec_trigger(struct snd_pcm_substream *substream,
int cmd,
struct snd_soc_dai *dai)
{
struct snd_soc_component *component = dai->component;
struct sirf_audio_codec *sirf_audio_codec = snd_soc_component_get_drvdata(component);
int playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK;
/*
* This is a workaround, When stop playback,
* need disable HP amp, avoid the current noise.
*/
switch (cmd) {
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
if (playback) {
snd_soc_component_update_bits(component, AUDIO_IC_CODEC_CTRL0,
IC_HSLEN | IC_HSREN, 0);
sirf_audio_codec_tx_disable(sirf_audio_codec);
} else
sirf_audio_codec_rx_disable(sirf_audio_codec);
break;
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
if (playback) {
sirf_audio_codec_tx_enable(sirf_audio_codec);
snd_soc_component_update_bits(component, AUDIO_IC_CODEC_CTRL0,
IC_HSLEN | IC_HSREN, IC_HSLEN | IC_HSREN);
} else
sirf_audio_codec_rx_enable(sirf_audio_codec,
substream->runtime->channels);
break;
default:
return -EINVAL;
}
return 0;
}
static const struct snd_soc_dai_ops sirf_audio_codec_dai_ops = {
.trigger = sirf_audio_codec_trigger,
};
static struct snd_soc_dai_driver sirf_audio_codec_dai = {
.name = "sirf-audio-codec",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.ops = &sirf_audio_codec_dai_ops,
};
static int sirf_audio_codec_probe(struct snd_soc_component *component)
{
struct snd_soc_dapm_context *dapm = snd_soc_component_get_dapm(component);
pm_runtime_enable(component->dev);
if (of_device_is_compatible(component->dev->of_node, "sirf,prima2-audio-codec")) {
snd_soc_dapm_new_controls(dapm,
prima2_output_driver_dapm_widgets,
ARRAY_SIZE(prima2_output_driver_dapm_widgets));
snd_soc_dapm_new_controls(dapm,
&prima2_codec_clock_dapm_widget, 1);
return snd_soc_add_component_controls(component,
volume_controls_prima2,
ARRAY_SIZE(volume_controls_prima2));
}
if (of_device_is_compatible(component->dev->of_node, "sirf,atlas6-audio-codec")) {
snd_soc_dapm_new_controls(dapm,
atlas6_output_driver_dapm_widgets,
ARRAY_SIZE(atlas6_output_driver_dapm_widgets));
snd_soc_dapm_new_controls(dapm,
&atlas6_codec_clock_dapm_widget, 1);
return snd_soc_add_component_controls(component,
volume_controls_atlas6,
ARRAY_SIZE(volume_controls_atlas6));
}
return -EINVAL;
}
static void sirf_audio_codec_remove(struct snd_soc_component *component)
{
pm_runtime_disable(component->dev);
}
static const struct snd_soc_component_driver soc_codec_device_sirf_audio_codec = {
.probe = sirf_audio_codec_probe,
.remove = sirf_audio_codec_remove,
.dapm_widgets = sirf_audio_codec_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(sirf_audio_codec_dapm_widgets),
.dapm_routes = sirf_audio_codec_map,
.num_dapm_routes = ARRAY_SIZE(sirf_audio_codec_map),
.use_pmdown_time = 1,
.endianness = 1,
.non_legacy_dai_naming = 1,
};
static const struct of_device_id sirf_audio_codec_of_match[] = {
{ .compatible = "sirf,prima2-audio-codec" },
{ .compatible = "sirf,atlas6-audio-codec" },
{}
};
MODULE_DEVICE_TABLE(of, sirf_audio_codec_of_match);
static const struct regmap_config sirf_audio_codec_regmap_config = {
.reg_bits = 32,
.reg_stride = 4,
.val_bits = 32,
.max_register = AUDIO_PORT_IC_RXFIFO_INT_MSK,
.cache_type = REGCACHE_NONE,
};
static int sirf_audio_codec_driver_probe(struct platform_device *pdev)
{
int ret;
struct sirf_audio_codec *sirf_audio_codec;
void __iomem *base;
sirf_audio_codec = devm_kzalloc(&pdev->dev,
sizeof(struct sirf_audio_codec), GFP_KERNEL);
if (!sirf_audio_codec)
return -ENOMEM;
platform_set_drvdata(pdev, sirf_audio_codec);
base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(base))
return PTR_ERR(base);
sirf_audio_codec->regmap = devm_regmap_init_mmio(&pdev->dev, base,
&sirf_audio_codec_regmap_config);
if (IS_ERR(sirf_audio_codec->regmap))
return PTR_ERR(sirf_audio_codec->regmap);
sirf_audio_codec->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(sirf_audio_codec->clk)) {
dev_err(&pdev->dev, "Get clock failed.\n");
return PTR_ERR(sirf_audio_codec->clk);
}
ret = clk_prepare_enable(sirf_audio_codec->clk);
if (ret) {
dev_err(&pdev->dev, "Enable clock failed.\n");
return ret;
}
ret = devm_snd_soc_register_component(&(pdev->dev),
&soc_codec_device_sirf_audio_codec,
&sirf_audio_codec_dai, 1);
if (ret) {
dev_err(&pdev->dev, "Register Audio Codec dai failed.\n");
goto err_clk_put;
}
/*
* Always open charge pump, if not, when the charge pump closed the
* adc will not stable
*/
regmap_update_bits(sirf_audio_codec->regmap, AUDIO_IC_CODEC_CTRL0,
IC_CPFREQ, IC_CPFREQ);
if (of_device_is_compatible(pdev->dev.of_node, "sirf,atlas6-audio-codec"))
regmap_update_bits(sirf_audio_codec->regmap,
AUDIO_IC_CODEC_CTRL0, IC_CPEN, IC_CPEN);
return 0;
err_clk_put:
clk_disable_unprepare(sirf_audio_codec->clk);
return ret;
}
static int sirf_audio_codec_driver_remove(struct platform_device *pdev)
{
struct sirf_audio_codec *sirf_audio_codec = platform_get_drvdata(pdev);
clk_disable_unprepare(sirf_audio_codec->clk);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int sirf_audio_codec_suspend(struct device *dev)
{
struct sirf_audio_codec *sirf_audio_codec = dev_get_drvdata(dev);
regmap_read(sirf_audio_codec->regmap, AUDIO_IC_CODEC_CTRL0,
&sirf_audio_codec->reg_ctrl0);
regmap_read(sirf_audio_codec->regmap, AUDIO_IC_CODEC_CTRL1,
&sirf_audio_codec->reg_ctrl1);
clk_disable_unprepare(sirf_audio_codec->clk);
return 0;
}
static int sirf_audio_codec_resume(struct device *dev)
{
struct sirf_audio_codec *sirf_audio_codec = dev_get_drvdata(dev);
int ret;
ret = clk_prepare_enable(sirf_audio_codec->clk);
if (ret)
return ret;
regmap_write(sirf_audio_codec->regmap, AUDIO_IC_CODEC_CTRL0,
sirf_audio_codec->reg_ctrl0);
regmap_write(sirf_audio_codec->regmap, AUDIO_IC_CODEC_CTRL1,
sirf_audio_codec->reg_ctrl1);
return 0;
}
#endif
static const struct dev_pm_ops sirf_audio_codec_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(sirf_audio_codec_suspend, sirf_audio_codec_resume)
};
static struct platform_driver sirf_audio_codec_driver = {
.driver = {
.name = "sirf-audio-codec",
.of_match_table = sirf_audio_codec_of_match,
.pm = &sirf_audio_codec_pm_ops,
},
.probe = sirf_audio_codec_driver_probe,
.remove = sirf_audio_codec_driver_remove,
};
module_platform_driver(sirf_audio_codec_driver);
MODULE_DESCRIPTION("SiRF audio codec driver");
MODULE_AUTHOR("RongJun Ying <Rongjun.Ying@csr.com>");
MODULE_LICENSE("GPL v2");
| {
"language": "C"
} |
/*
* corgi.c -- SoC audio for Corgi
*
* Copyright 2005 Wolfson Microelectronics PLC.
* Copyright 2005 Openedhand Ltd.
*
* Authors: Liam Girdwood <lrg@slimlogic.co.uk>
* Richard Purdie <richard@openedhand.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/timer.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <asm/mach-types.h>
#include <mach/corgi.h>
#include <mach/audio.h>
#include "../codecs/wm8731.h"
#include "pxa2xx-pcm.h"
#include "pxa2xx-i2s.h"
#define CORGI_HP 0
#define CORGI_MIC 1
#define CORGI_LINE 2
#define CORGI_HEADSET 3
#define CORGI_HP_OFF 4
#define CORGI_SPK_ON 0
#define CORGI_SPK_OFF 1
/* audio clock in Hz - rounded from 12.235MHz */
#define CORGI_AUDIO_CLOCK 12288000
static int corgi_jack_func;
static int corgi_spk_func;
static void corgi_ext_control(struct snd_soc_codec *codec)
{
/* set up jack connection */
switch (corgi_jack_func) {
case CORGI_HP:
/* set = unmute headphone */
gpio_set_value(CORGI_GPIO_MUTE_L, 1);
gpio_set_value(CORGI_GPIO_MUTE_R, 1);
snd_soc_dapm_disable_pin(codec, "Mic Jack");
snd_soc_dapm_disable_pin(codec, "Line Jack");
snd_soc_dapm_enable_pin(codec, "Headphone Jack");
snd_soc_dapm_disable_pin(codec, "Headset Jack");
break;
case CORGI_MIC:
/* reset = mute headphone */
gpio_set_value(CORGI_GPIO_MUTE_L, 0);
gpio_set_value(CORGI_GPIO_MUTE_R, 0);
snd_soc_dapm_enable_pin(codec, "Mic Jack");
snd_soc_dapm_disable_pin(codec, "Line Jack");
snd_soc_dapm_disable_pin(codec, "Headphone Jack");
snd_soc_dapm_disable_pin(codec, "Headset Jack");
break;
case CORGI_LINE:
gpio_set_value(CORGI_GPIO_MUTE_L, 0);
gpio_set_value(CORGI_GPIO_MUTE_R, 0);
snd_soc_dapm_disable_pin(codec, "Mic Jack");
snd_soc_dapm_enable_pin(codec, "Line Jack");
snd_soc_dapm_disable_pin(codec, "Headphone Jack");
snd_soc_dapm_disable_pin(codec, "Headset Jack");
break;
case CORGI_HEADSET:
gpio_set_value(CORGI_GPIO_MUTE_L, 0);
gpio_set_value(CORGI_GPIO_MUTE_R, 1);
snd_soc_dapm_enable_pin(codec, "Mic Jack");
snd_soc_dapm_disable_pin(codec, "Line Jack");
snd_soc_dapm_disable_pin(codec, "Headphone Jack");
snd_soc_dapm_enable_pin(codec, "Headset Jack");
break;
}
if (corgi_spk_func == CORGI_SPK_ON)
snd_soc_dapm_enable_pin(codec, "Ext Spk");
else
snd_soc_dapm_disable_pin(codec, "Ext Spk");
/* signal a DAPM event */
snd_soc_dapm_sync(codec);
}
static int corgi_startup(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->socdev->card->codec;
/* check the jack status at stream startup */
corgi_ext_control(codec);
return 0;
}
/* we need to unmute the HP at shutdown as the mute burns power on corgi */
static void corgi_shutdown(struct snd_pcm_substream *substream)
{
/* set = unmute headphone */
gpio_set_value(CORGI_GPIO_MUTE_L, 1);
gpio_set_value(CORGI_GPIO_MUTE_R, 1);
}
static int corgi_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->dai->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai;
unsigned int clk = 0;
int ret = 0;
switch (params_rate(params)) {
case 8000:
case 16000:
case 48000:
case 96000:
clk = 12288000;
break;
case 11025:
case 22050:
case 44100:
clk = 11289600;
break;
}
/* set codec DAI configuration */
ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
/* set cpu DAI configuration */
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
/* set the codec system clock for DAC and ADC */
ret = snd_soc_dai_set_sysclk(codec_dai, WM8731_SYSCLK, clk,
SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
/* set the I2S system clock as input (unused) */
ret = snd_soc_dai_set_sysclk(cpu_dai, PXA2XX_I2S_SYSCLK, 0,
SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
return 0;
}
static struct snd_soc_ops corgi_ops = {
.startup = corgi_startup,
.hw_params = corgi_hw_params,
.shutdown = corgi_shutdown,
};
static int corgi_get_jack(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = corgi_jack_func;
return 0;
}
static int corgi_set_jack(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
if (corgi_jack_func == ucontrol->value.integer.value[0])
return 0;
corgi_jack_func = ucontrol->value.integer.value[0];
corgi_ext_control(codec);
return 1;
}
static int corgi_get_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = corgi_spk_func;
return 0;
}
static int corgi_set_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
if (corgi_spk_func == ucontrol->value.integer.value[0])
return 0;
corgi_spk_func = ucontrol->value.integer.value[0];
corgi_ext_control(codec);
return 1;
}
static int corgi_amp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
gpio_set_value(CORGI_GPIO_APM_ON, SND_SOC_DAPM_EVENT_ON(event));
return 0;
}
static int corgi_mic_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
gpio_set_value(CORGI_GPIO_MIC_BIAS, SND_SOC_DAPM_EVENT_ON(event));
return 0;
}
/* corgi machine dapm widgets */
static const struct snd_soc_dapm_widget wm8731_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_MIC("Mic Jack", corgi_mic_event),
SND_SOC_DAPM_SPK("Ext Spk", corgi_amp_event),
SND_SOC_DAPM_LINE("Line Jack", NULL),
SND_SOC_DAPM_HP("Headset Jack", NULL),
};
/* Corgi machine audio map (connections to the codec pins) */
static const struct snd_soc_dapm_route audio_map[] = {
/* headset Jack - in = micin, out = LHPOUT*/
{"Headset Jack", NULL, "LHPOUT"},
/* headphone connected to LHPOUT1, RHPOUT1 */
{"Headphone Jack", NULL, "LHPOUT"},
{"Headphone Jack", NULL, "RHPOUT"},
/* speaker connected to LOUT, ROUT */
{"Ext Spk", NULL, "ROUT"},
{"Ext Spk", NULL, "LOUT"},
/* mic is connected to MICIN (via right channel of headphone jack) */
{"MICIN", NULL, "Mic Jack"},
/* Same as the above but no mic bias for line signals */
{"MICIN", NULL, "Line Jack"},
};
static const char *jack_function[] = {"Headphone", "Mic", "Line", "Headset",
"Off"};
static const char *spk_function[] = {"On", "Off"};
static const struct soc_enum corgi_enum[] = {
SOC_ENUM_SINGLE_EXT(5, jack_function),
SOC_ENUM_SINGLE_EXT(2, spk_function),
};
static const struct snd_kcontrol_new wm8731_corgi_controls[] = {
SOC_ENUM_EXT("Jack Function", corgi_enum[0], corgi_get_jack,
corgi_set_jack),
SOC_ENUM_EXT("Speaker Function", corgi_enum[1], corgi_get_spk,
corgi_set_spk),
};
/*
* Logic for a wm8731 as connected on a Sharp SL-C7x0 Device
*/
static int corgi_wm8731_init(struct snd_soc_codec *codec)
{
int err;
snd_soc_dapm_nc_pin(codec, "LLINEIN");
snd_soc_dapm_nc_pin(codec, "RLINEIN");
/* Add corgi specific controls */
err = snd_soc_add_controls(codec, wm8731_corgi_controls,
ARRAY_SIZE(wm8731_corgi_controls));
if (err < 0)
return err;
/* Add corgi specific widgets */
snd_soc_dapm_new_controls(codec, wm8731_dapm_widgets,
ARRAY_SIZE(wm8731_dapm_widgets));
/* Set up corgi specific audio path audio_map */
snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map));
snd_soc_dapm_sync(codec);
return 0;
}
/* corgi digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link corgi_dai = {
.name = "WM8731",
.stream_name = "WM8731",
.cpu_dai = &pxa_i2s_dai,
.codec_dai = &wm8731_dai,
.init = corgi_wm8731_init,
.ops = &corgi_ops,
};
/* corgi audio machine driver */
static struct snd_soc_card snd_soc_corgi = {
.name = "Corgi",
.platform = &pxa2xx_soc_platform,
.dai_link = &corgi_dai,
.num_links = 1,
};
/* corgi audio subsystem */
static struct snd_soc_device corgi_snd_devdata = {
.card = &snd_soc_corgi,
.codec_dev = &soc_codec_dev_wm8731,
};
static struct platform_device *corgi_snd_device;
static int __init corgi_init(void)
{
int ret;
if (!(machine_is_corgi() || machine_is_shepherd() ||
machine_is_husky()))
return -ENODEV;
corgi_snd_device = platform_device_alloc("soc-audio", -1);
if (!corgi_snd_device)
return -ENOMEM;
platform_set_drvdata(corgi_snd_device, &corgi_snd_devdata);
corgi_snd_devdata.dev = &corgi_snd_device->dev;
ret = platform_device_add(corgi_snd_device);
if (ret)
platform_device_put(corgi_snd_device);
return ret;
}
static void __exit corgi_exit(void)
{
platform_device_unregister(corgi_snd_device);
}
module_init(corgi_init);
module_exit(corgi_exit);
/* Module information */
MODULE_AUTHOR("Richard Purdie");
MODULE_DESCRIPTION("ALSA SoC Corgi");
MODULE_LICENSE("GPL");
| {
"language": "C"
} |
/**
* @file
* @brief i.MX6 Enhanced Configurable SPI driver
* @author Denis Deryugin <deryugin.denis@gmail.com>
* @version 0.1
* @date 12.06.2017
*/
#include <embox/unit.h>
#include <framework/mod/options.h>
#include <util/log.h>
#include <drivers/common/memory.h>
#include <drivers/spi.h>
#include <drivers/clk/ccm_imx6.h>
#include <drivers/iomuxc.h>
#include "imx6_ecspi.h"
EMBOX_UNIT_INIT(imx6_ecspi2_init);
#define BASE_ADDR OPTION_GET(NUMBER, base_addr)
#define PINS_GROUP OPTION_GET(NUMBER, pins_group)
static struct imx6_ecspi imx6_ecspi2 = {
.base_addr = BASE_ADDR,
.cs_count = 1,
.cs_array = {
{4, 29}
},
.cs_iomux = {
IOMUXC_SW_MUX_CTL_PAD_CSI0_DATA11,
}
};
static void imx_ecspi2_pins_init(void) {
int gpio_n, port;
int i;
/* SS0 (CS0) */
/* FIXME SPI NSS doesn't work somewhy, so we use gpio instead of:
* iomuxc_write(IOMUXC_SW_MUX_CTL_PAD_CSI0_DATA11, 0x12);
* iomuxc_write(IOMUXC_ECSPI2_SS0_SELECT_INPUT, 0x2);
*/
/* Init all Chip Selects */
for (i = 0; i < imx6_ecspi2.cs_count; i++) {
/* Force GPIO mode. */
iomuxc_write(imx6_ecspi2.cs_iomux[i], 0x15);
gpio_n = imx6_ecspi2.cs_array[i][0];
port = imx6_ecspi2.cs_array[i][1];
gpio_setup_mode(gpio_n, 1 << port, GPIO_MODE_OUTPUT);
gpio_set(gpio_n, 1 << port, 1);
}
/* Init selected GPIO group. */
#if PINS_GROUP == 1
/* MISO */
iomuxc_write(IOMUXC_SW_MUX_CTL_PAD_CSI0_DATA10, 0x12);
iomuxc_write(IOMUXC_ECSPI2_MISO_SELECT_INPUT, 0x2);
/* MOSI */
iomuxc_write(IOMUXC_SW_MUX_CTL_PAD_CSI0_DATA09, 0x12);
iomuxc_write(IOMUXC_ECSPI2_MOSI_SELECT_INPUT, 0x2);
/* CLK */
iomuxc_write(IOMUXC_SW_MUX_CTL_PAD_CSI0_DATA08, 0x12);
iomuxc_write(IOMUXC_ECSPI2_CSPI_CLK_IN_SELECT_INPUT, 0x2);
#else
#error "Wrong pins group for SPI2"
#endif
}
static int imx6_ecspi2_init(void) {
log_debug("");
clk_enable("ecspi2");
imx_ecspi2_pins_init();
return imx6_ecspi_init(&imx6_ecspi2);
}
PERIPH_MEMORY_DEFINE(imx6_ecspi2, BASE_ADDR, 0x44);
SPI_DEV_DEF("ixm6_ecspi2", &imx6_ecspi_ops, &imx6_ecspi2, 1);
| {
"language": "C"
} |
/*
* Author: Garrett Barboza <garrett.barboza@kapricasecurity.com>
*
* Copyright (c) 2014 Kaprica Security, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "libcgc.h"
#include "cgc_malloc.h"
#include "cgc_stdlib.h"
static void cgc_free_huge(struct blk_t *blk)
{
cgc_deallocate(blk, blk->size);
}
void cgc_free(void *ptr)
{
if (ptr == NULL)
return;
struct blk_t *blk = (struct blk_t *)((intptr_t)ptr - HEADER_PADDING);
if (blk->free != 0)
return;
if (blk->size >= NEW_CHUNK_SIZE) {
cgc_free_huge(blk);
} else {
cgc_insert_into_flist(blk);
cgc_coalesce(blk);
}
}
| {
"language": "C"
} |
/*
* TS3A227E Autonomous Audio Accessory Detection and Configuration Switch
*
* Copyright (C) 2014 Google, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/of_gpio.h>
#include <linux/regmap.h>
#include <sound/core.h>
#include <sound/jack.h>
#include <sound/soc.h>
#include "ts3a227e.h"
struct ts3a227e {
struct device *dev;
struct regmap *regmap;
struct snd_soc_jack *jack;
bool plugged;
bool mic_present;
unsigned int buttons_held;
int irq;
};
/* Button values to be reported on the jack */
static const int ts3a227e_buttons[] = {
SND_JACK_BTN_0,
SND_JACK_BTN_1,
SND_JACK_BTN_2,
SND_JACK_BTN_3,
};
#define TS3A227E_NUM_BUTTONS 4
#define TS3A227E_JACK_MASK (SND_JACK_HEADPHONE | \
SND_JACK_MICROPHONE | \
SND_JACK_BTN_0 | \
SND_JACK_BTN_1 | \
SND_JACK_BTN_2 | \
SND_JACK_BTN_3)
/* TS3A227E registers */
#define TS3A227E_REG_DEVICE_ID 0x00
#define TS3A227E_REG_INTERRUPT 0x01
#define TS3A227E_REG_KP_INTERRUPT 0x02
#define TS3A227E_REG_INTERRUPT_DISABLE 0x03
#define TS3A227E_REG_SETTING_1 0x04
#define TS3A227E_REG_SETTING_2 0x05
#define TS3A227E_REG_SETTING_3 0x06
#define TS3A227E_REG_SWITCH_CONTROL_1 0x07
#define TS3A227E_REG_SWITCH_CONTROL_2 0x08
#define TS3A227E_REG_SWITCH_STATUS_1 0x09
#define TS3A227E_REG_SWITCH_STATUS_2 0x0a
#define TS3A227E_REG_ACCESSORY_STATUS 0x0b
#define TS3A227E_REG_ADC_OUTPUT 0x0c
#define TS3A227E_REG_KP_THRESHOLD_1 0x0d
#define TS3A227E_REG_KP_THRESHOLD_2 0x0e
#define TS3A227E_REG_KP_THRESHOLD_3 0x0f
/* TS3A227E_REG_INTERRUPT 0x01 */
#define INS_REM_EVENT 0x01
#define DETECTION_COMPLETE_EVENT 0x02
/* TS3A227E_REG_KP_INTERRUPT 0x02 */
#define PRESS_MASK(idx) (0x01 << (2 * (idx)))
#define RELEASE_MASK(idx) (0x02 << (2 * (idx)))
/* TS3A227E_REG_INTERRUPT_DISABLE 0x03 */
#define INS_REM_INT_DISABLE 0x01
#define DETECTION_COMPLETE_INT_DISABLE 0x02
#define ADC_COMPLETE_INT_DISABLE 0x04
#define INTB_DISABLE 0x08
/* TS3A227E_REG_SETTING_2 0x05 */
#define KP_ENABLE 0x04
/* TS3A227E_REG_SETTING_3 0x06 */
#define MICBIAS_SETTING_SFT (3)
#define MICBIAS_SETTING_MASK (0x7 << MICBIAS_SETTING_SFT)
/* TS3A227E_REG_ACCESSORY_STATUS 0x0b */
#define TYPE_3_POLE 0x01
#define TYPE_4_POLE_OMTP 0x02
#define TYPE_4_POLE_STANDARD 0x04
#define JACK_INSERTED 0x08
#define EITHER_MIC_MASK (TYPE_4_POLE_OMTP | TYPE_4_POLE_STANDARD)
static const struct reg_default ts3a227e_reg_defaults[] = {
{ TS3A227E_REG_DEVICE_ID, 0x10 },
{ TS3A227E_REG_INTERRUPT, 0x00 },
{ TS3A227E_REG_KP_INTERRUPT, 0x00 },
{ TS3A227E_REG_INTERRUPT_DISABLE, 0x08 },
{ TS3A227E_REG_SETTING_1, 0x23 },
{ TS3A227E_REG_SETTING_2, 0x00 },
{ TS3A227E_REG_SETTING_3, 0x0e },
{ TS3A227E_REG_SWITCH_CONTROL_1, 0x00 },
{ TS3A227E_REG_SWITCH_CONTROL_2, 0x00 },
{ TS3A227E_REG_SWITCH_STATUS_1, 0x0c },
{ TS3A227E_REG_SWITCH_STATUS_2, 0x00 },
{ TS3A227E_REG_ACCESSORY_STATUS, 0x00 },
{ TS3A227E_REG_ADC_OUTPUT, 0x00 },
{ TS3A227E_REG_KP_THRESHOLD_1, 0x20 },
{ TS3A227E_REG_KP_THRESHOLD_2, 0x40 },
{ TS3A227E_REG_KP_THRESHOLD_3, 0x68 },
};
static bool ts3a227e_readable_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case TS3A227E_REG_DEVICE_ID ... TS3A227E_REG_KP_THRESHOLD_3:
return true;
default:
return false;
}
}
static bool ts3a227e_writeable_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case TS3A227E_REG_INTERRUPT_DISABLE ... TS3A227E_REG_SWITCH_CONTROL_2:
case TS3A227E_REG_KP_THRESHOLD_1 ... TS3A227E_REG_KP_THRESHOLD_3:
return true;
default:
return false;
}
}
static bool ts3a227e_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case TS3A227E_REG_INTERRUPT ... TS3A227E_REG_INTERRUPT_DISABLE:
case TS3A227E_REG_SETTING_2:
case TS3A227E_REG_SWITCH_STATUS_1 ... TS3A227E_REG_ADC_OUTPUT:
return true;
default:
return false;
}
}
static void ts3a227e_jack_report(struct ts3a227e *ts3a227e)
{
unsigned int i;
int report = 0;
if (!ts3a227e->jack)
return;
if (ts3a227e->plugged)
report = SND_JACK_HEADPHONE;
if (ts3a227e->mic_present)
report |= SND_JACK_MICROPHONE;
for (i = 0; i < TS3A227E_NUM_BUTTONS; i++) {
if (ts3a227e->buttons_held & (1 << i))
report |= ts3a227e_buttons[i];
}
snd_soc_jack_report(ts3a227e->jack, report, TS3A227E_JACK_MASK);
}
static void ts3a227e_new_jack_state(struct ts3a227e *ts3a227e, unsigned acc_reg)
{
bool plugged, mic_present;
plugged = !!(acc_reg & JACK_INSERTED);
mic_present = plugged && !!(acc_reg & EITHER_MIC_MASK);
ts3a227e->plugged = plugged;
if (mic_present != ts3a227e->mic_present) {
ts3a227e->mic_present = mic_present;
ts3a227e->buttons_held = 0;
if (mic_present) {
/* Enable key press detection. */
regmap_update_bits(ts3a227e->regmap,
TS3A227E_REG_SETTING_2,
KP_ENABLE, KP_ENABLE);
}
}
}
static irqreturn_t ts3a227e_interrupt(int irq, void *data)
{
struct ts3a227e *ts3a227e = (struct ts3a227e *)data;
struct regmap *regmap = ts3a227e->regmap;
unsigned int int_reg, kp_int_reg, acc_reg, i;
struct device *dev = ts3a227e->dev;
int ret;
/* Check for plug/unplug. */
ret = regmap_read(regmap, TS3A227E_REG_INTERRUPT, &int_reg);
if (ret) {
dev_err(dev, "failed to clear interrupt ret=%d\n", ret);
return IRQ_NONE;
}
if (int_reg & (DETECTION_COMPLETE_EVENT | INS_REM_EVENT)) {
regmap_read(regmap, TS3A227E_REG_ACCESSORY_STATUS, &acc_reg);
ts3a227e_new_jack_state(ts3a227e, acc_reg);
}
/* Report any key events. */
ret = regmap_read(regmap, TS3A227E_REG_KP_INTERRUPT, &kp_int_reg);
if (ret) {
dev_err(dev, "failed to clear key interrupt ret=%d\n", ret);
return IRQ_NONE;
}
for (i = 0; i < TS3A227E_NUM_BUTTONS; i++) {
if (kp_int_reg & PRESS_MASK(i))
ts3a227e->buttons_held |= (1 << i);
if (kp_int_reg & RELEASE_MASK(i))
ts3a227e->buttons_held &= ~(1 << i);
}
ts3a227e_jack_report(ts3a227e);
return IRQ_HANDLED;
}
/**
* ts3a227e_enable_jack_detect - Specify a jack for event reporting
*
* @component: component to register the jack with
* @jack: jack to use to report headset and button events on
*
* After this function has been called the headset insert/remove and button
* events 0-3 will be routed to the given jack. Jack can be null to stop
* reporting.
*/
int ts3a227e_enable_jack_detect(struct snd_soc_component *component,
struct snd_soc_jack *jack)
{
struct ts3a227e *ts3a227e = snd_soc_component_get_drvdata(component);
snd_jack_set_key(jack->jack, SND_JACK_BTN_0, KEY_MEDIA);
snd_jack_set_key(jack->jack, SND_JACK_BTN_1, KEY_VOICECOMMAND);
snd_jack_set_key(jack->jack, SND_JACK_BTN_2, KEY_VOLUMEUP);
snd_jack_set_key(jack->jack, SND_JACK_BTN_3, KEY_VOLUMEDOWN);
ts3a227e->jack = jack;
ts3a227e_jack_report(ts3a227e);
return 0;
}
EXPORT_SYMBOL_GPL(ts3a227e_enable_jack_detect);
static struct snd_soc_component_driver ts3a227e_soc_driver;
static const struct regmap_config ts3a227e_regmap_config = {
.val_bits = 8,
.reg_bits = 8,
.max_register = TS3A227E_REG_KP_THRESHOLD_3,
.readable_reg = ts3a227e_readable_reg,
.writeable_reg = ts3a227e_writeable_reg,
.volatile_reg = ts3a227e_volatile_reg,
.cache_type = REGCACHE_RBTREE,
.reg_defaults = ts3a227e_reg_defaults,
.num_reg_defaults = ARRAY_SIZE(ts3a227e_reg_defaults),
};
static int ts3a227e_parse_device_property(struct ts3a227e *ts3a227e,
struct device *dev)
{
u32 micbias;
int err;
err = device_property_read_u32(dev, "ti,micbias", &micbias);
if (!err) {
regmap_update_bits(ts3a227e->regmap, TS3A227E_REG_SETTING_3,
MICBIAS_SETTING_MASK,
(micbias & 0x07) << MICBIAS_SETTING_SFT);
}
return 0;
}
static int ts3a227e_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct ts3a227e *ts3a227e;
struct device *dev = &i2c->dev;
int ret;
unsigned int acc_reg;
ts3a227e = devm_kzalloc(&i2c->dev, sizeof(*ts3a227e), GFP_KERNEL);
if (ts3a227e == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, ts3a227e);
ts3a227e->dev = dev;
ts3a227e->irq = i2c->irq;
ts3a227e->regmap = devm_regmap_init_i2c(i2c, &ts3a227e_regmap_config);
if (IS_ERR(ts3a227e->regmap))
return PTR_ERR(ts3a227e->regmap);
ret = ts3a227e_parse_device_property(ts3a227e, dev);
if (ret) {
dev_err(dev, "Failed to parse device property: %d\n", ret);
return ret;
}
ret = devm_request_threaded_irq(dev, i2c->irq, NULL, ts3a227e_interrupt,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
"TS3A227E", ts3a227e);
if (ret) {
dev_err(dev, "Cannot request irq %d (%d)\n", i2c->irq, ret);
return ret;
}
ret = devm_snd_soc_register_component(&i2c->dev, &ts3a227e_soc_driver,
NULL, 0);
if (ret)
return ret;
/* Enable interrupts except for ADC complete. */
regmap_update_bits(ts3a227e->regmap, TS3A227E_REG_INTERRUPT_DISABLE,
INTB_DISABLE | ADC_COMPLETE_INT_DISABLE,
ADC_COMPLETE_INT_DISABLE);
/* Read jack status because chip might not trigger interrupt at boot. */
regmap_read(ts3a227e->regmap, TS3A227E_REG_ACCESSORY_STATUS, &acc_reg);
ts3a227e_new_jack_state(ts3a227e, acc_reg);
ts3a227e_jack_report(ts3a227e);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int ts3a227e_suspend(struct device *dev)
{
struct ts3a227e *ts3a227e = dev_get_drvdata(dev);
dev_dbg(ts3a227e->dev, "suspend disable irq\n");
disable_irq(ts3a227e->irq);
return 0;
}
static int ts3a227e_resume(struct device *dev)
{
struct ts3a227e *ts3a227e = dev_get_drvdata(dev);
dev_dbg(ts3a227e->dev, "resume enable irq\n");
enable_irq(ts3a227e->irq);
return 0;
}
#endif
static const struct dev_pm_ops ts3a227e_pm = {
SET_SYSTEM_SLEEP_PM_OPS(ts3a227e_suspend, ts3a227e_resume)
};
static const struct i2c_device_id ts3a227e_i2c_ids[] = {
{ "ts3a227e", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, ts3a227e_i2c_ids);
static const struct of_device_id ts3a227e_of_match[] = {
{ .compatible = "ti,ts3a227e", },
{ }
};
MODULE_DEVICE_TABLE(of, ts3a227e_of_match);
static struct i2c_driver ts3a227e_driver = {
.driver = {
.name = "ts3a227e",
.pm = &ts3a227e_pm,
.of_match_table = of_match_ptr(ts3a227e_of_match),
},
.probe = ts3a227e_i2c_probe,
.id_table = ts3a227e_i2c_ids,
};
module_i2c_driver(ts3a227e_driver);
MODULE_DESCRIPTION("ASoC ts3a227e driver");
MODULE_AUTHOR("Dylan Reid <dgreid@chromium.org>");
MODULE_LICENSE("GPL v2");
| {
"language": "C"
} |
/* 2-D Fourier finite-difference wave extrapolation, smooth point source, depress high frequency */
/*
Copyright (C) 2009 University of Texas at Austin
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <rsf.h>
#include <math.h>
#include <limits.h>
#include "abcpass.h"
#include "ffdstep.h"
#include "srcsm.h"
#ifdef _OPENMP
#include <omp.h>
#endif
int main(int argc, char* argv[])
{
int nx, nz, nt, ix, iz, it, nbt, nbb, nbl, nbr, nxb, nzb, isx, isz;
float dt, dx, dz, o1, o2;
float **old, **cur, **tmp, *wav;
float **v, v0, ***aa, w, g1, g2, ct, cb, cl, cr; /* top, bottom, left, right */
float ax, az, factor;
sf_file out, vel, source;
bool opt; /* optimal padding */
sf_init(argc,argv);
out = sf_output("out");
vel = sf_input("vel"); /* velocity */
source = sf_input("in"); /* source wavlet*/
/* if (SF_FLOAT != sf_gettype(inp)) sf_error("Need float input"); */
if (SF_FLOAT != sf_gettype(vel)) sf_error("Need float input");
if (SF_FLOAT != sf_gettype(source)) sf_error("Need float input");
if (!sf_histint(vel,"n1",&nx)) sf_error("No n1= in input");
if (!sf_histfloat(vel,"d1",&dx)) sf_error("No d1= in input");
if (!sf_histint(vel,"n2",&nz)) sf_error("No n2= in input");
if (!sf_histfloat(vel,"d2",&dz)) sf_error("No d2= in input");
if (!sf_histfloat(vel,"o1",&o1)) o1=0.0;
if (!sf_histfloat(vel,"o2",&o2)) o1=0.0;
/* if (!sf_histint(inp,"n2",&nt)) sf_error("No n2= in input"); */
/* if (!sf_histfloat(inp,"d2",&dt)) sf_error("No d2= in input"); */
if (!sf_getbool("opt",&opt)) opt=true;
/* if y, determine optimal size for efficiency */
if (!sf_getfloat("dt",&dt)) sf_error("Need dt input");
if (!sf_getint("nt",&nt)) sf_error("Need nt input");
if (!sf_getint("isx",&isx)) sf_error("Need isx input");
if (!sf_getint("isz",&isz)) sf_error("Need isz input");
if (!sf_getint("nbt",&nbt)) nbt=44;
if (!sf_getint("nbb",&nbb)) nbb=44;
if (!sf_getint("nbl",&nbl)) nbl=44;
if (!sf_getint("nbr",&nbr)) nbr=44;
if (!sf_getfloat("ct",&ct)) ct = 0.01; /*decaying parameter*/
if (!sf_getfloat("cb",&cb)) cb = 0.01; /*decaying parameter*/
if (!sf_getfloat("cl",&cl)) cl = 0.01; /*decaying parameter*/
if (!sf_getfloat("cr",&cr)) cr = 0.01; /*decaying parameter*/
if (!sf_getfloat("ax",&ax)) ax= 5.0; /*suppress HF parameter*/
if (!sf_getfloat("az",&az)) az= 5.0; /*suppress HF parameter*/
if (!sf_getfloat("factor",&factor)) factor= 5.0/6.0; /*suppress HF parameter*/
sf_putint(out,"n1",nx);
sf_putfloat(out,"d1",dx);
/* sf_putfloat(out,"o1",x0); */
sf_putint(out,"n2",nz);
sf_putfloat(out,"d2",dz);
sf_putint(out,"n3",nt);
sf_putfloat(out,"d3",dt);
sf_putfloat(out,"o1",o1);
sf_putfloat(out,"o2",o2);
sf_putfloat(out,"o3",0.0);
nxb = nx + nbl + nbr;
nzb = nz + nbt + nbb;
/*
nkx = nxb;
nkz = nzb;
dkx = 1./(2.0*kiss_fft_next_fast_size(nxb-1)*dx);
dkz = 1./(2.0*kiss_fft_next_fast_size(nzb-1)*dz);
*/
wav = sf_floatalloc(nt);
sf_floatread(wav,nt,source);
old = sf_floatalloc2(nxb,nzb);
cur = sf_floatalloc2(nxb,nzb);
aa = sf_floatalloc3(3,nxb,nzb);
bd_init(nx,nz,nbt,nbb,nbl,nbr,ct,cb,cl,cr);
v = sf_floatalloc2(nxb,nzb);
/*input & extend velocity model*/
for (iz=nbt; iz<nz+nbt; iz++){
sf_floatread(v[iz]+nbl,nx,vel);
for (ix=0; ix<nbl; ix++){
v[iz][ix] = v[iz][nbl];
}
for (ix=0; ix<nbr; ix++){
v[iz][nx+nbl+ix] = v[iz][nx+nbl-1];
}
}
for (iz=0; iz<nbt; iz++){
for (ix=0; ix<nxb; ix++){
v[iz][ix] = v[nbt][ix];
}
}
for (iz=0; iz<nbb; iz++){
for (ix=0; ix<nxb; ix++){
v[nz+nbt+iz][ix] = v[nz+nbt-1][ix];
}
}
v0 =0.0;
for (iz=0; iz < nzb; iz++) {
for (ix=0; ix < nxb; ix++) {
v0 += v[iz][ix]*v[iz][ix];
}
}
v0 = sqrtf(v0/(nxb*nzb));
for (iz=0; iz < nzb; iz++){
for (ix=0; ix < nxb; ix++) {
w = v[iz][ix]*v[iz][ix];
g1 = dt*dt*(v[iz][ix]*v[iz][ix]-v0*v0)/(12.0*dx*dx);
g2 = dt*dt*(v[iz][ix]*v[iz][ix]-v0*v0)/(12.0*dz*dz);
aa[iz][ix][1] = w*g1;
aa[iz][ix][2] = w*g2;
aa[iz][ix][0] = w-2.0*aa[iz][ix][1]-2.0*aa[iz][ix][2];
}
}
for (iz=0; iz < nzb; iz++) {
for (ix=0; ix < nxb; ix++) {
cur[iz][ix] = 0.0;
old[iz][ix] = 0.0;
}
}
/* propagation in time */
ffdstep_init(nxb,nzb,dx,dz);
srcsm_init(dz,dx);
for (it=0; it < nt; it++) {
ffdstep_dehf(old, cur, aa, nxb, nzb, v0, dt, ax, az, factor);
old[isz+nbt][isx+nbl] += wav[it];
source_smooth(old,isz+nbt,isx+nbl,wav[it]);
bd_decay(old);
bd_decay(cur);
tmp = old;
old = cur;
cur = tmp;
for (iz=nbt; iz<nz+nbt; iz++){
sf_floatwrite(cur[iz]+nbl,nx,out);
}
}
ffdstep_close();
bd_close();
free(**aa);
free(*aa);
free(aa);
free(*v);
free(*cur);
free(*old);
free(v);
free(cur);
free(old);
exit(0);
}
| {
"language": "C"
} |
/*******************************************************************************
* Copyright (c) 2008-2013 The Khronos Group Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and/or associated documentation files (the
* "Materials"), to deal in the Materials without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Materials, and to
* permit persons to whom the Materials are furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Materials.
*
* THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
******************************************************************************/
/* $Revision: 11928 $ on $Date: 2010-07-13 09:04:56 -0700 (Tue, 13 Jul 2010) $ */
/* cl_ext.h contains OpenCL extensions which don't have external */
/* (OpenGL, D3D) dependencies. */
#ifndef __CL_EXT_H
#define __CL_EXT_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __APPLE__
#include <OpenCL/cl.h>
#include <AvailabilityMacros.h>
#else
#include <CL/cl.h>
#endif
/* cl_khr_fp16 extension - no extension #define since it has no functions */
#define CL_DEVICE_HALF_FP_CONFIG 0x1033
/* Memory object destruction
*
* Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR
*
* Registers a user callback function that will be called when the memory object is deleted and its resources
* freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback
* stack associated with memobj. The registered user callback functions are called in the reverse order in
* which they were registered. The user callback functions are called and then the memory object is deleted
* and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be
* notified when the memory referenced by host_ptr, specified when the memory object is created and used as
* the storage bits for the memory object, can be reused or freed.
*
* The application may not call CL api's with the cl_mem object passed to the pfn_notify.
*
* Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS)
* before using.
*/
#define cl_APPLE_SetMemObjectDestructor 1
cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem /* memobj */,
void (* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/),
void * /*user_data */ ) CL_EXT_SUFFIX__VERSION_1_0;
/* Context Logging Functions
*
* The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext().
* Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS)
* before using.
*
* clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger
*/
#define cl_APPLE_ContextLoggingFunctions 1
extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * /* errstr */,
const void * /* private_info */,
size_t /* cb */,
void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0;
/* clLogMessagesToStdout sends all log messages to the file descriptor stdout */
extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * /* errstr */,
const void * /* private_info */,
size_t /* cb */,
void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0;
/* clLogMessagesToStderr sends all log messages to the file descriptor stderr */
extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * /* errstr */,
const void * /* private_info */,
size_t /* cb */,
void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0;
/************************
* cl_khr_icd extension *
************************/
#define cl_khr_icd 1
/* cl_platform_info */
#define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920
/* Additional Error Codes */
#define CL_PLATFORM_NOT_FOUND_KHR -1001
extern CL_API_ENTRY cl_int CL_API_CALL
clIcdGetPlatformIDsKHR(cl_uint /* num_entries */,
cl_platform_id * /* platforms */,
cl_uint * /* num_platforms */);
typedef CL_API_ENTRY cl_int (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)(
cl_uint /* num_entries */,
cl_platform_id * /* platforms */,
cl_uint * /* num_platforms */);
/* Extension: cl_khr_image2D_buffer
*
* This extension allows a 2D image to be created from a cl_mem buffer without a copy.
* The type associated with a 2D image created from a buffer in an OpenCL program is image2d_t.
* Both the sampler and sampler-less read_image built-in functions are supported for 2D images
* and 2D images created from a buffer. Similarly, the write_image built-ins are also supported
* for 2D images created from a buffer.
*
* When the 2D image from buffer is created, the client must specify the width,
* height, image format (i.e. channel order and channel data type) and optionally the row pitch
*
* The pitch specified must be a multiple of CL_DEVICE_IMAGE_PITCH_ALIGNMENT pixels.
* The base address of the buffer must be aligned to CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT pixels.
*/
/*************************************
* cl_khr_initalize_memory extension *
*************************************/
#define CL_CONTEXT_MEMORY_INITIALIZE_KHR 0x200E
/**************************************
* cl_khr_terminate_context extension *
**************************************/
#define CL_DEVICE_TERMINATE_CAPABILITY_KHR 0x200F
#define CL_CONTEXT_TERMINATE_KHR 0x2010
#define cl_khr_terminate_context 1
extern CL_API_ENTRY cl_int CL_API_CALL clTerminateContextKHR(cl_context /* context */) CL_EXT_SUFFIX__VERSION_1_2;
typedef CL_API_ENTRY cl_int (CL_API_CALL *clTerminateContextKHR_fn)(cl_context /* context */) CL_EXT_SUFFIX__VERSION_1_2;
/*
* Extension: cl_khr_spir
*
* This extension adds support to create an OpenCL program object from a
* Standard Portable Intermediate Representation (SPIR) instance
*/
/******************************************
* cl_nv_device_attribute_query extension *
******************************************/
/* cl_nv_device_attribute_query extension - no extension #define since it has no functions */
#define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000
#define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001
#define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002
#define CL_DEVICE_WARP_SIZE_NV 0x4003
#define CL_DEVICE_GPU_OVERLAP_NV 0x4004
#define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005
#define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006
/*********************************
* cl_amd_device_attribute_query *
*********************************/
#define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036
#ifdef CL_VERSION_1_1
/***********************************
* cl_ext_device_fission extension *
***********************************/
#define cl_ext_device_fission 1
extern CL_API_ENTRY cl_int CL_API_CALL
clReleaseDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1;
typedef CL_API_ENTRY cl_int
(CL_API_CALL *clReleaseDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1;
extern CL_API_ENTRY cl_int CL_API_CALL
clRetainDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1;
typedef CL_API_ENTRY cl_int
(CL_API_CALL *clRetainDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1;
typedef cl_ulong cl_device_partition_property_ext;
extern CL_API_ENTRY cl_int CL_API_CALL
clCreateSubDevicesEXT( cl_device_id /*in_device*/,
const cl_device_partition_property_ext * /* properties */,
cl_uint /*num_entries*/,
cl_device_id * /*out_devices*/,
cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1;
typedef CL_API_ENTRY cl_int
( CL_API_CALL * clCreateSubDevicesEXT_fn)( cl_device_id /*in_device*/,
const cl_device_partition_property_ext * /* properties */,
cl_uint /*num_entries*/,
cl_device_id * /*out_devices*/,
cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1;
/* cl_device_partition_property_ext */
#define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050
#define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051
#define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052
#define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053
/* clDeviceGetInfo selectors */
#define CL_DEVICE_PARENT_DEVICE_EXT 0x4054
#define CL_DEVICE_PARTITION_TYPES_EXT 0x4055
#define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056
#define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057
#define CL_DEVICE_PARTITION_STYLE_EXT 0x4058
/* error codes */
#define CL_DEVICE_PARTITION_FAILED_EXT -1057
#define CL_INVALID_PARTITION_COUNT_EXT -1058
#define CL_INVALID_PARTITION_NAME_EXT -1059
/* CL_AFFINITY_DOMAINs */
#define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1
#define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2
#define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3
#define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4
#define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10
#define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100
/* cl_device_partition_property_ext list terminators */
#define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0)
#define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0)
#define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1)
/*********************************
* cl_qcom_ext_host_ptr extension
*********************************/
#define CL_MEM_EXT_HOST_PTR_QCOM (1 << 29)
#define CL_DEVICE_EXT_MEM_PADDING_IN_BYTES_QCOM 0x40A0
#define CL_DEVICE_PAGE_SIZE_QCOM 0x40A1
#define CL_IMAGE_ROW_ALIGNMENT_QCOM 0x40A2
#define CL_IMAGE_SLICE_ALIGNMENT_QCOM 0x40A3
#define CL_MEM_HOST_UNCACHED_QCOM 0x40A4
#define CL_MEM_HOST_WRITEBACK_QCOM 0x40A5
#define CL_MEM_HOST_WRITETHROUGH_QCOM 0x40A6
#define CL_MEM_HOST_WRITE_COMBINING_QCOM 0x40A7
typedef cl_uint cl_image_pitch_info_qcom;
extern CL_API_ENTRY cl_int CL_API_CALL
clGetDeviceImageInfoQCOM(cl_device_id device,
size_t image_width,
size_t image_height,
const cl_image_format *image_format,
cl_image_pitch_info_qcom param_name,
size_t param_value_size,
void *param_value,
size_t *param_value_size_ret);
typedef struct _cl_mem_ext_host_ptr
{
// Type of external memory allocation.
// Legal values will be defined in layered extensions.
cl_uint allocation_type;
// Host cache policy for this external memory allocation.
cl_uint host_cache_policy;
} cl_mem_ext_host_ptr;
/*********************************
* cl_qcom_ion_host_ptr extension
*********************************/
#define CL_MEM_ION_HOST_PTR_QCOM 0x40A8
typedef struct _cl_mem_ion_host_ptr
{
// Type of external memory allocation.
// Must be CL_MEM_ION_HOST_PTR_QCOM for ION allocations.
cl_mem_ext_host_ptr ext_host_ptr;
// ION file descriptor
int ion_filedesc;
// Host pointer to the ION allocated memory
void* ion_hostptr;
} cl_mem_ion_host_ptr;
#endif /* CL_VERSION_1_1 */
#ifdef __cplusplus
}
#endif
#endif /* __CL_EXT_H */
| {
"language": "C"
} |
/* ----------------------------------------------------------------------------
* SAM Software Package License
* ----------------------------------------------------------------------------
* Copyright (c) 2012, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following condition is met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ----------------------------------------------------------------------------
*/
#ifndef _SAM3XA_PMC_COMPONENT_
#define _SAM3XA_PMC_COMPONENT_
/* ============================================================================= */
/** SOFTWARE API DEFINITION FOR Power Management Controller */
/* ============================================================================= */
/** \addtogroup SAM3XA_PMC Power Management Controller */
/*@{*/
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
/** \brief Pmc hardware registers */
typedef struct {
WoReg PMC_SCER; /**< \brief (Pmc Offset: 0x0000) System Clock Enable Register */
WoReg PMC_SCDR; /**< \brief (Pmc Offset: 0x0004) System Clock Disable Register */
RoReg PMC_SCSR; /**< \brief (Pmc Offset: 0x0008) System Clock Status Register */
RoReg Reserved1[1];
WoReg PMC_PCER0; /**< \brief (Pmc Offset: 0x0010) Peripheral Clock Enable Register 0 */
WoReg PMC_PCDR0; /**< \brief (Pmc Offset: 0x0014) Peripheral Clock Disable Register 0 */
RoReg PMC_PCSR0; /**< \brief (Pmc Offset: 0x0018) Peripheral Clock Status Register 0 */
RwReg CKGR_UCKR; /**< \brief (Pmc Offset: 0x001C) UTMI Clock Register */
RwReg CKGR_MOR; /**< \brief (Pmc Offset: 0x0020) Main Oscillator Register */
RoReg CKGR_MCFR; /**< \brief (Pmc Offset: 0x0024) Main Clock Frequency Register */
RwReg CKGR_PLLAR; /**< \brief (Pmc Offset: 0x0028) PLLA Register */
RoReg Reserved2[1];
RwReg PMC_MCKR; /**< \brief (Pmc Offset: 0x0030) Master Clock Register */
RoReg Reserved3[1];
RwReg PMC_USB; /**< \brief (Pmc Offset: 0x0038) USB Clock Register */
RoReg Reserved4[1];
RwReg PMC_PCK[3]; /**< \brief (Pmc Offset: 0x0040) Programmable Clock 0 Register */
RoReg Reserved5[5];
WoReg PMC_IER; /**< \brief (Pmc Offset: 0x0060) Interrupt Enable Register */
WoReg PMC_IDR; /**< \brief (Pmc Offset: 0x0064) Interrupt Disable Register */
RoReg PMC_SR; /**< \brief (Pmc Offset: 0x0068) Status Register */
RoReg PMC_IMR; /**< \brief (Pmc Offset: 0x006C) Interrupt Mask Register */
RwReg PMC_FSMR; /**< \brief (Pmc Offset: 0x0070) Fast Startup Mode Register */
RwReg PMC_FSPR; /**< \brief (Pmc Offset: 0x0074) Fast Startup Polarity Register */
WoReg PMC_FOCR; /**< \brief (Pmc Offset: 0x0078) Fault Output Clear Register */
RoReg Reserved6[26];
RwReg PMC_WPMR; /**< \brief (Pmc Offset: 0x00E4) Write Protect Mode Register */
RoReg PMC_WPSR; /**< \brief (Pmc Offset: 0x00E8) Write Protect Status Register */
RoReg Reserved7[5];
WoReg PMC_PCER1; /**< \brief (Pmc Offset: 0x0100) Peripheral Clock Enable Register 1 */
WoReg PMC_PCDR1; /**< \brief (Pmc Offset: 0x0104) Peripheral Clock Disable Register 1 */
RoReg PMC_PCSR1; /**< \brief (Pmc Offset: 0x0108) Peripheral Clock Status Register 1 */
RwReg PMC_PCR; /**< \brief (Pmc Offset: 0x010C) Peripheral Control Register */
} Pmc;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
/* -------- PMC_SCER : (PMC Offset: 0x0000) System Clock Enable Register -------- */
#define PMC_SCER_UOTGCLK (0x1u << 5) /**< \brief (PMC_SCER) Enable USB OTG Clock (48 MHz, USB_48M) for UTMI */
#define PMC_SCER_PCK0 (0x1u << 8) /**< \brief (PMC_SCER) Programmable Clock 0 Output Enable */
#define PMC_SCER_PCK1 (0x1u << 9) /**< \brief (PMC_SCER) Programmable Clock 1 Output Enable */
#define PMC_SCER_PCK2 (0x1u << 10) /**< \brief (PMC_SCER) Programmable Clock 2 Output Enable */
/* -------- PMC_SCDR : (PMC Offset: 0x0004) System Clock Disable Register -------- */
#define PMC_SCDR_UOTGCLK (0x1u << 5) /**< \brief (PMC_SCDR) Disable USB OTG Clock (48 MHz, USB_48M) for UTMI */
#define PMC_SCDR_PCK0 (0x1u << 8) /**< \brief (PMC_SCDR) Programmable Clock 0 Output Disable */
#define PMC_SCDR_PCK1 (0x1u << 9) /**< \brief (PMC_SCDR) Programmable Clock 1 Output Disable */
#define PMC_SCDR_PCK2 (0x1u << 10) /**< \brief (PMC_SCDR) Programmable Clock 2 Output Disable */
/* -------- PMC_SCSR : (PMC Offset: 0x0008) System Clock Status Register -------- */
#define PMC_SCSR_UOTGCLK (0x1u << 5) /**< \brief (PMC_SCSR) USB OTG Clock (48 MHz, USB_48M) Clock Status */
#define PMC_SCSR_PCK0 (0x1u << 8) /**< \brief (PMC_SCSR) Programmable Clock 0 Output Status */
#define PMC_SCSR_PCK1 (0x1u << 9) /**< \brief (PMC_SCSR) Programmable Clock 1 Output Status */
#define PMC_SCSR_PCK2 (0x1u << 10) /**< \brief (PMC_SCSR) Programmable Clock 2 Output Status */
/* -------- PMC_PCER0 : (PMC Offset: 0x0010) Peripheral Clock Enable Register 0 -------- */
#define PMC_PCER0_PID2 (0x1u << 2) /**< \brief (PMC_PCER0) Peripheral Clock 2 Enable */
#define PMC_PCER0_PID3 (0x1u << 3) /**< \brief (PMC_PCER0) Peripheral Clock 3 Enable */
#define PMC_PCER0_PID4 (0x1u << 4) /**< \brief (PMC_PCER0) Peripheral Clock 4 Enable */
#define PMC_PCER0_PID5 (0x1u << 5) /**< \brief (PMC_PCER0) Peripheral Clock 5 Enable */
#define PMC_PCER0_PID6 (0x1u << 6) /**< \brief (PMC_PCER0) Peripheral Clock 6 Enable */
#define PMC_PCER0_PID7 (0x1u << 7) /**< \brief (PMC_PCER0) Peripheral Clock 7 Enable */
#define PMC_PCER0_PID8 (0x1u << 8) /**< \brief (PMC_PCER0) Peripheral Clock 8 Enable */
#define PMC_PCER0_PID9 (0x1u << 9) /**< \brief (PMC_PCER0) Peripheral Clock 9 Enable */
#define PMC_PCER0_PID10 (0x1u << 10) /**< \brief (PMC_PCER0) Peripheral Clock 10 Enable */
#define PMC_PCER0_PID11 (0x1u << 11) /**< \brief (PMC_PCER0) Peripheral Clock 11 Enable */
#define PMC_PCER0_PID12 (0x1u << 12) /**< \brief (PMC_PCER0) Peripheral Clock 12 Enable */
#define PMC_PCER0_PID13 (0x1u << 13) /**< \brief (PMC_PCER0) Peripheral Clock 13 Enable */
#define PMC_PCER0_PID14 (0x1u << 14) /**< \brief (PMC_PCER0) Peripheral Clock 14 Enable */
#define PMC_PCER0_PID15 (0x1u << 15) /**< \brief (PMC_PCER0) Peripheral Clock 15 Enable */
#define PMC_PCER0_PID16 (0x1u << 16) /**< \brief (PMC_PCER0) Peripheral Clock 16 Enable */
#define PMC_PCER0_PID17 (0x1u << 17) /**< \brief (PMC_PCER0) Peripheral Clock 17 Enable */
#define PMC_PCER0_PID18 (0x1u << 18) /**< \brief (PMC_PCER0) Peripheral Clock 18 Enable */
#define PMC_PCER0_PID19 (0x1u << 19) /**< \brief (PMC_PCER0) Peripheral Clock 19 Enable */
#define PMC_PCER0_PID20 (0x1u << 20) /**< \brief (PMC_PCER0) Peripheral Clock 20 Enable */
#define PMC_PCER0_PID21 (0x1u << 21) /**< \brief (PMC_PCER0) Peripheral Clock 21 Enable */
#define PMC_PCER0_PID22 (0x1u << 22) /**< \brief (PMC_PCER0) Peripheral Clock 22 Enable */
#define PMC_PCER0_PID23 (0x1u << 23) /**< \brief (PMC_PCER0) Peripheral Clock 23 Enable */
#define PMC_PCER0_PID24 (0x1u << 24) /**< \brief (PMC_PCER0) Peripheral Clock 24 Enable */
#define PMC_PCER0_PID25 (0x1u << 25) /**< \brief (PMC_PCER0) Peripheral Clock 25 Enable */
#define PMC_PCER0_PID26 (0x1u << 26) /**< \brief (PMC_PCER0) Peripheral Clock 26 Enable */
#define PMC_PCER0_PID27 (0x1u << 27) /**< \brief (PMC_PCER0) Peripheral Clock 27 Enable */
#define PMC_PCER0_PID28 (0x1u << 28) /**< \brief (PMC_PCER0) Peripheral Clock 28 Enable */
#define PMC_PCER0_PID29 (0x1u << 29) /**< \brief (PMC_PCER0) Peripheral Clock 29 Enable */
#define PMC_PCER0_PID30 (0x1u << 30) /**< \brief (PMC_PCER0) Peripheral Clock 30 Enable */
#define PMC_PCER0_PID31 (0x1u << 31) /**< \brief (PMC_PCER0) Peripheral Clock 31 Enable */
/* -------- PMC_PCDR0 : (PMC Offset: 0x0014) Peripheral Clock Disable Register 0 -------- */
#define PMC_PCDR0_PID2 (0x1u << 2) /**< \brief (PMC_PCDR0) Peripheral Clock 2 Disable */
#define PMC_PCDR0_PID3 (0x1u << 3) /**< \brief (PMC_PCDR0) Peripheral Clock 3 Disable */
#define PMC_PCDR0_PID4 (0x1u << 4) /**< \brief (PMC_PCDR0) Peripheral Clock 4 Disable */
#define PMC_PCDR0_PID5 (0x1u << 5) /**< \brief (PMC_PCDR0) Peripheral Clock 5 Disable */
#define PMC_PCDR0_PID6 (0x1u << 6) /**< \brief (PMC_PCDR0) Peripheral Clock 6 Disable */
#define PMC_PCDR0_PID7 (0x1u << 7) /**< \brief (PMC_PCDR0) Peripheral Clock 7 Disable */
#define PMC_PCDR0_PID8 (0x1u << 8) /**< \brief (PMC_PCDR0) Peripheral Clock 8 Disable */
#define PMC_PCDR0_PID9 (0x1u << 9) /**< \brief (PMC_PCDR0) Peripheral Clock 9 Disable */
#define PMC_PCDR0_PID10 (0x1u << 10) /**< \brief (PMC_PCDR0) Peripheral Clock 10 Disable */
#define PMC_PCDR0_PID11 (0x1u << 11) /**< \brief (PMC_PCDR0) Peripheral Clock 11 Disable */
#define PMC_PCDR0_PID12 (0x1u << 12) /**< \brief (PMC_PCDR0) Peripheral Clock 12 Disable */
#define PMC_PCDR0_PID13 (0x1u << 13) /**< \brief (PMC_PCDR0) Peripheral Clock 13 Disable */
#define PMC_PCDR0_PID14 (0x1u << 14) /**< \brief (PMC_PCDR0) Peripheral Clock 14 Disable */
#define PMC_PCDR0_PID15 (0x1u << 15) /**< \brief (PMC_PCDR0) Peripheral Clock 15 Disable */
#define PMC_PCDR0_PID16 (0x1u << 16) /**< \brief (PMC_PCDR0) Peripheral Clock 16 Disable */
#define PMC_PCDR0_PID17 (0x1u << 17) /**< \brief (PMC_PCDR0) Peripheral Clock 17 Disable */
#define PMC_PCDR0_PID18 (0x1u << 18) /**< \brief (PMC_PCDR0) Peripheral Clock 18 Disable */
#define PMC_PCDR0_PID19 (0x1u << 19) /**< \brief (PMC_PCDR0) Peripheral Clock 19 Disable */
#define PMC_PCDR0_PID20 (0x1u << 20) /**< \brief (PMC_PCDR0) Peripheral Clock 20 Disable */
#define PMC_PCDR0_PID21 (0x1u << 21) /**< \brief (PMC_PCDR0) Peripheral Clock 21 Disable */
#define PMC_PCDR0_PID22 (0x1u << 22) /**< \brief (PMC_PCDR0) Peripheral Clock 22 Disable */
#define PMC_PCDR0_PID23 (0x1u << 23) /**< \brief (PMC_PCDR0) Peripheral Clock 23 Disable */
#define PMC_PCDR0_PID24 (0x1u << 24) /**< \brief (PMC_PCDR0) Peripheral Clock 24 Disable */
#define PMC_PCDR0_PID25 (0x1u << 25) /**< \brief (PMC_PCDR0) Peripheral Clock 25 Disable */
#define PMC_PCDR0_PID26 (0x1u << 26) /**< \brief (PMC_PCDR0) Peripheral Clock 26 Disable */
#define PMC_PCDR0_PID27 (0x1u << 27) /**< \brief (PMC_PCDR0) Peripheral Clock 27 Disable */
#define PMC_PCDR0_PID28 (0x1u << 28) /**< \brief (PMC_PCDR0) Peripheral Clock 28 Disable */
#define PMC_PCDR0_PID29 (0x1u << 29) /**< \brief (PMC_PCDR0) Peripheral Clock 29 Disable */
#define PMC_PCDR0_PID30 (0x1u << 30) /**< \brief (PMC_PCDR0) Peripheral Clock 30 Disable */
#define PMC_PCDR0_PID31 (0x1u << 31) /**< \brief (PMC_PCDR0) Peripheral Clock 31 Disable */
/* -------- PMC_PCSR0 : (PMC Offset: 0x0018) Peripheral Clock Status Register 0 -------- */
#define PMC_PCSR0_PID2 (0x1u << 2) /**< \brief (PMC_PCSR0) Peripheral Clock 2 Status */
#define PMC_PCSR0_PID3 (0x1u << 3) /**< \brief (PMC_PCSR0) Peripheral Clock 3 Status */
#define PMC_PCSR0_PID4 (0x1u << 4) /**< \brief (PMC_PCSR0) Peripheral Clock 4 Status */
#define PMC_PCSR0_PID5 (0x1u << 5) /**< \brief (PMC_PCSR0) Peripheral Clock 5 Status */
#define PMC_PCSR0_PID6 (0x1u << 6) /**< \brief (PMC_PCSR0) Peripheral Clock 6 Status */
#define PMC_PCSR0_PID7 (0x1u << 7) /**< \brief (PMC_PCSR0) Peripheral Clock 7 Status */
#define PMC_PCSR0_PID8 (0x1u << 8) /**< \brief (PMC_PCSR0) Peripheral Clock 8 Status */
#define PMC_PCSR0_PID9 (0x1u << 9) /**< \brief (PMC_PCSR0) Peripheral Clock 9 Status */
#define PMC_PCSR0_PID10 (0x1u << 10) /**< \brief (PMC_PCSR0) Peripheral Clock 10 Status */
#define PMC_PCSR0_PID11 (0x1u << 11) /**< \brief (PMC_PCSR0) Peripheral Clock 11 Status */
#define PMC_PCSR0_PID12 (0x1u << 12) /**< \brief (PMC_PCSR0) Peripheral Clock 12 Status */
#define PMC_PCSR0_PID13 (0x1u << 13) /**< \brief (PMC_PCSR0) Peripheral Clock 13 Status */
#define PMC_PCSR0_PID14 (0x1u << 14) /**< \brief (PMC_PCSR0) Peripheral Clock 14 Status */
#define PMC_PCSR0_PID15 (0x1u << 15) /**< \brief (PMC_PCSR0) Peripheral Clock 15 Status */
#define PMC_PCSR0_PID16 (0x1u << 16) /**< \brief (PMC_PCSR0) Peripheral Clock 16 Status */
#define PMC_PCSR0_PID17 (0x1u << 17) /**< \brief (PMC_PCSR0) Peripheral Clock 17 Status */
#define PMC_PCSR0_PID18 (0x1u << 18) /**< \brief (PMC_PCSR0) Peripheral Clock 18 Status */
#define PMC_PCSR0_PID19 (0x1u << 19) /**< \brief (PMC_PCSR0) Peripheral Clock 19 Status */
#define PMC_PCSR0_PID20 (0x1u << 20) /**< \brief (PMC_PCSR0) Peripheral Clock 20 Status */
#define PMC_PCSR0_PID21 (0x1u << 21) /**< \brief (PMC_PCSR0) Peripheral Clock 21 Status */
#define PMC_PCSR0_PID22 (0x1u << 22) /**< \brief (PMC_PCSR0) Peripheral Clock 22 Status */
#define PMC_PCSR0_PID23 (0x1u << 23) /**< \brief (PMC_PCSR0) Peripheral Clock 23 Status */
#define PMC_PCSR0_PID24 (0x1u << 24) /**< \brief (PMC_PCSR0) Peripheral Clock 24 Status */
#define PMC_PCSR0_PID25 (0x1u << 25) /**< \brief (PMC_PCSR0) Peripheral Clock 25 Status */
#define PMC_PCSR0_PID26 (0x1u << 26) /**< \brief (PMC_PCSR0) Peripheral Clock 26 Status */
#define PMC_PCSR0_PID27 (0x1u << 27) /**< \brief (PMC_PCSR0) Peripheral Clock 27 Status */
#define PMC_PCSR0_PID28 (0x1u << 28) /**< \brief (PMC_PCSR0) Peripheral Clock 28 Status */
#define PMC_PCSR0_PID29 (0x1u << 29) /**< \brief (PMC_PCSR0) Peripheral Clock 29 Status */
#define PMC_PCSR0_PID30 (0x1u << 30) /**< \brief (PMC_PCSR0) Peripheral Clock 30 Status */
#define PMC_PCSR0_PID31 (0x1u << 31) /**< \brief (PMC_PCSR0) Peripheral Clock 31 Status */
/* -------- CKGR_UCKR : (PMC Offset: 0x001C) UTMI Clock Register -------- */
#define CKGR_UCKR_UPLLEN (0x1u << 16) /**< \brief (CKGR_UCKR) UTMI PLL Enable */
#define CKGR_UCKR_UPLLCOUNT_Pos 20
#define CKGR_UCKR_UPLLCOUNT_Msk (0xfu << CKGR_UCKR_UPLLCOUNT_Pos) /**< \brief (CKGR_UCKR) UTMI PLL Start-up Time */
#define CKGR_UCKR_UPLLCOUNT(value) ((CKGR_UCKR_UPLLCOUNT_Msk & ((value) << CKGR_UCKR_UPLLCOUNT_Pos)))
/* -------- CKGR_MOR : (PMC Offset: 0x0020) Main Oscillator Register -------- */
#define CKGR_MOR_MOSCXTEN (0x1u << 0) /**< \brief (CKGR_MOR) Main Crystal Oscillator Enable */
#define CKGR_MOR_MOSCXTBY (0x1u << 1) /**< \brief (CKGR_MOR) Main Crystal Oscillator Bypass */
#define CKGR_MOR_MOSCRCEN (0x1u << 3) /**< \brief (CKGR_MOR) Main On-Chip RC Oscillator Enable */
#define CKGR_MOR_MOSCRCF_Pos 4
#define CKGR_MOR_MOSCRCF_Msk (0x7u << CKGR_MOR_MOSCRCF_Pos) /**< \brief (CKGR_MOR) Main On-Chip RC Oscillator Frequency Selection */
#define CKGR_MOR_MOSCRCF_4_MHz (0x0u << 4) /**< \brief (CKGR_MOR) The Fast RC Oscillator Frequency is at 4 MHz (default) */
#define CKGR_MOR_MOSCRCF_8_MHz (0x1u << 4) /**< \brief (CKGR_MOR) The Fast RC Oscillator Frequency is at 8 MHz */
#define CKGR_MOR_MOSCRCF_12_MHz (0x2u << 4) /**< \brief (CKGR_MOR) The Fast RC Oscillator Frequency is at 12 MHz */
#define CKGR_MOR_MOSCXTST_Pos 8
#define CKGR_MOR_MOSCXTST_Msk (0xffu << CKGR_MOR_MOSCXTST_Pos) /**< \brief (CKGR_MOR) Main Crystal Oscillator Start-up Time */
#define CKGR_MOR_MOSCXTST(value) ((CKGR_MOR_MOSCXTST_Msk & ((value) << CKGR_MOR_MOSCXTST_Pos)))
#define CKGR_MOR_KEY_Pos 16
#define CKGR_MOR_KEY_Msk (0xffu << CKGR_MOR_KEY_Pos) /**< \brief (CKGR_MOR) Password */
#define CKGR_MOR_KEY(value) ((CKGR_MOR_KEY_Msk & ((value) << CKGR_MOR_KEY_Pos)))
#define CKGR_MOR_MOSCSEL (0x1u << 24) /**< \brief (CKGR_MOR) Main Oscillator Selection */
#define CKGR_MOR_CFDEN (0x1u << 25) /**< \brief (CKGR_MOR) Clock Failure Detector Enable */
/* -------- CKGR_MCFR : (PMC Offset: 0x0024) Main Clock Frequency Register -------- */
#define CKGR_MCFR_MAINF_Pos 0
#define CKGR_MCFR_MAINF_Msk (0xffffu << CKGR_MCFR_MAINF_Pos) /**< \brief (CKGR_MCFR) Main Clock Frequency */
#define CKGR_MCFR_MAINFRDY (0x1u << 16) /**< \brief (CKGR_MCFR) Main Clock Ready */
/* -------- CKGR_PLLAR : (PMC Offset: 0x0028) PLLA Register -------- */
#define CKGR_PLLAR_DIVA_Pos 0
#define CKGR_PLLAR_DIVA_Msk (0xffu << CKGR_PLLAR_DIVA_Pos) /**< \brief (CKGR_PLLAR) Divider */
#define CKGR_PLLAR_DIVA(value) ((CKGR_PLLAR_DIVA_Msk & ((value) << CKGR_PLLAR_DIVA_Pos)))
#define CKGR_PLLAR_PLLACOUNT_Pos 8
#define CKGR_PLLAR_PLLACOUNT_Msk (0x3fu << CKGR_PLLAR_PLLACOUNT_Pos) /**< \brief (CKGR_PLLAR) PLLA Counter */
#define CKGR_PLLAR_PLLACOUNT(value) ((CKGR_PLLAR_PLLACOUNT_Msk & ((value) << CKGR_PLLAR_PLLACOUNT_Pos)))
#define CKGR_PLLAR_MULA_Pos 16
#define CKGR_PLLAR_MULA_Msk (0x7ffu << CKGR_PLLAR_MULA_Pos) /**< \brief (CKGR_PLLAR) PLLA Multiplier */
#define CKGR_PLLAR_MULA(value) ((CKGR_PLLAR_MULA_Msk & ((value) << CKGR_PLLAR_MULA_Pos)))
#define CKGR_PLLAR_ONE (0x1u << 29) /**< \brief (CKGR_PLLAR) Must Be Set to 1 */
/* -------- PMC_MCKR : (PMC Offset: 0x0030) Master Clock Register -------- */
#define PMC_MCKR_CSS_Pos 0
#define PMC_MCKR_CSS_Msk (0x3u << PMC_MCKR_CSS_Pos) /**< \brief (PMC_MCKR) Master Clock Source Selection */
#define PMC_MCKR_CSS_SLOW_CLK (0x0u << 0) /**< \brief (PMC_MCKR) Slow Clock is selected */
#define PMC_MCKR_CSS_MAIN_CLK (0x1u << 0) /**< \brief (PMC_MCKR) Main Clock is selected */
#define PMC_MCKR_CSS_PLLA_CLK (0x2u << 0) /**< \brief (PMC_MCKR) PLLA Clock is selected */
#define PMC_MCKR_CSS_UPLL_CLK (0x3u << 0) /**< \brief (PMC_MCKR) UPLL Clock is selected */
#define PMC_MCKR_PRES_Pos 4
#define PMC_MCKR_PRES_Msk (0x7u << PMC_MCKR_PRES_Pos) /**< \brief (PMC_MCKR) Processor Clock Prescaler */
#define PMC_MCKR_PRES_CLK_1 (0x0u << 4) /**< \brief (PMC_MCKR) Selected clock */
#define PMC_MCKR_PRES_CLK_2 (0x1u << 4) /**< \brief (PMC_MCKR) Selected clock divided by 2 */
#define PMC_MCKR_PRES_CLK_4 (0x2u << 4) /**< \brief (PMC_MCKR) Selected clock divided by 4 */
#define PMC_MCKR_PRES_CLK_8 (0x3u << 4) /**< \brief (PMC_MCKR) Selected clock divided by 8 */
#define PMC_MCKR_PRES_CLK_16 (0x4u << 4) /**< \brief (PMC_MCKR) Selected clock divided by 16 */
#define PMC_MCKR_PRES_CLK_32 (0x5u << 4) /**< \brief (PMC_MCKR) Selected clock divided by 32 */
#define PMC_MCKR_PRES_CLK_64 (0x6u << 4) /**< \brief (PMC_MCKR) Selected clock divided by 64 */
#define PMC_MCKR_PRES_CLK_3 (0x7u << 4) /**< \brief (PMC_MCKR) Selected clock divided by 3 */
#define PMC_MCKR_PLLADIV2 (0x1u << 12) /**< \brief (PMC_MCKR) PLLA Divisor by 2 */
#define PMC_MCKR_UPLLDIV2 (0x1u << 13) /**< \brief (PMC_MCKR) */
/* -------- PMC_USB : (PMC Offset: 0x0038) USB Clock Register -------- */
#define PMC_USB_USBS (0x1u << 0) /**< \brief (PMC_USB) USB Input Clock Selection */
#define PMC_USB_USBDIV_Pos 8
#define PMC_USB_USBDIV_Msk (0xfu << PMC_USB_USBDIV_Pos) /**< \brief (PMC_USB) Divider for USB Clock. */
#define PMC_USB_USBDIV(value) ((PMC_USB_USBDIV_Msk & ((value) << PMC_USB_USBDIV_Pos)))
/* -------- PMC_PCK[3] : (PMC Offset: 0x0040) Programmable Clock 0 Register -------- */
#define PMC_PCK_CSS_Pos 0
#define PMC_PCK_CSS_Msk (0x7u << PMC_PCK_CSS_Pos) /**< \brief (PMC_PCK[3]) Master Clock Source Selection */
#define PMC_PCK_CSS_SLOW_CLK (0x0u << 0) /**< \brief (PMC_PCK[3]) Slow Clock is selected */
#define PMC_PCK_CSS_MAIN_CLK (0x1u << 0) /**< \brief (PMC_PCK[3]) Main Clock is selected */
#define PMC_PCK_CSS_PLLA_CLK (0x2u << 0) /**< \brief (PMC_PCK[3]) PLLA Clock is selected */
#define PMC_PCK_CSS_UPLL_CLK (0x3u << 0) /**< \brief (PMC_PCK[3]) UPLL Clock is selected */
#define PMC_PCK_CSS_MCK (0x4u << 0) /**< \brief (PMC_PCK[3]) Master Clock is selected */
#define PMC_PCK_PRES_Pos 4
#define PMC_PCK_PRES_Msk (0x7u << PMC_PCK_PRES_Pos) /**< \brief (PMC_PCK[3]) Programmable Clock Prescaler */
#define PMC_PCK_PRES_CLK_1 (0x0u << 4) /**< \brief (PMC_PCK[3]) Selected clock */
#define PMC_PCK_PRES_CLK_2 (0x1u << 4) /**< \brief (PMC_PCK[3]) Selected clock divided by 2 */
#define PMC_PCK_PRES_CLK_4 (0x2u << 4) /**< \brief (PMC_PCK[3]) Selected clock divided by 4 */
#define PMC_PCK_PRES_CLK_8 (0x3u << 4) /**< \brief (PMC_PCK[3]) Selected clock divided by 8 */
#define PMC_PCK_PRES_CLK_16 (0x4u << 4) /**< \brief (PMC_PCK[3]) Selected clock divided by 16 */
#define PMC_PCK_PRES_CLK_32 (0x5u << 4) /**< \brief (PMC_PCK[3]) Selected clock divided by 32 */
#define PMC_PCK_PRES_CLK_64 (0x6u << 4) /**< \brief (PMC_PCK[3]) Selected clock divided by 64 */
/* -------- PMC_IER : (PMC Offset: 0x0060) Interrupt Enable Register -------- */
#define PMC_IER_MOSCXTS (0x1u << 0) /**< \brief (PMC_IER) Main Crystal Oscillator Status Interrupt Enable */
#define PMC_IER_LOCKA (0x1u << 1) /**< \brief (PMC_IER) PLLA Lock Interrupt Enable */
#define PMC_IER_MCKRDY (0x1u << 3) /**< \brief (PMC_IER) Master Clock Ready Interrupt Enable */
#define PMC_IER_LOCKU (0x1u << 6) /**< \brief (PMC_IER) UTMI PLL Lock Interrupt Enable */
#define PMC_IER_PCKRDY0 (0x1u << 8) /**< \brief (PMC_IER) Programmable Clock Ready 0 Interrupt Enable */
#define PMC_IER_PCKRDY1 (0x1u << 9) /**< \brief (PMC_IER) Programmable Clock Ready 1 Interrupt Enable */
#define PMC_IER_PCKRDY2 (0x1u << 10) /**< \brief (PMC_IER) Programmable Clock Ready 2 Interrupt Enable */
#define PMC_IER_MOSCSELS (0x1u << 16) /**< \brief (PMC_IER) Main Oscillator Selection Status Interrupt Enable */
#define PMC_IER_MOSCRCS (0x1u << 17) /**< \brief (PMC_IER) Main On-Chip RC Status Interrupt Enable */
#define PMC_IER_CFDEV (0x1u << 18) /**< \brief (PMC_IER) Clock Failure Detector Event Interrupt Enable */
/* -------- PMC_IDR : (PMC Offset: 0x0064) Interrupt Disable Register -------- */
#define PMC_IDR_MOSCXTS (0x1u << 0) /**< \brief (PMC_IDR) Main Crystal Oscillator Status Interrupt Disable */
#define PMC_IDR_LOCKA (0x1u << 1) /**< \brief (PMC_IDR) PLLA Lock Interrupt Disable */
#define PMC_IDR_MCKRDY (0x1u << 3) /**< \brief (PMC_IDR) Master Clock Ready Interrupt Disable */
#define PMC_IDR_LOCKU (0x1u << 6) /**< \brief (PMC_IDR) UTMI PLL Lock Interrupt Disable */
#define PMC_IDR_PCKRDY0 (0x1u << 8) /**< \brief (PMC_IDR) Programmable Clock Ready 0 Interrupt Disable */
#define PMC_IDR_PCKRDY1 (0x1u << 9) /**< \brief (PMC_IDR) Programmable Clock Ready 1 Interrupt Disable */
#define PMC_IDR_PCKRDY2 (0x1u << 10) /**< \brief (PMC_IDR) Programmable Clock Ready 2 Interrupt Disable */
#define PMC_IDR_MOSCSELS (0x1u << 16) /**< \brief (PMC_IDR) Main Oscillator Selection Status Interrupt Disable */
#define PMC_IDR_MOSCRCS (0x1u << 17) /**< \brief (PMC_IDR) Main On-Chip RC Status Interrupt Disable */
#define PMC_IDR_CFDEV (0x1u << 18) /**< \brief (PMC_IDR) Clock Failure Detector Event Interrupt Disable */
/* -------- PMC_SR : (PMC Offset: 0x0068) Status Register -------- */
#define PMC_SR_MOSCXTS (0x1u << 0) /**< \brief (PMC_SR) Main XTAL Oscillator Status */
#define PMC_SR_LOCKA (0x1u << 1) /**< \brief (PMC_SR) PLLA Lock Status */
#define PMC_SR_MCKRDY (0x1u << 3) /**< \brief (PMC_SR) Master Clock Status */
#define PMC_SR_LOCKU (0x1u << 6) /**< \brief (PMC_SR) UTMI PLL Lock Status */
#define PMC_SR_OSCSELS (0x1u << 7) /**< \brief (PMC_SR) Slow Clock Oscillator Selection */
#define PMC_SR_PCKRDY0 (0x1u << 8) /**< \brief (PMC_SR) Programmable Clock Ready Status */
#define PMC_SR_PCKRDY1 (0x1u << 9) /**< \brief (PMC_SR) Programmable Clock Ready Status */
#define PMC_SR_PCKRDY2 (0x1u << 10) /**< \brief (PMC_SR) Programmable Clock Ready Status */
#define PMC_SR_MOSCSELS (0x1u << 16) /**< \brief (PMC_SR) Main Oscillator Selection Status */
#define PMC_SR_MOSCRCS (0x1u << 17) /**< \brief (PMC_SR) Main On-Chip RC Oscillator Status */
#define PMC_SR_CFDEV (0x1u << 18) /**< \brief (PMC_SR) Clock Failure Detector Event */
#define PMC_SR_CFDS (0x1u << 19) /**< \brief (PMC_SR) Clock Failure Detector Status */
#define PMC_SR_FOS (0x1u << 20) /**< \brief (PMC_SR) Clock Failure Detector Fault Output Status */
/* -------- PMC_IMR : (PMC Offset: 0x006C) Interrupt Mask Register -------- */
#define PMC_IMR_MOSCXTS (0x1u << 0) /**< \brief (PMC_IMR) Main Crystal Oscillator Status Interrupt Mask */
#define PMC_IMR_LOCKA (0x1u << 1) /**< \brief (PMC_IMR) PLLA Lock Interrupt Mask */
#define PMC_IMR_MCKRDY (0x1u << 3) /**< \brief (PMC_IMR) Master Clock Ready Interrupt Mask */
#define PMC_IMR_LOCKU (0x1u << 6) /**< \brief (PMC_IMR) UTMI PLL Lock Interrupt Mask */
#define PMC_IMR_PCKRDY0 (0x1u << 8) /**< \brief (PMC_IMR) Programmable Clock Ready 0 Interrupt Mask */
#define PMC_IMR_PCKRDY1 (0x1u << 9) /**< \brief (PMC_IMR) Programmable Clock Ready 1 Interrupt Mask */
#define PMC_IMR_PCKRDY2 (0x1u << 10) /**< \brief (PMC_IMR) Programmable Clock Ready 2 Interrupt Mask */
#define PMC_IMR_MOSCSELS (0x1u << 16) /**< \brief (PMC_IMR) Main Oscillator Selection Status Interrupt Mask */
#define PMC_IMR_MOSCRCS (0x1u << 17) /**< \brief (PMC_IMR) Main On-Chip RC Status Interrupt Mask */
#define PMC_IMR_CFDEV (0x1u << 18) /**< \brief (PMC_IMR) Clock Failure Detector Event Interrupt Mask */
/* -------- PMC_FSMR : (PMC Offset: 0x0070) Fast Startup Mode Register -------- */
#define PMC_FSMR_FSTT0 (0x1u << 0) /**< \brief (PMC_FSMR) Fast Startup Input Enable 0 */
#define PMC_FSMR_FSTT1 (0x1u << 1) /**< \brief (PMC_FSMR) Fast Startup Input Enable 1 */
#define PMC_FSMR_FSTT2 (0x1u << 2) /**< \brief (PMC_FSMR) Fast Startup Input Enable 2 */
#define PMC_FSMR_FSTT3 (0x1u << 3) /**< \brief (PMC_FSMR) Fast Startup Input Enable 3 */
#define PMC_FSMR_FSTT4 (0x1u << 4) /**< \brief (PMC_FSMR) Fast Startup Input Enable 4 */
#define PMC_FSMR_FSTT5 (0x1u << 5) /**< \brief (PMC_FSMR) Fast Startup Input Enable 5 */
#define PMC_FSMR_FSTT6 (0x1u << 6) /**< \brief (PMC_FSMR) Fast Startup Input Enable 6 */
#define PMC_FSMR_FSTT7 (0x1u << 7) /**< \brief (PMC_FSMR) Fast Startup Input Enable 7 */
#define PMC_FSMR_FSTT8 (0x1u << 8) /**< \brief (PMC_FSMR) Fast Startup Input Enable 8 */
#define PMC_FSMR_FSTT9 (0x1u << 9) /**< \brief (PMC_FSMR) Fast Startup Input Enable 9 */
#define PMC_FSMR_FSTT10 (0x1u << 10) /**< \brief (PMC_FSMR) Fast Startup Input Enable 10 */
#define PMC_FSMR_FSTT11 (0x1u << 11) /**< \brief (PMC_FSMR) Fast Startup Input Enable 11 */
#define PMC_FSMR_FSTT12 (0x1u << 12) /**< \brief (PMC_FSMR) Fast Startup Input Enable 12 */
#define PMC_FSMR_FSTT13 (0x1u << 13) /**< \brief (PMC_FSMR) Fast Startup Input Enable 13 */
#define PMC_FSMR_FSTT14 (0x1u << 14) /**< \brief (PMC_FSMR) Fast Startup Input Enable 14 */
#define PMC_FSMR_FSTT15 (0x1u << 15) /**< \brief (PMC_FSMR) Fast Startup Input Enable 15 */
#define PMC_FSMR_RTTAL (0x1u << 16) /**< \brief (PMC_FSMR) RTT Alarm Enable */
#define PMC_FSMR_RTCAL (0x1u << 17) /**< \brief (PMC_FSMR) RTC Alarm Enable */
#define PMC_FSMR_USBAL (0x1u << 18) /**< \brief (PMC_FSMR) USB Alarm Enable */
#define PMC_FSMR_LPM (0x1u << 20) /**< \brief (PMC_FSMR) Low Power Mode */
/* -------- PMC_FSPR : (PMC Offset: 0x0074) Fast Startup Polarity Register -------- */
#define PMC_FSPR_FSTP0 (0x1u << 0) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP1 (0x1u << 1) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP2 (0x1u << 2) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP3 (0x1u << 3) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP4 (0x1u << 4) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP5 (0x1u << 5) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP6 (0x1u << 6) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP7 (0x1u << 7) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP8 (0x1u << 8) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP9 (0x1u << 9) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP10 (0x1u << 10) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP11 (0x1u << 11) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP12 (0x1u << 12) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP13 (0x1u << 13) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP14 (0x1u << 14) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
#define PMC_FSPR_FSTP15 (0x1u << 15) /**< \brief (PMC_FSPR) Fast Startup Input Polarityx */
/* -------- PMC_FOCR : (PMC Offset: 0x0078) Fault Output Clear Register -------- */
#define PMC_FOCR_FOCLR (0x1u << 0) /**< \brief (PMC_FOCR) Fault Output Clear */
/* -------- PMC_WPMR : (PMC Offset: 0x00E4) Write Protect Mode Register -------- */
#define PMC_WPMR_WPEN (0x1u << 0) /**< \brief (PMC_WPMR) Write Protect Enable */
#define PMC_WPMR_WPKEY_Pos 8
#define PMC_WPMR_WPKEY_Msk (0xffffffu << PMC_WPMR_WPKEY_Pos) /**< \brief (PMC_WPMR) Write Protect KEY */
#define PMC_WPMR_WPKEY(value) ((PMC_WPMR_WPKEY_Msk & ((value) << PMC_WPMR_WPKEY_Pos)))
/* -------- PMC_WPSR : (PMC Offset: 0x00E8) Write Protect Status Register -------- */
#define PMC_WPSR_WPVS (0x1u << 0) /**< \brief (PMC_WPSR) Write Protect Violation Status */
#define PMC_WPSR_WPVSRC_Pos 8
#define PMC_WPSR_WPVSRC_Msk (0xffffu << PMC_WPSR_WPVSRC_Pos) /**< \brief (PMC_WPSR) Write Protect Violation Source */
/* -------- PMC_PCER1 : (PMC Offset: 0x0100) Peripheral Clock Enable Register 1 -------- */
#define PMC_PCER1_PID32 (0x1u << 0) /**< \brief (PMC_PCER1) Peripheral Clock 32 Enable */
#define PMC_PCER1_PID33 (0x1u << 1) /**< \brief (PMC_PCER1) Peripheral Clock 33 Enable */
#define PMC_PCER1_PID34 (0x1u << 2) /**< \brief (PMC_PCER1) Peripheral Clock 34 Enable */
#define PMC_PCER1_PID35 (0x1u << 3) /**< \brief (PMC_PCER1) Peripheral Clock 35 Enable */
#define PMC_PCER1_PID36 (0x1u << 4) /**< \brief (PMC_PCER1) Peripheral Clock 36 Enable */
#define PMC_PCER1_PID37 (0x1u << 5) /**< \brief (PMC_PCER1) Peripheral Clock 37 Enable */
#define PMC_PCER1_PID38 (0x1u << 6) /**< \brief (PMC_PCER1) Peripheral Clock 38 Enable */
#define PMC_PCER1_PID39 (0x1u << 7) /**< \brief (PMC_PCER1) Peripheral Clock 39 Enable */
#define PMC_PCER1_PID40 (0x1u << 8) /**< \brief (PMC_PCER1) Peripheral Clock 40 Enable */
#define PMC_PCER1_PID41 (0x1u << 9) /**< \brief (PMC_PCER1) Peripheral Clock 41 Enable */
#define PMC_PCER1_PID42 (0x1u << 10) /**< \brief (PMC_PCER1) Peripheral Clock 42 Enable */
#define PMC_PCER1_PID43 (0x1u << 11) /**< \brief (PMC_PCER1) Peripheral Clock 43 Enable */
#define PMC_PCER1_PID44 (0x1u << 12) /**< \brief (PMC_PCER1) Peripheral Clock 44 Enable */
/* -------- PMC_PCDR1 : (PMC Offset: 0x0104) Peripheral Clock Disable Register 1 -------- */
#define PMC_PCDR1_PID32 (0x1u << 0) /**< \brief (PMC_PCDR1) Peripheral Clock 32 Disable */
#define PMC_PCDR1_PID33 (0x1u << 1) /**< \brief (PMC_PCDR1) Peripheral Clock 33 Disable */
#define PMC_PCDR1_PID34 (0x1u << 2) /**< \brief (PMC_PCDR1) Peripheral Clock 34 Disable */
#define PMC_PCDR1_PID35 (0x1u << 3) /**< \brief (PMC_PCDR1) Peripheral Clock 35 Disable */
#define PMC_PCDR1_PID36 (0x1u << 4) /**< \brief (PMC_PCDR1) Peripheral Clock 36 Disable */
#define PMC_PCDR1_PID37 (0x1u << 5) /**< \brief (PMC_PCDR1) Peripheral Clock 37 Disable */
#define PMC_PCDR1_PID38 (0x1u << 6) /**< \brief (PMC_PCDR1) Peripheral Clock 38 Disable */
#define PMC_PCDR1_PID39 (0x1u << 7) /**< \brief (PMC_PCDR1) Peripheral Clock 39 Disable */
#define PMC_PCDR1_PID40 (0x1u << 8) /**< \brief (PMC_PCDR1) Peripheral Clock 40 Disable */
#define PMC_PCDR1_PID41 (0x1u << 9) /**< \brief (PMC_PCDR1) Peripheral Clock 41 Disable */
#define PMC_PCDR1_PID42 (0x1u << 10) /**< \brief (PMC_PCDR1) Peripheral Clock 42 Disable */
#define PMC_PCDR1_PID43 (0x1u << 11) /**< \brief (PMC_PCDR1) Peripheral Clock 43 Disable */
#define PMC_PCDR1_PID44 (0x1u << 12) /**< \brief (PMC_PCDR1) Peripheral Clock 44 Disable */
/* -------- PMC_PCSR1 : (PMC Offset: 0x0108) Peripheral Clock Status Register 1 -------- */
#define PMC_PCSR1_PID32 (0x1u << 0) /**< \brief (PMC_PCSR1) Peripheral Clock 32 Status */
#define PMC_PCSR1_PID33 (0x1u << 1) /**< \brief (PMC_PCSR1) Peripheral Clock 33 Status */
#define PMC_PCSR1_PID34 (0x1u << 2) /**< \brief (PMC_PCSR1) Peripheral Clock 34 Status */
#define PMC_PCSR1_PID35 (0x1u << 3) /**< \brief (PMC_PCSR1) Peripheral Clock 35 Status */
#define PMC_PCSR1_PID36 (0x1u << 4) /**< \brief (PMC_PCSR1) Peripheral Clock 36 Status */
#define PMC_PCSR1_PID37 (0x1u << 5) /**< \brief (PMC_PCSR1) Peripheral Clock 37 Status */
#define PMC_PCSR1_PID38 (0x1u << 6) /**< \brief (PMC_PCSR1) Peripheral Clock 38 Status */
#define PMC_PCSR1_PID39 (0x1u << 7) /**< \brief (PMC_PCSR1) Peripheral Clock 39 Status */
#define PMC_PCSR1_PID40 (0x1u << 8) /**< \brief (PMC_PCSR1) Peripheral Clock 40 Status */
#define PMC_PCSR1_PID41 (0x1u << 9) /**< \brief (PMC_PCSR1) Peripheral Clock 41 Status */
#define PMC_PCSR1_PID42 (0x1u << 10) /**< \brief (PMC_PCSR1) Peripheral Clock 42 Status */
#define PMC_PCSR1_PID43 (0x1u << 11) /**< \brief (PMC_PCSR1) Peripheral Clock 43 Status */
#define PMC_PCSR1_PID44 (0x1u << 12) /**< \brief (PMC_PCSR1) Peripheral Clock 44 Status */
/* -------- PMC_PCR : (PMC Offset: 0x010C) Peripheral Control Register -------- */
#define PMC_PCR_PID_Pos 0
#define PMC_PCR_PID_Msk (0x3fu << PMC_PCR_PID_Pos) /**< \brief (PMC_PCR) Peripheral ID */
#define PMC_PCR_PID(value) ((PMC_PCR_PID_Msk & ((value) << PMC_PCR_PID_Pos)))
#define PMC_PCR_CMD (0x1u << 12) /**< \brief (PMC_PCR) Command */
#define PMC_PCR_DIV_Pos 16
#define PMC_PCR_DIV_Msk (0x3u << PMC_PCR_DIV_Pos) /**< \brief (PMC_PCR) Divisor Value */
#define PMC_PCR_DIV_PERIPH_DIV_MCK (0x0u << 16) /**< \brief (PMC_PCR) Peripheral clock is MCK */
#define PMC_PCR_DIV_PERIPH_DIV2_MCK (0x1u << 16) /**< \brief (PMC_PCR) Peripheral clock is MCK/2 */
#define PMC_PCR_DIV_PERIPH_DIV4_MCK (0x2u << 16) /**< \brief (PMC_PCR) Peripheral clock is MCK/4 */
#define PMC_PCR_EN (0x1u << 28) /**< \brief (PMC_PCR) Enable */
/*@}*/
#endif /* _SAM3XA_PMC_COMPONENT_ */
| {
"language": "C"
} |
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014-2020 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LCBIO_CTXEASY_H
#define LCBIO_CTXEASY_H
#include "connect.h"
#include "rdb/rope.h"
#include "ringbuffer.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @file
* This file contains routines for reading and writing from and to a socket
*/
/**
* @ingroup lcbio
* @defgroup lcbio-ctx Reading/Writing Routines
*
* @details
*
* # Attaching
*
* A context is first _attached_ to a socket and a _user-defined_ data object.
* The idea is that the context is the broker which schedules I/O on behalf
* of the application to the socket, and then receives events from the socket,
* passing it along to user-defined data.
*
* To create a new context, invoke the lcbio_ctx_new() function. When you are done
* with it call the lcbio_ctx_close() function.
*
* # Reading
*
* Reading data is done through first requesting an amount of data to read
* and then reading the data from the buffers when the lcbio_CTXPROCS#cb_read
* handler is invoked.
*
* Requesting an amount of data to be read may be dependent on some current
* parsing context. In cases where the expected message size is known the pattern
* is to initially request the size of the header; once the header has been
* delivered to the application, the application should request the full
* header+body size, and so on.
*
* For streaming based protocols where the amount of data is not known ahead of
* time, requesting a single byte may be sufficient. Note that typically the
* read callback will be invoked with _more_ bytes than requested.
*
* Data is read from the network as one or more chunks to improve performance
* and increase flexibility. Because of this model, you must iterate over the
* data read _or_ employ the underlying <rdb/rope.h> API. For streaming data
* sockets where data may simply be copied to another buffer, use the iterator
* API presented here.
*
* @note The RDB interface requires you to explicitly advance the read
* cursor in addition to actually obtaining the data. This is handled within
* the iterator interface declared in this file (but of course must be done
* manually if employing RDB directly).
*
*
* # Writing
*
* Writing can be done through a simple lcbio_ctx_put() which simply copies data
* to an output buffer, or can be done through more efficient but complex means -
* see the lcbio_ctx_wwant() function.
*
* # Scheduling
*
* Any I/O **must always be scheduled**. For maximal efficiency the various
* read/write functions only set internal flags within the contexts to act
* as hints that the application intends to read and write data. However in
* order to actually perform these operations, kernel/OS calls are needed.
*
* To indicate that no subsequent I/O operations will be requested until the next
* event loop iteration, _and_ to apply/schedule any existing I/O within the
* current iteration, the lcbio_ctx_schedule() function should be called.
*
*
* @addtogroup lcbio-ctx
* @{ */
typedef struct lcbio_CTX *lcbio_pCTX;
/**
* @brief Handlers for I/O events
*/
typedef struct {
/** Error handler invoked with the context and the received error */
void (*cb_err)(lcbio_pCTX, lcb_STATUS);
/** Read handler invoked with the context and the number of bytes read */
void (*cb_read)(lcbio_pCTX, unsigned total);
/** Triggered by lcbio_ctx_wwant() */
void (*cb_flush_ready)(lcbio_pCTX);
/** Triggered when data has been flushed from lcbio_ctx_put_ex() */
void (*cb_flush_done)(lcbio_pCTX, unsigned requested, unsigned nflushed);
} lcbio_CTXPROCS;
/**
* Container buffer handle containing a backref to the original context.
* @private
*/
typedef struct {
ringbuffer_t rb;
lcbio_pCTX parent;
} lcbio__EASYRB;
/**
* @brief Context for socket I/O
*
* The CTX structure represents an ownership of a socket. It provides routines
* for reading and writing from and to the socket, as well as associating
* application data with the socket.
*/
typedef struct lcbio_CTX {
lcbio_SOCKET *sock; /**< Socket resource */
lcbio_pTABLE io; /**< Cached IO table */
void *data; /**< Associative pointer */
void *event; /**< event pointer for E-model I/O */
lcb_sockdata_t *sd; /**< cached SD for C-model I/O */
lcbio__EASYRB *output; /**< for lcbio_ctx_put() */
lcb_socket_t fd; /**< cached FD for E-model I/O */
char evactive; /**< watcher is active for E-model I/O */
char wwant; /**< flag for lcbio_ctx_put_ex */
char state; /**< internal state */
char entered; /**< inside event handler */
unsigned npending; /**< reference count on pending I/O */
unsigned rdwant; /**< number of remaining bytes to read */
lcb_STATUS err; /**< pending error */
rdb_IOROPE ior; /**< for reads */
lcbio_pASYNC as_err; /**< async error handler */
lcbio_CTXPROCS procs; /**< callbacks */
const char *subsys; /**< Informational description of connection */
} lcbio_CTX;
/**@name Creating and Closing
*@{*/
/**
* Creates a new context object.
*
* The object remains valid until lcbio_ctx_close() is invoked.
*
* @param sock the underlying socket object. This function increments the
* socket's reference count.
* @param data user defined data to associate with context. The data may be
* obtained at a later point via lcbio_ctx_data()
*
* @param procs callback table
* @return a new context object.
*/
lcbio_CTX *lcbio_ctx_new(lcbio_SOCKET *sock, void *data, const lcbio_CTXPROCS *procs);
/**
* Callback invoked when the connection is about to be release
* @param sock the socket being released.
* @param releasable whether the socket may be reused
* @param arg an argument passed to the close() function.
*
* If you wish to reuse the socket (and reusable is true) then the socket's
* reference count should be incremented via lcbio_ref().
*/
typedef void (*lcbio_CTXCLOSE_cb)(lcbio_SOCKET *sock, int releasable, void *arg);
/**
* @brief Close the context object.
*
* This will invalidate any pending I/O operations
* and subsequent callbacks on the context will not be received. After calling
* this function, the pointer will be deemed invalid.
*
* @param ctx
* @param callback a callback to invoke (see above)
* @param arg argument passed to the callback
*/
void lcbio_ctx_close(lcbio_CTX *ctx, lcbio_CTXCLOSE_cb callback, void *arg);
typedef void (*lcbio_CTXDTOR_cb)(lcbio_pCTX);
void lcbio_ctx_close_ex(lcbio_CTX *ctx, lcbio_CTXCLOSE_cb cb, void *cbarg, lcbio_CTXDTOR_cb dtor, void *dtor_arg);
/**@}*/
/**@name Informational Routines
* @{*/
/**
* Get the data associated with the context. This is the pointer specified
* during the constructor
*/
#define lcbio_ctx_data(ctx) (ctx)->data
/** Get the associated lcbio_SOCKET object */
#define lcbio_ctx_sock(ctx) (ctx)->sock
/** Dump a textual representation of the context to the screen */
void lcbio_ctx_dump(lcbio_CTX *ctx, FILE *fp);
/**@}*/
/** Asynchronously trigger the error callback */
void lcbio_ctx_senderr(lcbio_CTX *ctx, lcb_STATUS err);
/**
* Schedule any pending I/O to be scheduled immediately. If data was requested
* via lcbio_ctx_rwant() then a request will be sent for reading. If data was
* requested to be flushed either via lcbio_ctx_put() or lcbio_ctx_wwant()
* then those will be scheduled as well.
*
* This call is a no-op if invoked from within the current handler, as this
* function is invoked implicitly after the I/O handler itself has returned.
*
* It is safe (though typically not efficient) to invoke this function
* multiple times. Each invocation may potentially involve system calls
* and buffer allocations, depending on the I/O plugin being used.
*/
void lcbio_ctx_schedule(lcbio_CTX *ctx);
/**
* @brief Add output data to the write buffer.
*
* The data added is copied to an internal buffer and flushed to the network
* when appropriate. If you wish to have more control over how the data is written
* then see the lcbio_ctx_wwant() function.
*
* @param ctx
* @param buf the buffer to write
* @param nbuf the size of the buffer to write
*/
void lcbio_ctx_put(lcbio_CTX *ctx, const void *buf, unsigned nbuf);
/**
* Invoke the lcbio_CTXPROCS#cb_flush_ready()
* callback when a flush may be invoked. Note that the
* callback may be invoked from within this function itself, or
* it may be invoked at some point later.
*
* In order to ensure that the callback is actually invoked (in
* cases where it is not invoked immediately), call lcbio_ctx_schedule()
* before returning to the loop.
*
* When the callback is invoked, you should call the lcbio_ctx_put_ex() function
* to actually enqueue the data to be written. The lcbio_ctx_put_ex() function
* should be called multiple times until either no write buffers remain
* or the function itself returns a false value. The lcbio_ctx_put_ex() function
* may either flush the data immediately or schedule for the data to be flushed
* depending on the I/O implementation and network conditions.
*
* Once the data is actually flushed to the socket's buffers, the
* lcbio_CTXPROCS#cb_flush_done() callback is invoked.
* This callback indicates the underlying buffers are no longer required and may
* be released or reused by the application. Note that the IOV array passed
* into lcbio_ctx_put_ex() is always _Conceptually_ copied (i.e.
* this may be a stack-based structure which does not need to remain valid
* outside the function call to lcbio_ctx_put_ex() itself).
*
* Additionally, note that the number of bytes flushed within the
* lcbio_CTXPROCS#cb_flush_done()
* callback may not equal the number of bytes initially placed inside the IOVs
* (i.e. it may be less). In this case the application is expected to update
* the IOV structures and the origin buffers appropriately.
*
* This model allows for efficient handling in both completion and event based
* environments.
*
* ### Implementation Notes
*
* For completion-based models, the lcbio_CTXPROCS#cb_flush_ready()
* callback is invoked immediately from the wwant() function, while the
* flush_done() is dependent on the actual completion of the write.
*
* For event-based models, the wwant flag is set inside the context and is then
* checked by the lcbio_ctx_schedule() function. When the event handler is invoked, the
* flush_ready() callback is invoked as well - typically in a loop until an
* `EWOULDBLOCK` is received on the socket itself.
*/
void lcbio_ctx_wwant(lcbio_CTX *ctx);
/**
* @brief Flush data from the lcbio_CTXPROCS#cb_flush_ready() callback
*
* This function is intended to be called from within the `cb_flush_ready`
* handler (see lcbio_ctx_wwant()).
*
* @param ctx
* @param iov the IOV array. The IOV array may point to a stack-based array
* @param niov number of elements in the array
* @param nb The total number of bytes described by all the elements of the
* array.
*
* @return nonzero if more data can be written (i.e. this function may be
* invoked again), zero otherwise.
*/
int lcbio_ctx_put_ex(lcbio_CTX *ctx, lcb_IOV *iov, unsigned niov, unsigned nb);
/**
* Require that the read callback not be invoked until at least `n`
* bytes are available within the buffer.
*
* @param ctx
* @param n the number of bytes required to be in the buffer before the
* callback should be invoked.
*
* @note
* Note that this flag does _not_ maintain state between successive callbacks.
* You must call this function each time you need more data as it is cleared
* before the invocation into the callback.
*
* @note
* This function sets the number of **total** bytes
* which must be available in the buffer before the callback is invoked. Thus
* you should set this to the total number of bytes needed, and **not** the
* number of remaining bytes that should be read.
*/
void lcbio_ctx_rwant(lcbio_CTX *ctx, unsigned n);
/** @private */
typedef struct {
unsigned remaining;
void *buf;
unsigned nbuf;
} lcbio_CTXRDITER;
/**
* Iterate over the read buffers
*
* @code{.c}
* static void read_callback(lcbio_CTX *ctx, void *arg, unsigned nb) {
* lcbio_CTXRDITER iter;
* LCBIO_CTX_ITERFOR(ctx, &iter, nb) {
* void *buf = lcbio_ctx_ribuf(&iter);
* unsigned nbuf = lcbio_ctx_risize(&iter);
* // do stuff with the buffer
* }
* }
* @endcode
*
* When each iteration is complete, the pointer returned by ctx_ribuf is
* no longer valid.
*
* @param ctx the context which contains the buffer
* @param[in,out] iter an empty iterator
* @param[in] nb the number of bytes to iterate over.
*/
#define LCBIO_CTX_ITERFOR(ctx, iter, nb) \
for (lcbio_ctx_ristart(ctx, iter, nb); !lcbio_ctx_ridone(iter); lcbio_ctx_rinext(ctx, iter))
/** Obtains the buffer from the current iterator */
#define lcbio_ctx_ribuf(iter) ((iter)->buf)
/** Obtains the length of the buffer from the current iterator */
#define lcbio_ctx_risize(iter) ((iter)->nbuf)
void lcbio_ctx_ristart(lcbio_CTX *ctx, lcbio_CTXRDITER *iter, unsigned nb);
void lcbio_ctx_rinext(lcbio_CTX *ctx, lcbio_CTXRDITER *iter);
#define lcbio_ctx_ridone(iter) (!(iter)->remaining)
#define LCBIO_CTX_RSCHEDULE(ctx, nb) \
do { \
lcbio_ctx_rwant(ctx, nb); \
lcbio_ctx_schedule(ctx); \
} while (0)
#ifdef __cplusplus
}
#endif
#endif
/** @} */
| {
"language": "C"
} |
#ifndef LINUX_KERNEL_PAGE_FLAGS_H
#define LINUX_KERNEL_PAGE_FLAGS_H
/*
* Stable page flag bits exported to user space
*/
#define KPF_LOCKED 0
#define KPF_ERROR 1
#define KPF_REFERENCED 2
#define KPF_UPTODATE 3
#define KPF_DIRTY 4
#define KPF_LRU 5
#define KPF_ACTIVE 6
#define KPF_SLAB 7
#define KPF_WRITEBACK 8
#define KPF_RECLAIM 9
#define KPF_BUDDY 10
/* 11-20: new additions in 2.6.31 */
#define KPF_MMAP 11
#define KPF_ANON 12
#define KPF_SWAPCACHE 13
#define KPF_SWAPBACKED 14
#define KPF_COMPOUND_HEAD 15
#define KPF_COMPOUND_TAIL 16
#define KPF_HUGE 17
#define KPF_UNEVICTABLE 18
#define KPF_HWPOISON 19
#define KPF_NOPAGE 20
#define KPF_KSM 21
/* kernel hacking assistances
* WARNING: subject to change, never rely on them!
*/
#define KPF_RESERVED 32
#define KPF_MLOCKED 33
#define KPF_MAPPEDTODISK 34
#define KPF_PRIVATE 35
#define KPF_PRIVATE_2 36
#define KPF_OWNER_PRIVATE 37
#define KPF_ARCH 38
#define KPF_UNCACHED 39
#endif /* LINUX_KERNEL_PAGE_FLAGS_H */
| {
"language": "C"
} |
// SPDX-License-Identifier: GPL-2.0-only
/* Low-level parallel-port routines for 8255-based PC-style hardware.
*
* Authors: Phil Blundell <philb@gnu.org>
* Tim Waugh <tim@cyberelk.demon.co.uk>
* Jose Renau <renau@acm.org>
* David Campbell
* Andrea Arcangeli
*
* based on work by Grant Guenther <grant@torque.net> and Phil Blundell.
*
* Cleaned up include files - Russell King <linux@arm.uk.linux.org>
* DMA support - Bert De Jonghe <bert@sophis.be>
* Many ECP bugs fixed. Fred Barnes & Jamie Lokier, 1999
* More PCI support now conditional on CONFIG_PCI, 03/2001, Paul G.
* Various hacks, Fred Barnes, 04/2001
* Updated probing logic - Adam Belay <ambx1@neo.rr.com>
*/
/* This driver should work with any hardware that is broadly compatible
* with that in the IBM PC. This applies to the majority of integrated
* I/O chipsets that are commonly available. The expected register
* layout is:
*
* base+0 data
* base+1 status
* base+2 control
*
* In addition, there are some optional registers:
*
* base+3 EPP address
* base+4 EPP data
* base+0x400 ECP config A
* base+0x401 ECP config B
* base+0x402 ECP control
*
* All registers are 8 bits wide and read/write. If your hardware differs
* only in register addresses (eg because your registers are on 32-bit
* word boundaries) then you can alter the constants in parport_pc.h to
* accommodate this.
*
* Note that the ECP registers may not start at offset 0x400 for PCI cards,
* but rather will start at port->base_hi.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched/signal.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/pci.h>
#include <linux/pnp.h>
#include <linux/platform_device.h>
#include <linux/sysctl.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <asm/dma.h>
#include <linux/parport.h>
#include <linux/parport_pc.h>
#include <linux/via.h>
#include <asm/parport.h>
#define PARPORT_PC_MAX_PORTS PARPORT_MAX
#ifdef CONFIG_ISA_DMA_API
#define HAS_DMA
#endif
/* ECR modes */
#define ECR_SPP 00
#define ECR_PS2 01
#define ECR_PPF 02
#define ECR_ECP 03
#define ECR_EPP 04
#define ECR_VND 05
#define ECR_TST 06
#define ECR_CNF 07
#define ECR_MODE_MASK 0xe0
#define ECR_WRITE(p, v) frob_econtrol((p), 0xff, (v))
#undef DEBUG
#define NR_SUPERIOS 3
static struct superio_struct { /* For Super-IO chips autodetection */
int io;
int irq;
int dma;
} superios[NR_SUPERIOS] = { {0,},};
static int user_specified;
#if defined(CONFIG_PARPORT_PC_SUPERIO) || \
(defined(CONFIG_PARPORT_1284) && defined(CONFIG_PARPORT_PC_FIFO))
static int verbose_probing;
#endif
static int pci_registered_parport;
static int pnp_registered_parport;
/* frob_control, but for ECR */
static void frob_econtrol(struct parport *pb, unsigned char m,
unsigned char v)
{
unsigned char ectr = 0;
if (m != 0xff)
ectr = inb(ECONTROL(pb));
pr_debug("frob_econtrol(%02x,%02x): %02x -> %02x\n",
m, v, ectr, (ectr & ~m) ^ v);
outb((ectr & ~m) ^ v, ECONTROL(pb));
}
static inline void frob_set_mode(struct parport *p, int mode)
{
frob_econtrol(p, ECR_MODE_MASK, mode << 5);
}
#ifdef CONFIG_PARPORT_PC_FIFO
/* Safely change the mode bits in the ECR
Returns:
0 : Success
-EBUSY: Could not drain FIFO in some finite amount of time,
mode not changed!
*/
static int change_mode(struct parport *p, int m)
{
const struct parport_pc_private *priv = p->physport->private_data;
unsigned char oecr;
int mode;
pr_debug("parport change_mode ECP-ISA to mode 0x%02x\n", m);
if (!priv->ecr) {
printk(KERN_DEBUG "change_mode: but there's no ECR!\n");
return 0;
}
/* Bits <7:5> contain the mode. */
oecr = inb(ECONTROL(p));
mode = (oecr >> 5) & 0x7;
if (mode == m)
return 0;
if (mode >= 2 && !(priv->ctr & 0x20)) {
/* This mode resets the FIFO, so we may
* have to wait for it to drain first. */
unsigned long expire = jiffies + p->physport->cad->timeout;
int counter;
switch (mode) {
case ECR_PPF: /* Parallel Port FIFO mode */
case ECR_ECP: /* ECP Parallel Port mode */
/* Busy wait for 200us */
for (counter = 0; counter < 40; counter++) {
if (inb(ECONTROL(p)) & 0x01)
break;
if (signal_pending(current))
break;
udelay(5);
}
/* Poll slowly. */
while (!(inb(ECONTROL(p)) & 0x01)) {
if (time_after_eq(jiffies, expire))
/* The FIFO is stuck. */
return -EBUSY;
schedule_timeout_interruptible(
msecs_to_jiffies(10));
if (signal_pending(current))
break;
}
}
}
if (mode >= 2 && m >= 2) {
/* We have to go through mode 001 */
oecr &= ~(7 << 5);
oecr |= ECR_PS2 << 5;
ECR_WRITE(p, oecr);
}
/* Set the mode. */
oecr &= ~(7 << 5);
oecr |= m << 5;
ECR_WRITE(p, oecr);
return 0;
}
#endif /* FIFO support */
/*
* Clear TIMEOUT BIT in EPP MODE
*
* This is also used in SPP detection.
*/
static int clear_epp_timeout(struct parport *pb)
{
unsigned char r;
if (!(parport_pc_read_status(pb) & 0x01))
return 1;
/* To clear timeout some chips require double read */
parport_pc_read_status(pb);
r = parport_pc_read_status(pb);
outb(r | 0x01, STATUS(pb)); /* Some reset by writing 1 */
outb(r & 0xfe, STATUS(pb)); /* Others by writing 0 */
r = parport_pc_read_status(pb);
return !(r & 0x01);
}
/*
* Access functions.
*
* Most of these aren't static because they may be used by the
* parport_xxx_yyy macros. extern __inline__ versions of several
* of these are in parport_pc.h.
*/
static void parport_pc_init_state(struct pardevice *dev,
struct parport_state *s)
{
s->u.pc.ctr = 0xc;
if (dev->irq_func &&
dev->port->irq != PARPORT_IRQ_NONE)
/* Set ackIntEn */
s->u.pc.ctr |= 0x10;
s->u.pc.ecr = 0x34; /* NetMos chip can cause problems 0x24;
* D.Gruszka VScom */
}
static void parport_pc_save_state(struct parport *p, struct parport_state *s)
{
const struct parport_pc_private *priv = p->physport->private_data;
s->u.pc.ctr = priv->ctr;
if (priv->ecr)
s->u.pc.ecr = inb(ECONTROL(p));
}
static void parport_pc_restore_state(struct parport *p,
struct parport_state *s)
{
struct parport_pc_private *priv = p->physport->private_data;
register unsigned char c = s->u.pc.ctr & priv->ctr_writable;
outb(c, CONTROL(p));
priv->ctr = c;
if (priv->ecr)
ECR_WRITE(p, s->u.pc.ecr);
}
#ifdef CONFIG_PARPORT_1284
static size_t parport_pc_epp_read_data(struct parport *port, void *buf,
size_t length, int flags)
{
size_t got = 0;
if (flags & PARPORT_W91284PIC) {
unsigned char status;
size_t left = length;
/* use knowledge about data lines..:
* nFault is 0 if there is at least 1 byte in the Warp's FIFO
* pError is 1 if there are 16 bytes in the Warp's FIFO
*/
status = inb(STATUS(port));
while (!(status & 0x08) && got < length) {
if (left >= 16 && (status & 0x20) && !(status & 0x08)) {
/* can grab 16 bytes from warp fifo */
if (!((long)buf & 0x03))
insl(EPPDATA(port), buf, 4);
else
insb(EPPDATA(port), buf, 16);
buf += 16;
got += 16;
left -= 16;
} else {
/* grab single byte from the warp fifo */
*((char *)buf) = inb(EPPDATA(port));
buf++;
got++;
left--;
}
status = inb(STATUS(port));
if (status & 0x01) {
/* EPP timeout should never occur... */
printk(KERN_DEBUG "%s: EPP timeout occurred while talking to w91284pic (should not have done)\n",
port->name);
clear_epp_timeout(port);
}
}
return got;
}
if ((flags & PARPORT_EPP_FAST) && (length > 1)) {
if (!(((long)buf | length) & 0x03))
insl(EPPDATA(port), buf, (length >> 2));
else
insb(EPPDATA(port), buf, length);
if (inb(STATUS(port)) & 0x01) {
clear_epp_timeout(port);
return -EIO;
}
return length;
}
for (; got < length; got++) {
*((char *)buf) = inb(EPPDATA(port));
buf++;
if (inb(STATUS(port)) & 0x01) {
/* EPP timeout */
clear_epp_timeout(port);
break;
}
}
return got;
}
static size_t parport_pc_epp_write_data(struct parport *port, const void *buf,
size_t length, int flags)
{
size_t written = 0;
if ((flags & PARPORT_EPP_FAST) && (length > 1)) {
if (!(((long)buf | length) & 0x03))
outsl(EPPDATA(port), buf, (length >> 2));
else
outsb(EPPDATA(port), buf, length);
if (inb(STATUS(port)) & 0x01) {
clear_epp_timeout(port);
return -EIO;
}
return length;
}
for (; written < length; written++) {
outb(*((char *)buf), EPPDATA(port));
buf++;
if (inb(STATUS(port)) & 0x01) {
clear_epp_timeout(port);
break;
}
}
return written;
}
static size_t parport_pc_epp_read_addr(struct parport *port, void *buf,
size_t length, int flags)
{
size_t got = 0;
if ((flags & PARPORT_EPP_FAST) && (length > 1)) {
insb(EPPADDR(port), buf, length);
if (inb(STATUS(port)) & 0x01) {
clear_epp_timeout(port);
return -EIO;
}
return length;
}
for (; got < length; got++) {
*((char *)buf) = inb(EPPADDR(port));
buf++;
if (inb(STATUS(port)) & 0x01) {
clear_epp_timeout(port);
break;
}
}
return got;
}
static size_t parport_pc_epp_write_addr(struct parport *port,
const void *buf, size_t length,
int flags)
{
size_t written = 0;
if ((flags & PARPORT_EPP_FAST) && (length > 1)) {
outsb(EPPADDR(port), buf, length);
if (inb(STATUS(port)) & 0x01) {
clear_epp_timeout(port);
return -EIO;
}
return length;
}
for (; written < length; written++) {
outb(*((char *)buf), EPPADDR(port));
buf++;
if (inb(STATUS(port)) & 0x01) {
clear_epp_timeout(port);
break;
}
}
return written;
}
static size_t parport_pc_ecpepp_read_data(struct parport *port, void *buf,
size_t length, int flags)
{
size_t got;
frob_set_mode(port, ECR_EPP);
parport_pc_data_reverse(port);
parport_pc_write_control(port, 0x4);
got = parport_pc_epp_read_data(port, buf, length, flags);
frob_set_mode(port, ECR_PS2);
return got;
}
static size_t parport_pc_ecpepp_write_data(struct parport *port,
const void *buf, size_t length,
int flags)
{
size_t written;
frob_set_mode(port, ECR_EPP);
parport_pc_write_control(port, 0x4);
parport_pc_data_forward(port);
written = parport_pc_epp_write_data(port, buf, length, flags);
frob_set_mode(port, ECR_PS2);
return written;
}
static size_t parport_pc_ecpepp_read_addr(struct parport *port, void *buf,
size_t length, int flags)
{
size_t got;
frob_set_mode(port, ECR_EPP);
parport_pc_data_reverse(port);
parport_pc_write_control(port, 0x4);
got = parport_pc_epp_read_addr(port, buf, length, flags);
frob_set_mode(port, ECR_PS2);
return got;
}
static size_t parport_pc_ecpepp_write_addr(struct parport *port,
const void *buf, size_t length,
int flags)
{
size_t written;
frob_set_mode(port, ECR_EPP);
parport_pc_write_control(port, 0x4);
parport_pc_data_forward(port);
written = parport_pc_epp_write_addr(port, buf, length, flags);
frob_set_mode(port, ECR_PS2);
return written;
}
#endif /* IEEE 1284 support */
#ifdef CONFIG_PARPORT_PC_FIFO
static size_t parport_pc_fifo_write_block_pio(struct parport *port,
const void *buf, size_t length)
{
int ret = 0;
const unsigned char *bufp = buf;
size_t left = length;
unsigned long expire = jiffies + port->physport->cad->timeout;
const int fifo = FIFO(port);
int poll_for = 8; /* 80 usecs */
const struct parport_pc_private *priv = port->physport->private_data;
const int fifo_depth = priv->fifo_depth;
port = port->physport;
/* We don't want to be interrupted every character. */
parport_pc_disable_irq(port);
/* set nErrIntrEn and serviceIntr */
frob_econtrol(port, (1<<4) | (1<<2), (1<<4) | (1<<2));
/* Forward mode. */
parport_pc_data_forward(port); /* Must be in PS2 mode */
while (left) {
unsigned char byte;
unsigned char ecrval = inb(ECONTROL(port));
int i = 0;
if (need_resched() && time_before(jiffies, expire))
/* Can't yield the port. */
schedule();
/* Anyone else waiting for the port? */
if (port->waithead) {
printk(KERN_DEBUG "Somebody wants the port\n");
break;
}
if (ecrval & 0x02) {
/* FIFO is full. Wait for interrupt. */
/* Clear serviceIntr */
ECR_WRITE(port, ecrval & ~(1<<2));
false_alarm:
ret = parport_wait_event(port, HZ);
if (ret < 0)
break;
ret = 0;
if (!time_before(jiffies, expire)) {
/* Timed out. */
printk(KERN_DEBUG "FIFO write timed out\n");
break;
}
ecrval = inb(ECONTROL(port));
if (!(ecrval & (1<<2))) {
if (need_resched() &&
time_before(jiffies, expire))
schedule();
goto false_alarm;
}
continue;
}
/* Can't fail now. */
expire = jiffies + port->cad->timeout;
poll:
if (signal_pending(current))
break;
if (ecrval & 0x01) {
/* FIFO is empty. Blast it full. */
const int n = left < fifo_depth ? left : fifo_depth;
outsb(fifo, bufp, n);
bufp += n;
left -= n;
/* Adjust the poll time. */
if (i < (poll_for - 2))
poll_for--;
continue;
} else if (i++ < poll_for) {
udelay(10);
ecrval = inb(ECONTROL(port));
goto poll;
}
/* Half-full(call me an optimist) */
byte = *bufp++;
outb(byte, fifo);
left--;
}
dump_parport_state("leave fifo_write_block_pio", port);
return length - left;
}
#ifdef HAS_DMA
static size_t parport_pc_fifo_write_block_dma(struct parport *port,
const void *buf, size_t length)
{
int ret = 0;
unsigned long dmaflag;
size_t left = length;
const struct parport_pc_private *priv = port->physport->private_data;
struct device *dev = port->physport->dev;
dma_addr_t dma_addr, dma_handle;
size_t maxlen = 0x10000; /* max 64k per DMA transfer */
unsigned long start = (unsigned long) buf;
unsigned long end = (unsigned long) buf + length - 1;
dump_parport_state("enter fifo_write_block_dma", port);
if (end < MAX_DMA_ADDRESS) {
/* If it would cross a 64k boundary, cap it at the end. */
if ((start ^ end) & ~0xffffUL)
maxlen = 0x10000 - (start & 0xffff);
dma_addr = dma_handle = dma_map_single(dev, (void *)buf, length,
DMA_TO_DEVICE);
} else {
/* above 16 MB we use a bounce buffer as ISA-DMA
is not possible */
maxlen = PAGE_SIZE; /* sizeof(priv->dma_buf) */
dma_addr = priv->dma_handle;
dma_handle = 0;
}
port = port->physport;
/* We don't want to be interrupted every character. */
parport_pc_disable_irq(port);
/* set nErrIntrEn and serviceIntr */
frob_econtrol(port, (1<<4) | (1<<2), (1<<4) | (1<<2));
/* Forward mode. */
parport_pc_data_forward(port); /* Must be in PS2 mode */
while (left) {
unsigned long expire = jiffies + port->physport->cad->timeout;
size_t count = left;
if (count > maxlen)
count = maxlen;
if (!dma_handle) /* bounce buffer ! */
memcpy(priv->dma_buf, buf, count);
dmaflag = claim_dma_lock();
disable_dma(port->dma);
clear_dma_ff(port->dma);
set_dma_mode(port->dma, DMA_MODE_WRITE);
set_dma_addr(port->dma, dma_addr);
set_dma_count(port->dma, count);
/* Set DMA mode */
frob_econtrol(port, 1<<3, 1<<3);
/* Clear serviceIntr */
frob_econtrol(port, 1<<2, 0);
enable_dma(port->dma);
release_dma_lock(dmaflag);
/* assume DMA will be successful */
left -= count;
buf += count;
if (dma_handle)
dma_addr += count;
/* Wait for interrupt. */
false_alarm:
ret = parport_wait_event(port, HZ);
if (ret < 0)
break;
ret = 0;
if (!time_before(jiffies, expire)) {
/* Timed out. */
printk(KERN_DEBUG "DMA write timed out\n");
break;
}
/* Is serviceIntr set? */
if (!(inb(ECONTROL(port)) & (1<<2))) {
cond_resched();
goto false_alarm;
}
dmaflag = claim_dma_lock();
disable_dma(port->dma);
clear_dma_ff(port->dma);
count = get_dma_residue(port->dma);
release_dma_lock(dmaflag);
cond_resched(); /* Can't yield the port. */
/* Anyone else waiting for the port? */
if (port->waithead) {
printk(KERN_DEBUG "Somebody wants the port\n");
break;
}
/* update for possible DMA residue ! */
buf -= count;
left += count;
if (dma_handle)
dma_addr -= count;
}
/* Maybe got here through break, so adjust for DMA residue! */
dmaflag = claim_dma_lock();
disable_dma(port->dma);
clear_dma_ff(port->dma);
left += get_dma_residue(port->dma);
release_dma_lock(dmaflag);
/* Turn off DMA mode */
frob_econtrol(port, 1<<3, 0);
if (dma_handle)
dma_unmap_single(dev, dma_handle, length, DMA_TO_DEVICE);
dump_parport_state("leave fifo_write_block_dma", port);
return length - left;
}
#endif
static inline size_t parport_pc_fifo_write_block(struct parport *port,
const void *buf, size_t length)
{
#ifdef HAS_DMA
if (port->dma != PARPORT_DMA_NONE)
return parport_pc_fifo_write_block_dma(port, buf, length);
#endif
return parport_pc_fifo_write_block_pio(port, buf, length);
}
/* Parallel Port FIFO mode (ECP chipsets) */
static size_t parport_pc_compat_write_block_pio(struct parport *port,
const void *buf, size_t length,
int flags)
{
size_t written;
int r;
unsigned long expire;
const struct parport_pc_private *priv = port->physport->private_data;
/* Special case: a timeout of zero means we cannot call schedule().
* Also if O_NONBLOCK is set then use the default implementation. */
if (port->physport->cad->timeout <= PARPORT_INACTIVITY_O_NONBLOCK)
return parport_ieee1284_write_compat(port, buf,
length, flags);
/* Set up parallel port FIFO mode.*/
parport_pc_data_forward(port); /* Must be in PS2 mode */
parport_pc_frob_control(port, PARPORT_CONTROL_STROBE, 0);
r = change_mode(port, ECR_PPF); /* Parallel port FIFO */
if (r)
printk(KERN_DEBUG "%s: Warning change_mode ECR_PPF failed\n",
port->name);
port->physport->ieee1284.phase = IEEE1284_PH_FWD_DATA;
/* Write the data to the FIFO. */
written = parport_pc_fifo_write_block(port, buf, length);
/* Finish up. */
/* For some hardware we don't want to touch the mode until
* the FIFO is empty, so allow 4 seconds for each position
* in the fifo.
*/
expire = jiffies + (priv->fifo_depth * HZ * 4);
do {
/* Wait for the FIFO to empty */
r = change_mode(port, ECR_PS2);
if (r != -EBUSY)
break;
} while (time_before(jiffies, expire));
if (r == -EBUSY) {
printk(KERN_DEBUG "%s: FIFO is stuck\n", port->name);
/* Prevent further data transfer. */
frob_set_mode(port, ECR_TST);
/* Adjust for the contents of the FIFO. */
for (written -= priv->fifo_depth; ; written++) {
if (inb(ECONTROL(port)) & 0x2) {
/* Full up. */
break;
}
outb(0, FIFO(port));
}
/* Reset the FIFO and return to PS2 mode. */
frob_set_mode(port, ECR_PS2);
}
r = parport_wait_peripheral(port,
PARPORT_STATUS_BUSY,
PARPORT_STATUS_BUSY);
if (r)
printk(KERN_DEBUG "%s: BUSY timeout (%d) in compat_write_block_pio\n",
port->name, r);
port->physport->ieee1284.phase = IEEE1284_PH_FWD_IDLE;
return written;
}
/* ECP */
#ifdef CONFIG_PARPORT_1284
static size_t parport_pc_ecp_write_block_pio(struct parport *port,
const void *buf, size_t length,
int flags)
{
size_t written;
int r;
unsigned long expire;
const struct parport_pc_private *priv = port->physport->private_data;
/* Special case: a timeout of zero means we cannot call schedule().
* Also if O_NONBLOCK is set then use the default implementation. */
if (port->physport->cad->timeout <= PARPORT_INACTIVITY_O_NONBLOCK)
return parport_ieee1284_ecp_write_data(port, buf,
length, flags);
/* Switch to forward mode if necessary. */
if (port->physport->ieee1284.phase != IEEE1284_PH_FWD_IDLE) {
/* Event 47: Set nInit high. */
parport_frob_control(port,
PARPORT_CONTROL_INIT
| PARPORT_CONTROL_AUTOFD,
PARPORT_CONTROL_INIT
| PARPORT_CONTROL_AUTOFD);
/* Event 49: PError goes high. */
r = parport_wait_peripheral(port,
PARPORT_STATUS_PAPEROUT,
PARPORT_STATUS_PAPEROUT);
if (r) {
printk(KERN_DEBUG "%s: PError timeout (%d) in ecp_write_block_pio\n",
port->name, r);
}
}
/* Set up ECP parallel port mode.*/
parport_pc_data_forward(port); /* Must be in PS2 mode */
parport_pc_frob_control(port,
PARPORT_CONTROL_STROBE |
PARPORT_CONTROL_AUTOFD,
0);
r = change_mode(port, ECR_ECP); /* ECP FIFO */
if (r)
printk(KERN_DEBUG "%s: Warning change_mode ECR_ECP failed\n",
port->name);
port->physport->ieee1284.phase = IEEE1284_PH_FWD_DATA;
/* Write the data to the FIFO. */
written = parport_pc_fifo_write_block(port, buf, length);
/* Finish up. */
/* For some hardware we don't want to touch the mode until
* the FIFO is empty, so allow 4 seconds for each position
* in the fifo.
*/
expire = jiffies + (priv->fifo_depth * (HZ * 4));
do {
/* Wait for the FIFO to empty */
r = change_mode(port, ECR_PS2);
if (r != -EBUSY)
break;
} while (time_before(jiffies, expire));
if (r == -EBUSY) {
printk(KERN_DEBUG "%s: FIFO is stuck\n", port->name);
/* Prevent further data transfer. */
frob_set_mode(port, ECR_TST);
/* Adjust for the contents of the FIFO. */
for (written -= priv->fifo_depth; ; written++) {
if (inb(ECONTROL(port)) & 0x2) {
/* Full up. */
break;
}
outb(0, FIFO(port));
}
/* Reset the FIFO and return to PS2 mode. */
frob_set_mode(port, ECR_PS2);
/* Host transfer recovery. */
parport_pc_data_reverse(port); /* Must be in PS2 mode */
udelay(5);
parport_frob_control(port, PARPORT_CONTROL_INIT, 0);
r = parport_wait_peripheral(port, PARPORT_STATUS_PAPEROUT, 0);
if (r)
printk(KERN_DEBUG "%s: PE,1 timeout (%d) in ecp_write_block_pio\n",
port->name, r);
parport_frob_control(port,
PARPORT_CONTROL_INIT,
PARPORT_CONTROL_INIT);
r = parport_wait_peripheral(port,
PARPORT_STATUS_PAPEROUT,
PARPORT_STATUS_PAPEROUT);
if (r)
printk(KERN_DEBUG "%s: PE,2 timeout (%d) in ecp_write_block_pio\n",
port->name, r);
}
r = parport_wait_peripheral(port,
PARPORT_STATUS_BUSY,
PARPORT_STATUS_BUSY);
if (r)
printk(KERN_DEBUG "%s: BUSY timeout (%d) in ecp_write_block_pio\n",
port->name, r);
port->physport->ieee1284.phase = IEEE1284_PH_FWD_IDLE;
return written;
}
#endif /* IEEE 1284 support */
#endif /* Allowed to use FIFO/DMA */
/*
* ******************************************
* INITIALISATION AND MODULE STUFF BELOW HERE
* ******************************************
*/
/* GCC is not inlining extern inline function later overwritten to non-inline,
so we use outlined_ variants here. */
static const struct parport_operations parport_pc_ops = {
.write_data = parport_pc_write_data,
.read_data = parport_pc_read_data,
.write_control = parport_pc_write_control,
.read_control = parport_pc_read_control,
.frob_control = parport_pc_frob_control,
.read_status = parport_pc_read_status,
.enable_irq = parport_pc_enable_irq,
.disable_irq = parport_pc_disable_irq,
.data_forward = parport_pc_data_forward,
.data_reverse = parport_pc_data_reverse,
.init_state = parport_pc_init_state,
.save_state = parport_pc_save_state,
.restore_state = parport_pc_restore_state,
.epp_write_data = parport_ieee1284_epp_write_data,
.epp_read_data = parport_ieee1284_epp_read_data,
.epp_write_addr = parport_ieee1284_epp_write_addr,
.epp_read_addr = parport_ieee1284_epp_read_addr,
.ecp_write_data = parport_ieee1284_ecp_write_data,
.ecp_read_data = parport_ieee1284_ecp_read_data,
.ecp_write_addr = parport_ieee1284_ecp_write_addr,
.compat_write_data = parport_ieee1284_write_compat,
.nibble_read_data = parport_ieee1284_read_nibble,
.byte_read_data = parport_ieee1284_read_byte,
.owner = THIS_MODULE,
};
#ifdef CONFIG_PARPORT_PC_SUPERIO
static struct superio_struct *find_free_superio(void)
{
int i;
for (i = 0; i < NR_SUPERIOS; i++)
if (superios[i].io == 0)
return &superios[i];
return NULL;
}
/* Super-IO chipset detection, Winbond, SMSC */
static void show_parconfig_smsc37c669(int io, int key)
{
int cr1, cr4, cra, cr23, cr26, cr27;
struct superio_struct *s;
static const char *const modes[] = {
"SPP and Bidirectional (PS/2)",
"EPP and SPP",
"ECP",
"ECP and EPP" };
outb(key, io);
outb(key, io);
outb(1, io);
cr1 = inb(io + 1);
outb(4, io);
cr4 = inb(io + 1);
outb(0x0a, io);
cra = inb(io + 1);
outb(0x23, io);
cr23 = inb(io + 1);
outb(0x26, io);
cr26 = inb(io + 1);
outb(0x27, io);
cr27 = inb(io + 1);
outb(0xaa, io);
if (verbose_probing) {
pr_info("SMSC 37c669 LPT Config: cr_1=0x%02x, 4=0x%02x, A=0x%2x, 23=0x%02x, 26=0x%02x, 27=0x%02x\n",
cr1, cr4, cra, cr23, cr26, cr27);
/* The documentation calls DMA and IRQ-Lines by letters, so
the board maker can/will wire them
appropriately/randomly... G=reserved H=IDE-irq, */
pr_info("SMSC LPT Config: io=0x%04x, irq=%c, dma=%c, fifo threshold=%d\n",
cr23 * 4,
(cr27 & 0x0f) ? 'A' - 1 + (cr27 & 0x0f) : '-',
(cr26 & 0x0f) ? 'A' - 1 + (cr26 & 0x0f) : '-',
cra & 0x0f);
pr_info("SMSC LPT Config: enabled=%s power=%s\n",
(cr23 * 4 >= 0x100) ? "yes" : "no",
(cr1 & 4) ? "yes" : "no");
pr_info("SMSC LPT Config: Port mode=%s, EPP version =%s\n",
(cr1 & 0x08) ? "Standard mode only (SPP)"
: modes[cr4 & 0x03],
(cr4 & 0x40) ? "1.7" : "1.9");
}
/* Heuristics ! BIOS setup for this mainboard device limits
the choices to standard settings, i.e. io-address and IRQ
are related, however DMA can be 1 or 3, assume DMA_A=DMA1,
DMA_C=DMA3 (this is true e.g. for TYAN 1564D Tomcat IV) */
if (cr23 * 4 >= 0x100) { /* if active */
s = find_free_superio();
if (s == NULL)
pr_info("Super-IO: too many chips!\n");
else {
int d;
switch (cr23 * 4) {
case 0x3bc:
s->io = 0x3bc;
s->irq = 7;
break;
case 0x378:
s->io = 0x378;
s->irq = 7;
break;
case 0x278:
s->io = 0x278;
s->irq = 5;
}
d = (cr26 & 0x0f);
if (d == 1 || d == 3)
s->dma = d;
else
s->dma = PARPORT_DMA_NONE;
}
}
}
static void show_parconfig_winbond(int io, int key)
{
int cr30, cr60, cr61, cr70, cr74, crf0;
struct superio_struct *s;
static const char *const modes[] = {
"Standard (SPP) and Bidirectional(PS/2)", /* 0 */
"EPP-1.9 and SPP",
"ECP",
"ECP and EPP-1.9",
"Standard (SPP)",
"EPP-1.7 and SPP", /* 5 */
"undefined!",
"ECP and EPP-1.7" };
static char *const irqtypes[] = {
"pulsed low, high-Z",
"follows nACK" };
/* The registers are called compatible-PnP because the
register layout is modelled after ISA-PnP, the access
method is just another ... */
outb(key, io);
outb(key, io);
outb(0x07, io); /* Register 7: Select Logical Device */
outb(0x01, io + 1); /* LD1 is Parallel Port */
outb(0x30, io);
cr30 = inb(io + 1);
outb(0x60, io);
cr60 = inb(io + 1);
outb(0x61, io);
cr61 = inb(io + 1);
outb(0x70, io);
cr70 = inb(io + 1);
outb(0x74, io);
cr74 = inb(io + 1);
outb(0xf0, io);
crf0 = inb(io + 1);
outb(0xaa, io);
if (verbose_probing) {
pr_info("Winbond LPT Config: cr_30=%02x 60,61=%02x%02x 70=%02x 74=%02x, f0=%02x\n",
cr30, cr60, cr61, cr70, cr74, crf0);
pr_info("Winbond LPT Config: active=%s, io=0x%02x%02x irq=%d, ",
(cr30 & 0x01) ? "yes" : "no", cr60, cr61, cr70 & 0x0f);
if ((cr74 & 0x07) > 3)
pr_cont("dma=none\n");
else
pr_cont("dma=%d\n", cr74 & 0x07);
pr_info("Winbond LPT Config: irqtype=%s, ECP fifo threshold=%d\n",
irqtypes[crf0 >> 7], (crf0 >> 3) & 0x0f);
pr_info("Winbond LPT Config: Port mode=%s\n",
modes[crf0 & 0x07]);
}
if (cr30 & 0x01) { /* the settings can be interrogated later ... */
s = find_free_superio();
if (s == NULL)
pr_info("Super-IO: too many chips!\n");
else {
s->io = (cr60 << 8) | cr61;
s->irq = cr70 & 0x0f;
s->dma = (((cr74 & 0x07) > 3) ?
PARPORT_DMA_NONE : (cr74 & 0x07));
}
}
}
static void decode_winbond(int efer, int key, int devid, int devrev, int oldid)
{
const char *type = "unknown";
int id, progif = 2;
if (devid == devrev)
/* simple heuristics, we happened to read some
non-winbond register */
return;
id = (devid << 8) | devrev;
/* Values are from public data sheets pdf files, I can just
confirm 83977TF is correct :-) */
if (id == 0x9771)
type = "83977F/AF";
else if (id == 0x9773)
type = "83977TF / SMSC 97w33x/97w34x";
else if (id == 0x9774)
type = "83977ATF";
else if ((id & ~0x0f) == 0x5270)
type = "83977CTF / SMSC 97w36x";
else if ((id & ~0x0f) == 0x52f0)
type = "83977EF / SMSC 97w35x";
else if ((id & ~0x0f) == 0x5210)
type = "83627";
else if ((id & ~0x0f) == 0x6010)
type = "83697HF";
else if ((oldid & 0x0f) == 0x0a) {
type = "83877F";
progif = 1;
} else if ((oldid & 0x0f) == 0x0b) {
type = "83877AF";
progif = 1;
} else if ((oldid & 0x0f) == 0x0c) {
type = "83877TF";
progif = 1;
} else if ((oldid & 0x0f) == 0x0d) {
type = "83877ATF";
progif = 1;
} else
progif = 0;
if (verbose_probing)
pr_info("Winbond chip at EFER=0x%x key=0x%02x devid=%02x devrev=%02x oldid=%02x type=%s\n",
efer, key, devid, devrev, oldid, type);
if (progif == 2)
show_parconfig_winbond(efer, key);
}
static void decode_smsc(int efer, int key, int devid, int devrev)
{
const char *type = "unknown";
void (*func)(int io, int key);
int id;
if (devid == devrev)
/* simple heuristics, we happened to read some
non-smsc register */
return;
func = NULL;
id = (devid << 8) | devrev;
if (id == 0x0302) {
type = "37c669";
func = show_parconfig_smsc37c669;
} else if (id == 0x6582)
type = "37c665IR";
else if (devid == 0x65)
type = "37c665GT";
else if (devid == 0x66)
type = "37c666GT";
if (verbose_probing)
pr_info("SMSC chip at EFER=0x%x key=0x%02x devid=%02x devrev=%02x type=%s\n",
efer, key, devid, devrev, type);
if (func)
func(efer, key);
}
static void winbond_check(int io, int key)
{
int origval, devid, devrev, oldid, x_devid, x_devrev, x_oldid;
if (!request_region(io, 3, __func__))
return;
origval = inb(io); /* Save original value */
/* First probe without key */
outb(0x20, io);
x_devid = inb(io + 1);
outb(0x21, io);
x_devrev = inb(io + 1);
outb(0x09, io);
x_oldid = inb(io + 1);
outb(key, io);
outb(key, io); /* Write Magic Sequence to EFER, extended
function enable register */
outb(0x20, io); /* Write EFIR, extended function index register */
devid = inb(io + 1); /* Read EFDR, extended function data register */
outb(0x21, io);
devrev = inb(io + 1);
outb(0x09, io);
oldid = inb(io + 1);
outb(0xaa, io); /* Magic Seal */
outb(origval, io); /* in case we poked some entirely different hardware */
if ((x_devid == devid) && (x_devrev == devrev) && (x_oldid == oldid))
goto out; /* protection against false positives */
decode_winbond(io, key, devid, devrev, oldid);
out:
release_region(io, 3);
}
static void winbond_check2(int io, int key)
{
int origval[3], devid, devrev, oldid, x_devid, x_devrev, x_oldid;
if (!request_region(io, 3, __func__))
return;
origval[0] = inb(io); /* Save original values */
origval[1] = inb(io + 1);
origval[2] = inb(io + 2);
/* First probe without the key */
outb(0x20, io + 2);
x_devid = inb(io + 2);
outb(0x21, io + 1);
x_devrev = inb(io + 2);
outb(0x09, io + 1);
x_oldid = inb(io + 2);
outb(key, io); /* Write Magic Byte to EFER, extended
function enable register */
outb(0x20, io + 2); /* Write EFIR, extended function index register */
devid = inb(io + 2); /* Read EFDR, extended function data register */
outb(0x21, io + 1);
devrev = inb(io + 2);
outb(0x09, io + 1);
oldid = inb(io + 2);
outb(0xaa, io); /* Magic Seal */
outb(origval[0], io); /* in case we poked some entirely different hardware */
outb(origval[1], io + 1);
outb(origval[2], io + 2);
if (x_devid == devid && x_devrev == devrev && x_oldid == oldid)
goto out; /* protection against false positives */
decode_winbond(io, key, devid, devrev, oldid);
out:
release_region(io, 3);
}
static void smsc_check(int io, int key)
{
int origval, id, rev, oldid, oldrev, x_id, x_rev, x_oldid, x_oldrev;
if (!request_region(io, 3, __func__))
return;
origval = inb(io); /* Save original value */
/* First probe without the key */
outb(0x0d, io);
x_oldid = inb(io + 1);
outb(0x0e, io);
x_oldrev = inb(io + 1);
outb(0x20, io);
x_id = inb(io + 1);
outb(0x21, io);
x_rev = inb(io + 1);
outb(key, io);
outb(key, io); /* Write Magic Sequence to EFER, extended
function enable register */
outb(0x0d, io); /* Write EFIR, extended function index register */
oldid = inb(io + 1); /* Read EFDR, extended function data register */
outb(0x0e, io);
oldrev = inb(io + 1);
outb(0x20, io);
id = inb(io + 1);
outb(0x21, io);
rev = inb(io + 1);
outb(0xaa, io); /* Magic Seal */
outb(origval, io); /* in case we poked some entirely different hardware */
if (x_id == id && x_oldrev == oldrev &&
x_oldid == oldid && x_rev == rev)
goto out; /* protection against false positives */
decode_smsc(io, key, oldid, oldrev);
out:
release_region(io, 3);
}
static void detect_and_report_winbond(void)
{
if (verbose_probing)
printk(KERN_DEBUG "Winbond Super-IO detection, now testing ports 3F0,370,250,4E,2E ...\n");
winbond_check(0x3f0, 0x87);
winbond_check(0x370, 0x87);
winbond_check(0x2e , 0x87);
winbond_check(0x4e , 0x87);
winbond_check(0x3f0, 0x86);
winbond_check2(0x250, 0x88);
winbond_check2(0x250, 0x89);
}
static void detect_and_report_smsc(void)
{
if (verbose_probing)
printk(KERN_DEBUG "SMSC Super-IO detection, now testing Ports 2F0, 370 ...\n");
smsc_check(0x3f0, 0x55);
smsc_check(0x370, 0x55);
smsc_check(0x3f0, 0x44);
smsc_check(0x370, 0x44);
}
static void detect_and_report_it87(void)
{
u16 dev;
u8 origval, r;
if (verbose_probing)
printk(KERN_DEBUG "IT8705 Super-IO detection, now testing port 2E ...\n");
if (!request_muxed_region(0x2e, 2, __func__))
return;
origval = inb(0x2e); /* Save original value */
outb(0x87, 0x2e);
outb(0x01, 0x2e);
outb(0x55, 0x2e);
outb(0x55, 0x2e);
outb(0x20, 0x2e);
dev = inb(0x2f) << 8;
outb(0x21, 0x2e);
dev |= inb(0x2f);
if (dev == 0x8712 || dev == 0x8705 || dev == 0x8715 ||
dev == 0x8716 || dev == 0x8718 || dev == 0x8726) {
pr_info("IT%04X SuperIO detected\n", dev);
outb(0x07, 0x2E); /* Parallel Port */
outb(0x03, 0x2F);
outb(0xF0, 0x2E); /* BOOT 0x80 off */
r = inb(0x2f);
outb(0xF0, 0x2E);
outb(r | 8, 0x2F);
outb(0x02, 0x2E); /* Lock */
outb(0x02, 0x2F);
} else {
outb(origval, 0x2e); /* Oops, sorry to disturb */
}
release_region(0x2e, 2);
}
#endif /* CONFIG_PARPORT_PC_SUPERIO */
static struct superio_struct *find_superio(struct parport *p)
{
int i;
for (i = 0; i < NR_SUPERIOS; i++)
if (superios[i].io == p->base)
return &superios[i];
return NULL;
}
static int get_superio_dma(struct parport *p)
{
struct superio_struct *s = find_superio(p);
if (s)
return s->dma;
return PARPORT_DMA_NONE;
}
static int get_superio_irq(struct parport *p)
{
struct superio_struct *s = find_superio(p);
if (s)
return s->irq;
return PARPORT_IRQ_NONE;
}
/* --- Mode detection ------------------------------------- */
/*
* Checks for port existence, all ports support SPP MODE
* Returns:
* 0 : No parallel port at this address
* PARPORT_MODE_PCSPP : SPP port detected
* (if the user specified an ioport himself,
* this shall always be the case!)
*
*/
static int parport_SPP_supported(struct parport *pb)
{
unsigned char r, w;
/*
* first clear an eventually pending EPP timeout
* I (sailer@ife.ee.ethz.ch) have an SMSC chipset
* that does not even respond to SPP cycles if an EPP
* timeout is pending
*/
clear_epp_timeout(pb);
/* Do a simple read-write test to make sure the port exists. */
w = 0xc;
outb(w, CONTROL(pb));
/* Is there a control register that we can read from? Some
* ports don't allow reads, so read_control just returns a
* software copy. Some ports _do_ allow reads, so bypass the
* software copy here. In addition, some bits aren't
* writable. */
r = inb(CONTROL(pb));
if ((r & 0xf) == w) {
w = 0xe;
outb(w, CONTROL(pb));
r = inb(CONTROL(pb));
outb(0xc, CONTROL(pb));
if ((r & 0xf) == w)
return PARPORT_MODE_PCSPP;
}
if (user_specified)
/* That didn't work, but the user thinks there's a
* port here. */
pr_info("parport 0x%lx (WARNING): CTR: wrote 0x%02x, read 0x%02x\n",
pb->base, w, r);
/* Try the data register. The data lines aren't tri-stated at
* this stage, so we expect back what we wrote. */
w = 0xaa;
parport_pc_write_data(pb, w);
r = parport_pc_read_data(pb);
if (r == w) {
w = 0x55;
parport_pc_write_data(pb, w);
r = parport_pc_read_data(pb);
if (r == w)
return PARPORT_MODE_PCSPP;
}
if (user_specified) {
/* Didn't work, but the user is convinced this is the
* place. */
pr_info("parport 0x%lx (WARNING): DATA: wrote 0x%02x, read 0x%02x\n",
pb->base, w, r);
pr_info("parport 0x%lx: You gave this address, but there is probably no parallel port there!\n",
pb->base);
}
/* It's possible that we can't read the control register or
* the data register. In that case just believe the user. */
if (user_specified)
return PARPORT_MODE_PCSPP;
return 0;
}
/* Check for ECR
*
* Old style XT ports alias io ports every 0x400, hence accessing ECR
* on these cards actually accesses the CTR.
*
* Modern cards don't do this but reading from ECR will return 0xff
* regardless of what is written here if the card does NOT support
* ECP.
*
* We first check to see if ECR is the same as CTR. If not, the low
* two bits of ECR aren't writable, so we check by writing ECR and
* reading it back to see if it's what we expect.
*/
static int parport_ECR_present(struct parport *pb)
{
struct parport_pc_private *priv = pb->private_data;
unsigned char r = 0xc;
outb(r, CONTROL(pb));
if ((inb(ECONTROL(pb)) & 0x3) == (r & 0x3)) {
outb(r ^ 0x2, CONTROL(pb)); /* Toggle bit 1 */
r = inb(CONTROL(pb));
if ((inb(ECONTROL(pb)) & 0x2) == (r & 0x2))
goto no_reg; /* Sure that no ECR register exists */
}
if ((inb(ECONTROL(pb)) & 0x3) != 0x1)
goto no_reg;
ECR_WRITE(pb, 0x34);
if (inb(ECONTROL(pb)) != 0x35)
goto no_reg;
priv->ecr = 1;
outb(0xc, CONTROL(pb));
/* Go to mode 000 */
frob_set_mode(pb, ECR_SPP);
return 1;
no_reg:
outb(0xc, CONTROL(pb));
return 0;
}
#ifdef CONFIG_PARPORT_1284
/* Detect PS/2 support.
*
* Bit 5 (0x20) sets the PS/2 data direction; setting this high
* allows us to read data from the data lines. In theory we would get back
* 0xff but any peripheral attached to the port may drag some or all of the
* lines down to zero. So if we get back anything that isn't the contents
* of the data register we deem PS/2 support to be present.
*
* Some SPP ports have "half PS/2" ability - you can't turn off the line
* drivers, but an external peripheral with sufficiently beefy drivers of
* its own can overpower them and assert its own levels onto the bus, from
* where they can then be read back as normal. Ports with this property
* and the right type of device attached are likely to fail the SPP test,
* (as they will appear to have stuck bits) and so the fact that they might
* be misdetected here is rather academic.
*/
static int parport_PS2_supported(struct parport *pb)
{
int ok = 0;
clear_epp_timeout(pb);
/* try to tri-state the buffer */
parport_pc_data_reverse(pb);
parport_pc_write_data(pb, 0x55);
if (parport_pc_read_data(pb) != 0x55)
ok++;
parport_pc_write_data(pb, 0xaa);
if (parport_pc_read_data(pb) != 0xaa)
ok++;
/* cancel input mode */
parport_pc_data_forward(pb);
if (ok) {
pb->modes |= PARPORT_MODE_TRISTATE;
} else {
struct parport_pc_private *priv = pb->private_data;
priv->ctr_writable &= ~0x20;
}
return ok;
}
#ifdef CONFIG_PARPORT_PC_FIFO
static int parport_ECP_supported(struct parport *pb)
{
int i;
int config, configb;
int pword;
struct parport_pc_private *priv = pb->private_data;
/* Translate ECP intrLine to ISA irq value */
static const int intrline[] = { 0, 7, 9, 10, 11, 14, 15, 5 };
/* If there is no ECR, we have no hope of supporting ECP. */
if (!priv->ecr)
return 0;
/* Find out FIFO depth */
ECR_WRITE(pb, ECR_SPP << 5); /* Reset FIFO */
ECR_WRITE(pb, ECR_TST << 5); /* TEST FIFO */
for (i = 0; i < 1024 && !(inb(ECONTROL(pb)) & 0x02); i++)
outb(0xaa, FIFO(pb));
/*
* Using LGS chipset it uses ECR register, but
* it doesn't support ECP or FIFO MODE
*/
if (i == 1024) {
ECR_WRITE(pb, ECR_SPP << 5);
return 0;
}
priv->fifo_depth = i;
if (verbose_probing)
printk(KERN_DEBUG "0x%lx: FIFO is %d bytes\n", pb->base, i);
/* Find out writeIntrThreshold */
frob_econtrol(pb, 1<<2, 1<<2);
frob_econtrol(pb, 1<<2, 0);
for (i = 1; i <= priv->fifo_depth; i++) {
inb(FIFO(pb));
udelay(50);
if (inb(ECONTROL(pb)) & (1<<2))
break;
}
if (i <= priv->fifo_depth) {
if (verbose_probing)
printk(KERN_DEBUG "0x%lx: writeIntrThreshold is %d\n",
pb->base, i);
} else
/* Number of bytes we know we can write if we get an
interrupt. */
i = 0;
priv->writeIntrThreshold = i;
/* Find out readIntrThreshold */
frob_set_mode(pb, ECR_PS2); /* Reset FIFO and enable PS2 */
parport_pc_data_reverse(pb); /* Must be in PS2 mode */
frob_set_mode(pb, ECR_TST); /* Test FIFO */
frob_econtrol(pb, 1<<2, 1<<2);
frob_econtrol(pb, 1<<2, 0);
for (i = 1; i <= priv->fifo_depth; i++) {
outb(0xaa, FIFO(pb));
if (inb(ECONTROL(pb)) & (1<<2))
break;
}
if (i <= priv->fifo_depth) {
if (verbose_probing)
pr_info("0x%lx: readIntrThreshold is %d\n",
pb->base, i);
} else
/* Number of bytes we can read if we get an interrupt. */
i = 0;
priv->readIntrThreshold = i;
ECR_WRITE(pb, ECR_SPP << 5); /* Reset FIFO */
ECR_WRITE(pb, 0xf4); /* Configuration mode */
config = inb(CONFIGA(pb));
pword = (config >> 4) & 0x7;
switch (pword) {
case 0:
pword = 2;
pr_warn("0x%lx: Unsupported pword size!\n", pb->base);
break;
case 2:
pword = 4;
pr_warn("0x%lx: Unsupported pword size!\n", pb->base);
break;
default:
pr_warn("0x%lx: Unknown implementation ID\n", pb->base);
/* Fall through - Assume 1 */
case 1:
pword = 1;
}
priv->pword = pword;
if (verbose_probing) {
printk(KERN_DEBUG "0x%lx: PWord is %d bits\n",
pb->base, 8 * pword);
printk(KERN_DEBUG "0x%lx: Interrupts are ISA-%s\n",
pb->base, config & 0x80 ? "Level" : "Pulses");
configb = inb(CONFIGB(pb));
printk(KERN_DEBUG "0x%lx: ECP port cfgA=0x%02x cfgB=0x%02x\n",
pb->base, config, configb);
printk(KERN_DEBUG "0x%lx: ECP settings irq=", pb->base);
if ((configb >> 3) & 0x07)
pr_cont("%d", intrline[(configb >> 3) & 0x07]);
else
pr_cont("<none or set by other means>");
pr_cont(" dma=");
if ((configb & 0x03) == 0x00)
pr_cont("<none or set by other means>\n");
else
pr_cont("%d\n", configb & 0x07);
}
/* Go back to mode 000 */
frob_set_mode(pb, ECR_SPP);
return 1;
}
#endif
#ifdef CONFIG_X86_32
static int intel_bug_present_check_epp(struct parport *pb)
{
const struct parport_pc_private *priv = pb->private_data;
int bug_present = 0;
if (priv->ecr) {
/* store value of ECR */
unsigned char ecr = inb(ECONTROL(pb));
unsigned char i;
for (i = 0x00; i < 0x80; i += 0x20) {
ECR_WRITE(pb, i);
if (clear_epp_timeout(pb)) {
/* Phony EPP in ECP. */
bug_present = 1;
break;
}
}
/* return ECR into the inital state */
ECR_WRITE(pb, ecr);
}
return bug_present;
}
static int intel_bug_present(struct parport *pb)
{
/* Check whether the device is legacy, not PCI or PCMCIA. Only legacy is known to be affected. */
if (pb->dev != NULL) {
return 0;
}
return intel_bug_present_check_epp(pb);
}
#else
static int intel_bug_present(struct parport *pb)
{
return 0;
}
#endif /* CONFIG_X86_32 */
static int parport_ECPPS2_supported(struct parport *pb)
{
const struct parport_pc_private *priv = pb->private_data;
int result;
unsigned char oecr;
if (!priv->ecr)
return 0;
oecr = inb(ECONTROL(pb));
ECR_WRITE(pb, ECR_PS2 << 5);
result = parport_PS2_supported(pb);
ECR_WRITE(pb, oecr);
return result;
}
/* EPP mode detection */
static int parport_EPP_supported(struct parport *pb)
{
/*
* Theory:
* Bit 0 of STR is the EPP timeout bit, this bit is 0
* when EPP is possible and is set high when an EPP timeout
* occurs (EPP uses the HALT line to stop the CPU while it does
* the byte transfer, an EPP timeout occurs if the attached
* device fails to respond after 10 micro seconds).
*
* This bit is cleared by either reading it (National Semi)
* or writing a 1 to the bit (SMC, UMC, WinBond), others ???
* This bit is always high in non EPP modes.
*/
/* If EPP timeout bit clear then EPP available */
if (!clear_epp_timeout(pb))
return 0; /* No way to clear timeout */
/* Check for Intel bug. */
if (intel_bug_present(pb))
return 0;
pb->modes |= PARPORT_MODE_EPP;
/* Set up access functions to use EPP hardware. */
pb->ops->epp_read_data = parport_pc_epp_read_data;
pb->ops->epp_write_data = parport_pc_epp_write_data;
pb->ops->epp_read_addr = parport_pc_epp_read_addr;
pb->ops->epp_write_addr = parport_pc_epp_write_addr;
return 1;
}
static int parport_ECPEPP_supported(struct parport *pb)
{
struct parport_pc_private *priv = pb->private_data;
int result;
unsigned char oecr;
if (!priv->ecr)
return 0;
oecr = inb(ECONTROL(pb));
/* Search for SMC style EPP+ECP mode */
ECR_WRITE(pb, 0x80);
outb(0x04, CONTROL(pb));
result = parport_EPP_supported(pb);
ECR_WRITE(pb, oecr);
if (result) {
/* Set up access functions to use ECP+EPP hardware. */
pb->ops->epp_read_data = parport_pc_ecpepp_read_data;
pb->ops->epp_write_data = parport_pc_ecpepp_write_data;
pb->ops->epp_read_addr = parport_pc_ecpepp_read_addr;
pb->ops->epp_write_addr = parport_pc_ecpepp_write_addr;
}
return result;
}
#else /* No IEEE 1284 support */
/* Don't bother probing for modes we know we won't use. */
static int parport_PS2_supported(struct parport *pb) { return 0; }
#ifdef CONFIG_PARPORT_PC_FIFO
static int parport_ECP_supported(struct parport *pb)
{
return 0;
}
#endif
static int parport_EPP_supported(struct parport *pb)
{
return 0;
}
static int parport_ECPEPP_supported(struct parport *pb)
{
return 0;
}
static int parport_ECPPS2_supported(struct parport *pb)
{
return 0;
}
#endif /* No IEEE 1284 support */
/* --- IRQ detection -------------------------------------- */
/* Only if supports ECP mode */
static int programmable_irq_support(struct parport *pb)
{
int irq, intrLine;
unsigned char oecr = inb(ECONTROL(pb));
static const int lookup[8] = {
PARPORT_IRQ_NONE, 7, 9, 10, 11, 14, 15, 5
};
ECR_WRITE(pb, ECR_CNF << 5); /* Configuration MODE */
intrLine = (inb(CONFIGB(pb)) >> 3) & 0x07;
irq = lookup[intrLine];
ECR_WRITE(pb, oecr);
return irq;
}
static int irq_probe_ECP(struct parport *pb)
{
int i;
unsigned long irqs;
irqs = probe_irq_on();
ECR_WRITE(pb, ECR_SPP << 5); /* Reset FIFO */
ECR_WRITE(pb, (ECR_TST << 5) | 0x04);
ECR_WRITE(pb, ECR_TST << 5);
/* If Full FIFO sure that writeIntrThreshold is generated */
for (i = 0; i < 1024 && !(inb(ECONTROL(pb)) & 0x02) ; i++)
outb(0xaa, FIFO(pb));
pb->irq = probe_irq_off(irqs);
ECR_WRITE(pb, ECR_SPP << 5);
if (pb->irq <= 0)
pb->irq = PARPORT_IRQ_NONE;
return pb->irq;
}
/*
* This detection seems that only works in National Semiconductors
* This doesn't work in SMC, LGS, and Winbond
*/
static int irq_probe_EPP(struct parport *pb)
{
#ifndef ADVANCED_DETECT
return PARPORT_IRQ_NONE;
#else
int irqs;
unsigned char oecr;
if (pb->modes & PARPORT_MODE_PCECR)
oecr = inb(ECONTROL(pb));
irqs = probe_irq_on();
if (pb->modes & PARPORT_MODE_PCECR)
frob_econtrol(pb, 0x10, 0x10);
clear_epp_timeout(pb);
parport_pc_frob_control(pb, 0x20, 0x20);
parport_pc_frob_control(pb, 0x10, 0x10);
clear_epp_timeout(pb);
/* Device isn't expecting an EPP read
* and generates an IRQ.
*/
parport_pc_read_epp(pb);
udelay(20);
pb->irq = probe_irq_off(irqs);
if (pb->modes & PARPORT_MODE_PCECR)
ECR_WRITE(pb, oecr);
parport_pc_write_control(pb, 0xc);
if (pb->irq <= 0)
pb->irq = PARPORT_IRQ_NONE;
return pb->irq;
#endif /* Advanced detection */
}
static int irq_probe_SPP(struct parport *pb)
{
/* Don't even try to do this. */
return PARPORT_IRQ_NONE;
}
/* We will attempt to share interrupt requests since other devices
* such as sound cards and network cards seem to like using the
* printer IRQs.
*
* When ECP is available we can autoprobe for IRQs.
* NOTE: If we can autoprobe it, we can register the IRQ.
*/
static int parport_irq_probe(struct parport *pb)
{
struct parport_pc_private *priv = pb->private_data;
if (priv->ecr) {
pb->irq = programmable_irq_support(pb);
if (pb->irq == PARPORT_IRQ_NONE)
pb->irq = irq_probe_ECP(pb);
}
if ((pb->irq == PARPORT_IRQ_NONE) && priv->ecr &&
(pb->modes & PARPORT_MODE_EPP))
pb->irq = irq_probe_EPP(pb);
clear_epp_timeout(pb);
if (pb->irq == PARPORT_IRQ_NONE && (pb->modes & PARPORT_MODE_EPP))
pb->irq = irq_probe_EPP(pb);
clear_epp_timeout(pb);
if (pb->irq == PARPORT_IRQ_NONE)
pb->irq = irq_probe_SPP(pb);
if (pb->irq == PARPORT_IRQ_NONE)
pb->irq = get_superio_irq(pb);
return pb->irq;
}
/* --- DMA detection -------------------------------------- */
/* Only if chipset conforms to ECP ISA Interface Standard */
static int programmable_dma_support(struct parport *p)
{
unsigned char oecr = inb(ECONTROL(p));
int dma;
frob_set_mode(p, ECR_CNF);
dma = inb(CONFIGB(p)) & 0x07;
/* 000: Indicates jumpered 8-bit DMA if read-only.
100: Indicates jumpered 16-bit DMA if read-only. */
if ((dma & 0x03) == 0)
dma = PARPORT_DMA_NONE;
ECR_WRITE(p, oecr);
return dma;
}
static int parport_dma_probe(struct parport *p)
{
const struct parport_pc_private *priv = p->private_data;
if (priv->ecr) /* ask ECP chipset first */
p->dma = programmable_dma_support(p);
if (p->dma == PARPORT_DMA_NONE) {
/* ask known Super-IO chips proper, although these
claim ECP compatible, some don't report their DMA
conforming to ECP standards */
p->dma = get_superio_dma(p);
}
return p->dma;
}
/* --- Initialisation code -------------------------------- */
static LIST_HEAD(ports_list);
static DEFINE_SPINLOCK(ports_lock);
struct parport *parport_pc_probe_port(unsigned long int base,
unsigned long int base_hi,
int irq, int dma,
struct device *dev,
int irqflags)
{
struct parport_pc_private *priv;
struct parport_operations *ops;
struct parport *p;
int probedirq = PARPORT_IRQ_NONE;
struct resource *base_res;
struct resource *ECR_res = NULL;
struct resource *EPP_res = NULL;
struct platform_device *pdev = NULL;
int ret;
if (!dev) {
/* We need a physical device to attach to, but none was
* provided. Create our own. */
pdev = platform_device_register_simple("parport_pc",
base, NULL, 0);
if (IS_ERR(pdev))
return NULL;
dev = &pdev->dev;
ret = dma_coerce_mask_and_coherent(dev, DMA_BIT_MASK(24));
if (ret) {
dev_err(dev, "Unable to set coherent dma mask: disabling DMA\n");
dma = PARPORT_DMA_NONE;
}
}
ops = kmalloc(sizeof(struct parport_operations), GFP_KERNEL);
if (!ops)
goto out1;
priv = kmalloc(sizeof(struct parport_pc_private), GFP_KERNEL);
if (!priv)
goto out2;
/* a misnomer, actually - it's allocate and reserve parport number */
p = parport_register_port(base, irq, dma, ops);
if (!p)
goto out3;
base_res = request_region(base, 3, p->name);
if (!base_res)
goto out4;
memcpy(ops, &parport_pc_ops, sizeof(struct parport_operations));
priv->ctr = 0xc;
priv->ctr_writable = ~0x10;
priv->ecr = 0;
priv->fifo_depth = 0;
priv->dma_buf = NULL;
priv->dma_handle = 0;
INIT_LIST_HEAD(&priv->list);
priv->port = p;
p->dev = dev;
p->base_hi = base_hi;
p->modes = PARPORT_MODE_PCSPP | PARPORT_MODE_SAFEININT;
p->private_data = priv;
if (base_hi) {
ECR_res = request_region(base_hi, 3, p->name);
if (ECR_res)
parport_ECR_present(p);
}
if (base != 0x3bc) {
EPP_res = request_region(base+0x3, 5, p->name);
if (EPP_res)
if (!parport_EPP_supported(p))
parport_ECPEPP_supported(p);
}
if (!parport_SPP_supported(p))
/* No port. */
goto out5;
if (priv->ecr)
parport_ECPPS2_supported(p);
else
parport_PS2_supported(p);
p->size = (p->modes & PARPORT_MODE_EPP) ? 8 : 3;
pr_info("%s: PC-style at 0x%lx", p->name, p->base);
if (p->base_hi && priv->ecr)
pr_cont(" (0x%lx)", p->base_hi);
if (p->irq == PARPORT_IRQ_AUTO) {
p->irq = PARPORT_IRQ_NONE;
parport_irq_probe(p);
} else if (p->irq == PARPORT_IRQ_PROBEONLY) {
p->irq = PARPORT_IRQ_NONE;
parport_irq_probe(p);
probedirq = p->irq;
p->irq = PARPORT_IRQ_NONE;
}
if (p->irq != PARPORT_IRQ_NONE) {
pr_cont(", irq %d", p->irq);
priv->ctr_writable |= 0x10;
if (p->dma == PARPORT_DMA_AUTO) {
p->dma = PARPORT_DMA_NONE;
parport_dma_probe(p);
}
}
if (p->dma == PARPORT_DMA_AUTO) /* To use DMA, giving the irq
is mandatory (see above) */
p->dma = PARPORT_DMA_NONE;
#ifdef CONFIG_PARPORT_PC_FIFO
if (parport_ECP_supported(p) &&
p->dma != PARPORT_DMA_NOFIFO &&
priv->fifo_depth > 0 && p->irq != PARPORT_IRQ_NONE) {
p->modes |= PARPORT_MODE_ECP | PARPORT_MODE_COMPAT;
p->ops->compat_write_data = parport_pc_compat_write_block_pio;
#ifdef CONFIG_PARPORT_1284
p->ops->ecp_write_data = parport_pc_ecp_write_block_pio;
/* currently broken, but working on it.. (FB) */
/* p->ops->ecp_read_data = parport_pc_ecp_read_block_pio; */
#endif /* IEEE 1284 support */
if (p->dma != PARPORT_DMA_NONE) {
pr_cont(", dma %d", p->dma);
p->modes |= PARPORT_MODE_DMA;
} else
pr_cont(", using FIFO");
} else
/* We can't use the DMA channel after all. */
p->dma = PARPORT_DMA_NONE;
#endif /* Allowed to use FIFO/DMA */
pr_cont(" [");
#define printmode(x) \
do { \
if (p->modes & PARPORT_MODE_##x) \
pr_cont("%s%s", f++ ? "," : "", #x); \
} while (0)
{
int f = 0;
printmode(PCSPP);
printmode(TRISTATE);
printmode(COMPAT);
printmode(EPP);
printmode(ECP);
printmode(DMA);
}
#undef printmode
#ifndef CONFIG_PARPORT_1284
pr_cont("(,...)");
#endif /* CONFIG_PARPORT_1284 */
pr_cont("]\n");
if (probedirq != PARPORT_IRQ_NONE)
pr_info("%s: irq %d detected\n", p->name, probedirq);
/* If No ECP release the ports grabbed above. */
if (ECR_res && (p->modes & PARPORT_MODE_ECP) == 0) {
release_region(base_hi, 3);
ECR_res = NULL;
}
/* Likewise for EEP ports */
if (EPP_res && (p->modes & PARPORT_MODE_EPP) == 0) {
release_region(base+3, 5);
EPP_res = NULL;
}
if (p->irq != PARPORT_IRQ_NONE) {
if (request_irq(p->irq, parport_irq_handler,
irqflags, p->name, p)) {
pr_warn("%s: irq %d in use, resorting to polled operation\n",
p->name, p->irq);
p->irq = PARPORT_IRQ_NONE;
p->dma = PARPORT_DMA_NONE;
}
#ifdef CONFIG_PARPORT_PC_FIFO
#ifdef HAS_DMA
if (p->dma != PARPORT_DMA_NONE) {
if (request_dma(p->dma, p->name)) {
pr_warn("%s: dma %d in use, resorting to PIO operation\n",
p->name, p->dma);
p->dma = PARPORT_DMA_NONE;
} else {
priv->dma_buf =
dma_alloc_coherent(dev,
PAGE_SIZE,
&priv->dma_handle,
GFP_KERNEL);
if (!priv->dma_buf) {
pr_warn("%s: cannot get buffer for DMA, resorting to PIO operation\n",
p->name);
free_dma(p->dma);
p->dma = PARPORT_DMA_NONE;
}
}
}
#endif
#endif
}
/* Done probing. Now put the port into a sensible start-up state. */
if (priv->ecr)
/*
* Put the ECP detected port in PS2 mode.
* Do this also for ports that have ECR but don't do ECP.
*/
ECR_WRITE(p, 0x34);
parport_pc_write_data(p, 0);
parport_pc_data_forward(p);
/* Now that we've told the sharing engine about the port, and
found out its characteristics, let the high-level drivers
know about it. */
spin_lock(&ports_lock);
list_add(&priv->list, &ports_list);
spin_unlock(&ports_lock);
parport_announce_port(p);
return p;
out5:
if (ECR_res)
release_region(base_hi, 3);
if (EPP_res)
release_region(base+0x3, 5);
release_region(base, 3);
out4:
parport_del_port(p);
out3:
kfree(priv);
out2:
kfree(ops);
out1:
if (pdev)
platform_device_unregister(pdev);
return NULL;
}
EXPORT_SYMBOL(parport_pc_probe_port);
void parport_pc_unregister_port(struct parport *p)
{
struct parport_pc_private *priv = p->private_data;
struct parport_operations *ops = p->ops;
parport_remove_port(p);
spin_lock(&ports_lock);
list_del_init(&priv->list);
spin_unlock(&ports_lock);
#if defined(CONFIG_PARPORT_PC_FIFO) && defined(HAS_DMA)
if (p->dma != PARPORT_DMA_NONE)
free_dma(p->dma);
#endif
if (p->irq != PARPORT_IRQ_NONE)
free_irq(p->irq, p);
release_region(p->base, 3);
if (p->size > 3)
release_region(p->base + 3, p->size - 3);
if (p->modes & PARPORT_MODE_ECP)
release_region(p->base_hi, 3);
#if defined(CONFIG_PARPORT_PC_FIFO) && defined(HAS_DMA)
if (priv->dma_buf)
dma_free_coherent(p->physport->dev, PAGE_SIZE,
priv->dma_buf,
priv->dma_handle);
#endif
kfree(p->private_data);
parport_del_port(p);
kfree(ops); /* hope no-one cached it */
}
EXPORT_SYMBOL(parport_pc_unregister_port);
#ifdef CONFIG_PCI
/* ITE support maintained by Rich Liu <richliu@poorman.org> */
static int sio_ite_8872_probe(struct pci_dev *pdev, int autoirq, int autodma,
const struct parport_pc_via_data *via)
{
short inta_addr[6] = { 0x2A0, 0x2C0, 0x220, 0x240, 0x1E0 };
u32 ite8872set;
u32 ite8872_lpt, ite8872_lpthi;
u8 ite8872_irq, type;
int irq;
int i;
pr_debug("sio_ite_8872_probe()\n");
/* make sure which one chip */
for (i = 0; i < 5; i++) {
if (request_region(inta_addr[i], 32, "it887x")) {
int test;
pci_write_config_dword(pdev, 0x60,
0xe5000000 | inta_addr[i]);
pci_write_config_dword(pdev, 0x78,
0x00000000 | inta_addr[i]);
test = inb(inta_addr[i]);
if (test != 0xff)
break;
release_region(inta_addr[i], 32);
}
}
if (i >= 5) {
pr_info("parport_pc: cannot find ITE8872 INTA\n");
return 0;
}
type = inb(inta_addr[i] + 0x18);
type &= 0x0f;
switch (type) {
case 0x2:
pr_info("parport_pc: ITE8871 found (1P)\n");
ite8872set = 0x64200000;
break;
case 0xa:
pr_info("parport_pc: ITE8875 found (1P)\n");
ite8872set = 0x64200000;
break;
case 0xe:
pr_info("parport_pc: ITE8872 found (2S1P)\n");
ite8872set = 0x64e00000;
break;
case 0x6:
pr_info("parport_pc: ITE8873 found (1S)\n");
release_region(inta_addr[i], 32);
return 0;
case 0x8:
pr_info("parport_pc: ITE8874 found (2S)\n");
release_region(inta_addr[i], 32);
return 0;
default:
pr_info("parport_pc: unknown ITE887x\n");
pr_info("parport_pc: please mail 'lspci -nvv' output to Rich.Liu@ite.com.tw\n");
release_region(inta_addr[i], 32);
return 0;
}
pci_read_config_byte(pdev, 0x3c, &ite8872_irq);
pci_read_config_dword(pdev, 0x1c, &ite8872_lpt);
ite8872_lpt &= 0x0000ff00;
pci_read_config_dword(pdev, 0x20, &ite8872_lpthi);
ite8872_lpthi &= 0x0000ff00;
pci_write_config_dword(pdev, 0x6c, 0xe3000000 | ite8872_lpt);
pci_write_config_dword(pdev, 0x70, 0xe3000000 | ite8872_lpthi);
pci_write_config_dword(pdev, 0x80, (ite8872_lpthi<<16) | ite8872_lpt);
/* SET SPP&EPP , Parallel Port NO DMA , Enable All Function */
/* SET Parallel IRQ */
pci_write_config_dword(pdev, 0x9c,
ite8872set | (ite8872_irq * 0x11111));
pr_debug("ITE887x: The IRQ is %d\n", ite8872_irq);
pr_debug("ITE887x: The PARALLEL I/O port is 0x%x\n", ite8872_lpt);
pr_debug("ITE887x: The PARALLEL I/O porthi is 0x%x\n", ite8872_lpthi);
/* Let the user (or defaults) steer us away from interrupts */
irq = ite8872_irq;
if (autoirq != PARPORT_IRQ_AUTO)
irq = PARPORT_IRQ_NONE;
/*
* Release the resource so that parport_pc_probe_port can get it.
*/
release_region(inta_addr[i], 32);
if (parport_pc_probe_port(ite8872_lpt, ite8872_lpthi,
irq, PARPORT_DMA_NONE, &pdev->dev, 0)) {
pr_info("parport_pc: ITE 8872 parallel port: io=0x%X",
ite8872_lpt);
if (irq != PARPORT_IRQ_NONE)
pr_cont(", irq=%d", irq);
pr_cont("\n");
return 1;
}
return 0;
}
/* VIA 8231 support by Pavel Fedin <sonic_amiga@rambler.ru>
based on VIA 686a support code by Jeff Garzik <jgarzik@pobox.com> */
static int parport_init_mode;
/* Data for two known VIA chips */
static struct parport_pc_via_data via_686a_data = {
0x51,
0x50,
0x85,
0x02,
0xE2,
0xF0,
0xE6
};
static struct parport_pc_via_data via_8231_data = {
0x45,
0x44,
0x50,
0x04,
0xF2,
0xFA,
0xF6
};
static int sio_via_probe(struct pci_dev *pdev, int autoirq, int autodma,
const struct parport_pc_via_data *via)
{
u8 tmp, tmp2, siofunc;
u8 ppcontrol = 0;
int dma, irq;
unsigned port1, port2;
unsigned have_epp = 0;
printk(KERN_DEBUG "parport_pc: VIA 686A/8231 detected\n");
switch (parport_init_mode) {
case 1:
printk(KERN_DEBUG "parport_pc: setting SPP mode\n");
siofunc = VIA_FUNCTION_PARPORT_SPP;
break;
case 2:
printk(KERN_DEBUG "parport_pc: setting PS/2 mode\n");
siofunc = VIA_FUNCTION_PARPORT_SPP;
ppcontrol = VIA_PARPORT_BIDIR;
break;
case 3:
printk(KERN_DEBUG "parport_pc: setting EPP mode\n");
siofunc = VIA_FUNCTION_PARPORT_EPP;
ppcontrol = VIA_PARPORT_BIDIR;
have_epp = 1;
break;
case 4:
printk(KERN_DEBUG "parport_pc: setting ECP mode\n");
siofunc = VIA_FUNCTION_PARPORT_ECP;
ppcontrol = VIA_PARPORT_BIDIR;
break;
case 5:
printk(KERN_DEBUG "parport_pc: setting EPP+ECP mode\n");
siofunc = VIA_FUNCTION_PARPORT_ECP;
ppcontrol = VIA_PARPORT_BIDIR|VIA_PARPORT_ECPEPP;
have_epp = 1;
break;
default:
printk(KERN_DEBUG "parport_pc: probing current configuration\n");
siofunc = VIA_FUNCTION_PROBE;
break;
}
/*
* unlock super i/o configuration
*/
pci_read_config_byte(pdev, via->via_pci_superio_config_reg, &tmp);
tmp |= via->via_pci_superio_config_data;
pci_write_config_byte(pdev, via->via_pci_superio_config_reg, tmp);
/* Bits 1-0: Parallel Port Mode / Enable */
outb(via->viacfg_function, VIA_CONFIG_INDEX);
tmp = inb(VIA_CONFIG_DATA);
/* Bit 5: EPP+ECP enable; bit 7: PS/2 bidirectional port enable */
outb(via->viacfg_parport_control, VIA_CONFIG_INDEX);
tmp2 = inb(VIA_CONFIG_DATA);
if (siofunc == VIA_FUNCTION_PROBE) {
siofunc = tmp & VIA_FUNCTION_PARPORT_DISABLE;
ppcontrol = tmp2;
} else {
tmp &= ~VIA_FUNCTION_PARPORT_DISABLE;
tmp |= siofunc;
outb(via->viacfg_function, VIA_CONFIG_INDEX);
outb(tmp, VIA_CONFIG_DATA);
tmp2 &= ~(VIA_PARPORT_BIDIR|VIA_PARPORT_ECPEPP);
tmp2 |= ppcontrol;
outb(via->viacfg_parport_control, VIA_CONFIG_INDEX);
outb(tmp2, VIA_CONFIG_DATA);
}
/* Parallel Port I/O Base Address, bits 9-2 */
outb(via->viacfg_parport_base, VIA_CONFIG_INDEX);
port1 = inb(VIA_CONFIG_DATA) << 2;
printk(KERN_DEBUG "parport_pc: Current parallel port base: 0x%X\n",
port1);
if (port1 == 0x3BC && have_epp) {
outb(via->viacfg_parport_base, VIA_CONFIG_INDEX);
outb((0x378 >> 2), VIA_CONFIG_DATA);
printk(KERN_DEBUG "parport_pc: Parallel port base changed to 0x378\n");
port1 = 0x378;
}
/*
* lock super i/o configuration
*/
pci_read_config_byte(pdev, via->via_pci_superio_config_reg, &tmp);
tmp &= ~via->via_pci_superio_config_data;
pci_write_config_byte(pdev, via->via_pci_superio_config_reg, tmp);
if (siofunc == VIA_FUNCTION_PARPORT_DISABLE) {
pr_info("parport_pc: VIA parallel port disabled in BIOS\n");
return 0;
}
/* Bits 7-4: PnP Routing for Parallel Port IRQ */
pci_read_config_byte(pdev, via->via_pci_parport_irq_reg, &tmp);
irq = ((tmp & VIA_IRQCONTROL_PARALLEL) >> 4);
if (siofunc == VIA_FUNCTION_PARPORT_ECP) {
/* Bits 3-2: PnP Routing for Parallel Port DMA */
pci_read_config_byte(pdev, via->via_pci_parport_dma_reg, &tmp);
dma = ((tmp & VIA_DMACONTROL_PARALLEL) >> 2);
} else
/* if ECP not enabled, DMA is not enabled, assumed
bogus 'dma' value */
dma = PARPORT_DMA_NONE;
/* Let the user (or defaults) steer us away from interrupts and DMA */
if (autoirq == PARPORT_IRQ_NONE) {
irq = PARPORT_IRQ_NONE;
dma = PARPORT_DMA_NONE;
}
if (autodma == PARPORT_DMA_NONE)
dma = PARPORT_DMA_NONE;
switch (port1) {
case 0x3bc:
port2 = 0x7bc; break;
case 0x378:
port2 = 0x778; break;
case 0x278:
port2 = 0x678; break;
default:
pr_info("parport_pc: Weird VIA parport base 0x%X, ignoring\n",
port1);
return 0;
}
/* filter bogus IRQs */
switch (irq) {
case 0:
case 2:
case 8:
case 13:
irq = PARPORT_IRQ_NONE;
break;
default: /* do nothing */
break;
}
/* finally, do the probe with values obtained */
if (parport_pc_probe_port(port1, port2, irq, dma, &pdev->dev, 0)) {
pr_info("parport_pc: VIA parallel port: io=0x%X", port1);
if (irq != PARPORT_IRQ_NONE)
pr_cont(", irq=%d", irq);
if (dma != PARPORT_DMA_NONE)
pr_cont(", dma=%d", dma);
pr_cont("\n");
return 1;
}
pr_warn("parport_pc: Strange, can't probe VIA parallel port: io=0x%X, irq=%d, dma=%d\n",
port1, irq, dma);
return 0;
}
enum parport_pc_sio_types {
sio_via_686a = 0, /* Via VT82C686A motherboard Super I/O */
sio_via_8231, /* Via VT8231 south bridge integrated Super IO */
sio_ite_8872,
last_sio
};
/* each element directly indexed from enum list, above */
static struct parport_pc_superio {
int (*probe) (struct pci_dev *pdev, int autoirq, int autodma,
const struct parport_pc_via_data *via);
const struct parport_pc_via_data *via;
} parport_pc_superio_info[] = {
{ sio_via_probe, &via_686a_data, },
{ sio_via_probe, &via_8231_data, },
{ sio_ite_8872_probe, NULL, },
};
enum parport_pc_pci_cards {
siig_1p_10x = last_sio,
siig_2p_10x,
siig_1p_20x,
siig_2p_20x,
lava_parallel,
lava_parallel_dual_a,
lava_parallel_dual_b,
boca_ioppar,
plx_9050,
timedia_4006a,
timedia_4014,
timedia_4008a,
timedia_4018,
timedia_9018a,
syba_2p_epp,
syba_1p_ecp,
titan_010l,
avlab_1p,
avlab_2p,
oxsemi_952,
oxsemi_954,
oxsemi_840,
oxsemi_pcie_pport,
aks_0100,
mobility_pp,
netmos_9705,
netmos_9715,
netmos_9755,
netmos_9805,
netmos_9815,
netmos_9901,
netmos_9865,
quatech_sppxp100,
wch_ch382l,
};
/* each element directly indexed from enum list, above
* (but offset by last_sio) */
static struct parport_pc_pci {
int numports;
struct { /* BAR (base address registers) numbers in the config
space header */
int lo;
int hi;
/* -1 if not there, >6 for offset-method (max BAR is 6) */
} addr[4];
/* If set, this is called immediately after pci_enable_device.
* If it returns non-zero, no probing will take place and the
* ports will not be used. */
int (*preinit_hook) (struct pci_dev *pdev, int autoirq, int autodma);
/* If set, this is called after probing for ports. If 'failed'
* is non-zero we couldn't use any of the ports. */
void (*postinit_hook) (struct pci_dev *pdev, int failed);
} cards[] = {
/* siig_1p_10x */ { 1, { { 2, 3 }, } },
/* siig_2p_10x */ { 2, { { 2, 3 }, { 4, 5 }, } },
/* siig_1p_20x */ { 1, { { 0, 1 }, } },
/* siig_2p_20x */ { 2, { { 0, 1 }, { 2, 3 }, } },
/* lava_parallel */ { 1, { { 0, -1 }, } },
/* lava_parallel_dual_a */ { 1, { { 0, -1 }, } },
/* lava_parallel_dual_b */ { 1, { { 0, -1 }, } },
/* boca_ioppar */ { 1, { { 0, -1 }, } },
/* plx_9050 */ { 2, { { 4, -1 }, { 5, -1 }, } },
/* timedia_4006a */ { 1, { { 0, -1 }, } },
/* timedia_4014 */ { 2, { { 0, -1 }, { 2, -1 }, } },
/* timedia_4008a */ { 1, { { 0, 1 }, } },
/* timedia_4018 */ { 2, { { 0, 1 }, { 2, 3 }, } },
/* timedia_9018a */ { 2, { { 0, 1 }, { 2, 3 }, } },
/* SYBA uses fixed offsets in
a 1K io window */
/* syba_2p_epp AP138B */ { 2, { { 0, 0x078 }, { 0, 0x178 }, } },
/* syba_1p_ecp W83787 */ { 1, { { 0, 0x078 }, } },
/* titan_010l */ { 1, { { 3, -1 }, } },
/* avlab_1p */ { 1, { { 0, 1}, } },
/* avlab_2p */ { 2, { { 0, 1}, { 2, 3 },} },
/* The Oxford Semi cards are unusual: 954 doesn't support ECP,
* and 840 locks up if you write 1 to bit 2! */
/* oxsemi_952 */ { 1, { { 0, 1 }, } },
/* oxsemi_954 */ { 1, { { 0, -1 }, } },
/* oxsemi_840 */ { 1, { { 0, 1 }, } },
/* oxsemi_pcie_pport */ { 1, { { 0, 1 }, } },
/* aks_0100 */ { 1, { { 0, -1 }, } },
/* mobility_pp */ { 1, { { 0, 1 }, } },
/* The netmos entries below are untested */
/* netmos_9705 */ { 1, { { 0, -1 }, } },
/* netmos_9715 */ { 2, { { 0, 1 }, { 2, 3 },} },
/* netmos_9755 */ { 2, { { 0, 1 }, { 2, 3 },} },
/* netmos_9805 */ { 1, { { 0, 1 }, } },
/* netmos_9815 */ { 2, { { 0, 1 }, { 2, 3 }, } },
/* netmos_9901 */ { 1, { { 0, -1 }, } },
/* netmos_9865 */ { 1, { { 0, -1 }, } },
/* quatech_sppxp100 */ { 1, { { 0, 1 }, } },
/* wch_ch382l */ { 1, { { 2, -1 }, } },
};
static const struct pci_device_id parport_pc_pci_tbl[] = {
/* Super-IO onboard chips */
{ 0x1106, 0x0686, PCI_ANY_ID, PCI_ANY_ID, 0, 0, sio_via_686a },
{ 0x1106, 0x8231, PCI_ANY_ID, PCI_ANY_ID, 0, 0, sio_via_8231 },
{ PCI_VENDOR_ID_ITE, PCI_DEVICE_ID_ITE_8872,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, sio_ite_8872 },
/* PCI cards */
{ PCI_VENDOR_ID_SIIG, PCI_DEVICE_ID_SIIG_1P_10x,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, siig_1p_10x },
{ PCI_VENDOR_ID_SIIG, PCI_DEVICE_ID_SIIG_2P_10x,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, siig_2p_10x },
{ PCI_VENDOR_ID_SIIG, PCI_DEVICE_ID_SIIG_1P_20x,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, siig_1p_20x },
{ PCI_VENDOR_ID_SIIG, PCI_DEVICE_ID_SIIG_2P_20x,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, siig_2p_20x },
{ PCI_VENDOR_ID_LAVA, PCI_DEVICE_ID_LAVA_PARALLEL,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, lava_parallel },
{ PCI_VENDOR_ID_LAVA, PCI_DEVICE_ID_LAVA_DUAL_PAR_A,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, lava_parallel_dual_a },
{ PCI_VENDOR_ID_LAVA, PCI_DEVICE_ID_LAVA_DUAL_PAR_B,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, lava_parallel_dual_b },
{ PCI_VENDOR_ID_LAVA, PCI_DEVICE_ID_LAVA_BOCA_IOPPAR,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, boca_ioppar },
{ PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050,
PCI_SUBVENDOR_ID_EXSYS, PCI_SUBDEVICE_ID_EXSYS_4014, 0, 0, plx_9050 },
/* PCI_VENDOR_ID_TIMEDIA/SUNIX has many differing cards ...*/
{ 0x1409, 0x7268, 0x1409, 0x0101, 0, 0, timedia_4006a },
{ 0x1409, 0x7268, 0x1409, 0x0102, 0, 0, timedia_4014 },
{ 0x1409, 0x7268, 0x1409, 0x0103, 0, 0, timedia_4008a },
{ 0x1409, 0x7268, 0x1409, 0x0104, 0, 0, timedia_4018 },
{ 0x1409, 0x7268, 0x1409, 0x9018, 0, 0, timedia_9018a },
{ PCI_VENDOR_ID_SYBA, PCI_DEVICE_ID_SYBA_2P_EPP,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, syba_2p_epp },
{ PCI_VENDOR_ID_SYBA, PCI_DEVICE_ID_SYBA_1P_ECP,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, syba_1p_ecp },
{ PCI_VENDOR_ID_TITAN, PCI_DEVICE_ID_TITAN_010L,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, titan_010l },
/* PCI_VENDOR_ID_AVLAB/Intek21 has another bunch of cards ...*/
/* AFAVLAB_TK9902 */
{ 0x14db, 0x2120, PCI_ANY_ID, PCI_ANY_ID, 0, 0, avlab_1p},
{ 0x14db, 0x2121, PCI_ANY_ID, PCI_ANY_ID, 0, 0, avlab_2p},
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_16PCI952PP,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_952 },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_16PCI954PP,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_954 },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_12PCI840,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_840 },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_PCIe840,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_pcie_pport },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_PCIe840_G,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_pcie_pport },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_PCIe952_0,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_pcie_pport },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_PCIe952_0_G,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_pcie_pport },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_PCIe952_1,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_pcie_pport },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_PCIe952_1_G,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_pcie_pport },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_PCIe952_1_U,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_pcie_pport },
{ PCI_VENDOR_ID_OXSEMI, PCI_DEVICE_ID_OXSEMI_PCIe952_1_GU,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, oxsemi_pcie_pport },
{ PCI_VENDOR_ID_AKS, PCI_DEVICE_ID_AKS_ALADDINCARD,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, aks_0100 },
{ 0x14f2, 0x0121, PCI_ANY_ID, PCI_ANY_ID, 0, 0, mobility_pp },
/* NetMos communication controllers */
{ PCI_VENDOR_ID_NETMOS, PCI_DEVICE_ID_NETMOS_9705,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, netmos_9705 },
{ PCI_VENDOR_ID_NETMOS, PCI_DEVICE_ID_NETMOS_9715,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, netmos_9715 },
{ PCI_VENDOR_ID_NETMOS, PCI_DEVICE_ID_NETMOS_9755,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, netmos_9755 },
{ PCI_VENDOR_ID_NETMOS, PCI_DEVICE_ID_NETMOS_9805,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, netmos_9805 },
{ PCI_VENDOR_ID_NETMOS, PCI_DEVICE_ID_NETMOS_9815,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, netmos_9815 },
{ PCI_VENDOR_ID_NETMOS, PCI_DEVICE_ID_NETMOS_9901,
0xA000, 0x2000, 0, 0, netmos_9901 },
{ PCI_VENDOR_ID_NETMOS, PCI_DEVICE_ID_NETMOS_9865,
0xA000, 0x1000, 0, 0, netmos_9865 },
{ PCI_VENDOR_ID_NETMOS, PCI_DEVICE_ID_NETMOS_9865,
0xA000, 0x2000, 0, 0, netmos_9865 },
/* Quatech SPPXP-100 Parallel port PCI ExpressCard */
{ PCI_VENDOR_ID_QUATECH, PCI_DEVICE_ID_QUATECH_SPPXP_100,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, quatech_sppxp100 },
/* WCH CH382L PCI-E single parallel port card */
{ 0x1c00, 0x3050, 0x1c00, 0x3050, 0, 0, wch_ch382l },
{ 0, } /* terminate list */
};
MODULE_DEVICE_TABLE(pci, parport_pc_pci_tbl);
struct pci_parport_data {
int num;
struct parport *ports[2];
};
static int parport_pc_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
int err, count, n, i = id->driver_data;
struct pci_parport_data *data;
if (i < last_sio)
/* This is an onboard Super-IO and has already been probed */
return 0;
/* This is a PCI card */
i -= last_sio;
count = 0;
err = pci_enable_device(dev);
if (err)
return err;
data = kmalloc(sizeof(struct pci_parport_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
if (cards[i].preinit_hook &&
cards[i].preinit_hook(dev, PARPORT_IRQ_NONE, PARPORT_DMA_NONE)) {
kfree(data);
return -ENODEV;
}
for (n = 0; n < cards[i].numports; n++) {
int lo = cards[i].addr[n].lo;
int hi = cards[i].addr[n].hi;
int irq;
unsigned long io_lo, io_hi;
io_lo = pci_resource_start(dev, lo);
io_hi = 0;
if ((hi >= 0) && (hi <= 6))
io_hi = pci_resource_start(dev, hi);
else if (hi > 6)
io_lo += hi; /* Reinterpret the meaning of
"hi" as an offset (see SYBA
def.) */
/* TODO: test if sharing interrupts works */
irq = dev->irq;
if (irq == IRQ_NONE) {
printk(KERN_DEBUG "PCI parallel port detected: %04x:%04x, I/O at %#lx(%#lx)\n",
id->vendor, id->device, io_lo, io_hi);
irq = PARPORT_IRQ_NONE;
} else {
printk(KERN_DEBUG "PCI parallel port detected: %04x:%04x, I/O at %#lx(%#lx), IRQ %d\n",
id->vendor, id->device, io_lo, io_hi, irq);
}
data->ports[count] =
parport_pc_probe_port(io_lo, io_hi, irq,
PARPORT_DMA_NONE, &dev->dev,
IRQF_SHARED);
if (data->ports[count])
count++;
}
data->num = count;
if (cards[i].postinit_hook)
cards[i].postinit_hook(dev, count == 0);
if (count) {
pci_set_drvdata(dev, data);
return 0;
}
kfree(data);
return -ENODEV;
}
static void parport_pc_pci_remove(struct pci_dev *dev)
{
struct pci_parport_data *data = pci_get_drvdata(dev);
int i;
if (data) {
for (i = data->num - 1; i >= 0; i--)
parport_pc_unregister_port(data->ports[i]);
kfree(data);
}
}
static struct pci_driver parport_pc_pci_driver = {
.name = "parport_pc",
.id_table = parport_pc_pci_tbl,
.probe = parport_pc_pci_probe,
.remove = parport_pc_pci_remove,
};
static int __init parport_pc_init_superio(int autoirq, int autodma)
{
const struct pci_device_id *id;
struct pci_dev *pdev = NULL;
int ret = 0;
for_each_pci_dev(pdev) {
id = pci_match_id(parport_pc_pci_tbl, pdev);
if (id == NULL || id->driver_data >= last_sio)
continue;
if (parport_pc_superio_info[id->driver_data].probe(
pdev, autoirq, autodma,
parport_pc_superio_info[id->driver_data].via)) {
ret++;
}
}
return ret; /* number of devices found */
}
#else
static struct pci_driver parport_pc_pci_driver;
static int __init parport_pc_init_superio(int autoirq, int autodma)
{
return 0;
}
#endif /* CONFIG_PCI */
#ifdef CONFIG_PNP
static const struct pnp_device_id parport_pc_pnp_tbl[] = {
/* Standard LPT Printer Port */
{.id = "PNP0400", .driver_data = 0},
/* ECP Printer Port */
{.id = "PNP0401", .driver_data = 0},
{ }
};
MODULE_DEVICE_TABLE(pnp, parport_pc_pnp_tbl);
static int parport_pc_pnp_probe(struct pnp_dev *dev,
const struct pnp_device_id *id)
{
struct parport *pdata;
unsigned long io_lo, io_hi;
int dma, irq;
if (pnp_port_valid(dev, 0) &&
!(pnp_port_flags(dev, 0) & IORESOURCE_DISABLED)) {
io_lo = pnp_port_start(dev, 0);
} else
return -EINVAL;
if (pnp_port_valid(dev, 1) &&
!(pnp_port_flags(dev, 1) & IORESOURCE_DISABLED)) {
io_hi = pnp_port_start(dev, 1);
} else
io_hi = 0;
if (pnp_irq_valid(dev, 0) &&
!(pnp_irq_flags(dev, 0) & IORESOURCE_DISABLED)) {
irq = pnp_irq(dev, 0);
} else
irq = PARPORT_IRQ_NONE;
if (pnp_dma_valid(dev, 0) &&
!(pnp_dma_flags(dev, 0) & IORESOURCE_DISABLED)) {
dma = pnp_dma(dev, 0);
} else
dma = PARPORT_DMA_NONE;
dev_info(&dev->dev, "reported by %s\n", dev->protocol->name);
pdata = parport_pc_probe_port(io_lo, io_hi, irq, dma, &dev->dev, 0);
if (pdata == NULL)
return -ENODEV;
pnp_set_drvdata(dev, pdata);
return 0;
}
static void parport_pc_pnp_remove(struct pnp_dev *dev)
{
struct parport *pdata = (struct parport *)pnp_get_drvdata(dev);
if (!pdata)
return;
parport_pc_unregister_port(pdata);
}
/* we only need the pnp layer to activate the device, at least for now */
static struct pnp_driver parport_pc_pnp_driver = {
.name = "parport_pc",
.id_table = parport_pc_pnp_tbl,
.probe = parport_pc_pnp_probe,
.remove = parport_pc_pnp_remove,
};
#else
static struct pnp_driver parport_pc_pnp_driver;
#endif /* CONFIG_PNP */
static int parport_pc_platform_probe(struct platform_device *pdev)
{
/* Always succeed, the actual probing is done in
* parport_pc_probe_port(). */
return 0;
}
static struct platform_driver parport_pc_platform_driver = {
.driver = {
.name = "parport_pc",
},
.probe = parport_pc_platform_probe,
};
/* This is called by parport_pc_find_nonpci_ports (in asm/parport.h) */
static int __attribute__((unused))
parport_pc_find_isa_ports(int autoirq, int autodma)
{
int count = 0;
if (parport_pc_probe_port(0x3bc, 0x7bc, autoirq, autodma, NULL, 0))
count++;
if (parport_pc_probe_port(0x378, 0x778, autoirq, autodma, NULL, 0))
count++;
if (parport_pc_probe_port(0x278, 0x678, autoirq, autodma, NULL, 0))
count++;
return count;
}
/* This function is called by parport_pc_init if the user didn't
* specify any ports to probe. Its job is to find some ports. Order
* is important here -- we want ISA ports to be registered first,
* followed by PCI cards (for least surprise), but before that we want
* to do chipset-specific tests for some onboard ports that we know
* about.
*
* autoirq is PARPORT_IRQ_NONE, PARPORT_IRQ_AUTO, or PARPORT_IRQ_PROBEONLY
* autodma is PARPORT_DMA_NONE or PARPORT_DMA_AUTO
*/
static void __init parport_pc_find_ports(int autoirq, int autodma)
{
int count = 0, err;
#ifdef CONFIG_PARPORT_PC_SUPERIO
detect_and_report_it87();
detect_and_report_winbond();
detect_and_report_smsc();
#endif
/* Onboard SuperIO chipsets that show themselves on the PCI bus. */
count += parport_pc_init_superio(autoirq, autodma);
/* PnP ports, skip detection if SuperIO already found them */
if (!count) {
err = pnp_register_driver(&parport_pc_pnp_driver);
if (!err)
pnp_registered_parport = 1;
}
/* ISA ports and whatever (see asm/parport.h). */
parport_pc_find_nonpci_ports(autoirq, autodma);
err = pci_register_driver(&parport_pc_pci_driver);
if (!err)
pci_registered_parport = 1;
}
/*
* Piles of crap below pretend to be a parser for module and kernel
* parameters. Say "thank you" to whoever had come up with that
* syntax and keep in mind that code below is a cleaned up version.
*/
static int __initdata io[PARPORT_PC_MAX_PORTS+1] = {
[0 ... PARPORT_PC_MAX_PORTS] = 0
};
static int __initdata io_hi[PARPORT_PC_MAX_PORTS+1] = {
[0 ... PARPORT_PC_MAX_PORTS] = PARPORT_IOHI_AUTO
};
static int __initdata dmaval[PARPORT_PC_MAX_PORTS] = {
[0 ... PARPORT_PC_MAX_PORTS-1] = PARPORT_DMA_NONE
};
static int __initdata irqval[PARPORT_PC_MAX_PORTS] = {
[0 ... PARPORT_PC_MAX_PORTS-1] = PARPORT_IRQ_PROBEONLY
};
static int __init parport_parse_param(const char *s, int *val,
int automatic, int none, int nofifo)
{
if (!s)
return 0;
if (!strncmp(s, "auto", 4))
*val = automatic;
else if (!strncmp(s, "none", 4))
*val = none;
else if (nofifo && !strncmp(s, "nofifo", 6))
*val = nofifo;
else {
char *ep;
unsigned long r = simple_strtoul(s, &ep, 0);
if (ep != s)
*val = r;
else {
pr_err("parport: bad specifier `%s'\n", s);
return -1;
}
}
return 0;
}
static int __init parport_parse_irq(const char *irqstr, int *val)
{
return parport_parse_param(irqstr, val, PARPORT_IRQ_AUTO,
PARPORT_IRQ_NONE, 0);
}
static int __init parport_parse_dma(const char *dmastr, int *val)
{
return parport_parse_param(dmastr, val, PARPORT_DMA_AUTO,
PARPORT_DMA_NONE, PARPORT_DMA_NOFIFO);
}
#ifdef CONFIG_PCI
static int __init parport_init_mode_setup(char *str)
{
printk(KERN_DEBUG "parport_pc.c: Specified parameter parport_init_mode=%s\n",
str);
if (!strcmp(str, "spp"))
parport_init_mode = 1;
if (!strcmp(str, "ps2"))
parport_init_mode = 2;
if (!strcmp(str, "epp"))
parport_init_mode = 3;
if (!strcmp(str, "ecp"))
parport_init_mode = 4;
if (!strcmp(str, "ecpepp"))
parport_init_mode = 5;
return 1;
}
#endif
#ifdef MODULE
static char *irq[PARPORT_PC_MAX_PORTS];
static char *dma[PARPORT_PC_MAX_PORTS];
MODULE_PARM_DESC(io, "Base I/O address (SPP regs)");
module_param_hw_array(io, int, ioport, NULL, 0);
MODULE_PARM_DESC(io_hi, "Base I/O address (ECR)");
module_param_hw_array(io_hi, int, ioport, NULL, 0);
MODULE_PARM_DESC(irq, "IRQ line");
module_param_hw_array(irq, charp, irq, NULL, 0);
MODULE_PARM_DESC(dma, "DMA channel");
module_param_hw_array(dma, charp, dma, NULL, 0);
#if defined(CONFIG_PARPORT_PC_SUPERIO) || \
(defined(CONFIG_PARPORT_1284) && defined(CONFIG_PARPORT_PC_FIFO))
MODULE_PARM_DESC(verbose_probing, "Log chit-chat during initialisation");
module_param(verbose_probing, int, 0644);
#endif
#ifdef CONFIG_PCI
static char *init_mode;
MODULE_PARM_DESC(init_mode,
"Initialise mode for VIA VT8231 port (spp, ps2, epp, ecp or ecpepp)");
module_param(init_mode, charp, 0);
#endif
static int __init parse_parport_params(void)
{
unsigned int i;
int val;
#ifdef CONFIG_PCI
if (init_mode)
parport_init_mode_setup(init_mode);
#endif
for (i = 0; i < PARPORT_PC_MAX_PORTS && io[i]; i++) {
if (parport_parse_irq(irq[i], &val))
return 1;
irqval[i] = val;
if (parport_parse_dma(dma[i], &val))
return 1;
dmaval[i] = val;
}
if (!io[0]) {
/* The user can make us use any IRQs or DMAs we find. */
if (irq[0] && !parport_parse_irq(irq[0], &val))
switch (val) {
case PARPORT_IRQ_NONE:
case PARPORT_IRQ_AUTO:
irqval[0] = val;
break;
default:
pr_warn("parport_pc: irq specified without base address. Use 'io=' to specify one\n");
}
if (dma[0] && !parport_parse_dma(dma[0], &val))
switch (val) {
case PARPORT_DMA_NONE:
case PARPORT_DMA_AUTO:
dmaval[0] = val;
break;
default:
pr_warn("parport_pc: dma specified without base address. Use 'io=' to specify one\n");
}
}
return 0;
}
#else
static int parport_setup_ptr __initdata;
/*
* Acceptable parameters:
*
* parport=0
* parport=auto
* parport=0xBASE[,IRQ[,DMA]]
*
* IRQ/DMA may be numeric or 'auto' or 'none'
*/
static int __init parport_setup(char *str)
{
char *endptr;
char *sep;
int val;
if (!str || !*str || (*str == '0' && !*(str+1))) {
/* Disable parport if "parport=0" in cmdline */
io[0] = PARPORT_DISABLE;
return 1;
}
if (!strncmp(str, "auto", 4)) {
irqval[0] = PARPORT_IRQ_AUTO;
dmaval[0] = PARPORT_DMA_AUTO;
return 1;
}
val = simple_strtoul(str, &endptr, 0);
if (endptr == str) {
pr_warn("parport=%s not understood\n", str);
return 1;
}
if (parport_setup_ptr == PARPORT_PC_MAX_PORTS) {
pr_err("parport=%s ignored, too many ports\n", str);
return 1;
}
io[parport_setup_ptr] = val;
irqval[parport_setup_ptr] = PARPORT_IRQ_NONE;
dmaval[parport_setup_ptr] = PARPORT_DMA_NONE;
sep = strchr(str, ',');
if (sep++) {
if (parport_parse_irq(sep, &val))
return 1;
irqval[parport_setup_ptr] = val;
sep = strchr(sep, ',');
if (sep++) {
if (parport_parse_dma(sep, &val))
return 1;
dmaval[parport_setup_ptr] = val;
}
}
parport_setup_ptr++;
return 1;
}
static int __init parse_parport_params(void)
{
return io[0] == PARPORT_DISABLE;
}
__setup("parport=", parport_setup);
/*
* Acceptable parameters:
*
* parport_init_mode=[spp|ps2|epp|ecp|ecpepp]
*/
#ifdef CONFIG_PCI
__setup("parport_init_mode=", parport_init_mode_setup);
#endif
#endif
/* "Parser" ends here */
static int __init parport_pc_init(void)
{
int err;
if (parse_parport_params())
return -EINVAL;
err = platform_driver_register(&parport_pc_platform_driver);
if (err)
return err;
if (io[0]) {
int i;
/* Only probe the ports we were given. */
user_specified = 1;
for (i = 0; i < PARPORT_PC_MAX_PORTS; i++) {
if (!io[i])
break;
if (io_hi[i] == PARPORT_IOHI_AUTO)
io_hi[i] = 0x400 + io[i];
parport_pc_probe_port(io[i], io_hi[i],
irqval[i], dmaval[i], NULL, 0);
}
} else
parport_pc_find_ports(irqval[0], dmaval[0]);
return 0;
}
static void __exit parport_pc_exit(void)
{
if (pci_registered_parport)
pci_unregister_driver(&parport_pc_pci_driver);
if (pnp_registered_parport)
pnp_unregister_driver(&parport_pc_pnp_driver);
platform_driver_unregister(&parport_pc_platform_driver);
while (!list_empty(&ports_list)) {
struct parport_pc_private *priv;
struct parport *port;
struct device *dev;
priv = list_entry(ports_list.next,
struct parport_pc_private, list);
port = priv->port;
dev = port->dev;
parport_pc_unregister_port(port);
if (dev && dev->bus == &platform_bus_type)
platform_device_unregister(to_platform_device(dev));
}
}
MODULE_AUTHOR("Phil Blundell, Tim Waugh, others");
MODULE_DESCRIPTION("PC-style parallel port driver");
MODULE_LICENSE("GPL");
module_init(parport_pc_init)
module_exit(parport_pc_exit)
| {
"language": "C"
} |
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2010-2014 Intel Corporation
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/queue.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <inttypes.h>
#include <sys/epoll.h>
#include <sys/signalfd.h>
#include <sys/ioctl.h>
#include <sys/eventfd.h>
#include <assert.h>
#include <stdbool.h>
#include <rte_common.h>
#include <rte_interrupts.h>
#include <rte_memory.h>
#include <rte_launch.h>
#include <rte_eal.h>
#include <rte_per_lcore.h>
#include <rte_lcore.h>
#include <rte_atomic.h>
#include <rte_branch_prediction.h>
#include <rte_debug.h>
#include <rte_log.h>
#include <rte_malloc.h>
#include <rte_errno.h>
#include <rte_spinlock.h>
#include <rte_pause.h>
#include "eal_private.h"
#include "eal_vfio.h"
#include "eal_thread.h"
#define EAL_INTR_EPOLL_WAIT_FOREVER (-1)
#define NB_OTHER_INTR 1
static RTE_DEFINE_PER_LCORE(int, _epfd) = -1; /**< epoll fd per thread */
/**
* union for pipe fds.
*/
union intr_pipefds{
struct {
int pipefd[2];
};
struct {
int readfd;
int writefd;
};
};
/**
* union buffer for reading on different devices
*/
union rte_intr_read_buffer {
int uio_intr_count; /* for uio device */
#ifdef VFIO_PRESENT
uint64_t vfio_intr_count; /* for vfio device */
#endif
uint64_t timerfd_num; /* for timerfd */
char charbuf[16]; /* for others */
};
TAILQ_HEAD(rte_intr_cb_list, rte_intr_callback);
TAILQ_HEAD(rte_intr_source_list, rte_intr_source);
struct rte_intr_callback {
TAILQ_ENTRY(rte_intr_callback) next;
rte_intr_callback_fn cb_fn; /**< callback address */
void *cb_arg; /**< parameter for callback */
};
struct rte_intr_source {
TAILQ_ENTRY(rte_intr_source) next;
struct rte_intr_handle intr_handle; /**< interrupt handle */
struct rte_intr_cb_list callbacks; /**< user callbacks */
uint32_t active;
};
/* global spinlock for interrupt data operation */
static rte_spinlock_t intr_lock = RTE_SPINLOCK_INITIALIZER;
/* union buffer for pipe read/write */
static union intr_pipefds intr_pipe;
/* interrupt sources list */
static struct rte_intr_source_list intr_sources;
/* interrupt handling thread */
static pthread_t intr_thread;
/* VFIO interrupts */
#ifdef VFIO_PRESENT
#define IRQ_SET_BUF_LEN (sizeof(struct vfio_irq_set) + sizeof(int))
/* irq set buffer length for queue interrupts and LSC interrupt */
#define MSIX_IRQ_SET_BUF_LEN (sizeof(struct vfio_irq_set) + \
sizeof(int) * (RTE_MAX_RXTX_INTR_VEC_ID + 1))
/* enable legacy (INTx) interrupts */
static int
vfio_enable_intx(const struct rte_intr_handle *intr_handle) {
struct vfio_irq_set *irq_set;
char irq_set_buf[IRQ_SET_BUF_LEN];
int len, ret;
int *fd_ptr;
len = sizeof(irq_set_buf);
/* enable INTx */
irq_set = (struct vfio_irq_set *) irq_set_buf;
irq_set->argsz = len;
irq_set->count = 1;
irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
irq_set->start = 0;
fd_ptr = (int *) &irq_set->data;
*fd_ptr = intr_handle->fd;
ret = ioctl(intr_handle->vfio_dev_fd, VFIO_DEVICE_SET_IRQS, irq_set);
if (ret) {
RTE_LOG(ERR, EAL, "Error enabling INTx interrupts for fd %d\n",
intr_handle->fd);
return -1;
}
/* unmask INTx after enabling */
memset(irq_set, 0, len);
len = sizeof(struct vfio_irq_set);
irq_set->argsz = len;
irq_set->count = 1;
irq_set->flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK;
irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
irq_set->start = 0;
ret = ioctl(intr_handle->vfio_dev_fd, VFIO_DEVICE_SET_IRQS, irq_set);
if (ret) {
RTE_LOG(ERR, EAL, "Error unmasking INTx interrupts for fd %d\n",
intr_handle->fd);
return -1;
}
return 0;
}
/* disable legacy (INTx) interrupts */
static int
vfio_disable_intx(const struct rte_intr_handle *intr_handle) {
struct vfio_irq_set *irq_set;
char irq_set_buf[IRQ_SET_BUF_LEN];
int len, ret;
len = sizeof(struct vfio_irq_set);
/* mask interrupts before disabling */
irq_set = (struct vfio_irq_set *) irq_set_buf;
irq_set->argsz = len;
irq_set->count = 1;
irq_set->flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK;
irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
irq_set->start = 0;
ret = ioctl(intr_handle->vfio_dev_fd, VFIO_DEVICE_SET_IRQS, irq_set);
if (ret) {
RTE_LOG(ERR, EAL, "Error masking INTx interrupts for fd %d\n",
intr_handle->fd);
return -1;
}
/* disable INTx*/
memset(irq_set, 0, len);
irq_set->argsz = len;
irq_set->count = 0;
irq_set->flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
irq_set->start = 0;
ret = ioctl(intr_handle->vfio_dev_fd, VFIO_DEVICE_SET_IRQS, irq_set);
if (ret) {
RTE_LOG(ERR, EAL,
"Error disabling INTx interrupts for fd %d\n", intr_handle->fd);
return -1;
}
return 0;
}
/* enable MSI interrupts */
static int
vfio_enable_msi(const struct rte_intr_handle *intr_handle) {
int len, ret;
char irq_set_buf[IRQ_SET_BUF_LEN];
struct vfio_irq_set *irq_set;
int *fd_ptr;
len = sizeof(irq_set_buf);
irq_set = (struct vfio_irq_set *) irq_set_buf;
irq_set->argsz = len;
irq_set->count = 1;
irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set->index = VFIO_PCI_MSI_IRQ_INDEX;
irq_set->start = 0;
fd_ptr = (int *) &irq_set->data;
*fd_ptr = intr_handle->fd;
ret = ioctl(intr_handle->vfio_dev_fd, VFIO_DEVICE_SET_IRQS, irq_set);
if (ret) {
RTE_LOG(ERR, EAL, "Error enabling MSI interrupts for fd %d\n",
intr_handle->fd);
return -1;
}
return 0;
}
/* disable MSI interrupts */
static int
vfio_disable_msi(const struct rte_intr_handle *intr_handle) {
struct vfio_irq_set *irq_set;
char irq_set_buf[IRQ_SET_BUF_LEN];
int len, ret;
len = sizeof(struct vfio_irq_set);
irq_set = (struct vfio_irq_set *) irq_set_buf;
irq_set->argsz = len;
irq_set->count = 0;
irq_set->flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set->index = VFIO_PCI_MSI_IRQ_INDEX;
irq_set->start = 0;
ret = ioctl(intr_handle->vfio_dev_fd, VFIO_DEVICE_SET_IRQS, irq_set);
if (ret)
RTE_LOG(ERR, EAL,
"Error disabling MSI interrupts for fd %d\n", intr_handle->fd);
return ret;
}
/* enable MSI-X interrupts */
static int
vfio_enable_msix(const struct rte_intr_handle *intr_handle) {
int len, ret;
char irq_set_buf[MSIX_IRQ_SET_BUF_LEN];
struct vfio_irq_set *irq_set;
int *fd_ptr;
len = sizeof(irq_set_buf);
irq_set = (struct vfio_irq_set *) irq_set_buf;
irq_set->argsz = len;
/* 0 < irq_set->count < RTE_MAX_RXTX_INTR_VEC_ID + 1 */
irq_set->count = intr_handle->max_intr ?
(intr_handle->max_intr > RTE_MAX_RXTX_INTR_VEC_ID + 1 ?
RTE_MAX_RXTX_INTR_VEC_ID + 1 : intr_handle->max_intr) : 1;
irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
irq_set->start = 0;
fd_ptr = (int *) &irq_set->data;
/* INTR vector offset 0 reserve for non-efds mapping */
fd_ptr[RTE_INTR_VEC_ZERO_OFFSET] = intr_handle->fd;
memcpy(&fd_ptr[RTE_INTR_VEC_RXTX_OFFSET], intr_handle->efds,
sizeof(*intr_handle->efds) * intr_handle->nb_efd);
ret = ioctl(intr_handle->vfio_dev_fd, VFIO_DEVICE_SET_IRQS, irq_set);
if (ret) {
RTE_LOG(ERR, EAL, "Error enabling MSI-X interrupts for fd %d\n",
intr_handle->fd);
return -1;
}
return 0;
}
/* disable MSI-X interrupts */
static int
vfio_disable_msix(const struct rte_intr_handle *intr_handle) {
struct vfio_irq_set *irq_set;
char irq_set_buf[MSIX_IRQ_SET_BUF_LEN];
int len, ret;
len = sizeof(struct vfio_irq_set);
irq_set = (struct vfio_irq_set *) irq_set_buf;
irq_set->argsz = len;
irq_set->count = 0;
irq_set->flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
irq_set->start = 0;
ret = ioctl(intr_handle->vfio_dev_fd, VFIO_DEVICE_SET_IRQS, irq_set);
if (ret)
RTE_LOG(ERR, EAL,
"Error disabling MSI-X interrupts for fd %d\n", intr_handle->fd);
return ret;
}
#endif
static int
uio_intx_intr_disable(const struct rte_intr_handle *intr_handle)
{
unsigned char command_high;
/* use UIO config file descriptor for uio_pci_generic */
if (pread(intr_handle->uio_cfg_fd, &command_high, 1, 5) != 1) {
RTE_LOG(ERR, EAL,
"Error reading interrupts status for fd %d\n",
intr_handle->uio_cfg_fd);
return -1;
}
/* disable interrupts */
command_high |= 0x4;
if (pwrite(intr_handle->uio_cfg_fd, &command_high, 1, 5) != 1) {
RTE_LOG(ERR, EAL,
"Error disabling interrupts for fd %d\n",
intr_handle->uio_cfg_fd);
return -1;
}
return 0;
}
static int
uio_intx_intr_enable(const struct rte_intr_handle *intr_handle)
{
unsigned char command_high;
/* use UIO config file descriptor for uio_pci_generic */
if (pread(intr_handle->uio_cfg_fd, &command_high, 1, 5) != 1) {
RTE_LOG(ERR, EAL,
"Error reading interrupts status for fd %d\n",
intr_handle->uio_cfg_fd);
return -1;
}
/* enable interrupts */
command_high &= ~0x4;
if (pwrite(intr_handle->uio_cfg_fd, &command_high, 1, 5) != 1) {
RTE_LOG(ERR, EAL,
"Error enabling interrupts for fd %d\n",
intr_handle->uio_cfg_fd);
return -1;
}
return 0;
}
static int
uio_intr_disable(const struct rte_intr_handle *intr_handle)
{
const int value = 0;
if (write(intr_handle->fd, &value, sizeof(value)) < 0) {
RTE_LOG(ERR, EAL,
"Error disabling interrupts for fd %d (%s)\n",
intr_handle->fd, strerror(errno));
return -1;
}
return 0;
}
static int
uio_intr_enable(const struct rte_intr_handle *intr_handle)
{
const int value = 1;
if (write(intr_handle->fd, &value, sizeof(value)) < 0) {
RTE_LOG(ERR, EAL,
"Error enabling interrupts for fd %d (%s)\n",
intr_handle->fd, strerror(errno));
return -1;
}
return 0;
}
int
rte_intr_callback_register(const struct rte_intr_handle *intr_handle,
rte_intr_callback_fn cb, void *cb_arg)
{
int ret, wake_thread;
struct rte_intr_source *src;
struct rte_intr_callback *callback;
wake_thread = 0;
/* first do parameter checking */
if (intr_handle == NULL || intr_handle->fd < 0 || cb == NULL) {
RTE_LOG(ERR, EAL,
"Registering with invalid input parameter\n");
return -EINVAL;
}
/* allocate a new interrupt callback entity */
callback = rte_zmalloc("interrupt callback list",
sizeof(*callback), 0);
if (callback == NULL) {
RTE_LOG(ERR, EAL, "Can not allocate memory\n");
return -ENOMEM;
}
callback->cb_fn = cb;
callback->cb_arg = cb_arg;
rte_spinlock_lock(&intr_lock);
/* check if there is at least one callback registered for the fd */
TAILQ_FOREACH(src, &intr_sources, next) {
if (src->intr_handle.fd == intr_handle->fd) {
/* we had no interrupts for this */
if TAILQ_EMPTY(&src->callbacks)
wake_thread = 1;
TAILQ_INSERT_TAIL(&(src->callbacks), callback, next);
ret = 0;
break;
}
}
/* no existing callbacks for this - add new source */
if (src == NULL) {
if ((src = rte_zmalloc("interrupt source list",
sizeof(*src), 0)) == NULL) {
RTE_LOG(ERR, EAL, "Can not allocate memory\n");
rte_free(callback);
ret = -ENOMEM;
} else {
src->intr_handle = *intr_handle;
TAILQ_INIT(&src->callbacks);
TAILQ_INSERT_TAIL(&(src->callbacks), callback, next);
TAILQ_INSERT_TAIL(&intr_sources, src, next);
wake_thread = 1;
ret = 0;
}
}
rte_spinlock_unlock(&intr_lock);
/**
* check if need to notify the pipe fd waited by epoll_wait to
* rebuild the wait list.
*/
if (wake_thread)
if (write(intr_pipe.writefd, "1", 1) < 0)
return -EPIPE;
return ret;
}
int
rte_intr_callback_unregister(const struct rte_intr_handle *intr_handle,
rte_intr_callback_fn cb_fn, void *cb_arg)
{
int ret;
struct rte_intr_source *src;
struct rte_intr_callback *cb, *next;
/* do parameter checking first */
if (intr_handle == NULL || intr_handle->fd < 0) {
RTE_LOG(ERR, EAL,
"Unregistering with invalid input parameter\n");
return -EINVAL;
}
rte_spinlock_lock(&intr_lock);
/* check if the insterrupt source for the fd is existent */
TAILQ_FOREACH(src, &intr_sources, next)
if (src->intr_handle.fd == intr_handle->fd)
break;
/* No interrupt source registered for the fd */
if (src == NULL) {
ret = -ENOENT;
/* interrupt source has some active callbacks right now. */
} else if (src->active != 0) {
ret = -EAGAIN;
/* ok to remove. */
} else {
ret = 0;
/*walk through the callbacks and remove all that match. */
for (cb = TAILQ_FIRST(&src->callbacks); cb != NULL; cb = next) {
next = TAILQ_NEXT(cb, next);
if (cb->cb_fn == cb_fn && (cb_arg == (void *)-1 ||
cb->cb_arg == cb_arg)) {
TAILQ_REMOVE(&src->callbacks, cb, next);
rte_free(cb);
ret++;
}
}
/* all callbacks for that source are removed. */
if (TAILQ_EMPTY(&src->callbacks)) {
TAILQ_REMOVE(&intr_sources, src, next);
rte_free(src);
}
}
rte_spinlock_unlock(&intr_lock);
/* notify the pipe fd waited by epoll_wait to rebuild the wait list */
if (ret >= 0 && write(intr_pipe.writefd, "1", 1) < 0) {
ret = -EPIPE;
}
return ret;
}
int
rte_intr_enable(const struct rte_intr_handle *intr_handle)
{
if (intr_handle && intr_handle->type == RTE_INTR_HANDLE_VDEV)
return 0;
if (!intr_handle || intr_handle->fd < 0 || intr_handle->uio_cfg_fd < 0)
return -1;
switch (intr_handle->type){
/* write to the uio fd to enable the interrupt */
case RTE_INTR_HANDLE_UIO:
if (uio_intr_enable(intr_handle))
return -1;
break;
case RTE_INTR_HANDLE_UIO_INTX:
if (uio_intx_intr_enable(intr_handle))
return -1;
break;
/* not used at this moment */
case RTE_INTR_HANDLE_ALARM:
return -1;
#ifdef VFIO_PRESENT
case RTE_INTR_HANDLE_VFIO_MSIX:
if (vfio_enable_msix(intr_handle))
return -1;
break;
case RTE_INTR_HANDLE_VFIO_MSI:
if (vfio_enable_msi(intr_handle))
return -1;
break;
case RTE_INTR_HANDLE_VFIO_LEGACY:
if (vfio_enable_intx(intr_handle))
return -1;
break;
#endif
/* unknown handle type */
default:
RTE_LOG(ERR, EAL,
"Unknown handle type of fd %d\n",
intr_handle->fd);
return -1;
}
return 0;
}
int
rte_intr_disable(const struct rte_intr_handle *intr_handle)
{
if (intr_handle && intr_handle->type == RTE_INTR_HANDLE_VDEV)
return 0;
if (!intr_handle || intr_handle->fd < 0 || intr_handle->uio_cfg_fd < 0)
return -1;
switch (intr_handle->type){
/* write to the uio fd to disable the interrupt */
case RTE_INTR_HANDLE_UIO:
if (uio_intr_disable(intr_handle))
return -1;
break;
case RTE_INTR_HANDLE_UIO_INTX:
if (uio_intx_intr_disable(intr_handle))
return -1;
break;
/* not used at this moment */
case RTE_INTR_HANDLE_ALARM:
return -1;
#ifdef VFIO_PRESENT
case RTE_INTR_HANDLE_VFIO_MSIX:
if (vfio_disable_msix(intr_handle))
return -1;
break;
case RTE_INTR_HANDLE_VFIO_MSI:
if (vfio_disable_msi(intr_handle))
return -1;
break;
case RTE_INTR_HANDLE_VFIO_LEGACY:
if (vfio_disable_intx(intr_handle))
return -1;
break;
#endif
/* unknown handle type */
default:
RTE_LOG(ERR, EAL,
"Unknown handle type of fd %d\n",
intr_handle->fd);
return -1;
}
return 0;
}
static int
eal_intr_process_interrupts(struct epoll_event *events, int nfds)
{
bool call = false;
int n, bytes_read;
struct rte_intr_source *src;
struct rte_intr_callback *cb;
union rte_intr_read_buffer buf;
struct rte_intr_callback active_cb;
for (n = 0; n < nfds; n++) {
/**
* if the pipe fd is ready to read, return out to
* rebuild the wait list.
*/
if (events[n].data.fd == intr_pipe.readfd){
int r = read(intr_pipe.readfd, buf.charbuf,
sizeof(buf.charbuf));
RTE_SET_USED(r);
return -1;
}
rte_spinlock_lock(&intr_lock);
TAILQ_FOREACH(src, &intr_sources, next)
if (src->intr_handle.fd ==
events[n].data.fd)
break;
if (src == NULL){
rte_spinlock_unlock(&intr_lock);
continue;
}
/* mark this interrupt source as active and release the lock. */
src->active = 1;
rte_spinlock_unlock(&intr_lock);
/* set the length to be read dor different handle type */
switch (src->intr_handle.type) {
case RTE_INTR_HANDLE_UIO:
case RTE_INTR_HANDLE_UIO_INTX:
bytes_read = sizeof(buf.uio_intr_count);
break;
case RTE_INTR_HANDLE_ALARM:
bytes_read = sizeof(buf.timerfd_num);
break;
#ifdef VFIO_PRESENT
case RTE_INTR_HANDLE_VFIO_MSIX:
case RTE_INTR_HANDLE_VFIO_MSI:
case RTE_INTR_HANDLE_VFIO_LEGACY:
bytes_read = sizeof(buf.vfio_intr_count);
break;
#endif
case RTE_INTR_HANDLE_VDEV:
case RTE_INTR_HANDLE_EXT:
bytes_read = 0;
call = true;
break;
default:
bytes_read = 1;
break;
}
if (bytes_read > 0) {
/**
* read out to clear the ready-to-be-read flag
* for epoll_wait.
*/
bytes_read = read(events[n].data.fd, &buf, bytes_read);
if (bytes_read < 0) {
if (errno == EINTR || errno == EWOULDBLOCK)
continue;
RTE_LOG(ERR, EAL, "Error reading from file "
"descriptor %d: %s\n",
events[n].data.fd,
strerror(errno));
} else if (bytes_read == 0)
RTE_LOG(ERR, EAL, "Read nothing from file "
"descriptor %d\n", events[n].data.fd);
else
call = true;
}
/* grab a lock, again to call callbacks and update status. */
rte_spinlock_lock(&intr_lock);
if (call) {
/* Finally, call all callbacks. */
TAILQ_FOREACH(cb, &src->callbacks, next) {
/* make a copy and unlock. */
active_cb = *cb;
rte_spinlock_unlock(&intr_lock);
/* call the actual callback */
active_cb.cb_fn(active_cb.cb_arg);
/*get the lock back. */
rte_spinlock_lock(&intr_lock);
}
}
/* we done with that interrupt source, release it. */
src->active = 0;
rte_spinlock_unlock(&intr_lock);
}
return 0;
}
/**
* It handles all the interrupts.
*
* @param pfd
* epoll file descriptor.
* @param totalfds
* The number of file descriptors added in epoll.
*
* @return
* void
*/
static void
eal_intr_handle_interrupts(int pfd, unsigned totalfds)
{
struct epoll_event events[totalfds];
int nfds = 0;
for(;;) {
nfds = epoll_wait(pfd, events, totalfds,
EAL_INTR_EPOLL_WAIT_FOREVER);
/* epoll_wait fail */
if (nfds < 0) {
if (errno == EINTR)
continue;
RTE_LOG(ERR, EAL,
"epoll_wait returns with fail\n");
return;
}
/* epoll_wait timeout, will never happens here */
else if (nfds == 0)
continue;
/* epoll_wait has at least one fd ready to read */
if (eal_intr_process_interrupts(events, nfds) < 0)
return;
}
}
/**
* It builds/rebuilds up the epoll file descriptor with all the
* file descriptors being waited on. Then handles the interrupts.
*
* @param arg
* pointer. (unused)
*
* @return
* never return;
*/
static __attribute__((noreturn)) void *
eal_intr_thread_main(__rte_unused void *arg)
{
struct epoll_event ev;
/* host thread, never break out */
for (;;) {
/* build up the epoll fd with all descriptors we are to
* wait on then pass it to the handle_interrupts function
*/
static struct epoll_event pipe_event = {
.events = EPOLLIN | EPOLLPRI,
};
struct rte_intr_source *src;
unsigned numfds = 0;
/* create epoll fd */
int pfd = epoll_create(1);
if (pfd < 0)
rte_panic("Cannot create epoll instance\n");
pipe_event.data.fd = intr_pipe.readfd;
/**
* add pipe fd into wait list, this pipe is used to
* rebuild the wait list.
*/
if (epoll_ctl(pfd, EPOLL_CTL_ADD, intr_pipe.readfd,
&pipe_event) < 0) {
rte_panic("Error adding fd to %d epoll_ctl, %s\n",
intr_pipe.readfd, strerror(errno));
}
numfds++;
rte_spinlock_lock(&intr_lock);
TAILQ_FOREACH(src, &intr_sources, next) {
if (src->callbacks.tqh_first == NULL)
continue; /* skip those with no callbacks */
ev.events = EPOLLIN | EPOLLPRI | EPOLLRDHUP | EPOLLHUP;
ev.data.fd = src->intr_handle.fd;
/**
* add all the uio device file descriptor
* into wait list.
*/
if (epoll_ctl(pfd, EPOLL_CTL_ADD,
src->intr_handle.fd, &ev) < 0){
rte_panic("Error adding fd %d epoll_ctl, %s\n",
src->intr_handle.fd, strerror(errno));
}
else
numfds++;
}
rte_spinlock_unlock(&intr_lock);
/* serve the interrupt */
eal_intr_handle_interrupts(pfd, numfds);
/**
* when we return, we need to rebuild the
* list of fds to monitor.
*/
close(pfd);
}
}
int
rte_eal_intr_init(void)
{
int ret = 0, ret_1 = 0;
char thread_name[RTE_MAX_THREAD_NAME_LEN];
/* init the global interrupt source head */
TAILQ_INIT(&intr_sources);
/**
* create a pipe which will be waited by epoll and notified to
* rebuild the wait list of epoll.
*/
if (pipe(intr_pipe.pipefd) < 0) {
rte_errno = errno;
return -1;
}
/* create the host thread to wait/handle the interrupt */
ret = pthread_create(&intr_thread, NULL,
eal_intr_thread_main, NULL);
if (ret != 0) {
rte_errno = ret;
RTE_LOG(ERR, EAL,
"Failed to create thread for interrupt handling\n");
} else {
/* Set thread_name for aid in debugging. */
snprintf(thread_name, RTE_MAX_THREAD_NAME_LEN,
"eal-intr-thread");
ret_1 = rte_thread_setname(intr_thread, thread_name);
if (ret_1 != 0)
RTE_LOG(DEBUG, EAL,
"Failed to set thread name for interrupt handling\n");
}
return -ret;
}
static void
eal_intr_proc_rxtx_intr(int fd, const struct rte_intr_handle *intr_handle)
{
union rte_intr_read_buffer buf;
int bytes_read = 0;
int nbytes;
switch (intr_handle->type) {
case RTE_INTR_HANDLE_UIO:
case RTE_INTR_HANDLE_UIO_INTX:
bytes_read = sizeof(buf.uio_intr_count);
break;
#ifdef VFIO_PRESENT
case RTE_INTR_HANDLE_VFIO_MSIX:
case RTE_INTR_HANDLE_VFIO_MSI:
case RTE_INTR_HANDLE_VFIO_LEGACY:
bytes_read = sizeof(buf.vfio_intr_count);
break;
#endif
case RTE_INTR_HANDLE_VDEV:
bytes_read = intr_handle->efd_counter_size;
/* For vdev, number of bytes to read is set by driver */
break;
case RTE_INTR_HANDLE_EXT:
return;
default:
bytes_read = 1;
RTE_LOG(INFO, EAL, "unexpected intr type\n");
break;
}
/**
* read out to clear the ready-to-be-read flag
* for epoll_wait.
*/
if (bytes_read == 0)
return;
do {
nbytes = read(fd, &buf, bytes_read);
if (nbytes < 0) {
if (errno == EINTR || errno == EWOULDBLOCK ||
errno == EAGAIN)
continue;
RTE_LOG(ERR, EAL,
"Error reading from fd %d: %s\n",
fd, strerror(errno));
} else if (nbytes == 0)
RTE_LOG(ERR, EAL, "Read nothing from fd %d\n", fd);
return;
} while (1);
}
static int
eal_epoll_process_event(struct epoll_event *evs, unsigned int n,
struct rte_epoll_event *events)
{
unsigned int i, count = 0;
struct rte_epoll_event *rev;
for (i = 0; i < n; i++) {
rev = evs[i].data.ptr;
if (!rev || !rte_atomic32_cmpset(&rev->status, RTE_EPOLL_VALID,
RTE_EPOLL_EXEC))
continue;
events[count].status = RTE_EPOLL_VALID;
events[count].fd = rev->fd;
events[count].epfd = rev->epfd;
events[count].epdata.event = rev->epdata.event;
events[count].epdata.data = rev->epdata.data;
if (rev->epdata.cb_fun)
rev->epdata.cb_fun(rev->fd,
rev->epdata.cb_arg);
rte_compiler_barrier();
rev->status = RTE_EPOLL_VALID;
count++;
}
return count;
}
static inline int
eal_init_tls_epfd(void)
{
int pfd = epoll_create(255);
if (pfd < 0) {
RTE_LOG(ERR, EAL,
"Cannot create epoll instance\n");
return -1;
}
return pfd;
}
int
rte_intr_tls_epfd(void)
{
if (RTE_PER_LCORE(_epfd) == -1)
RTE_PER_LCORE(_epfd) = eal_init_tls_epfd();
return RTE_PER_LCORE(_epfd);
}
int
rte_epoll_wait(int epfd, struct rte_epoll_event *events,
int maxevents, int timeout)
{
struct epoll_event evs[maxevents];
int rc;
if (!events) {
RTE_LOG(ERR, EAL, "rte_epoll_event can't be NULL\n");
return -1;
}
/* using per thread epoll fd */
if (epfd == RTE_EPOLL_PER_THREAD)
epfd = rte_intr_tls_epfd();
while (1) {
rc = epoll_wait(epfd, evs, maxevents, timeout);
if (likely(rc > 0)) {
/* epoll_wait has at least one fd ready to read */
rc = eal_epoll_process_event(evs, rc, events);
break;
} else if (rc < 0) {
if (errno == EINTR)
continue;
/* epoll_wait fail */
RTE_LOG(ERR, EAL, "epoll_wait returns with fail %s\n",
strerror(errno));
rc = -1;
break;
} else {
/* rc == 0, epoll_wait timed out */
break;
}
}
return rc;
}
static inline void
eal_epoll_data_safe_free(struct rte_epoll_event *ev)
{
while (!rte_atomic32_cmpset(&ev->status, RTE_EPOLL_VALID,
RTE_EPOLL_INVALID))
while (ev->status != RTE_EPOLL_VALID)
rte_pause();
memset(&ev->epdata, 0, sizeof(ev->epdata));
ev->fd = -1;
ev->epfd = -1;
}
int
rte_epoll_ctl(int epfd, int op, int fd,
struct rte_epoll_event *event)
{
struct epoll_event ev;
if (!event) {
RTE_LOG(ERR, EAL, "rte_epoll_event can't be NULL\n");
return -1;
}
/* using per thread epoll fd */
if (epfd == RTE_EPOLL_PER_THREAD)
epfd = rte_intr_tls_epfd();
if (op == EPOLL_CTL_ADD) {
event->status = RTE_EPOLL_VALID;
event->fd = fd; /* ignore fd in event */
event->epfd = epfd;
ev.data.ptr = (void *)event;
}
ev.events = event->epdata.event;
if (epoll_ctl(epfd, op, fd, &ev) < 0) {
RTE_LOG(ERR, EAL, "Error op %d fd %d epoll_ctl, %s\n",
op, fd, strerror(errno));
if (op == EPOLL_CTL_ADD)
/* rollback status when CTL_ADD fail */
event->status = RTE_EPOLL_INVALID;
return -1;
}
if (op == EPOLL_CTL_DEL && event->status != RTE_EPOLL_INVALID)
eal_epoll_data_safe_free(event);
return 0;
}
int
rte_intr_rx_ctl(struct rte_intr_handle *intr_handle, int epfd,
int op, unsigned int vec, void *data)
{
struct rte_epoll_event *rev;
struct rte_epoll_data *epdata;
int epfd_op;
unsigned int efd_idx;
int rc = 0;
efd_idx = (vec >= RTE_INTR_VEC_RXTX_OFFSET) ?
(vec - RTE_INTR_VEC_RXTX_OFFSET) : vec;
if (!intr_handle || intr_handle->nb_efd == 0 ||
efd_idx >= intr_handle->nb_efd) {
RTE_LOG(ERR, EAL, "Wrong intr vector number.\n");
return -EPERM;
}
switch (op) {
case RTE_INTR_EVENT_ADD:
epfd_op = EPOLL_CTL_ADD;
rev = &intr_handle->elist[efd_idx];
if (rev->status != RTE_EPOLL_INVALID) {
RTE_LOG(INFO, EAL, "Event already been added.\n");
return -EEXIST;
}
/* attach to intr vector fd */
epdata = &rev->epdata;
epdata->event = EPOLLIN | EPOLLPRI | EPOLLET;
epdata->data = data;
epdata->cb_fun = (rte_intr_event_cb_t)eal_intr_proc_rxtx_intr;
epdata->cb_arg = (void *)intr_handle;
rc = rte_epoll_ctl(epfd, epfd_op,
intr_handle->efds[efd_idx], rev);
if (!rc)
RTE_LOG(DEBUG, EAL,
"efd %d associated with vec %d added on epfd %d"
"\n", rev->fd, vec, epfd);
else
rc = -EPERM;
break;
case RTE_INTR_EVENT_DEL:
epfd_op = EPOLL_CTL_DEL;
rev = &intr_handle->elist[efd_idx];
if (rev->status == RTE_EPOLL_INVALID) {
RTE_LOG(INFO, EAL, "Event does not exist.\n");
return -EPERM;
}
rc = rte_epoll_ctl(rev->epfd, epfd_op, rev->fd, rev);
if (rc)
rc = -EPERM;
break;
default:
RTE_LOG(ERR, EAL, "event op type mismatch\n");
rc = -EPERM;
}
return rc;
}
void
rte_intr_free_epoll_fd(struct rte_intr_handle *intr_handle)
{
uint32_t i;
struct rte_epoll_event *rev;
for (i = 0; i < intr_handle->nb_efd; i++) {
rev = &intr_handle->elist[i];
if (rev->status == RTE_EPOLL_INVALID)
continue;
if (rte_epoll_ctl(rev->epfd, EPOLL_CTL_DEL, rev->fd, rev)) {
/* force free if the entry valid */
eal_epoll_data_safe_free(rev);
rev->status = RTE_EPOLL_INVALID;
}
}
}
int
rte_intr_efd_enable(struct rte_intr_handle *intr_handle, uint32_t nb_efd)
{
uint32_t i;
int fd;
uint32_t n = RTE_MIN(nb_efd, (uint32_t)RTE_MAX_RXTX_INTR_VEC_ID);
assert(nb_efd != 0);
if (intr_handle->type == RTE_INTR_HANDLE_VFIO_MSIX) {
for (i = 0; i < n; i++) {
fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (fd < 0) {
RTE_LOG(ERR, EAL,
"can't setup eventfd, error %i (%s)\n",
errno, strerror(errno));
return -errno;
}
intr_handle->efds[i] = fd;
}
intr_handle->nb_efd = n;
intr_handle->max_intr = NB_OTHER_INTR + n;
} else if (intr_handle->type == RTE_INTR_HANDLE_VDEV) {
/* only check, initialization would be done in vdev driver.*/
if (intr_handle->efd_counter_size >
sizeof(union rte_intr_read_buffer)) {
RTE_LOG(ERR, EAL, "the efd_counter_size is oversized");
return -EINVAL;
}
} else {
intr_handle->efds[0] = intr_handle->fd;
intr_handle->nb_efd = RTE_MIN(nb_efd, 1U);
intr_handle->max_intr = NB_OTHER_INTR;
}
return 0;
}
void
rte_intr_efd_disable(struct rte_intr_handle *intr_handle)
{
uint32_t i;
rte_intr_free_epoll_fd(intr_handle);
if (intr_handle->max_intr > intr_handle->nb_efd) {
for (i = 0; i < intr_handle->nb_efd; i++)
close(intr_handle->efds[i]);
}
intr_handle->nb_efd = 0;
intr_handle->max_intr = 0;
}
int
rte_intr_dp_is_en(struct rte_intr_handle *intr_handle)
{
return !(!intr_handle->nb_efd);
}
int
rte_intr_allow_others(struct rte_intr_handle *intr_handle)
{
if (!rte_intr_dp_is_en(intr_handle))
return 1;
else
return !!(intr_handle->max_intr - intr_handle->nb_efd);
}
int
rte_intr_cap_multiple(struct rte_intr_handle *intr_handle)
{
if (intr_handle->type == RTE_INTR_HANDLE_VFIO_MSIX)
return 1;
if (intr_handle->type == RTE_INTR_HANDLE_VDEV)
return 1;
return 0;
}
| {
"language": "C"
} |
/* Test mpz_urandomm.
Copyright 2002 Free Software Foundation, Inc.
This file is part of the GNU MP Library test suite.
The GNU MP Library test suite is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
The GNU MP Library test suite 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
the GNU MP Library test suite. If not, see https://www.gnu.org/licenses/. */
#include <stdio.h>
#include "gmp-impl.h"
#include "tests.h"
#ifndef TRUE
#define TRUE (1)
#endif
#ifndef FALSE
#define FALSE (0)
#endif
int
check_params (void)
{
gmp_randstate_t r1, r2;
mpz_t a, b, m;
int i;
int result;
result = TRUE;
mpz_init (a);
mpz_init (b);
mpz_init (m);
if (result)
{
/* Test the consistency between urandomm and urandomb. */
gmp_randinit_default (r1);
gmp_randinit_default (r2);
gmp_randseed_ui (r1, 85L);
gmp_randseed_ui (r2, 85L);
mpz_set_ui (m, 0L);
mpz_setbit (m, 80L);
for (i = 0; i < 100; i++)
{
mpz_urandomm (a, r1, m);
mpz_urandomb (b, r2, 80L);
if (mpz_cmp (a, b) != 0)
{
result = FALSE;
printf ("mpz_urandomm != mpz_urandomb\n");
break;
}
}
gmp_randclear (r1);
gmp_randclear (r2);
}
if (result)
{
/* Test that mpz_urandomm returns the correct result with a
broken LC. */
mpz_set_ui (a, 0L);
gmp_randinit_lc_2exp (r1, a, 0xffL, 8L);
mpz_set_ui (m, 5L);
/* Warning: This code hangs in gmp 4.1 and below */
for (i = 0; i < 100; i++)
{
mpz_urandomm (a, r1, m);
if (mpz_cmp_ui (a, 2L) != 0)
{
result = FALSE;
gmp_printf ("mpz_urandomm returns %Zd instead of 2\n", a);
break;
}
}
gmp_randclear (r1);
}
if (result)
{
/* Test that the results are always in range for either
positive or negative values of m. */
gmp_randinit_default (r1);
mpz_set_ui (m, 5L);
mpz_set_si (b, -5L);
for (i = 0; i < 100; i++)
{
mpz_urandomm (a, r1, m);
if (mpz_cmp_ui (a, 5L) >= 0 || mpz_sgn (a) < 0)
{
result = FALSE;
gmp_printf ("Out-of-range or non-positive value: %Zd\n", a);
break;
}
mpz_urandomm (a, r1, b);
if (mpz_cmp_ui (a, 5L) >= 0 || mpz_sgn (a) < 0)
{
result = FALSE;
gmp_printf ("Out-of-range or non-positive value (from negative modulus): %Zd\n", a);
break;
}
}
gmp_randclear (r1);
}
if (result)
{
/* Test that m=1 forces always result=0. */
gmp_randinit_default (r1);
mpz_set_ui (m, 1L);
for (i = 0; i < 100; i++)
{
mpz_urandomm (a, r1, m);
if (mpz_sgn (a) != 0)
{
result = FALSE;
gmp_printf ("mpz_urandomm fails with m=1 (result=%Zd)\n", a);
break;
}
}
gmp_randclear (r1);
}
mpz_clear (a);
mpz_clear (b);
mpz_clear (m);
return result;
}
int
main (int argc, char *argv[])
{
int result = TRUE;
tests_start ();
if (result)
if (!check_params ())
result = FALSE;
tests_end ();
if (result)
return 0; /* pass */
else
return 1; /* fail */
}
| {
"language": "C"
} |
From 231e4a9b4b972662a6832f714a05525a3754892d Mon Sep 17 00:00:00 2001
From: Filippo Arcidiacono <filippo.arcidiacono@st.com>
Date: Thu, 9 May 2013 09:04:20 +0200
Subject: libdl: fix dlopen implementation from statically linked application
Calling dlopen from statically linked application is actually broken,
because _dl_find_hash enters into an infinite loop when trying to
resolve symbols. In this case it doesn't need to extend the global
scope, it is readyto be used as it is, because _dl_loaded_modules already points
to the dlopened library.
The patch also fixesi a typo in __LDSO_LD_LIBRARY_PATH__ macro, that was
preventing to get the actual value of the LD_LIBRARY_PATH.
Signed-off-by: Filippo Arcidiacono <filippo.arcidiacono@st.com>
Signed-off-by: Carmelo Amoroso <carmelo.amoroso@st.com>
---
ldso/libdl/libdl.c | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
--- a/ldso/libdl/libdl.c
+++ b/ldso/libdl/libdl.c
@@ -377,7 +377,7 @@
if (getenv("LD_BIND_NOW"))
now_flag = RTLD_NOW;
-#if !defined SHARED && defined __LDSO_LIBRARY_PATH__
+#if !defined SHARED && defined __LDSO_LD_LIBRARY_PATH__
/* When statically linked, the _dl_library_path is not yet initialized */
_dl_library_path = getenv("LD_LIBRARY_PATH");
#endif
@@ -544,11 +544,18 @@
* to the GOT tables. We need to do this in reverse order so that COPY
* directives work correctly */
- /* Get the tail of the list */
+#ifdef SHARED
+ /*
+ * Get the tail of the list.
+ * In the static case doesn't need to extend the global scope, it is
+ * ready to be used as it is, because _dl_loaded_modules already points
+ * to the dlopened library.
+ */
for (ls = &_dl_loaded_modules->symbol_scope; ls && ls->next; ls = ls->next);
/* Extend the global scope by adding the local scope of the dlopened DSO. */
ls->next = &dyn_chain->dyn->symbol_scope;
+#endif
#ifdef __mips__
/*
* Relocation of the GOT entries for MIPS have to be done
| {
"language": "C"
} |
/* crypto/bio/bio.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef HEADER_BIO_H
#define HEADER_BIO_H
#include <openssl/e_os2.h>
#ifndef OPENSSL_NO_FP_API
# include <stdio.h>
#endif
#include <stdarg.h>
#include <openssl/crypto.h>
#ifndef OPENSSL_NO_SCTP
# ifndef OPENSSL_SYS_VMS
# include <stdint.h>
# else
# include <inttypes.h>
# endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* These are the 'types' of BIOs */
#define BIO_TYPE_NONE 0
#define BIO_TYPE_MEM (1|0x0400)
#define BIO_TYPE_FILE (2|0x0400)
#define BIO_TYPE_FD (4|0x0400|0x0100)
#define BIO_TYPE_SOCKET (5|0x0400|0x0100)
#define BIO_TYPE_NULL (6|0x0400)
#define BIO_TYPE_SSL (7|0x0200)
#define BIO_TYPE_MD (8|0x0200) /* passive filter */
#define BIO_TYPE_BUFFER (9|0x0200) /* filter */
#define BIO_TYPE_CIPHER (10|0x0200) /* filter */
#define BIO_TYPE_BASE64 (11|0x0200) /* filter */
#define BIO_TYPE_CONNECT (12|0x0400|0x0100) /* socket - connect */
#define BIO_TYPE_ACCEPT (13|0x0400|0x0100) /* socket for accept */
#define BIO_TYPE_PROXY_CLIENT (14|0x0200) /* client proxy BIO */
#define BIO_TYPE_PROXY_SERVER (15|0x0200) /* server proxy BIO */
#define BIO_TYPE_NBIO_TEST (16|0x0200) /* server proxy BIO */
#define BIO_TYPE_NULL_FILTER (17|0x0200)
#define BIO_TYPE_BER (18|0x0200) /* BER -> bin filter */
#define BIO_TYPE_BIO (19|0x0400) /* (half a) BIO pair */
#define BIO_TYPE_LINEBUFFER (20|0x0200) /* filter */
#define BIO_TYPE_DGRAM (21|0x0400|0x0100)
#ifndef OPENSSL_NO_SCTP
#define BIO_TYPE_DGRAM_SCTP (24|0x0400|0x0100)
#endif
#define BIO_TYPE_ASN1 (22|0x0200) /* filter */
#define BIO_TYPE_COMP (23|0x0200) /* filter */
#define BIO_TYPE_DESCRIPTOR 0x0100 /* socket, fd, connect or accept */
#define BIO_TYPE_FILTER 0x0200
#define BIO_TYPE_SOURCE_SINK 0x0400
/* BIO_FILENAME_READ|BIO_CLOSE to open or close on free.
* BIO_set_fp(in,stdin,BIO_NOCLOSE); */
#define BIO_NOCLOSE 0x00
#define BIO_CLOSE 0x01
/* These are used in the following macros and are passed to
* BIO_ctrl() */
#define BIO_CTRL_RESET 1 /* opt - rewind/zero etc */
#define BIO_CTRL_EOF 2 /* opt - are we at the eof */
#define BIO_CTRL_INFO 3 /* opt - extra tit-bits */
#define BIO_CTRL_SET 4 /* man - set the 'IO' type */
#define BIO_CTRL_GET 5 /* man - get the 'IO' type */
#define BIO_CTRL_PUSH 6 /* opt - internal, used to signify change */
#define BIO_CTRL_POP 7 /* opt - internal, used to signify change */
#define BIO_CTRL_GET_CLOSE 8 /* man - set the 'close' on free */
#define BIO_CTRL_SET_CLOSE 9 /* man - set the 'close' on free */
#define BIO_CTRL_PENDING 10 /* opt - is their more data buffered */
#define BIO_CTRL_FLUSH 11 /* opt - 'flush' buffered output */
#define BIO_CTRL_DUP 12 /* man - extra stuff for 'duped' BIO */
#define BIO_CTRL_WPENDING 13 /* opt - number of bytes still to write */
/* callback is int cb(BIO *bio,state,ret); */
#define BIO_CTRL_SET_CALLBACK 14 /* opt - set callback function */
#define BIO_CTRL_GET_CALLBACK 15 /* opt - set callback function */
#define BIO_CTRL_SET_FILENAME 30 /* BIO_s_file special */
/* dgram BIO stuff */
#define BIO_CTRL_DGRAM_CONNECT 31 /* BIO dgram special */
#define BIO_CTRL_DGRAM_SET_CONNECTED 32 /* allow for an externally
* connected socket to be
* passed in */
#define BIO_CTRL_DGRAM_SET_RECV_TIMEOUT 33 /* setsockopt, essentially */
#define BIO_CTRL_DGRAM_GET_RECV_TIMEOUT 34 /* getsockopt, essentially */
#define BIO_CTRL_DGRAM_SET_SEND_TIMEOUT 35 /* setsockopt, essentially */
#define BIO_CTRL_DGRAM_GET_SEND_TIMEOUT 36 /* getsockopt, essentially */
#define BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP 37 /* flag whether the last */
#define BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP 38 /* I/O operation tiemd out */
/* #ifdef IP_MTU_DISCOVER */
#define BIO_CTRL_DGRAM_MTU_DISCOVER 39 /* set DF bit on egress packets */
/* #endif */
#define BIO_CTRL_DGRAM_QUERY_MTU 40 /* as kernel for current MTU */
#define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47
#define BIO_CTRL_DGRAM_GET_MTU 41 /* get cached value for MTU */
#define BIO_CTRL_DGRAM_SET_MTU 42 /* set cached value for
* MTU. want to use this
* if asking the kernel
* fails */
#define BIO_CTRL_DGRAM_MTU_EXCEEDED 43 /* check whether the MTU
* was exceed in the
* previous write
* operation */
#define BIO_CTRL_DGRAM_GET_PEER 46
#define BIO_CTRL_DGRAM_SET_PEER 44 /* Destination for the data */
#define BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT 45 /* Next DTLS handshake timeout to
* adjust socket timeouts */
#ifndef OPENSSL_NO_SCTP
/* SCTP stuff */
#define BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE 50
#define BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY 51
#define BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY 52
#define BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD 53
#define BIO_CTRL_DGRAM_SCTP_GET_SNDINFO 60
#define BIO_CTRL_DGRAM_SCTP_SET_SNDINFO 61
#define BIO_CTRL_DGRAM_SCTP_GET_RCVINFO 62
#define BIO_CTRL_DGRAM_SCTP_SET_RCVINFO 63
#define BIO_CTRL_DGRAM_SCTP_GET_PRINFO 64
#define BIO_CTRL_DGRAM_SCTP_SET_PRINFO 65
#define BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN 70
#endif
/* modifiers */
#define BIO_FP_READ 0x02
#define BIO_FP_WRITE 0x04
#define BIO_FP_APPEND 0x08
#define BIO_FP_TEXT 0x10
#define BIO_FLAGS_READ 0x01
#define BIO_FLAGS_WRITE 0x02
#define BIO_FLAGS_IO_SPECIAL 0x04
#define BIO_FLAGS_RWS (BIO_FLAGS_READ|BIO_FLAGS_WRITE|BIO_FLAGS_IO_SPECIAL)
#define BIO_FLAGS_SHOULD_RETRY 0x08
#ifndef BIO_FLAGS_UPLINK
/* "UPLINK" flag denotes file descriptors provided by application.
It defaults to 0, as most platforms don't require UPLINK interface. */
#define BIO_FLAGS_UPLINK 0
#endif
/* Used in BIO_gethostbyname() */
#define BIO_GHBN_CTRL_HITS 1
#define BIO_GHBN_CTRL_MISSES 2
#define BIO_GHBN_CTRL_CACHE_SIZE 3
#define BIO_GHBN_CTRL_GET_ENTRY 4
#define BIO_GHBN_CTRL_FLUSH 5
/* Mostly used in the SSL BIO */
/* Not used anymore
* #define BIO_FLAGS_PROTOCOL_DELAYED_READ 0x10
* #define BIO_FLAGS_PROTOCOL_DELAYED_WRITE 0x20
* #define BIO_FLAGS_PROTOCOL_STARTUP 0x40
*/
#define BIO_FLAGS_BASE64_NO_NL 0x100
/* This is used with memory BIOs: it means we shouldn't free up or change the
* data in any way.
*/
#define BIO_FLAGS_MEM_RDONLY 0x200
typedef struct bio_st BIO;
void BIO_set_flags(BIO *b, int flags);
int BIO_test_flags(const BIO *b, int flags);
void BIO_clear_flags(BIO *b, int flags);
#define BIO_get_flags(b) BIO_test_flags(b, ~(0x0))
#define BIO_set_retry_special(b) \
BIO_set_flags(b, (BIO_FLAGS_IO_SPECIAL|BIO_FLAGS_SHOULD_RETRY))
#define BIO_set_retry_read(b) \
BIO_set_flags(b, (BIO_FLAGS_READ|BIO_FLAGS_SHOULD_RETRY))
#define BIO_set_retry_write(b) \
BIO_set_flags(b, (BIO_FLAGS_WRITE|BIO_FLAGS_SHOULD_RETRY))
/* These are normally used internally in BIOs */
#define BIO_clear_retry_flags(b) \
BIO_clear_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
#define BIO_get_retry_flags(b) \
BIO_test_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
/* These should be used by the application to tell why we should retry */
#define BIO_should_read(a) BIO_test_flags(a, BIO_FLAGS_READ)
#define BIO_should_write(a) BIO_test_flags(a, BIO_FLAGS_WRITE)
#define BIO_should_io_special(a) BIO_test_flags(a, BIO_FLAGS_IO_SPECIAL)
#define BIO_retry_type(a) BIO_test_flags(a, BIO_FLAGS_RWS)
#define BIO_should_retry(a) BIO_test_flags(a, BIO_FLAGS_SHOULD_RETRY)
/* The next three are used in conjunction with the
* BIO_should_io_special() condition. After this returns true,
* BIO *BIO_get_retry_BIO(BIO *bio, int *reason); will walk the BIO
* stack and return the 'reason' for the special and the offending BIO.
* Given a BIO, BIO_get_retry_reason(bio) will return the code. */
/* Returned from the SSL bio when the certificate retrieval code had an error */
#define BIO_RR_SSL_X509_LOOKUP 0x01
/* Returned from the connect BIO when a connect would have blocked */
#define BIO_RR_CONNECT 0x02
/* Returned from the accept BIO when an accept would have blocked */
#define BIO_RR_ACCEPT 0x03
/* These are passed by the BIO callback */
#define BIO_CB_FREE 0x01
#define BIO_CB_READ 0x02
#define BIO_CB_WRITE 0x03
#define BIO_CB_PUTS 0x04
#define BIO_CB_GETS 0x05
#define BIO_CB_CTRL 0x06
/* The callback is called before and after the underling operation,
* The BIO_CB_RETURN flag indicates if it is after the call */
#define BIO_CB_RETURN 0x80
#define BIO_CB_return(a) ((a)|BIO_CB_RETURN))
#define BIO_cb_pre(a) (!((a)&BIO_CB_RETURN))
#define BIO_cb_post(a) ((a)&BIO_CB_RETURN)
long (*BIO_get_callback(const BIO *b)) (struct bio_st *,int,const char *,int, long,long);
void BIO_set_callback(BIO *b,
long (*callback)(struct bio_st *,int,const char *,int, long,long));
char *BIO_get_callback_arg(const BIO *b);
void BIO_set_callback_arg(BIO *b, char *arg);
const char * BIO_method_name(const BIO *b);
int BIO_method_type(const BIO *b);
typedef void bio_info_cb(struct bio_st *, int, const char *, int, long, long);
typedef struct bio_method_st
{
int type;
const char *name;
int (*bwrite)(BIO *, const char *, int);
int (*bread)(BIO *, char *, int);
int (*bputs)(BIO *, const char *);
int (*bgets)(BIO *, char *, int);
long (*ctrl)(BIO *, int, long, void *);
int (*create)(BIO *);
int (*destroy)(BIO *);
long (*callback_ctrl)(BIO *, int, bio_info_cb *);
} BIO_METHOD;
struct bio_st
{
BIO_METHOD *method;
/* bio, mode, argp, argi, argl, ret */
long (*callback)(struct bio_st *,int,const char *,int, long,long);
char *cb_arg; /* first argument for the callback */
int init;
int shutdown;
int flags; /* extra storage */
int retry_reason;
int num;
void *ptr;
struct bio_st *next_bio; /* used by filter BIOs */
struct bio_st *prev_bio; /* used by filter BIOs */
int references;
unsigned long num_read;
unsigned long num_write;
CRYPTO_EX_DATA ex_data;
};
DECLARE_STACK_OF(BIO)
typedef struct bio_f_buffer_ctx_struct
{
/* Buffers are setup like this:
*
* <---------------------- size ----------------------->
* +---------------------------------------------------+
* | consumed | remaining | free space |
* +---------------------------------------------------+
* <-- off --><------- len ------->
*/
/* BIO *bio; */ /* this is now in the BIO struct */
int ibuf_size; /* how big is the input buffer */
int obuf_size; /* how big is the output buffer */
char *ibuf; /* the char array */
int ibuf_len; /* how many bytes are in it */
int ibuf_off; /* write/read offset */
char *obuf; /* the char array */
int obuf_len; /* how many bytes are in it */
int obuf_off; /* write/read offset */
} BIO_F_BUFFER_CTX;
/* Prefix and suffix callback in ASN1 BIO */
typedef int asn1_ps_func(BIO *b, unsigned char **pbuf, int *plen, void *parg);
#ifndef OPENSSL_NO_SCTP
/* SCTP parameter structs */
struct bio_dgram_sctp_sndinfo
{
uint16_t snd_sid;
uint16_t snd_flags;
uint32_t snd_ppid;
uint32_t snd_context;
};
struct bio_dgram_sctp_rcvinfo
{
uint16_t rcv_sid;
uint16_t rcv_ssn;
uint16_t rcv_flags;
uint32_t rcv_ppid;
uint32_t rcv_tsn;
uint32_t rcv_cumtsn;
uint32_t rcv_context;
};
struct bio_dgram_sctp_prinfo
{
uint16_t pr_policy;
uint32_t pr_value;
};
#endif
/* connect BIO stuff */
#define BIO_CONN_S_BEFORE 1
#define BIO_CONN_S_GET_IP 2
#define BIO_CONN_S_GET_PORT 3
#define BIO_CONN_S_CREATE_SOCKET 4
#define BIO_CONN_S_CONNECT 5
#define BIO_CONN_S_OK 6
#define BIO_CONN_S_BLOCKED_CONNECT 7
#define BIO_CONN_S_NBIO 8
/*#define BIO_CONN_get_param_hostname BIO_ctrl */
#define BIO_C_SET_CONNECT 100
#define BIO_C_DO_STATE_MACHINE 101
#define BIO_C_SET_NBIO 102
#define BIO_C_SET_PROXY_PARAM 103
#define BIO_C_SET_FD 104
#define BIO_C_GET_FD 105
#define BIO_C_SET_FILE_PTR 106
#define BIO_C_GET_FILE_PTR 107
#define BIO_C_SET_FILENAME 108
#define BIO_C_SET_SSL 109
#define BIO_C_GET_SSL 110
#define BIO_C_SET_MD 111
#define BIO_C_GET_MD 112
#define BIO_C_GET_CIPHER_STATUS 113
#define BIO_C_SET_BUF_MEM 114
#define BIO_C_GET_BUF_MEM_PTR 115
#define BIO_C_GET_BUFF_NUM_LINES 116
#define BIO_C_SET_BUFF_SIZE 117
#define BIO_C_SET_ACCEPT 118
#define BIO_C_SSL_MODE 119
#define BIO_C_GET_MD_CTX 120
#define BIO_C_GET_PROXY_PARAM 121
#define BIO_C_SET_BUFF_READ_DATA 122 /* data to read first */
#define BIO_C_GET_CONNECT 123
#define BIO_C_GET_ACCEPT 124
#define BIO_C_SET_SSL_RENEGOTIATE_BYTES 125
#define BIO_C_GET_SSL_NUM_RENEGOTIATES 126
#define BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT 127
#define BIO_C_FILE_SEEK 128
#define BIO_C_GET_CIPHER_CTX 129
#define BIO_C_SET_BUF_MEM_EOF_RETURN 130/*return end of input value*/
#define BIO_C_SET_BIND_MODE 131
#define BIO_C_GET_BIND_MODE 132
#define BIO_C_FILE_TELL 133
#define BIO_C_GET_SOCKS 134
#define BIO_C_SET_SOCKS 135
#define BIO_C_SET_WRITE_BUF_SIZE 136/* for BIO_s_bio */
#define BIO_C_GET_WRITE_BUF_SIZE 137
#define BIO_C_MAKE_BIO_PAIR 138
#define BIO_C_DESTROY_BIO_PAIR 139
#define BIO_C_GET_WRITE_GUARANTEE 140
#define BIO_C_GET_READ_REQUEST 141
#define BIO_C_SHUTDOWN_WR 142
#define BIO_C_NREAD0 143
#define BIO_C_NREAD 144
#define BIO_C_NWRITE0 145
#define BIO_C_NWRITE 146
#define BIO_C_RESET_READ_REQUEST 147
#define BIO_C_SET_MD_CTX 148
#define BIO_C_SET_PREFIX 149
#define BIO_C_GET_PREFIX 150
#define BIO_C_SET_SUFFIX 151
#define BIO_C_GET_SUFFIX 152
#define BIO_C_SET_EX_ARG 153
#define BIO_C_GET_EX_ARG 154
#define BIO_set_app_data(s,arg) BIO_set_ex_data(s,0,arg)
#define BIO_get_app_data(s) BIO_get_ex_data(s,0)
/* BIO_s_connect() and BIO_s_socks4a_connect() */
#define BIO_set_conn_hostname(b,name) BIO_ctrl(b,BIO_C_SET_CONNECT,0,(char *)name)
#define BIO_set_conn_port(b,port) BIO_ctrl(b,BIO_C_SET_CONNECT,1,(char *)port)
#define BIO_set_conn_ip(b,ip) BIO_ctrl(b,BIO_C_SET_CONNECT,2,(char *)ip)
#define BIO_set_conn_int_port(b,port) BIO_ctrl(b,BIO_C_SET_CONNECT,3,(char *)port)
#define BIO_get_conn_hostname(b) BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,0)
#define BIO_get_conn_port(b) BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,1)
#define BIO_get_conn_ip(b) BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,2)
#define BIO_get_conn_int_port(b) BIO_int_ctrl(b,BIO_C_GET_CONNECT,3,0)
#define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL)
/* BIO_s_accept_socket() */
#define BIO_set_accept_port(b,name) BIO_ctrl(b,BIO_C_SET_ACCEPT,0,(char *)name)
#define BIO_get_accept_port(b) BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,0)
/* #define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL) */
#define BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,1,(n)?(void *)"a":NULL)
#define BIO_set_accept_bios(b,bio) BIO_ctrl(b,BIO_C_SET_ACCEPT,2,(char *)bio)
#define BIO_BIND_NORMAL 0
#define BIO_BIND_REUSEADDR_IF_UNUSED 1
#define BIO_BIND_REUSEADDR 2
#define BIO_set_bind_mode(b,mode) BIO_ctrl(b,BIO_C_SET_BIND_MODE,mode,NULL)
#define BIO_get_bind_mode(b,mode) BIO_ctrl(b,BIO_C_GET_BIND_MODE,0,NULL)
#define BIO_do_connect(b) BIO_do_handshake(b)
#define BIO_do_accept(b) BIO_do_handshake(b)
#define BIO_do_handshake(b) BIO_ctrl(b,BIO_C_DO_STATE_MACHINE,0,NULL)
/* BIO_s_proxy_client() */
#define BIO_set_url(b,url) BIO_ctrl(b,BIO_C_SET_PROXY_PARAM,0,(char *)(url))
#define BIO_set_proxies(b,p) BIO_ctrl(b,BIO_C_SET_PROXY_PARAM,1,(char *)(p))
/* BIO_set_nbio(b,n) */
#define BIO_set_filter_bio(b,s) BIO_ctrl(b,BIO_C_SET_PROXY_PARAM,2,(char *)(s))
/* BIO *BIO_get_filter_bio(BIO *bio); */
#define BIO_set_proxy_cb(b,cb) BIO_callback_ctrl(b,BIO_C_SET_PROXY_PARAM,3,(void *(*cb)()))
#define BIO_set_proxy_header(b,sk) BIO_ctrl(b,BIO_C_SET_PROXY_PARAM,4,(char *)sk)
#define BIO_set_no_connect_return(b,bool) BIO_int_ctrl(b,BIO_C_SET_PROXY_PARAM,5,bool)
#define BIO_get_proxy_header(b,skp) BIO_ctrl(b,BIO_C_GET_PROXY_PARAM,0,(char *)skp)
#define BIO_get_proxies(b,pxy_p) BIO_ctrl(b,BIO_C_GET_PROXY_PARAM,1,(char *)(pxy_p))
#define BIO_get_url(b,url) BIO_ctrl(b,BIO_C_GET_PROXY_PARAM,2,(char *)(url))
#define BIO_get_no_connect_return(b) BIO_ctrl(b,BIO_C_GET_PROXY_PARAM,5,NULL)
#define BIO_set_fd(b,fd,c) BIO_int_ctrl(b,BIO_C_SET_FD,c,fd)
#define BIO_get_fd(b,c) BIO_ctrl(b,BIO_C_GET_FD,0,(char *)c)
#define BIO_set_fp(b,fp,c) BIO_ctrl(b,BIO_C_SET_FILE_PTR,c,(char *)fp)
#define BIO_get_fp(b,fpp) BIO_ctrl(b,BIO_C_GET_FILE_PTR,0,(char *)fpp)
#define BIO_seek(b,ofs) (int)BIO_ctrl(b,BIO_C_FILE_SEEK,ofs,NULL)
#define BIO_tell(b) (int)BIO_ctrl(b,BIO_C_FILE_TELL,0,NULL)
/* name is cast to lose const, but might be better to route through a function
so we can do it safely */
#ifdef CONST_STRICT
/* If you are wondering why this isn't defined, its because CONST_STRICT is
* purely a compile-time kludge to allow const to be checked.
*/
int BIO_read_filename(BIO *b,const char *name);
#else
#define BIO_read_filename(b,name) BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_READ,(char *)name)
#endif
#define BIO_write_filename(b,name) BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_WRITE,name)
#define BIO_append_filename(b,name) BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_APPEND,name)
#define BIO_rw_filename(b,name) BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_READ|BIO_FP_WRITE,name)
/* WARNING WARNING, this ups the reference count on the read bio of the
* SSL structure. This is because the ssl read BIO is now pointed to by
* the next_bio field in the bio. So when you free the BIO, make sure
* you are doing a BIO_free_all() to catch the underlying BIO. */
#define BIO_set_ssl(b,ssl,c) BIO_ctrl(b,BIO_C_SET_SSL,c,(char *)ssl)
#define BIO_get_ssl(b,sslp) BIO_ctrl(b,BIO_C_GET_SSL,0,(char *)sslp)
#define BIO_set_ssl_mode(b,client) BIO_ctrl(b,BIO_C_SSL_MODE,client,NULL)
#define BIO_set_ssl_renegotiate_bytes(b,num) \
BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_BYTES,num,NULL);
#define BIO_get_num_renegotiates(b) \
BIO_ctrl(b,BIO_C_GET_SSL_NUM_RENEGOTIATES,0,NULL);
#define BIO_set_ssl_renegotiate_timeout(b,seconds) \
BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT,seconds,NULL);
/* defined in evp.h */
/* #define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,1,(char *)md) */
#define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)pp)
#define BIO_set_mem_buf(b,bm,c) BIO_ctrl(b,BIO_C_SET_BUF_MEM,c,(char *)bm)
#define BIO_get_mem_ptr(b,pp) BIO_ctrl(b,BIO_C_GET_BUF_MEM_PTR,0,(char *)pp)
#define BIO_set_mem_eof_return(b,v) \
BIO_ctrl(b,BIO_C_SET_BUF_MEM_EOF_RETURN,v,NULL)
/* For the BIO_f_buffer() type */
#define BIO_get_buffer_num_lines(b) BIO_ctrl(b,BIO_C_GET_BUFF_NUM_LINES,0,NULL)
#define BIO_set_buffer_size(b,size) BIO_ctrl(b,BIO_C_SET_BUFF_SIZE,size,NULL)
#define BIO_set_read_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,0)
#define BIO_set_write_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,1)
#define BIO_set_buffer_read_data(b,buf,num) BIO_ctrl(b,BIO_C_SET_BUFF_READ_DATA,num,buf)
/* Don't use the next one unless you know what you are doing :-) */
#define BIO_dup_state(b,ret) BIO_ctrl(b,BIO_CTRL_DUP,0,(char *)(ret))
#define BIO_reset(b) (int)BIO_ctrl(b,BIO_CTRL_RESET,0,NULL)
#define BIO_eof(b) (int)BIO_ctrl(b,BIO_CTRL_EOF,0,NULL)
#define BIO_set_close(b,c) (int)BIO_ctrl(b,BIO_CTRL_SET_CLOSE,(c),NULL)
#define BIO_get_close(b) (int)BIO_ctrl(b,BIO_CTRL_GET_CLOSE,0,NULL)
#define BIO_pending(b) (int)BIO_ctrl(b,BIO_CTRL_PENDING,0,NULL)
#define BIO_wpending(b) (int)BIO_ctrl(b,BIO_CTRL_WPENDING,0,NULL)
/* ...pending macros have inappropriate return type */
size_t BIO_ctrl_pending(BIO *b);
size_t BIO_ctrl_wpending(BIO *b);
#define BIO_flush(b) (int)BIO_ctrl(b,BIO_CTRL_FLUSH,0,NULL)
#define BIO_get_info_callback(b,cbp) (int)BIO_ctrl(b,BIO_CTRL_GET_CALLBACK,0, \
cbp)
#define BIO_set_info_callback(b,cb) (int)BIO_callback_ctrl(b,BIO_CTRL_SET_CALLBACK,cb)
/* For the BIO_f_buffer() type */
#define BIO_buffer_get_num_lines(b) BIO_ctrl(b,BIO_CTRL_GET,0,NULL)
/* For BIO_s_bio() */
#define BIO_set_write_buf_size(b,size) (int)BIO_ctrl(b,BIO_C_SET_WRITE_BUF_SIZE,size,NULL)
#define BIO_get_write_buf_size(b,size) (size_t)BIO_ctrl(b,BIO_C_GET_WRITE_BUF_SIZE,size,NULL)
#define BIO_make_bio_pair(b1,b2) (int)BIO_ctrl(b1,BIO_C_MAKE_BIO_PAIR,0,b2)
#define BIO_destroy_bio_pair(b) (int)BIO_ctrl(b,BIO_C_DESTROY_BIO_PAIR,0,NULL)
#define BIO_shutdown_wr(b) (int)BIO_ctrl(b, BIO_C_SHUTDOWN_WR, 0, NULL)
/* macros with inappropriate type -- but ...pending macros use int too: */
#define BIO_get_write_guarantee(b) (int)BIO_ctrl(b,BIO_C_GET_WRITE_GUARANTEE,0,NULL)
#define BIO_get_read_request(b) (int)BIO_ctrl(b,BIO_C_GET_READ_REQUEST,0,NULL)
size_t BIO_ctrl_get_write_guarantee(BIO *b);
size_t BIO_ctrl_get_read_request(BIO *b);
int BIO_ctrl_reset_read_request(BIO *b);
/* ctrl macros for dgram */
#define BIO_ctrl_dgram_connect(b,peer) \
(int)BIO_ctrl(b,BIO_CTRL_DGRAM_CONNECT,0, (char *)peer)
#define BIO_ctrl_set_connected(b, state, peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_CONNECTED, state, (char *)peer)
#define BIO_dgram_recv_timedout(b) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)
#define BIO_dgram_send_timedout(b) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP, 0, NULL)
#define BIO_dgram_get_peer(b,peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_PEER, 0, (char *)peer)
#define BIO_dgram_set_peer(b,peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, (char *)peer)
/* These two aren't currently implemented */
/* int BIO_get_ex_num(BIO *bio); */
/* void BIO_set_ex_free_func(BIO *bio,int idx,void (*cb)()); */
int BIO_set_ex_data(BIO *bio,int idx,void *data);
void *BIO_get_ex_data(BIO *bio,int idx);
int BIO_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
unsigned long BIO_number_read(BIO *bio);
unsigned long BIO_number_written(BIO *bio);
/* For BIO_f_asn1() */
int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix,
asn1_ps_func *prefix_free);
int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix,
asn1_ps_func **pprefix_free);
int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix,
asn1_ps_func *suffix_free);
int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix,
asn1_ps_func **psuffix_free);
# ifndef OPENSSL_NO_FP_API
BIO_METHOD *BIO_s_file(void );
BIO *BIO_new_file(const char *filename, const char *mode);
BIO *BIO_new_fp(FILE *stream, int close_flag);
# define BIO_s_file_internal BIO_s_file
# endif
BIO * BIO_new(BIO_METHOD *type);
int BIO_set(BIO *a,BIO_METHOD *type);
int BIO_free(BIO *a);
void BIO_vfree(BIO *a);
int BIO_read(BIO *b, void *data, int len);
int BIO_gets(BIO *bp,char *buf, int size);
int BIO_write(BIO *b, const void *data, int len);
int BIO_puts(BIO *bp,const char *buf);
int BIO_indent(BIO *b,int indent,int max);
long BIO_ctrl(BIO *bp,int cmd,long larg,void *parg);
long BIO_callback_ctrl(BIO *b, int cmd, void (*fp)(struct bio_st *, int, const char *, int, long, long));
char * BIO_ptr_ctrl(BIO *bp,int cmd,long larg);
long BIO_int_ctrl(BIO *bp,int cmd,long larg,int iarg);
BIO * BIO_push(BIO *b,BIO *append);
BIO * BIO_pop(BIO *b);
void BIO_free_all(BIO *a);
BIO * BIO_find_type(BIO *b,int bio_type);
BIO * BIO_next(BIO *b);
BIO * BIO_get_retry_BIO(BIO *bio, int *reason);
int BIO_get_retry_reason(BIO *bio);
BIO * BIO_dup_chain(BIO *in);
int BIO_nread0(BIO *bio, char **buf);
int BIO_nread(BIO *bio, char **buf, int num);
int BIO_nwrite0(BIO *bio, char **buf);
int BIO_nwrite(BIO *bio, char **buf, int num);
long BIO_debug_callback(BIO *bio,int cmd,const char *argp,int argi,
long argl,long ret);
BIO_METHOD *BIO_s_mem(void);
BIO *BIO_new_mem_buf(void *buf, int len);
BIO_METHOD *BIO_s_socket(void);
BIO_METHOD *BIO_s_connect(void);
BIO_METHOD *BIO_s_accept(void);
BIO_METHOD *BIO_s_fd(void);
#ifndef OPENSSL_SYS_OS2
BIO_METHOD *BIO_s_log(void);
#endif
BIO_METHOD *BIO_s_bio(void);
BIO_METHOD *BIO_s_null(void);
BIO_METHOD *BIO_f_null(void);
BIO_METHOD *BIO_f_buffer(void);
#ifdef OPENSSL_SYS_VMS
BIO_METHOD *BIO_f_linebuffer(void);
#endif
BIO_METHOD *BIO_f_nbio_test(void);
#ifndef OPENSSL_NO_DGRAM
BIO_METHOD *BIO_s_datagram(void);
#ifndef OPENSSL_NO_SCTP
BIO_METHOD *BIO_s_datagram_sctp(void);
#endif
#endif
/* BIO_METHOD *BIO_f_ber(void); */
int BIO_sock_should_retry(int i);
int BIO_sock_non_fatal_error(int error);
int BIO_dgram_non_fatal_error(int error);
int BIO_fd_should_retry(int i);
int BIO_fd_non_fatal_error(int error);
int BIO_dump_cb(int (*cb)(const void *data, size_t len, void *u),
void *u, const char *s, int len);
int BIO_dump_indent_cb(int (*cb)(const void *data, size_t len, void *u),
void *u, const char *s, int len, int indent);
int BIO_dump(BIO *b,const char *bytes,int len);
int BIO_dump_indent(BIO *b,const char *bytes,int len,int indent);
#ifndef OPENSSL_NO_FP_API
int BIO_dump_fp(FILE *fp, const char *s, int len);
int BIO_dump_indent_fp(FILE *fp, const char *s, int len, int indent);
#endif
struct hostent *BIO_gethostbyname(const char *name);
/* We might want a thread-safe interface too:
* struct hostent *BIO_gethostbyname_r(const char *name,
* struct hostent *result, void *buffer, size_t buflen);
* or something similar (caller allocates a struct hostent,
* pointed to by "result", and additional buffer space for the various
* substructures; if the buffer does not suffice, NULL is returned
* and an appropriate error code is set).
*/
int BIO_sock_error(int sock);
int BIO_socket_ioctl(int fd, long type, void *arg);
int BIO_socket_nbio(int fd,int mode);
int BIO_get_port(const char *str, unsigned short *port_ptr);
int BIO_get_host_ip(const char *str, unsigned char *ip);
int BIO_get_accept_socket(char *host_port,int mode);
int BIO_accept(int sock,char **ip_port);
int BIO_sock_init(void );
void BIO_sock_cleanup(void);
int BIO_set_tcp_ndelay(int sock,int turn_on);
BIO *BIO_new_socket(int sock, int close_flag);
BIO *BIO_new_dgram(int fd, int close_flag);
#ifndef OPENSSL_NO_SCTP
BIO *BIO_new_dgram_sctp(int fd, int close_flag);
int BIO_dgram_is_sctp(BIO *bio);
int BIO_dgram_sctp_notification_cb(BIO *b,
void (*handle_notifications)(BIO *bio, void *context, void *buf),
void *context);
int BIO_dgram_sctp_wait_for_dry(BIO *b);
int BIO_dgram_sctp_msg_waiting(BIO *b);
#endif
BIO *BIO_new_fd(int fd, int close_flag);
BIO *BIO_new_connect(char *host_port);
BIO *BIO_new_accept(char *host_port);
int BIO_new_bio_pair(BIO **bio1, size_t writebuf1,
BIO **bio2, size_t writebuf2);
/* If successful, returns 1 and in *bio1, *bio2 two BIO pair endpoints.
* Otherwise returns 0 and sets *bio1 and *bio2 to NULL.
* Size 0 uses default value.
*/
void BIO_copy_next_retry(BIO *b);
/*long BIO_ghbn_ctrl(int cmd,int iarg,char *parg);*/
#ifdef __GNUC__
# define __bio_h__attr__ __attribute__
#else
# define __bio_h__attr__(x)
#endif
int BIO_printf(BIO *bio, const char *format, ...)
__bio_h__attr__((__format__(__printf__,2,3)));
int BIO_vprintf(BIO *bio, const char *format, va_list args)
__bio_h__attr__((__format__(__printf__,2,0)));
int BIO_snprintf(char *buf, size_t n, const char *format, ...)
__bio_h__attr__((__format__(__printf__,3,4)));
int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args)
__bio_h__attr__((__format__(__printf__,3,0)));
#undef __bio_h__attr__
/* BEGIN ERROR CODES */
/* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
void ERR_load_BIO_strings(void);
/* Error codes for the BIO functions. */
/* Function codes. */
#define BIO_F_ACPT_STATE 100
#define BIO_F_BIO_ACCEPT 101
#define BIO_F_BIO_BER_GET_HEADER 102
#define BIO_F_BIO_CALLBACK_CTRL 131
#define BIO_F_BIO_CTRL 103
#define BIO_F_BIO_GETHOSTBYNAME 120
#define BIO_F_BIO_GETS 104
#define BIO_F_BIO_GET_ACCEPT_SOCKET 105
#define BIO_F_BIO_GET_HOST_IP 106
#define BIO_F_BIO_GET_PORT 107
#define BIO_F_BIO_MAKE_PAIR 121
#define BIO_F_BIO_NEW 108
#define BIO_F_BIO_NEW_FILE 109
#define BIO_F_BIO_NEW_MEM_BUF 126
#define BIO_F_BIO_NREAD 123
#define BIO_F_BIO_NREAD0 124
#define BIO_F_BIO_NWRITE 125
#define BIO_F_BIO_NWRITE0 122
#define BIO_F_BIO_PUTS 110
#define BIO_F_BIO_READ 111
#define BIO_F_BIO_SOCK_INIT 112
#define BIO_F_BIO_WRITE 113
#define BIO_F_BUFFER_CTRL 114
#define BIO_F_CONN_CTRL 127
#define BIO_F_CONN_STATE 115
#define BIO_F_DGRAM_SCTP_READ 132
#define BIO_F_FILE_CTRL 116
#define BIO_F_FILE_READ 130
#define BIO_F_LINEBUFFER_CTRL 129
#define BIO_F_MEM_READ 128
#define BIO_F_MEM_WRITE 117
#define BIO_F_SSL_NEW 118
#define BIO_F_WSASTARTUP 119
/* Reason codes. */
#define BIO_R_ACCEPT_ERROR 100
#define BIO_R_BAD_FOPEN_MODE 101
#define BIO_R_BAD_HOSTNAME_LOOKUP 102
#define BIO_R_BROKEN_PIPE 124
#define BIO_R_CONNECT_ERROR 103
#define BIO_R_EOF_ON_MEMORY_BIO 127
#define BIO_R_ERROR_SETTING_NBIO 104
#define BIO_R_ERROR_SETTING_NBIO_ON_ACCEPTED_SOCKET 105
#define BIO_R_ERROR_SETTING_NBIO_ON_ACCEPT_SOCKET 106
#define BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET 107
#define BIO_R_INVALID_ARGUMENT 125
#define BIO_R_INVALID_IP_ADDRESS 108
#define BIO_R_IN_USE 123
#define BIO_R_KEEPALIVE 109
#define BIO_R_NBIO_CONNECT_ERROR 110
#define BIO_R_NO_ACCEPT_PORT_SPECIFIED 111
#define BIO_R_NO_HOSTNAME_SPECIFIED 112
#define BIO_R_NO_PORT_DEFINED 113
#define BIO_R_NO_PORT_SPECIFIED 114
#define BIO_R_NO_SUCH_FILE 128
#define BIO_R_NULL_PARAMETER 115
#define BIO_R_TAG_MISMATCH 116
#define BIO_R_UNABLE_TO_BIND_SOCKET 117
#define BIO_R_UNABLE_TO_CREATE_SOCKET 118
#define BIO_R_UNABLE_TO_LISTEN_SOCKET 119
#define BIO_R_UNINITIALIZED 120
#define BIO_R_UNSUPPORTED_METHOD 121
#define BIO_R_WRITE_TO_READ_ONLY_BIO 126
#define BIO_R_WSASTARTUP 122
#ifdef __cplusplus
}
#endif
#endif
| {
"language": "C"
} |
/* xoreos - A reimplementation of BioWare's Aurora engine
*
* xoreos is the legal property of its developers, whose names
* can be found in the AUTHORS file distributed with this source
* distribution.
*
* xoreos is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* xoreos 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 xoreos. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file
* TXB (another one of BioWare's own texture formats) loading.
*/
#ifndef GRAPHICS_IMAGES_TXB_H
#define GRAPHICS_IMAGES_TXB_H
#include "src/graphics/images/decoder.h"
namespace Common {
class SeekableReadStream;
}
namespace Graphics {
/** Another one of BioWare's own texture formats, TXB.
*
* This format is used by Jade Empire.
*
* Even though the Xbox versions of the Knights of the Old Republic games
* features textures with a .txb extension, these are actually in the TPC
* format, not this TXB format.
*/
class TXB : public ImageDecoder {
public:
TXB(Common::SeekableReadStream &txb);
~TXB();
private:
// Loading helpers
void load(Common::SeekableReadStream &txb);
void readHeader(Common::SeekableReadStream &txb, byte &encoding, uint32_t &dataSize);
void readData(Common::SeekableReadStream &txb, byte encoding);
void readTXI(Common::SeekableReadStream &txb);
static void deSwizzle(byte *dst, const byte *src, uint32_t width, uint32_t height, uint8_t bpp);
};
} // End of namespace Graphics
#endif // GRAPHICS_IMAGES_TXB_H
| {
"language": "C"
} |
// -*- C++ -*-
// Copyright (C) 2007-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// 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
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file parallel/partition.h
* @brief Parallel implementation of std::partition(),
* std::nth_element(), and std::partial_sort().
* This file is a GNU parallel extension to the Standard C++ Library.
*/
// Written by Johannes Singler and Felix Putze.
#ifndef _GLIBCXX_PARALLEL_PARTITION_H
#define _GLIBCXX_PARALLEL_PARTITION_H 1
#include <parallel/basic_iterator.h>
#include <parallel/sort.h>
#include <parallel/random_number.h>
#include <bits/stl_algo.h>
#include <parallel/parallel.h>
/** @brief Decide whether to declare certain variables volatile. */
#define _GLIBCXX_VOLATILE volatile
namespace __gnu_parallel
{
/** @brief Parallel implementation of std::partition.
* @param __begin Begin iterator of input sequence to split.
* @param __end End iterator of input sequence to split.
* @param __pred Partition predicate, possibly including some kind
* of pivot.
* @param __num_threads Maximum number of threads to use for this task.
* @return Number of elements not fulfilling the predicate. */
template<typename _RAIter, typename _Predicate>
typename std::iterator_traits<_RAIter>::difference_type
__parallel_partition(_RAIter __begin, _RAIter __end,
_Predicate __pred, _ThreadIndex __num_threads)
{
typedef std::iterator_traits<_RAIter> _TraitsType;
typedef typename _TraitsType::value_type _ValueType;
typedef typename _TraitsType::difference_type _DifferenceType;
_DifferenceType __n = __end - __begin;
_GLIBCXX_CALL(__n)
const _Settings& __s = _Settings::get();
// shared
_GLIBCXX_VOLATILE _DifferenceType __left = 0, __right = __n - 1,
__dist = __n,
__leftover_left, __leftover_right,
__leftnew, __rightnew;
// just 0 or 1, but int to allow atomic operations
int* __reserved_left = 0, * __reserved_right = 0;
_DifferenceType __chunk_size = __s.partition_chunk_size;
//at least two chunks per thread
if (__dist >= 2 * __num_threads * __chunk_size)
# pragma omp parallel num_threads(__num_threads)
{
# pragma omp single
{
__num_threads = omp_get_num_threads();
__reserved_left = new int[__num_threads];
__reserved_right = new int[__num_threads];
if (__s.partition_chunk_share > 0.0)
__chunk_size = std::max<_DifferenceType>
(__s.partition_chunk_size, (double)__n
* __s.partition_chunk_share / (double)__num_threads);
else
__chunk_size = __s.partition_chunk_size;
}
while (__dist >= 2 * __num_threads * __chunk_size)
{
# pragma omp single
{
_DifferenceType __num_chunks = __dist / __chunk_size;
for (_ThreadIndex __r = 0; __r < __num_threads; ++__r)
{
__reserved_left [__r] = 0; // false
__reserved_right[__r] = 0; // false
}
__leftover_left = 0;
__leftover_right = 0;
} //implicit barrier
// Private.
_DifferenceType __thread_left, __thread_left_border,
__thread_right, __thread_right_border;
__thread_left = __left + 1;
// Just to satisfy the condition below.
__thread_left_border = __thread_left - 1;
__thread_right = __n - 1;
// Just to satisfy the condition below.
__thread_right_border = __thread_right + 1;
bool __iam_finished = false;
while (!__iam_finished)
{
if (__thread_left > __thread_left_border)
{
_DifferenceType __former_dist =
__fetch_and_add(&__dist, -__chunk_size);
if (__former_dist < __chunk_size)
{
__fetch_and_add(&__dist, __chunk_size);
__iam_finished = true;
break;
}
else
{
__thread_left =
__fetch_and_add(&__left, __chunk_size);
__thread_left_border =
__thread_left + (__chunk_size - 1);
}
}
if (__thread_right < __thread_right_border)
{
_DifferenceType __former_dist =
__fetch_and_add(&__dist, -__chunk_size);
if (__former_dist < __chunk_size)
{
__fetch_and_add(&__dist, __chunk_size);
__iam_finished = true;
break;
}
else
{
__thread_right =
__fetch_and_add(&__right, -__chunk_size);
__thread_right_border =
__thread_right - (__chunk_size - 1);
}
}
// Swap as usual.
while (__thread_left < __thread_right)
{
while (__pred(__begin[__thread_left])
&& __thread_left <= __thread_left_border)
++__thread_left;
while (!__pred(__begin[__thread_right])
&& __thread_right >= __thread_right_border)
--__thread_right;
if (__thread_left > __thread_left_border
|| __thread_right < __thread_right_border)
// Fetch new chunk(__s).
break;
std::iter_swap(__begin + __thread_left,
__begin + __thread_right);
++__thread_left;
--__thread_right;
}
}
// Now swap the leftover chunks to the right places.
if (__thread_left <= __thread_left_border)
# pragma omp atomic
++__leftover_left;
if (__thread_right >= __thread_right_border)
# pragma omp atomic
++__leftover_right;
# pragma omp barrier
_DifferenceType
__leftold = __left,
__leftnew = __left - __leftover_left * __chunk_size,
__rightold = __right,
__rightnew = __right + __leftover_right * __chunk_size;
// <=> __thread_left_border + (__chunk_size - 1) >= __leftnew
if (__thread_left <= __thread_left_border
&& __thread_left_border >= __leftnew)
{
// Chunk already in place, reserve spot.
__reserved_left[(__left - (__thread_left_border + 1))
/ __chunk_size] = 1;
}
// <=> __thread_right_border - (__chunk_size - 1) <= __rightnew
if (__thread_right >= __thread_right_border
&& __thread_right_border <= __rightnew)
{
// Chunk already in place, reserve spot.
__reserved_right[((__thread_right_border - 1) - __right)
/ __chunk_size] = 1;
}
# pragma omp barrier
if (__thread_left <= __thread_left_border
&& __thread_left_border < __leftnew)
{
// Find spot and swap.
_DifferenceType __swapstart = -1;
for (int __r = 0; __r < __leftover_left; ++__r)
if (__reserved_left[__r] == 0
&& __compare_and_swap(&(__reserved_left[__r]), 0, 1))
{
__swapstart = __leftold - (__r + 1) * __chunk_size;
break;
}
#if _GLIBCXX_ASSERTIONS
_GLIBCXX_PARALLEL_ASSERT(__swapstart != -1);
#endif
std::swap_ranges(__begin + __thread_left_border
- (__chunk_size - 1),
__begin + __thread_left_border + 1,
__begin + __swapstart);
}
if (__thread_right >= __thread_right_border
&& __thread_right_border > __rightnew)
{
// Find spot and swap
_DifferenceType __swapstart = -1;
for (int __r = 0; __r < __leftover_right; ++__r)
if (__reserved_right[__r] == 0
&& __compare_and_swap(&(__reserved_right[__r]), 0, 1))
{
__swapstart = __rightold + __r * __chunk_size + 1;
break;
}
#if _GLIBCXX_ASSERTIONS
_GLIBCXX_PARALLEL_ASSERT(__swapstart != -1);
#endif
std::swap_ranges(__begin + __thread_right_border,
__begin + __thread_right_border
+ __chunk_size, __begin + __swapstart);
}
#if _GLIBCXX_ASSERTIONS
# pragma omp barrier
# pragma omp single
{
for (_DifferenceType __r = 0; __r < __leftover_left; ++__r)
_GLIBCXX_PARALLEL_ASSERT(__reserved_left[__r] == 1);
for (_DifferenceType __r = 0; __r < __leftover_right; ++__r)
_GLIBCXX_PARALLEL_ASSERT(__reserved_right[__r] == 1);
}
#endif
__left = __leftnew;
__right = __rightnew;
__dist = __right - __left + 1;
}
# pragma omp flush(__left, __right)
} // end "recursion" //parallel
_DifferenceType __final_left = __left, __final_right = __right;
while (__final_left < __final_right)
{
// Go right until key is geq than pivot.
while (__pred(__begin[__final_left])
&& __final_left < __final_right)
++__final_left;
// Go left until key is less than pivot.
while (!__pred(__begin[__final_right])
&& __final_left < __final_right)
--__final_right;
if (__final_left == __final_right)
break;
std::iter_swap(__begin + __final_left, __begin + __final_right);
++__final_left;
--__final_right;
}
// All elements on the left side are < piv, all elements on the
// right are >= piv
delete[] __reserved_left;
delete[] __reserved_right;
// Element "between" __final_left and __final_right might not have
// been regarded yet
if (__final_left < __n && !__pred(__begin[__final_left]))
// Really swapped.
return __final_left;
else
return __final_left + 1;
}
/**
* @brief Parallel implementation of std::nth_element().
* @param __begin Begin iterator of input sequence.
* @param __nth _Iterator of element that must be in position afterwards.
* @param __end End iterator of input sequence.
* @param __comp Comparator.
*/
template<typename _RAIter, typename _Compare>
void
__parallel_nth_element(_RAIter __begin, _RAIter __nth,
_RAIter __end, _Compare __comp)
{
typedef std::iterator_traits<_RAIter> _TraitsType;
typedef typename _TraitsType::value_type _ValueType;
typedef typename _TraitsType::difference_type _DifferenceType;
_GLIBCXX_CALL(__end - __begin)
_RAIter __split;
_RandomNumber __rng;
const _Settings& __s = _Settings::get();
_DifferenceType __minimum_length = std::max<_DifferenceType>(2,
std::max(__s.nth_element_minimal_n, __s.partition_minimal_n));
// Break if input range to small.
while (static_cast<_SequenceIndex>(__end - __begin) >= __minimum_length)
{
_DifferenceType __n = __end - __begin;
_RAIter __pivot_pos = __begin + __rng(__n);
// Swap __pivot_pos value to end.
if (__pivot_pos != (__end - 1))
std::iter_swap(__pivot_pos, __end - 1);
__pivot_pos = __end - 1;
// _Compare must have first_value_type, second_value_type,
// result_type
// _Compare ==
// __gnu_parallel::_Lexicographic<S, int,
// __gnu_parallel::_Less<S, S> >
// __pivot_pos == std::pair<S, int>*
__gnu_parallel::__binder2nd<_Compare, _ValueType, _ValueType, bool>
__pred(__comp, *__pivot_pos);
// Divide, leave pivot unchanged in last place.
_RAIter __split_pos1, __split_pos2;
__split_pos1 = __begin + __parallel_partition(__begin, __end - 1,
__pred,
__get_max_threads());
// Left side: < __pivot_pos; __right side: >= __pivot_pos
// Swap pivot back to middle.
if (__split_pos1 != __pivot_pos)
std::iter_swap(__split_pos1, __pivot_pos);
__pivot_pos = __split_pos1;
// In case all elements are equal, __split_pos1 == 0
if ((__split_pos1 + 1 - __begin) < (__n >> 7)
|| (__end - __split_pos1) < (__n >> 7))
{
// Very unequal split, one part smaller than one 128th
// elements not strictly larger than the pivot.
__gnu_parallel::__unary_negate<__gnu_parallel::
__binder1st<_Compare, _ValueType,
_ValueType, bool>, _ValueType>
__pred(__gnu_parallel::__binder1st<_Compare, _ValueType,
_ValueType, bool>(__comp, *__pivot_pos));
// Find other end of pivot-equal range.
__split_pos2 = __gnu_sequential::partition(__split_pos1 + 1,
__end, __pred);
}
else
// Only skip the pivot.
__split_pos2 = __split_pos1 + 1;
// Compare iterators.
if (__split_pos2 <= __nth)
__begin = __split_pos2;
else if (__nth < __split_pos1)
__end = __split_pos1;
else
break;
}
// Only at most _Settings::partition_minimal_n __elements __left.
__gnu_sequential::nth_element(__begin, __nth, __end, __comp);
}
/** @brief Parallel implementation of std::partial_sort().
* @param __begin Begin iterator of input sequence.
* @param __middle Sort until this position.
* @param __end End iterator of input sequence.
* @param __comp Comparator. */
template<typename _RAIter, typename _Compare>
void
__parallel_partial_sort(_RAIter __begin,
_RAIter __middle,
_RAIter __end, _Compare __comp)
{
__parallel_nth_element(__begin, __middle, __end, __comp);
std::sort(__begin, __middle, __comp);
}
} //namespace __gnu_parallel
#undef _GLIBCXX_VOLATILE
#endif /* _GLIBCXX_PARALLEL_PARTITION_H */
| {
"language": "C"
} |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int func_six(int x)
{
char b[32];
int r = write(1, b, sizeof(b));
return x;
}
int func_five(int x)
{
return func_six(x + 5);
}
int func_four(int x)
{
return func_five(x + 4);
}
int func_three(int x)
{
return func_four(x + 3);
}
int func_two(int x)
{
return func_three(x + 2);
}
int func_one(int x)
{
return func_two(x + 1);
}
int main(void)
{
func_one(10);
return 0;
}
| {
"language": "C"
} |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Copyright (C) IBM Corporation, 2004
*
* Author: Max Asböck <amax@us.ibm.com>
*
*/
#include <linux/sched.h>
#include "ibmasm.h"
#include "dot_command.h"
/*
* Reverse Heartbeat, i.e. heartbeats sent from the driver to the
* service processor.
* These heartbeats are initiated by user level programs.
*/
/* the reverse heartbeat dot command */
#pragma pack(1)
static struct {
struct dot_command_header header;
unsigned char command[3];
} rhb_dot_cmd = {
.header = {
.type = sp_read,
.command_size = 3,
.data_size = 0,
.status = 0
},
.command = { 4, 3, 6 }
};
#pragma pack()
void ibmasm_init_reverse_heartbeat(struct service_processor *sp, struct reverse_heartbeat *rhb)
{
init_waitqueue_head(&rhb->wait);
rhb->stopped = 0;
}
/**
* start_reverse_heartbeat
* Loop forever, sending a reverse heartbeat dot command to the service
* processor, then sleeping. The loop comes to an end if the service
* processor fails to respond 3 times or we were interrupted.
*/
int ibmasm_start_reverse_heartbeat(struct service_processor *sp, struct reverse_heartbeat *rhb)
{
struct command *cmd;
int times_failed = 0;
int result = 1;
cmd = ibmasm_new_command(sp, sizeof rhb_dot_cmd);
if (!cmd)
return -ENOMEM;
while (times_failed < 3) {
memcpy(cmd->buffer, (void *)&rhb_dot_cmd, sizeof rhb_dot_cmd);
cmd->status = IBMASM_CMD_PENDING;
ibmasm_exec_command(sp, cmd);
ibmasm_wait_for_response(cmd, IBMASM_CMD_TIMEOUT_NORMAL);
if (cmd->status != IBMASM_CMD_COMPLETE)
times_failed++;
wait_event_interruptible_timeout(rhb->wait,
rhb->stopped,
REVERSE_HEARTBEAT_TIMEOUT * HZ);
if (signal_pending(current) || rhb->stopped) {
result = -EINTR;
break;
}
}
command_put(cmd);
rhb->stopped = 0;
return result;
}
void ibmasm_stop_reverse_heartbeat(struct reverse_heartbeat *rhb)
{
rhb->stopped = 1;
wake_up_interruptible(&rhb->wait);
}
| {
"language": "C"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
** nssilock.h - Instrumented locking functions for NSS
**
** Description:
** nssilock provides instrumentation for locks and monitors in
** the NSS libraries. The instrumentation, when enabled, causes
** each call to the instrumented function to record data about
** the call to an external file. The external file
** subsequently used to extract performance data and other
** statistical information about the operation of locks used in
** the nss library.
**
** To enable compilation with instrumentation, build NSS with
** the compile time switch NEED_NSS_ILOCK defined.
**
** say: "gmake OS_CFLAGS+=-DNEED_NSS_ILOCK" at make time.
**
** At runtime, to enable recording from nssilock, one or more
** environment variables must be set. For each nssILockType to
** be recorded, an environment variable of the form NSS_ILOCK_x
** must be set to 1. For example:
**
** set NSS_ILOCK_Cert=1
**
** nssilock uses PRLOG is used to record to trace data. The
** PRLogModule name associated with nssilock data is: "nssilock".
** To enable recording of nssilock data you will need to set the
** environment variable NSPR_LOG_MODULES to enable
** recording for the nssilock log module. Similarly, you will
** need to set the environment variable NSPR_LOG_FILE to specify
** the filename to receive the recorded data. See prlog.h for usage.
** Example:
**
** export NSPR_LOG_MODULES=nssilock:6
** export NSPR_LOG_FILE=xxxLogfile
**
** Operation:
** nssilock wraps calls to NSPR's PZLock and PZMonitor functions
** with similarly named functions: PZ_NewLock(), etc. When NSS is
** built with lock instrumentation enabled, the PZ* functions are
** compiled into NSS; when lock instrumentation is disabled,
** calls to PZ* functions are directly mapped to PR* functions
** and the instrumentation arguments to the PZ* functions are
** compiled away.
**
**
** File Format:
** The format of the external file is implementation
** dependent. Where NSPR's PR_LOG() function is used, the file
** contains data defined for PR_LOG() plus the data written by
** the wrapped function. On some platforms and under some
** circumstances, platform dependent logging or
** instrumentation probes may be used. In any case, the
** relevant data provided by the lock instrumentation is:
**
** lockType, func, address, duration, line, file [heldTime]
**
** where:
**
** lockType: a character representation of nssILockType for the
** call. e.g. ... "cert"
**
** func: the function doing the tracing. e.g. "NewLock"
**
** address: address of the instrumented lock or monitor
**
** duration: is how long was spent in the instrumented function,
** in PRIntervalTime "ticks".
**
** line: the line number within the calling function
**
** file: the file from which the call was made
**
** heldTime: how long the lock/monitor was held. field
** present only for PZ_Unlock() and PZ_ExitMonitor().
**
** Design Notes:
** The design for lock instrumentation was influenced by the
** need to gather performance data on NSS 3.x. It is intended
** that the effort to modify NSS to use lock instrumentation
** be minimized. Existing calls to locking functions need only
** have their names changed to the instrumentation function
** names.
**
** Private NSS Interface:
** nssilock.h defines a private interface for use by NSS.
** nssilock.h is experimental in nature and is subject to
** change or revocation without notice. ... Don't mess with
** it.
**
*/
/*
* $Id:
*/
#ifndef _NSSILOCK_H_
#define _NSSILOCK_H_
#include "utilrename.h"
#include "prtypes.h"
#include "prmon.h"
#include "prlock.h"
#include "prcvar.h"
#include "nssilckt.h"
PR_BEGIN_EXTERN_C
#if defined(NEED_NSS_ILOCK)
#define PZ_NewLock(t) pz_NewLock((t), __FILE__, __LINE__)
extern PZLock *
pz_NewLock(
nssILockType ltype,
char *file,
PRIntn line);
#define PZ_Lock(k) pz_Lock((k), __FILE__, __LINE__)
extern void
pz_Lock(
PZLock *lock,
char *file,
PRIntn line);
#define PZ_Unlock(k) pz_Unlock((k), __FILE__, __LINE__)
extern PRStatus
pz_Unlock(
PZLock *lock,
char *file,
PRIntn line);
#define PZ_DestroyLock(k) pz_DestroyLock((k), __FILE__, __LINE__)
extern void
pz_DestroyLock(
PZLock *lock,
char *file,
PRIntn line);
#define PZ_NewCondVar(l) pz_NewCondVar((l), __FILE__, __LINE__)
extern PZCondVar *
pz_NewCondVar(
PZLock *lock,
char *file,
PRIntn line);
#define PZ_DestroyCondVar(v) pz_DestroyCondVar((v), __FILE__, __LINE__)
extern void
pz_DestroyCondVar(
PZCondVar *cvar,
char *file,
PRIntn line);
#define PZ_WaitCondVar(v, t) pz_WaitCondVar((v), (t), __FILE__, __LINE__)
extern PRStatus
pz_WaitCondVar(
PZCondVar *cvar,
PRIntervalTime timeout,
char *file,
PRIntn line);
#define PZ_NotifyCondVar(v) pz_NotifyCondVar((v), __FILE__, __LINE__)
extern PRStatus
pz_NotifyCondVar(
PZCondVar *cvar,
char *file,
PRIntn line);
#define PZ_NotifyAllCondVar(v) pz_NotifyAllCondVar((v), __FILE__, __LINE__)
extern PRStatus
pz_NotifyAllCondVar(
PZCondVar *cvar,
char *file,
PRIntn line);
#define PZ_NewMonitor(t) pz_NewMonitor((t), __FILE__, __LINE__)
extern PZMonitor *
pz_NewMonitor(
nssILockType ltype,
char *file,
PRIntn line);
#define PZ_DestroyMonitor(m) pz_DestroyMonitor((m), __FILE__, __LINE__)
extern void
pz_DestroyMonitor(
PZMonitor *mon,
char *file,
PRIntn line);
#define PZ_EnterMonitor(m) pz_EnterMonitor((m), __FILE__, __LINE__)
extern void
pz_EnterMonitor(
PZMonitor *mon,
char *file,
PRIntn line);
#define PZ_ExitMonitor(m) pz_ExitMonitor((m), __FILE__, __LINE__)
extern PRStatus
pz_ExitMonitor(
PZMonitor *mon,
char *file,
PRIntn line);
#define PZ_InMonitor(m) (PZ_GetMonitorEntryCount(m) > 0)
#define PZ_GetMonitorEntryCount(m) pz_GetMonitorEntryCount((m), __FILE__, __LINE__)
extern PRIntn
pz_GetMonitorEntryCount(
PZMonitor *mon,
char *file,
PRIntn line);
#define PZ_Wait(m, i) pz_Wait((m), ((i)), __FILE__, __LINE__)
extern PRStatus
pz_Wait(
PZMonitor *mon,
PRIntervalTime ticks,
char *file,
PRIntn line);
#define PZ_Notify(m) pz_Notify((m), __FILE__, __LINE__)
extern PRStatus
pz_Notify(
PZMonitor *mon,
char *file,
PRIntn line);
#define PZ_NotifyAll(m) pz_NotifyAll((m), __FILE__, __LINE__)
extern PRStatus
pz_NotifyAll(
PZMonitor *mon,
char *file,
PRIntn line);
#define PZ_TraceFlush() pz_TraceFlush()
extern void pz_TraceFlush(void);
#else /* NEED_NSS_ILOCK */
#define PZ_NewLock(t) PR_NewLock()
#define PZ_DestroyLock(k) PR_DestroyLock((k))
#define PZ_Lock(k) PR_Lock((k))
#define PZ_Unlock(k) PR_Unlock((k))
#define PZ_NewCondVar(l) PR_NewCondVar((l))
#define PZ_DestroyCondVar(v) PR_DestroyCondVar((v))
#define PZ_WaitCondVar(v, t) PR_WaitCondVar((v), (t))
#define PZ_NotifyCondVar(v) PR_NotifyCondVar((v))
#define PZ_NotifyAllCondVar(v) PR_NotifyAllCondVar((v))
#define PZ_NewMonitor(t) PR_NewMonitor()
#define PZ_DestroyMonitor(m) PR_DestroyMonitor((m))
#define PZ_EnterMonitor(m) PR_EnterMonitor((m))
#define PZ_ExitMonitor(m) PR_ExitMonitor((m))
#define PZ_InMonitor(m) PR_InMonitor((m))
#define PZ_Wait(m, t) PR_Wait(((m)), ((t)))
#define PZ_Notify(m) PR_Notify((m))
#define PZ_NotifyAll(m) PR_Notify((m))
#define PZ_TraceFlush() /* nothing */
#endif /* NEED_NSS_ILOCK */
PR_END_EXTERN_C
#endif /* _NSSILOCK_H_ */
| {
"language": "C"
} |
#include <spawn.h>
int posix_spawnattr_getsigmask(const posix_spawnattr_t *restrict attr, sigset_t *restrict mask)
{
*mask = attr->__mask;
return 0;
}
| {
"language": "C"
} |
# HG changeset patch
# User Yichun Zhang <agentzh@gmail.com>
# Date 1390506359 28800
# Node ID 17186b98c235c07e94c64e5853689f790f173756
# Parent 4b50d1f299d8a69f3e3f7975132e1490352642fe
Variable: setting $args should invalidate unparsed uri.
diff -r 4b50d1f299d8 -r 17186b98c235 src/http/ngx_http_variables.c
--- a/src/http/ngx_http_variables.c Fri Jan 10 11:22:14 2014 -0800
+++ b/src/http/ngx_http_variables.c Thu Jan 23 11:45:59 2014 -0800
@@ -15,6 +15,8 @@
ngx_http_variable_value_t *v, uintptr_t data);
static void ngx_http_variable_request_set(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data);
+static void ngx_http_variable_request_args_set(ngx_http_request_t *r,
+ ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_http_variable_request_get_size(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data);
static void ngx_http_variable_request_set_size(ngx_http_request_t *r,
@@ -218,7 +220,7 @@
NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("args"),
- ngx_http_variable_request_set,
+ ngx_http_variable_request_args_set,
ngx_http_variable_request,
offsetof(ngx_http_request_t, args),
NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 },
@@ -647,6 +649,15 @@
static void
+ngx_http_variable_request_args_set(ngx_http_request_t *r,
+ ngx_http_variable_value_t *v, uintptr_t data)
+{
+ r->valid_unparsed_uri = 0;
+ ngx_http_variable_request_set(r, v, data);
+}
+
+
+static void
ngx_http_variable_request_set(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data)
{
| {
"language": "C"
} |
//YWROBOT
#ifndef LiquidCrystal_I2C_h
#define LiquidCrystal_I2C_h
#include <inttypes.h>
#include "Print.h"
#include <Wire.h>
// commands
#define LCD_CLEARDISPLAY 0x01
#define LCD_RETURNHOME 0x02
#define LCD_ENTRYMODESET 0x04
#define LCD_DISPLAYCONTROL 0x08
#define LCD_CURSORSHIFT 0x10
#define LCD_FUNCTIONSET 0x20
#define LCD_SETCGRAMADDR 0x40
#define LCD_SETDDRAMADDR 0x80
// flags for display entry mode
#define LCD_ENTRYRIGHT 0x00
#define LCD_ENTRYLEFT 0x02
#define LCD_ENTRYSHIFTINCREMENT 0x01
#define LCD_ENTRYSHIFTDECREMENT 0x00
// flags for display on/off control
#define LCD_DISPLAYON 0x04
#define LCD_DISPLAYOFF 0x00
#define LCD_CURSORON 0x02
#define LCD_CURSOROFF 0x00
#define LCD_BLINKON 0x01
#define LCD_BLINKOFF 0x00
// flags for display/cursor shift
#define LCD_DISPLAYMOVE 0x08
#define LCD_CURSORMOVE 0x00
#define LCD_MOVERIGHT 0x04
#define LCD_MOVELEFT 0x00
// flags for function set
#define LCD_8BITMODE 0x10
#define LCD_4BITMODE 0x00
#define LCD_2LINE 0x08
#define LCD_1LINE 0x00
#define LCD_5x10DOTS 0x04
#define LCD_5x8DOTS 0x00
// flags for backlight control
#define LCD_BACKLIGHT 0x08
#define LCD_NOBACKLIGHT 0x00
#define En B00000100 // Enable bit
#define Rw B00000010 // Read/Write bit
#define Rs B00000001 // Register select bit
class LiquidCrystal_I2C : public Print {
public:
LiquidCrystal_I2C(uint8_t lcd_Addr,uint8_t lcd_cols,uint8_t lcd_rows);
void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS );
void clear();
void home();
void noDisplay();
void display();
void noBlink();
void blink();
void noCursor();
void cursor();
void scrollDisplayLeft();
void scrollDisplayRight();
void printLeft();
void printRight();
void leftToRight();
void rightToLeft();
void shiftIncrement();
void shiftDecrement();
void noBacklight();
void backlight();
void autoscroll();
void noAutoscroll();
void createChar(uint8_t, uint8_t[]);
void setCursor(uint8_t, uint8_t);
#if defined(ARDUINO) && ARDUINO >= 100
virtual size_t write(uint8_t);
#else
virtual void write(uint8_t);
#endif
void command(uint8_t);
void init();
////compatibility API function aliases
void blink_on(); // alias for blink()
void blink_off(); // alias for noBlink()
void cursor_on(); // alias for cursor()
void cursor_off(); // alias for noCursor()
void setBacklight(uint8_t new_val); // alias for backlight() and nobacklight()
void load_custom_character(uint8_t char_num, uint8_t *rows); // alias for createChar()
void printstr(const char[]);
////Unsupported API functions (not implemented in this library)
uint8_t status();
void setContrast(uint8_t new_val);
uint8_t keypad();
void setDelay(int,int);
void on();
void off();
uint8_t init_bargraph(uint8_t graphtype);
void draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end);
void draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end);
private:
void init_priv();
void send(uint8_t, uint8_t);
void write4bits(uint8_t);
void expanderWrite(uint8_t);
void pulseEnable(uint8_t);
uint8_t _Addr;
uint8_t _displayfunction;
uint8_t _displaycontrol;
uint8_t _displaymode;
uint8_t _numlines;
uint8_t _cols;
uint8_t _rows;
uint8_t _backlightval;
};
#endif
| {
"language": "C"
} |
/* Automatically generated header! Do not edit! */
#ifndef _INLINE_VAMOSTEST_H
#define _INLINE_VAMOSTEST_H
#ifndef AROS_LIBCALL_H
#include <aros/libcall.h>
#endif /* !AROS_LIBCALL_H */
#ifndef VAMOSTEST_BASE_NAME
#define VAMOSTEST_BASE_NAME VamosTestBase
#endif /* !VAMOSTEST_BASE_NAME */
#define Add(___a, ___b) \
AROS_LC2(ULONG, Add, \
AROS_LCA(ULONG, (___a), D0), \
AROS_LCA(ULONG, (___b), D1), \
struct Library *, VAMOSTEST_BASE_NAME, 7, /* s */)
#define Dummy(___a, ___b) \
AROS_LC2(ULONG, Dummy, \
AROS_LCA(ULONG, (___a), D0), \
AROS_LCA(ULONG, (___b), D1), \
struct Library *, VAMOSTEST_BASE_NAME, 9, /* s */)
#define PrintHello() \
AROS_LC0(void, PrintHello, \
struct Library *, VAMOSTEST_BASE_NAME, 5, /* s */)
#define PrintString(___str) \
AROS_LC1(void, PrintString, \
AROS_LCA(STRPTR, (___str), A0), \
struct Library *, VAMOSTEST_BASE_NAME, 6, /* s */)
#define RaiseError(___str) \
AROS_LC1(void, RaiseError, \
AROS_LCA(STRPTR, (___str), A0), \
struct Library *, VAMOSTEST_BASE_NAME, 10, /* s */)
#define Swap(___a, ___b) \
AROS_LC2(ULONG, Swap, \
AROS_LCA(ULONG, (___a), D0), \
AROS_LCA(ULONG, (___b), D1), \
struct Library *, VAMOSTEST_BASE_NAME, 8, /* s */)
#endif /* !_INLINE_VAMOSTEST_H */
| {
"language": "C"
} |
/*
* FCC driver for Motorola MPC82xx (PQ2).
*
* Copyright (c) 2003 Intracom S.A.
* by Pantelis Antoniou <panto@intracom.gr>
*
* 2005 (c) MontaVista Software, Inc.
* Vitaly Bordug <vbordug@ru.mvista.com>
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/ptrace.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/bitops.h>
#include <linux/fs.h>
#include <linux/platform_device.h>
#include <linux/phy.h>
#include <linux/of_device.h>
#include <linux/gfp.h>
#include <asm/immap_cpm2.h>
#include <asm/mpc8260.h>
#include <asm/cpm2.h>
#include <asm/pgtable.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include "fs_enet.h"
/*************************************************/
/* FCC access macros */
/* write, read, set bits, clear bits */
#define W32(_p, _m, _v) out_be32(&(_p)->_m, (_v))
#define R32(_p, _m) in_be32(&(_p)->_m)
#define S32(_p, _m, _v) W32(_p, _m, R32(_p, _m) | (_v))
#define C32(_p, _m, _v) W32(_p, _m, R32(_p, _m) & ~(_v))
#define W16(_p, _m, _v) out_be16(&(_p)->_m, (_v))
#define R16(_p, _m) in_be16(&(_p)->_m)
#define S16(_p, _m, _v) W16(_p, _m, R16(_p, _m) | (_v))
#define C16(_p, _m, _v) W16(_p, _m, R16(_p, _m) & ~(_v))
#define W8(_p, _m, _v) out_8(&(_p)->_m, (_v))
#define R8(_p, _m) in_8(&(_p)->_m)
#define S8(_p, _m, _v) W8(_p, _m, R8(_p, _m) | (_v))
#define C8(_p, _m, _v) W8(_p, _m, R8(_p, _m) & ~(_v))
/*************************************************/
#define FCC_MAX_MULTICAST_ADDRS 64
#define mk_mii_read(REG) (0x60020000 | ((REG & 0x1f) << 18))
#define mk_mii_write(REG, VAL) (0x50020000 | ((REG & 0x1f) << 18) | (VAL & 0xffff))
#define mk_mii_end 0
#define MAX_CR_CMD_LOOPS 10000
static inline int fcc_cr_cmd(struct fs_enet_private *fep, u32 op)
{
const struct fs_platform_info *fpi = fep->fpi;
return cpm_command(fpi->cp_command, op);
}
static int do_pd_setup(struct fs_enet_private *fep)
{
struct platform_device *ofdev = to_platform_device(fep->dev);
struct fs_platform_info *fpi = fep->fpi;
int ret = -EINVAL;
fep->interrupt = of_irq_to_resource(ofdev->dev.of_node, 0, NULL);
if (fep->interrupt == NO_IRQ)
goto out;
fep->fcc.fccp = of_iomap(ofdev->dev.of_node, 0);
if (!fep->fcc.fccp)
goto out;
fep->fcc.ep = of_iomap(ofdev->dev.of_node, 1);
if (!fep->fcc.ep)
goto out_fccp;
fep->fcc.fcccp = of_iomap(ofdev->dev.of_node, 2);
if (!fep->fcc.fcccp)
goto out_ep;
fep->fcc.mem = (void __iomem *)cpm2_immr;
fpi->dpram_offset = cpm_dpalloc(128, 32);
if (IS_ERR_VALUE(fpi->dpram_offset)) {
ret = fpi->dpram_offset;
goto out_fcccp;
}
return 0;
out_fcccp:
iounmap(fep->fcc.fcccp);
out_ep:
iounmap(fep->fcc.ep);
out_fccp:
iounmap(fep->fcc.fccp);
out:
return ret;
}
#define FCC_NAPI_RX_EVENT_MSK (FCC_ENET_RXF | FCC_ENET_RXB)
#define FCC_RX_EVENT (FCC_ENET_RXF)
#define FCC_TX_EVENT (FCC_ENET_TXB)
#define FCC_ERR_EVENT_MSK (FCC_ENET_TXE)
static int setup_data(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
if (do_pd_setup(fep) != 0)
return -EINVAL;
fep->ev_napi_rx = FCC_NAPI_RX_EVENT_MSK;
fep->ev_rx = FCC_RX_EVENT;
fep->ev_tx = FCC_TX_EVENT;
fep->ev_err = FCC_ERR_EVENT_MSK;
return 0;
}
static int allocate_bd(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
const struct fs_platform_info *fpi = fep->fpi;
fep->ring_base = (void __iomem __force *)dma_alloc_coherent(fep->dev,
(fpi->tx_ring + fpi->rx_ring) *
sizeof(cbd_t), &fep->ring_mem_addr,
GFP_KERNEL);
if (fep->ring_base == NULL)
return -ENOMEM;
return 0;
}
static void free_bd(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
const struct fs_platform_info *fpi = fep->fpi;
if (fep->ring_base)
dma_free_coherent(fep->dev,
(fpi->tx_ring + fpi->rx_ring) * sizeof(cbd_t),
(void __force *)fep->ring_base, fep->ring_mem_addr);
}
static void cleanup_data(struct net_device *dev)
{
/* nothing */
}
static void set_promiscuous_mode(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
S32(fccp, fcc_fpsmr, FCC_PSMR_PRO);
}
static void set_multicast_start(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_enet_t __iomem *ep = fep->fcc.ep;
W32(ep, fen_gaddrh, 0);
W32(ep, fen_gaddrl, 0);
}
static void set_multicast_one(struct net_device *dev, const u8 *mac)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_enet_t __iomem *ep = fep->fcc.ep;
u16 taddrh, taddrm, taddrl;
taddrh = ((u16)mac[5] << 8) | mac[4];
taddrm = ((u16)mac[3] << 8) | mac[2];
taddrl = ((u16)mac[1] << 8) | mac[0];
W16(ep, fen_taddrh, taddrh);
W16(ep, fen_taddrm, taddrm);
W16(ep, fen_taddrl, taddrl);
fcc_cr_cmd(fep, CPM_CR_SET_GADDR);
}
static void set_multicast_finish(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
fcc_enet_t __iomem *ep = fep->fcc.ep;
/* clear promiscuous always */
C32(fccp, fcc_fpsmr, FCC_PSMR_PRO);
/* if all multi or too many multicasts; just enable all */
if ((dev->flags & IFF_ALLMULTI) != 0 ||
netdev_mc_count(dev) > FCC_MAX_MULTICAST_ADDRS) {
W32(ep, fen_gaddrh, 0xffffffff);
W32(ep, fen_gaddrl, 0xffffffff);
}
/* read back */
fep->fcc.gaddrh = R32(ep, fen_gaddrh);
fep->fcc.gaddrl = R32(ep, fen_gaddrl);
}
static void set_multicast_list(struct net_device *dev)
{
struct netdev_hw_addr *ha;
if ((dev->flags & IFF_PROMISC) == 0) {
set_multicast_start(dev);
netdev_for_each_mc_addr(ha, dev)
set_multicast_one(dev, ha->addr);
set_multicast_finish(dev);
} else
set_promiscuous_mode(dev);
}
static void restart(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
const struct fs_platform_info *fpi = fep->fpi;
fcc_t __iomem *fccp = fep->fcc.fccp;
fcc_c_t __iomem *fcccp = fep->fcc.fcccp;
fcc_enet_t __iomem *ep = fep->fcc.ep;
dma_addr_t rx_bd_base_phys, tx_bd_base_phys;
u16 paddrh, paddrm, paddrl;
const unsigned char *mac;
int i;
C32(fccp, fcc_gfmr, FCC_GFMR_ENR | FCC_GFMR_ENT);
/* clear everything (slow & steady does it) */
for (i = 0; i < sizeof(*ep); i++)
out_8((u8 __iomem *)ep + i, 0);
/* get physical address */
rx_bd_base_phys = fep->ring_mem_addr;
tx_bd_base_phys = rx_bd_base_phys + sizeof(cbd_t) * fpi->rx_ring;
/* point to bds */
W32(ep, fen_genfcc.fcc_rbase, rx_bd_base_phys);
W32(ep, fen_genfcc.fcc_tbase, tx_bd_base_phys);
/* Set maximum bytes per receive buffer.
* It must be a multiple of 32.
*/
W16(ep, fen_genfcc.fcc_mrblr, PKT_MAXBLR_SIZE);
W32(ep, fen_genfcc.fcc_rstate, (CPMFCR_GBL | CPMFCR_EB) << 24);
W32(ep, fen_genfcc.fcc_tstate, (CPMFCR_GBL | CPMFCR_EB) << 24);
/* Allocate space in the reserved FCC area of DPRAM for the
* internal buffers. No one uses this space (yet), so we
* can do this. Later, we will add resource management for
* this area.
*/
W16(ep, fen_genfcc.fcc_riptr, fpi->dpram_offset);
W16(ep, fen_genfcc.fcc_tiptr, fpi->dpram_offset + 32);
W16(ep, fen_padptr, fpi->dpram_offset + 64);
/* fill with special symbol... */
memset_io(fep->fcc.mem + fpi->dpram_offset + 64, 0x88, 32);
W32(ep, fen_genfcc.fcc_rbptr, 0);
W32(ep, fen_genfcc.fcc_tbptr, 0);
W32(ep, fen_genfcc.fcc_rcrc, 0);
W32(ep, fen_genfcc.fcc_tcrc, 0);
W16(ep, fen_genfcc.fcc_res1, 0);
W32(ep, fen_genfcc.fcc_res2, 0);
/* no CAM */
W32(ep, fen_camptr, 0);
/* Set CRC preset and mask */
W32(ep, fen_cmask, 0xdebb20e3);
W32(ep, fen_cpres, 0xffffffff);
W32(ep, fen_crcec, 0); /* CRC Error counter */
W32(ep, fen_alec, 0); /* alignment error counter */
W32(ep, fen_disfc, 0); /* discard frame counter */
W16(ep, fen_retlim, 15); /* Retry limit threshold */
W16(ep, fen_pper, 0); /* Normal persistence */
/* set group address */
W32(ep, fen_gaddrh, fep->fcc.gaddrh);
W32(ep, fen_gaddrl, fep->fcc.gaddrh);
/* Clear hash filter tables */
W32(ep, fen_iaddrh, 0);
W32(ep, fen_iaddrl, 0);
/* Clear the Out-of-sequence TxBD */
W16(ep, fen_tfcstat, 0);
W16(ep, fen_tfclen, 0);
W32(ep, fen_tfcptr, 0);
W16(ep, fen_mflr, PKT_MAXBUF_SIZE); /* maximum frame length register */
W16(ep, fen_minflr, PKT_MINBUF_SIZE); /* minimum frame length register */
/* set address */
mac = dev->dev_addr;
paddrh = ((u16)mac[5] << 8) | mac[4];
paddrm = ((u16)mac[3] << 8) | mac[2];
paddrl = ((u16)mac[1] << 8) | mac[0];
W16(ep, fen_paddrh, paddrh);
W16(ep, fen_paddrm, paddrm);
W16(ep, fen_paddrl, paddrl);
W16(ep, fen_taddrh, 0);
W16(ep, fen_taddrm, 0);
W16(ep, fen_taddrl, 0);
W16(ep, fen_maxd1, 1520); /* maximum DMA1 length */
W16(ep, fen_maxd2, 1520); /* maximum DMA2 length */
/* Clear stat counters, in case we ever enable RMON */
W32(ep, fen_octc, 0);
W32(ep, fen_colc, 0);
W32(ep, fen_broc, 0);
W32(ep, fen_mulc, 0);
W32(ep, fen_uspc, 0);
W32(ep, fen_frgc, 0);
W32(ep, fen_ospc, 0);
W32(ep, fen_jbrc, 0);
W32(ep, fen_p64c, 0);
W32(ep, fen_p65c, 0);
W32(ep, fen_p128c, 0);
W32(ep, fen_p256c, 0);
W32(ep, fen_p512c, 0);
W32(ep, fen_p1024c, 0);
W16(ep, fen_rfthr, 0); /* Suggested by manual */
W16(ep, fen_rfcnt, 0);
W16(ep, fen_cftype, 0);
fs_init_bds(dev);
/* adjust to speed (for RMII mode) */
if (fpi->use_rmii) {
if (fep->phydev->speed == 100)
C8(fcccp, fcc_gfemr, 0x20);
else
S8(fcccp, fcc_gfemr, 0x20);
}
fcc_cr_cmd(fep, CPM_CR_INIT_TRX);
/* clear events */
W16(fccp, fcc_fcce, 0xffff);
/* Enable interrupts we wish to service */
W16(fccp, fcc_fccm, FCC_ENET_TXE | FCC_ENET_RXF | FCC_ENET_TXB);
/* Set GFMR to enable Ethernet operating mode */
W32(fccp, fcc_gfmr, FCC_GFMR_TCI | FCC_GFMR_MODE_ENET);
/* set sync/delimiters */
W16(fccp, fcc_fdsr, 0xd555);
W32(fccp, fcc_fpsmr, FCC_PSMR_ENCRC);
if (fpi->use_rmii)
S32(fccp, fcc_fpsmr, FCC_PSMR_RMII);
/* adjust to duplex mode */
if (fep->phydev->duplex)
S32(fccp, fcc_fpsmr, FCC_PSMR_FDE | FCC_PSMR_LPB);
else
C32(fccp, fcc_fpsmr, FCC_PSMR_FDE | FCC_PSMR_LPB);
/* Restore multicast and promiscuous settings */
set_multicast_list(dev);
S32(fccp, fcc_gfmr, FCC_GFMR_ENR | FCC_GFMR_ENT);
}
static void stop(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
/* stop ethernet */
C32(fccp, fcc_gfmr, FCC_GFMR_ENR | FCC_GFMR_ENT);
/* clear events */
W16(fccp, fcc_fcce, 0xffff);
/* clear interrupt mask */
W16(fccp, fcc_fccm, 0);
fs_cleanup_bds(dev);
}
static void napi_clear_rx_event(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
W16(fccp, fcc_fcce, FCC_NAPI_RX_EVENT_MSK);
}
static void napi_enable_rx(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
S16(fccp, fcc_fccm, FCC_NAPI_RX_EVENT_MSK);
}
static void napi_disable_rx(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
C16(fccp, fcc_fccm, FCC_NAPI_RX_EVENT_MSK);
}
static void rx_bd_done(struct net_device *dev)
{
/* nothing */
}
static void tx_kickstart(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
S16(fccp, fcc_ftodr, 0x8000);
}
static u32 get_int_events(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
return (u32)R16(fccp, fcc_fcce);
}
static void clear_int_events(struct net_device *dev, u32 int_events)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
W16(fccp, fcc_fcce, int_events & 0xffff);
}
static void ev_error(struct net_device *dev, u32 int_events)
{
struct fs_enet_private *fep = netdev_priv(dev);
dev_warn(fep->dev, "FS_ENET ERROR(s) 0x%x\n", int_events);
}
static int get_regs(struct net_device *dev, void *p, int *sizep)
{
struct fs_enet_private *fep = netdev_priv(dev);
if (*sizep < sizeof(fcc_t) + sizeof(fcc_enet_t) + 1)
return -EINVAL;
memcpy_fromio(p, fep->fcc.fccp, sizeof(fcc_t));
p = (char *)p + sizeof(fcc_t);
memcpy_fromio(p, fep->fcc.ep, sizeof(fcc_enet_t));
p = (char *)p + sizeof(fcc_enet_t);
memcpy_fromio(p, fep->fcc.fcccp, 1);
return 0;
}
static int get_regs_len(struct net_device *dev)
{
return sizeof(fcc_t) + sizeof(fcc_enet_t) + 1;
}
/* Some transmit errors cause the transmitter to shut
* down. We now issue a restart transmit.
* Also, to workaround 8260 device erratum CPM37, we must
* disable and then re-enable the transmitterfollowing a
* Late Collision, Underrun, or Retry Limit error.
* In addition, tbptr may point beyond BDs beyond still marked
* as ready due to internal pipelining, so we need to look back
* through the BDs and adjust tbptr to point to the last BD
* marked as ready. This may result in some buffers being
* retransmitted.
*/
static void tx_restart(struct net_device *dev)
{
struct fs_enet_private *fep = netdev_priv(dev);
fcc_t __iomem *fccp = fep->fcc.fccp;
const struct fs_platform_info *fpi = fep->fpi;
fcc_enet_t __iomem *ep = fep->fcc.ep;
cbd_t __iomem *curr_tbptr;
cbd_t __iomem *recheck_bd;
cbd_t __iomem *prev_bd;
cbd_t __iomem *last_tx_bd;
last_tx_bd = fep->tx_bd_base + (fpi->tx_ring * sizeof(cbd_t));
/* get the current bd held in TBPTR and scan back from this point */
recheck_bd = curr_tbptr = (cbd_t __iomem *)
((R32(ep, fen_genfcc.fcc_tbptr) - fep->ring_mem_addr) +
fep->ring_base);
prev_bd = (recheck_bd == fep->tx_bd_base) ? last_tx_bd : recheck_bd - 1;
/* Move through the bds in reverse, look for the earliest buffer
* that is not ready. Adjust TBPTR to the following buffer */
while ((CBDR_SC(prev_bd) & BD_ENET_TX_READY) != 0) {
/* Go back one buffer */
recheck_bd = prev_bd;
/* update the previous buffer */
prev_bd = (prev_bd == fep->tx_bd_base) ? last_tx_bd : prev_bd - 1;
/* We should never see all bds marked as ready, check anyway */
if (recheck_bd == curr_tbptr)
break;
}
/* Now update the TBPTR and dirty flag to the current buffer */
W32(ep, fen_genfcc.fcc_tbptr,
(uint) (((void *)recheck_bd - fep->ring_base) +
fep->ring_mem_addr));
fep->dirty_tx = recheck_bd;
C32(fccp, fcc_gfmr, FCC_GFMR_ENT);
udelay(10);
S32(fccp, fcc_gfmr, FCC_GFMR_ENT);
fcc_cr_cmd(fep, CPM_CR_RESTART_TX);
}
/*************************************************************************/
const struct fs_ops fs_fcc_ops = {
.setup_data = setup_data,
.cleanup_data = cleanup_data,
.set_multicast_list = set_multicast_list,
.restart = restart,
.stop = stop,
.napi_clear_rx_event = napi_clear_rx_event,
.napi_enable_rx = napi_enable_rx,
.napi_disable_rx = napi_disable_rx,
.rx_bd_done = rx_bd_done,
.tx_kickstart = tx_kickstart,
.get_int_events = get_int_events,
.clear_int_events = clear_int_events,
.ev_error = ev_error,
.get_regs = get_regs,
.get_regs_len = get_regs_len,
.tx_restart = tx_restart,
.allocate_bd = allocate_bd,
.free_bd = free_bd,
};
| {
"language": "C"
} |
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code 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 Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_util.h
*
* desc: utils
*
* $Archive: /source/code/botlib/l_util.h $
*
*****************************************************************************/
#define Vector2Angles(v,a) vectoangles(v,a)
#define MAX_PATH MAX_QPATH
#define Maximum(x,y) (x > y ? x : y)
#define Minimum(x,y) (x < y ? x : y)
| {
"language": "C"
} |
/***************************************************
* 版权声明
*
* 本操作系统名为:MINE
* 该操作系统未经授权不得以盈利或非盈利为目的进行开发,
* 只允许个人学习以及公开交流使用
*
* 代码最终所有权及解释权归田宇所有;
*
* 本模块作者: 田宇
* EMail: 345538255@qq.com
*
*
***************************************************/
#ifndef __APIC_H__
#define __APIC_H__
#include "linkage.h"
#include "ptrace.h"
#include "interrupt.h"
/*
*/
struct IOAPIC_map
{
unsigned int physical_address;
unsigned char * virtual_index_address;
unsigned int * virtual_data_address;
unsigned int * virtual_EOI_address;
}ioapic_map;
unsigned long ioapic_rte_read(unsigned char index);
void ioapic_rte_write(unsigned char index,unsigned long value);
/*
*/
void IOAPIC_pagetable_remap();
/*
*/
void do_IRQ(struct pt_regs * regs,unsigned long nr);
/*
*/
void APIC_IOAPIC_init();
void Local_APIC_init();
void IOAPIC_init();
#endif
| {
"language": "C"
} |
%{
/*
* Copyright (c) 1998 - 2000 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* 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 Institute 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 INSTITUTE 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 INSTITUTE 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 "compile_et.h"
#include "lex.h"
void yyerror (char *s);
static long name2number(const char *str);
extern char *yytext;
/* This is for bison */
#if !defined(alloca) && !defined(HAVE_ALLOCA)
#define alloca(x) malloc(x)
#endif
#define YYMALLOC malloc
#define YYFREE free
%}
%union {
char *string;
int number;
}
%token ET INDEX PREFIX EC ID END
%token <string> STRING
%token <number> NUMBER
%%
file : /* */
| header statements
;
header : id et
| et
;
id : ID STRING
{
id_str = $2;
}
;
et : ET STRING
{
base_id = name2number($2);
strlcpy(name, $2, sizeof(name));
free($2);
}
| ET STRING STRING
{
base_id = name2number($2);
strlcpy(name, $3, sizeof(name));
free($2);
free($3);
}
;
statements : statement
| statements statement
;
statement : INDEX NUMBER
{
number = $2;
}
| PREFIX STRING
{
free(prefix);
asprintf (&prefix, "%s_", $2);
if (prefix == NULL)
errx(1, "malloc");
free($2);
}
| PREFIX
{
prefix = realloc(prefix, 1);
if (prefix == NULL)
errx(1, "malloc");
*prefix = '\0';
}
| EC STRING ',' STRING
{
struct error_code *ec = malloc(sizeof(*ec));
if (ec == NULL)
errx(1, "malloc");
ec->next = NULL;
ec->number = number;
if(prefix && *prefix != '\0') {
asprintf (&ec->name, "%s%s", prefix, $2);
if (ec->name == NULL)
errx(1, "malloc");
free($2);
} else
ec->name = $2;
ec->string = $4;
APPEND(codes, ec);
number++;
}
| END
{
YYACCEPT;
}
;
%%
static long
name2number(const char *str)
{
const char *p;
long num = 0;
const char *x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz0123456789_";
if(strlen(str) > 4) {
yyerror("table name too long");
return 0;
}
for(p = str; *p; p++){
char *q = strchr(x, *p);
if(q == NULL) {
yyerror("invalid character in table name");
return 0;
}
num = (num << 6) + (q - x) + 1;
}
num <<= 8;
if(num > 0x7fffffff)
num = -(0xffffffff - num + 1);
return num;
}
void
yyerror (char *s)
{
_lex_error_message ("%s\n", s);
}
| {
"language": "C"
} |
/*
* librdkafka - Apache Kafka C library
*
* Copyright (c) 2017 Magnus Edenhill
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef _WIN32
#define RD_UNITTEST_QPC_OVERRIDES 1
#endif
#include "rd.h"
#include "rdunittest.h"
#include "rdvarint.h"
#include "rdbuf.h"
#include "crc32c.h"
#include "rdmurmur2.h"
#include "rdfnv1a.h"
#if WITH_HDRHISTOGRAM
#include "rdhdrhistogram.h"
#endif
#include "rdkafka_int.h"
#include "rdkafka_broker.h"
#include "rdkafka_request.h"
#include "rdsysqueue.h"
#include "rdkafka_sasl_oauthbearer.h"
#include "rdkafka_msgset.h"
#include "rdkafka_txnmgr.h"
rd_bool_t rd_unittest_assert_on_failure = rd_false;
rd_bool_t rd_unittest_on_ci = rd_false;
rd_bool_t rd_unittest_slow = rd_false;
#if ENABLE_CODECOV
/**
* @name Code coverage
* @{
*/
static rd_atomic64_t rd_ut_covnrs[RD_UT_COVNR_MAX+1];
void rd_ut_coverage (const char *file, const char *func, int line, int covnr) {
rd_assert(covnr >= 0 && covnr <= RD_UT_COVNR_MAX);
rd_atomic64_add(&rd_ut_covnrs[covnr], 1);
}
int64_t rd_ut_coverage_check (const char *file, const char *func, int line,
int covnr) {
int64_t r;
rd_assert(covnr >= 0 && covnr <= RD_UT_COVNR_MAX);
r = rd_atomic64_get(&rd_ut_covnrs[covnr]);
if (!r) {
fprintf(stderr,
"\033[31m"
"RDUT: FAIL: %s:%d: %s: "
"Code coverage nr %d: FAIL: "
"code path not executed: "
"perform `grep -RnF 'COVERAGE(%d)' src/` to find "
"source location"
"\033[0m\n",
file, line, func, covnr, covnr);
if (rd_unittest_assert_on_failure)
rd_assert(!*"unittest failure");
return 0;
}
fprintf(stderr,
"\033[34mRDUT: CCOV: %s:%d: %s: Code coverage nr %d: "
"PASS (%"PRId64" code path execution(s))\033[0m\n",
file, line, func, covnr, r);
return r;
}
/**@}*/
#endif /* ENABLE_CODECOV */
/**
* @name Test rdsysqueue.h / queue.h
* @{
*/
struct ut_tq {
TAILQ_ENTRY(ut_tq) link;
int v;
};
TAILQ_HEAD(ut_tq_head, ut_tq);
struct ut_tq_args {
const char *name; /**< Descriptive test name */
struct {
int base; /**< Base value */
int cnt; /**< Number of elements to add */
int step; /**< Value step */
} q[3]; /**< Queue element definition */
int qcnt; /**< Number of defs in .q */
int exp[16]; /**< Expected value order after join */
};
/**
* @brief Find the previous element (insert position) for
* value \p val in list \p head or NULL if \p val is less than
* the first element in \p head.
* @remarks \p head must be ascending sorted.
*/
static struct ut_tq *ut_tq_find_prev_pos (const struct ut_tq_head *head,
int val) {
struct ut_tq *e, *prev = NULL;
TAILQ_FOREACH(e, head, link) {
if (e->v > val)
return prev;
prev = e;
}
return prev;
}
static int ut_tq_test (const struct ut_tq_args *args) {
int totcnt = 0;
int fails = 0;
struct ut_tq_head *tqh[3];
struct ut_tq *e, *insert_after;
int i, qi;
RD_UT_SAY("Testing TAILQ: %s", args->name);
/*
* Verify TAILQ_INSERT_LIST:
* For each insert position test:
* - create two lists: tqh 0 and 1
* - add entries to both lists
* - insert list 1 into 0
* - verify expected order and correctness
*/
/* Use heap allocated heads to let valgrind/asan assist
* in detecting corruption. */
for (qi = 0 ; qi < args->qcnt ; qi++) {
tqh[qi] = rd_calloc(1, sizeof(*tqh[qi]));
TAILQ_INIT(tqh[qi]);
for (i = 0 ; i < args->q[qi].cnt ; i++) {
e = rd_malloc(sizeof(*e));
e->v = args->q[qi].base + (i * args->q[qi].step);
TAILQ_INSERT_TAIL(tqh[qi], e, link);
}
totcnt += args->q[qi].cnt;
}
for (qi = 1 ; qi < args->qcnt ; qi++) {
insert_after = ut_tq_find_prev_pos(tqh[0], args->q[qi].base);
if (!insert_after) {
/* Insert position is head of list,
* do two-step concat+move */
TAILQ_PREPEND(tqh[0], tqh[qi], ut_tq_head, link);
} else {
TAILQ_INSERT_LIST(tqh[0], insert_after, tqh[qi],
ut_tq_head,
struct ut_tq *, link);
}
RD_UT_ASSERT(TAILQ_EMPTY(tqh[qi]),
"expected empty tqh[%d]", qi);
RD_UT_ASSERT(!TAILQ_EMPTY(tqh[0]), "expected non-empty tqh[0]");
memset(tqh[qi], (int)'A', sizeof(*tqh[qi]));
rd_free(tqh[qi]);
}
RD_UT_ASSERT(TAILQ_LAST(tqh[0], ut_tq_head)->v == args->exp[totcnt-1],
"TAILQ_LAST val %d, expected %d",
TAILQ_LAST(tqh[0], ut_tq_head)->v, args->exp[totcnt-1]);
/* Add sentinel value to verify that INSERT_TAIL works
* after INSERT_LIST */
e = rd_malloc(sizeof(*e));
e->v = 99;
TAILQ_INSERT_TAIL(tqh[0], e, link);
totcnt++;
i = 0;
TAILQ_FOREACH(e, tqh[0], link) {
if (i >= totcnt) {
RD_UT_WARN("Too many elements in list tqh[0]: "
"idx %d > totcnt %d: element %p (value %d)",
i, totcnt, e, e->v);
fails++;
} else if (e->v != args->exp[i]) {
RD_UT_WARN("Element idx %d/%d in tqh[0] has value %d, "
"expected %d",
i, totcnt, e->v, args->exp[i]);
fails++;
} else if (i == totcnt - 1 &&
e != TAILQ_LAST(tqh[0], ut_tq_head)) {
RD_UT_WARN("TAILQ_LAST == %p, expected %p",
TAILQ_LAST(tqh[0], ut_tq_head), e);
fails++;
}
i++;
}
/* Then scan it in reverse */
i = totcnt - 1;
TAILQ_FOREACH_REVERSE(e, tqh[0], ut_tq_head, link) {
if (i < 0) {
RD_UT_WARN("REVERSE: Too many elements in list tqh[0]: "
"idx %d < 0: element %p (value %d)",
i, e, e->v);
fails++;
} else if (e->v != args->exp[i]) {
RD_UT_WARN("REVERSE: Element idx %d/%d in tqh[0] has "
"value %d, expected %d",
i, totcnt, e->v, args->exp[i]);
fails++;
} else if (i == totcnt - 1 &&
e != TAILQ_LAST(tqh[0], ut_tq_head)) {
RD_UT_WARN("REVERSE: TAILQ_LAST == %p, expected %p",
TAILQ_LAST(tqh[0], ut_tq_head), e);
fails++;
}
i--;
}
RD_UT_ASSERT(TAILQ_LAST(tqh[0], ut_tq_head)->v == args->exp[totcnt-1],
"TAILQ_LAST val %d, expected %d",
TAILQ_LAST(tqh[0], ut_tq_head)->v, args->exp[totcnt-1]);
while ((e = TAILQ_FIRST(tqh[0]))) {
TAILQ_REMOVE(tqh[0], e, link);
rd_free(e);
}
rd_free(tqh[0]);
return fails;
}
static int unittest_sysqueue (void) {
const struct ut_tq_args args[] = {
{
"empty tqh[0]",
{
{ 0, 0, 0 },
{ 0, 3, 1 }
},
2,
{ 0, 1, 2, 99 /*sentinel*/ }
},
{
"prepend 1,0",
{
{ 10, 3, 1 },
{ 0, 3, 1 }
},
2,
{ 0, 1, 2, 10, 11, 12, 99 }
},
{
"prepend 2,1,0",
{
{ 10, 3, 1 }, /* 10, 11, 12 */
{ 5, 3, 1 }, /* 5, 6, 7 */
{ 0, 2, 1 } /* 0, 1 */
},
3,
{ 0, 1, 5, 6, 7, 10, 11, 12, 99 }
},
{
"insert 1",
{
{ 0, 3, 2 },
{ 1, 2, 2 }
},
2,
{ 0, 1, 3, 2, 4, 99 }
},
{
"insert 1,2",
{
{ 0, 3, 3 }, /* 0, 3, 6 */
{ 1, 2, 3 }, /* 1, 4 */
{ 2, 1, 3 } /* 2 */
},
3,
{ 0, 1, 2, 4, 3, 6, 99 }
},
{
"append 1",
{
{ 0, 5, 1 },
{ 5, 5, 1 }
},
2,
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99 }
},
{
"append 1,2",
{
{ 0, 5, 1 }, /* 0, 1, 2, 3, 4 */
{ 5, 5, 1 }, /* 5, 6, 7, 8, 9 */
{ 11, 2, 1 } /* 11, 12 */
},
3,
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 99 }
},
{
"insert 1,0,2",
{
{ 5, 3, 1 }, /* 5, 6, 7 */
{ 0, 1, 1 }, /* 0 */
{ 10, 2, 1 } /* 10, 11 */
},
3,
{ 0, 5, 6, 7, 10, 11, 99 },
},
{
"insert 2,0,1",
{
{ 5, 3, 1 }, /* 5, 6, 7 */
{ 10, 2, 1 }, /* 10, 11 */
{ 0, 1, 1 } /* 0 */
},
3,
{ 0, 5, 6, 7, 10, 11, 99 },
},
{
NULL
}
};
int i;
int fails = 0;
for (i = 0 ; args[i].name != NULL; i++)
fails += ut_tq_test(&args[i]);
RD_UT_ASSERT(!fails, "See %d previous failure(s)", fails);
RD_UT_PASS();
}
/**@}*/
/**
* @name rd_clock() unittests
* @{
*/
#if RD_UNITTEST_QPC_OVERRIDES
/**
* These values are based off a machine with freq 14318180
* which would cause the original rd_clock() calculation to overflow
* after about 8 days.
* Details:
* https://github.com/confluentinc/confluent-kafka-dotnet/issues/603#issuecomment-417274540
*/
static const int64_t rd_ut_qpc_freq = 14318180;
static int64_t rd_ut_qpc_now;
BOOL rd_ut_QueryPerformanceFrequency(_Out_ LARGE_INTEGER * lpFrequency) {
lpFrequency->QuadPart = rd_ut_qpc_freq;
return TRUE;
}
BOOL rd_ut_QueryPerformanceCounter(_Out_ LARGE_INTEGER * lpPerformanceCount) {
lpPerformanceCount->QuadPart = rd_ut_qpc_now * rd_ut_qpc_freq;
return TRUE;
}
static int unittest_rdclock (void) {
rd_ts_t t1, t2;
/* First let "uptime" be fresh boot (0). */
rd_ut_qpc_now = 0;
t1 = rd_clock();
rd_ut_qpc_now++;
t2 = rd_clock();
RD_UT_ASSERT(t2 == t1 + (1 * 1000000),
"Expected t2 %"PRId64" to be 1s more than t1 %"PRId64,
t2, t1);
/* Then skip forward to 8 days, which should trigger the
* overflow in a faulty implementation. */
rd_ut_qpc_now = 8 * 86400;
t2 = rd_clock();
RD_UT_ASSERT(t2 == t1 + (8LL * 86400 * 1000000),
"Expected t2 %"PRId64" to be 8 days larger than t1 %"PRId64,
t2, t1);
/* And make sure we can run on a system with 38 years of uptime.. */
rd_ut_qpc_now = 38 * 365 * 86400;
t2 = rd_clock();
RD_UT_ASSERT(t2 == t1 + (38LL * 365 * 86400 * 1000000),
"Expected t2 %"PRId64" to be 38 years larger than t1 %"PRId64,
t2, t1);
RD_UT_PASS();
}
#endif
/**@}*/
extern int unittest_cgrp (void);
#if WITH_SASL_SCRAM
extern int unittest_scram (void);
#endif
extern int unittest_assignors (void);
int rd_unittest (void) {
int fails = 0;
const struct {
const char *name;
int (*call) (void);
} unittests[] = {
{ "sysqueue", unittest_sysqueue },
{ "rdbuf", unittest_rdbuf },
{ "rdvarint", unittest_rdvarint },
{ "crc32c", unittest_crc32c },
{ "msg", unittest_msg },
{ "murmurhash", unittest_murmur2 },
{ "fnv1a", unittest_fnv1a },
#if WITH_HDRHISTOGRAM
{ "rdhdrhistogram", unittest_rdhdrhistogram },
#endif
#ifdef _WIN32
{ "rdclock", unittest_rdclock },
#endif
{ "conf", unittest_conf },
{ "broker", unittest_broker },
{ "request", unittest_request },
#if WITH_SASL_OAUTHBEARER
{ "sasl_oauthbearer", unittest_sasl_oauthbearer },
#endif
{ "aborted_txns", unittest_aborted_txns },
{ "cgrp", unittest_cgrp },
#if WITH_SASL_SCRAM
{ "scram", unittest_scram },
#endif
{ "assignors", unittest_assignors },
{ NULL }
};
int i;
const char *match = rd_getenv("RD_UT_TEST", NULL);
int cnt = 0;
if (rd_getenv("RD_UT_ASSERT", NULL))
rd_unittest_assert_on_failure = rd_true;
if (rd_getenv("CI", NULL)) {
RD_UT_SAY("Unittests running on CI");
rd_unittest_on_ci = rd_true;
}
if (rd_unittest_on_ci || (ENABLE_DEVEL + 0)) {
RD_UT_SAY("Unittests will not error out on slow CPUs");
rd_unittest_slow = rd_true;
}
rd_kafka_global_init();
#if ENABLE_CODECOV
for (i = 0 ; i < RD_UT_COVNR_MAX+1 ; i++)
rd_atomic64_init(&rd_ut_covnrs[i], 0);
#endif
for (i = 0 ; unittests[i].name ; i++) {
int f;
if (match && strcmp(match, unittests[i].name))
continue;
f = unittests[i].call();
RD_UT_SAY("unittest: %s: %4s\033[0m",
unittests[i].name,
f ? "\033[31mFAIL" : "\033[32mPASS");
fails += f;
cnt++;
}
#if ENABLE_CODECOV
#if FIXME /* This check only works if all tests that use coverage checks
* are run, which we can't really know, so disable until we
* know what to do with this. */
if (!match) {
/* Verify all code paths were covered */
int cov_fails = 0;
for (i = 0 ; i < RD_UT_COVNR_MAX+1 ; i++) {
if (!RD_UT_COVERAGE_CHECK(i))
cov_fails++;
}
if (cov_fails > 0)
RD_UT_SAY("%d code coverage failure(s) (ignored)\n",
cov_fails);
}
#endif
#endif
if (!cnt && match)
RD_UT_WARN("No unittests matching \"%s\"", match);
return fails;
}
| {
"language": "C"
} |
/* src/config.h. Generated from config.h.in by configure. */
/* src/config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the <ext/rope> header file. */
/* #undef HAVE_EXT_ROPE */
/* Define to 1 if you have the <fnmatch.h> header file. */
#define HAVE_FNMATCH_H 1
/* Define to 1 if you have the <getopt.h> header file. */
#define HAVE_GETOPT_H 1
/* Define to 1 if you have the `gettimeofday' function. */
#define HAVE_GETTIMEOFDAY 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <malloc.h> header file. */
/* Manual edit: This is defined in AndroidConfig.h. */
#undef HAVE_MALLOC_H
#define HAVE_MALLOC_H 1
/* Define to 1 if you have the `memalign' function. */
#define HAVE_MEMALIGN 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `mprotect' function. */
#define HAVE_MPROTECT 1
/* Define to 1 if you have the `posix_memalign' function. */
#define HAVE_POSIX_MEMALIGN 1
/* Define to 1 if you have the `QueryPerformanceCounter' function. */
/* #undef HAVE_QUERYPERFORMANCECOUNTER */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strtoll' function. */
#define HAVE_STRTOLL 1
/* Define to 1 if you have the `strtoq' function. */
#define HAVE_STRTOQ 1
/* Define to 1 if you have the <sys/mman.h> header file. */
#define HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if the system has the type `uint16_t'. */
#define HAVE_UINT16_T 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if the system has the type `u_int16_t'. */
#define HAVE_U_INT16_T 1
/* Define to 1 if you have the <windows.h> header file. */
/* #undef HAVE_WINDOWS_H */
/* define if your compiler has __attribute__ */
#define HAVE___ATTRIBUTE__ 1
/* Define to 1 if the system has the type `__int16'. */
/* #undef HAVE___INT16 */
/* Name of package */
#define PACKAGE "open-vcdiff"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "opensource@google.com"
/* Define to the full name of this package. */
#define PACKAGE_NAME "open-vcdiff"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "open-vcdiff 0.7"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "open-vcdiff"
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.7"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Use custom compare function instead of memcmp */
#if defined(__i386__) || defined(__x86_64__)
#define VCDIFF_USE_BLOCK_COMPARE_WORDS 1
#else
/* #undef VCDIFF_USE_BLOCK_COMPARE_WORDS */
#endif
/* Version number of package */
#define VERSION "0.7"
| {
"language": "C"
} |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (c) 2016 Maxime Ripard. All rights reserved.
*/
#include <linux/clk-provider.h>
#include <linux/io.h>
#include <linux/of_address.h>
#include <linux/platform_device.h>
#include "ccu_common.h"
#include "ccu_reset.h"
#include "ccu_div.h"
#include "ccu_gate.h"
#include "ccu_mp.h"
#include "ccu_mult.h"
#include "ccu_nk.h"
#include "ccu_nkm.h"
#include "ccu_nkmp.h"
#include "ccu_nm.h"
#include "ccu_phase.h"
#include "ccu-sun50i-a64.h"
static struct ccu_nkmp pll_cpux_clk = {
.enable = BIT(31),
.lock = BIT(28),
.n = _SUNXI_CCU_MULT(8, 5),
.k = _SUNXI_CCU_MULT(4, 2),
.m = _SUNXI_CCU_DIV(0, 2),
.p = _SUNXI_CCU_DIV_MAX(16, 2, 4),
.common = {
.reg = 0x000,
.hw.init = CLK_HW_INIT("pll-cpux",
"osc24M",
&ccu_nkmp_ops,
CLK_SET_RATE_UNGATE),
},
};
/*
* The Audio PLL is supposed to have 4 outputs: 3 fixed factors from
* the base (2x, 4x and 8x), and one variable divider (the one true
* pll audio).
*
* With sigma-delta modulation for fractional-N on the audio PLL,
* we have to use specific dividers. This means the variable divider
* can no longer be used, as the audio codec requests the exact clock
* rates we support through this mechanism. So we now hard code the
* variable divider to 1. This means the clock rates will no longer
* match the clock names.
*/
#define SUN50I_A64_PLL_AUDIO_REG 0x008
static struct ccu_sdm_setting pll_audio_sdm_table[] = {
{ .rate = 22579200, .pattern = 0xc0010d84, .m = 8, .n = 7 },
{ .rate = 24576000, .pattern = 0xc000ac02, .m = 14, .n = 14 },
};
static SUNXI_CCU_NM_WITH_SDM_GATE_LOCK(pll_audio_base_clk, "pll-audio-base",
"osc24M", 0x008,
8, 7, /* N */
0, 5, /* M */
pll_audio_sdm_table, BIT(24),
0x284, BIT(31),
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
static SUNXI_CCU_NM_WITH_FRAC_GATE_LOCK_MIN_MAX(pll_video0_clk, "pll-video0",
"osc24M", 0x010,
192000000, /* Minimum rate */
1008000000, /* Maximum rate */
8, 7, /* N */
0, 4, /* M */
BIT(24), /* frac enable */
BIT(25), /* frac select */
270000000, /* frac rate 0 */
297000000, /* frac rate 1 */
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
static SUNXI_CCU_NM_WITH_FRAC_GATE_LOCK(pll_ve_clk, "pll-ve",
"osc24M", 0x018,
8, 7, /* N */
0, 4, /* M */
BIT(24), /* frac enable */
BIT(25), /* frac select */
270000000, /* frac rate 0 */
297000000, /* frac rate 1 */
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
static SUNXI_CCU_NKM_WITH_GATE_LOCK(pll_ddr0_clk, "pll-ddr0",
"osc24M", 0x020,
8, 5, /* N */
4, 2, /* K */
0, 2, /* M */
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
static struct ccu_nk pll_periph0_clk = {
.enable = BIT(31),
.lock = BIT(28),
.n = _SUNXI_CCU_MULT(8, 5),
.k = _SUNXI_CCU_MULT_MIN(4, 2, 2),
.fixed_post_div = 2,
.common = {
.reg = 0x028,
.features = CCU_FEATURE_FIXED_POSTDIV,
.hw.init = CLK_HW_INIT("pll-periph0", "osc24M",
&ccu_nk_ops, CLK_SET_RATE_UNGATE),
},
};
static struct ccu_nk pll_periph1_clk = {
.enable = BIT(31),
.lock = BIT(28),
.n = _SUNXI_CCU_MULT(8, 5),
.k = _SUNXI_CCU_MULT_MIN(4, 2, 2),
.fixed_post_div = 2,
.common = {
.reg = 0x02c,
.features = CCU_FEATURE_FIXED_POSTDIV,
.hw.init = CLK_HW_INIT("pll-periph1", "osc24M",
&ccu_nk_ops, CLK_SET_RATE_UNGATE),
},
};
static SUNXI_CCU_NM_WITH_FRAC_GATE_LOCK_MIN_MAX(pll_video1_clk, "pll-video1",
"osc24M", 0x030,
192000000, /* Minimum rate */
1008000000, /* Maximum rate */
8, 7, /* N */
0, 4, /* M */
BIT(24), /* frac enable */
BIT(25), /* frac select */
270000000, /* frac rate 0 */
297000000, /* frac rate 1 */
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
static SUNXI_CCU_NM_WITH_FRAC_GATE_LOCK(pll_gpu_clk, "pll-gpu",
"osc24M", 0x038,
8, 7, /* N */
0, 4, /* M */
BIT(24), /* frac enable */
BIT(25), /* frac select */
270000000, /* frac rate 0 */
297000000, /* frac rate 1 */
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
/*
* The output function can be changed to something more complex that
* we do not handle yet.
*
* Hardcode the mode so that we don't fall in that case.
*/
#define SUN50I_A64_PLL_MIPI_REG 0x040
static struct ccu_nkm pll_mipi_clk = {
/*
* The bit 23 and 22 are called "LDO{1,2}_EN" on the SoC's
* user manual, and by experiments the PLL doesn't work without
* these bits toggled.
*/
.enable = BIT(31) | BIT(23) | BIT(22),
.lock = BIT(28),
.n = _SUNXI_CCU_MULT(8, 4),
.k = _SUNXI_CCU_MULT_MIN(4, 2, 2),
.m = _SUNXI_CCU_DIV(0, 4),
.common = {
.reg = 0x040,
.hw.init = CLK_HW_INIT("pll-mipi", "pll-video0",
&ccu_nkm_ops, CLK_SET_RATE_UNGATE),
},
};
static SUNXI_CCU_NM_WITH_FRAC_GATE_LOCK(pll_hsic_clk, "pll-hsic",
"osc24M", 0x044,
8, 7, /* N */
0, 4, /* M */
BIT(24), /* frac enable */
BIT(25), /* frac select */
270000000, /* frac rate 0 */
297000000, /* frac rate 1 */
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
static SUNXI_CCU_NM_WITH_FRAC_GATE_LOCK(pll_de_clk, "pll-de",
"osc24M", 0x048,
8, 7, /* N */
0, 4, /* M */
BIT(24), /* frac enable */
BIT(25), /* frac select */
270000000, /* frac rate 0 */
297000000, /* frac rate 1 */
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
static SUNXI_CCU_NM_WITH_GATE_LOCK(pll_ddr1_clk, "pll-ddr1",
"osc24M", 0x04c,
8, 7, /* N */
0, 2, /* M */
BIT(31), /* gate */
BIT(28), /* lock */
CLK_SET_RATE_UNGATE);
static const char * const cpux_parents[] = { "osc32k", "osc24M",
"pll-cpux", "pll-cpux" };
static SUNXI_CCU_MUX(cpux_clk, "cpux", cpux_parents,
0x050, 16, 2, CLK_SET_RATE_PARENT | CLK_IS_CRITICAL);
static SUNXI_CCU_M(axi_clk, "axi", "cpux", 0x050, 0, 2, 0);
static const char * const ahb1_parents[] = { "osc32k", "osc24M",
"axi", "pll-periph0" };
static const struct ccu_mux_var_prediv ahb1_predivs[] = {
{ .index = 3, .shift = 6, .width = 2 },
};
static struct ccu_div ahb1_clk = {
.div = _SUNXI_CCU_DIV_FLAGS(4, 2, CLK_DIVIDER_POWER_OF_TWO),
.mux = {
.shift = 12,
.width = 2,
.var_predivs = ahb1_predivs,
.n_var_predivs = ARRAY_SIZE(ahb1_predivs),
},
.common = {
.reg = 0x054,
.features = CCU_FEATURE_VARIABLE_PREDIV,
.hw.init = CLK_HW_INIT_PARENTS("ahb1",
ahb1_parents,
&ccu_div_ops,
0),
},
};
static struct clk_div_table apb1_div_table[] = {
{ .val = 0, .div = 2 },
{ .val = 1, .div = 2 },
{ .val = 2, .div = 4 },
{ .val = 3, .div = 8 },
{ /* Sentinel */ },
};
static SUNXI_CCU_DIV_TABLE(apb1_clk, "apb1", "ahb1",
0x054, 8, 2, apb1_div_table, 0);
static const char * const apb2_parents[] = { "osc32k", "osc24M",
"pll-periph0-2x",
"pll-periph0-2x" };
static SUNXI_CCU_MP_WITH_MUX(apb2_clk, "apb2", apb2_parents, 0x058,
0, 5, /* M */
16, 2, /* P */
24, 2, /* mux */
0);
static const char * const ahb2_parents[] = { "ahb1", "pll-periph0" };
static const struct ccu_mux_fixed_prediv ahb2_fixed_predivs[] = {
{ .index = 1, .div = 2 },
};
static struct ccu_mux ahb2_clk = {
.mux = {
.shift = 0,
.width = 1,
.fixed_predivs = ahb2_fixed_predivs,
.n_predivs = ARRAY_SIZE(ahb2_fixed_predivs),
},
.common = {
.reg = 0x05c,
.features = CCU_FEATURE_FIXED_PREDIV,
.hw.init = CLK_HW_INIT_PARENTS("ahb2",
ahb2_parents,
&ccu_mux_ops,
0),
},
};
static SUNXI_CCU_GATE(bus_mipi_dsi_clk, "bus-mipi-dsi", "ahb1",
0x060, BIT(1), 0);
static SUNXI_CCU_GATE(bus_ce_clk, "bus-ce", "ahb1",
0x060, BIT(5), 0);
static SUNXI_CCU_GATE(bus_dma_clk, "bus-dma", "ahb1",
0x060, BIT(6), 0);
static SUNXI_CCU_GATE(bus_mmc0_clk, "bus-mmc0", "ahb1",
0x060, BIT(8), 0);
static SUNXI_CCU_GATE(bus_mmc1_clk, "bus-mmc1", "ahb1",
0x060, BIT(9), 0);
static SUNXI_CCU_GATE(bus_mmc2_clk, "bus-mmc2", "ahb1",
0x060, BIT(10), 0);
static SUNXI_CCU_GATE(bus_nand_clk, "bus-nand", "ahb1",
0x060, BIT(13), 0);
static SUNXI_CCU_GATE(bus_dram_clk, "bus-dram", "ahb1",
0x060, BIT(14), 0);
static SUNXI_CCU_GATE(bus_emac_clk, "bus-emac", "ahb2",
0x060, BIT(17), 0);
static SUNXI_CCU_GATE(bus_ts_clk, "bus-ts", "ahb1",
0x060, BIT(18), 0);
static SUNXI_CCU_GATE(bus_hstimer_clk, "bus-hstimer", "ahb1",
0x060, BIT(19), 0);
static SUNXI_CCU_GATE(bus_spi0_clk, "bus-spi0", "ahb1",
0x060, BIT(20), 0);
static SUNXI_CCU_GATE(bus_spi1_clk, "bus-spi1", "ahb1",
0x060, BIT(21), 0);
static SUNXI_CCU_GATE(bus_otg_clk, "bus-otg", "ahb1",
0x060, BIT(23), 0);
static SUNXI_CCU_GATE(bus_ehci0_clk, "bus-ehci0", "ahb1",
0x060, BIT(24), 0);
static SUNXI_CCU_GATE(bus_ehci1_clk, "bus-ehci1", "ahb2",
0x060, BIT(25), 0);
static SUNXI_CCU_GATE(bus_ohci0_clk, "bus-ohci0", "ahb1",
0x060, BIT(28), 0);
static SUNXI_CCU_GATE(bus_ohci1_clk, "bus-ohci1", "ahb2",
0x060, BIT(29), 0);
static SUNXI_CCU_GATE(bus_ve_clk, "bus-ve", "ahb1",
0x064, BIT(0), 0);
static SUNXI_CCU_GATE(bus_tcon0_clk, "bus-tcon0", "ahb1",
0x064, BIT(3), 0);
static SUNXI_CCU_GATE(bus_tcon1_clk, "bus-tcon1", "ahb1",
0x064, BIT(4), 0);
static SUNXI_CCU_GATE(bus_deinterlace_clk, "bus-deinterlace", "ahb1",
0x064, BIT(5), 0);
static SUNXI_CCU_GATE(bus_csi_clk, "bus-csi", "ahb1",
0x064, BIT(8), 0);
static SUNXI_CCU_GATE(bus_hdmi_clk, "bus-hdmi", "ahb1",
0x064, BIT(11), 0);
static SUNXI_CCU_GATE(bus_de_clk, "bus-de", "ahb1",
0x064, BIT(12), 0);
static SUNXI_CCU_GATE(bus_gpu_clk, "bus-gpu", "ahb1",
0x064, BIT(20), 0);
static SUNXI_CCU_GATE(bus_msgbox_clk, "bus-msgbox", "ahb1",
0x064, BIT(21), 0);
static SUNXI_CCU_GATE(bus_spinlock_clk, "bus-spinlock", "ahb1",
0x064, BIT(22), 0);
static SUNXI_CCU_GATE(bus_codec_clk, "bus-codec", "apb1",
0x068, BIT(0), 0);
static SUNXI_CCU_GATE(bus_spdif_clk, "bus-spdif", "apb1",
0x068, BIT(1), 0);
static SUNXI_CCU_GATE(bus_pio_clk, "bus-pio", "apb1",
0x068, BIT(5), 0);
static SUNXI_CCU_GATE(bus_ths_clk, "bus-ths", "apb1",
0x068, BIT(8), 0);
static SUNXI_CCU_GATE(bus_i2s0_clk, "bus-i2s0", "apb1",
0x068, BIT(12), 0);
static SUNXI_CCU_GATE(bus_i2s1_clk, "bus-i2s1", "apb1",
0x068, BIT(13), 0);
static SUNXI_CCU_GATE(bus_i2s2_clk, "bus-i2s2", "apb1",
0x068, BIT(14), 0);
static SUNXI_CCU_GATE(bus_i2c0_clk, "bus-i2c0", "apb2",
0x06c, BIT(0), 0);
static SUNXI_CCU_GATE(bus_i2c1_clk, "bus-i2c1", "apb2",
0x06c, BIT(1), 0);
static SUNXI_CCU_GATE(bus_i2c2_clk, "bus-i2c2", "apb2",
0x06c, BIT(2), 0);
static SUNXI_CCU_GATE(bus_scr_clk, "bus-scr", "apb2",
0x06c, BIT(5), 0);
static SUNXI_CCU_GATE(bus_uart0_clk, "bus-uart0", "apb2",
0x06c, BIT(16), 0);
static SUNXI_CCU_GATE(bus_uart1_clk, "bus-uart1", "apb2",
0x06c, BIT(17), 0);
static SUNXI_CCU_GATE(bus_uart2_clk, "bus-uart2", "apb2",
0x06c, BIT(18), 0);
static SUNXI_CCU_GATE(bus_uart3_clk, "bus-uart3", "apb2",
0x06c, BIT(19), 0);
static SUNXI_CCU_GATE(bus_uart4_clk, "bus-uart4", "apb2",
0x06c, BIT(20), 0);
static SUNXI_CCU_GATE(bus_dbg_clk, "bus-dbg", "ahb1",
0x070, BIT(7), 0);
static struct clk_div_table ths_div_table[] = {
{ .val = 0, .div = 1 },
{ .val = 1, .div = 2 },
{ .val = 2, .div = 4 },
{ .val = 3, .div = 6 },
};
static const char * const ths_parents[] = { "osc24M" };
static struct ccu_div ths_clk = {
.enable = BIT(31),
.div = _SUNXI_CCU_DIV_TABLE(0, 2, ths_div_table),
.mux = _SUNXI_CCU_MUX(24, 2),
.common = {
.reg = 0x074,
.hw.init = CLK_HW_INIT_PARENTS("ths",
ths_parents,
&ccu_div_ops,
0),
},
};
static const char * const mod0_default_parents[] = { "osc24M", "pll-periph0",
"pll-periph1" };
static SUNXI_CCU_MP_WITH_MUX_GATE(nand_clk, "nand", mod0_default_parents, 0x080,
0, 4, /* M */
16, 2, /* P */
24, 2, /* mux */
BIT(31), /* gate */
0);
/*
* MMC clocks are the new timing mode (see A83T & H3) variety, but without
* the mode switch. This means they have a 2x post divider between the clock
* and the MMC module. This is not documented in the manual, but is taken
* into consideration when setting the mmc module clocks in the BSP kernel.
* Without it, MMC performance is degraded.
*
* We model it here to be consistent with other SoCs supporting this mode.
* The alternative would be to add the 2x multiplier when setting the MMC
* module clock in the MMC driver, just for the A64.
*/
static const char * const mmc_default_parents[] = { "osc24M", "pll-periph0-2x",
"pll-periph1-2x" };
static SUNXI_CCU_MP_WITH_MUX_GATE_POSTDIV(mmc0_clk, "mmc0",
mmc_default_parents, 0x088,
0, 4, /* M */
16, 2, /* P */
24, 2, /* mux */
BIT(31), /* gate */
2, /* post-div */
0);
static SUNXI_CCU_MP_WITH_MUX_GATE_POSTDIV(mmc1_clk, "mmc1",
mmc_default_parents, 0x08c,
0, 4, /* M */
16, 2, /* P */
24, 2, /* mux */
BIT(31), /* gate */
2, /* post-div */
0);
static SUNXI_CCU_MP_WITH_MUX_GATE_POSTDIV(mmc2_clk, "mmc2",
mmc_default_parents, 0x090,
0, 4, /* M */
16, 2, /* P */
24, 2, /* mux */
BIT(31), /* gate */
2, /* post-div */
0);
static const char * const ts_parents[] = { "osc24M", "pll-periph0", };
static SUNXI_CCU_MP_WITH_MUX_GATE(ts_clk, "ts", ts_parents, 0x098,
0, 4, /* M */
16, 2, /* P */
24, 4, /* mux */
BIT(31), /* gate */
0);
static SUNXI_CCU_MP_WITH_MUX_GATE(ce_clk, "ce", mmc_default_parents, 0x09c,
0, 4, /* M */
16, 2, /* P */
24, 2, /* mux */
BIT(31), /* gate */
0);
static SUNXI_CCU_MP_WITH_MUX_GATE(spi0_clk, "spi0", mod0_default_parents, 0x0a0,
0, 4, /* M */
16, 2, /* P */
24, 2, /* mux */
BIT(31), /* gate */
0);
static SUNXI_CCU_MP_WITH_MUX_GATE(spi1_clk, "spi1", mod0_default_parents, 0x0a4,
0, 4, /* M */
16, 2, /* P */
24, 2, /* mux */
BIT(31), /* gate */
0);
static const char * const i2s_parents[] = { "pll-audio-8x", "pll-audio-4x",
"pll-audio-2x", "pll-audio" };
static SUNXI_CCU_MUX_WITH_GATE(i2s0_clk, "i2s0", i2s_parents,
0x0b0, 16, 2, BIT(31), CLK_SET_RATE_PARENT);
static SUNXI_CCU_MUX_WITH_GATE(i2s1_clk, "i2s1", i2s_parents,
0x0b4, 16, 2, BIT(31), CLK_SET_RATE_PARENT);
static SUNXI_CCU_MUX_WITH_GATE(i2s2_clk, "i2s2", i2s_parents,
0x0b8, 16, 2, BIT(31), CLK_SET_RATE_PARENT);
static SUNXI_CCU_M_WITH_GATE(spdif_clk, "spdif", "pll-audio",
0x0c0, 0, 4, BIT(31), CLK_SET_RATE_PARENT);
static SUNXI_CCU_GATE(usb_phy0_clk, "usb-phy0", "osc24M",
0x0cc, BIT(8), 0);
static SUNXI_CCU_GATE(usb_phy1_clk, "usb-phy1", "osc24M",
0x0cc, BIT(9), 0);
static SUNXI_CCU_GATE(usb_hsic_clk, "usb-hsic", "pll-hsic",
0x0cc, BIT(10), 0);
static SUNXI_CCU_GATE(usb_hsic_12m_clk, "usb-hsic-12M", "osc12M",
0x0cc, BIT(11), 0);
static SUNXI_CCU_GATE(usb_ohci0_clk, "usb-ohci0", "osc12M",
0x0cc, BIT(16), 0);
static SUNXI_CCU_GATE(usb_ohci1_clk, "usb-ohci1", "usb-ohci0",
0x0cc, BIT(17), 0);
static const char * const dram_parents[] = { "pll-ddr0", "pll-ddr1" };
static SUNXI_CCU_M_WITH_MUX(dram_clk, "dram", dram_parents,
0x0f4, 0, 4, 20, 2, CLK_IS_CRITICAL);
static SUNXI_CCU_GATE(dram_ve_clk, "dram-ve", "dram",
0x100, BIT(0), 0);
static SUNXI_CCU_GATE(dram_csi_clk, "dram-csi", "dram",
0x100, BIT(1), 0);
static SUNXI_CCU_GATE(dram_deinterlace_clk, "dram-deinterlace", "dram",
0x100, BIT(2), 0);
static SUNXI_CCU_GATE(dram_ts_clk, "dram-ts", "dram",
0x100, BIT(3), 0);
static const char * const de_parents[] = { "pll-periph0-2x", "pll-de" };
static SUNXI_CCU_M_WITH_MUX_GATE(de_clk, "de", de_parents,
0x104, 0, 4, 24, 3, BIT(31),
CLK_SET_RATE_PARENT);
static const char * const tcon0_parents[] = { "pll-mipi", "pll-video0-2x" };
static const u8 tcon0_table[] = { 0, 2, };
static SUNXI_CCU_MUX_TABLE_WITH_GATE(tcon0_clk, "tcon0", tcon0_parents,
tcon0_table, 0x118, 24, 3, BIT(31),
CLK_SET_RATE_PARENT);
static const char * const tcon1_parents[] = { "pll-video0", "pll-video1" };
static const u8 tcon1_table[] = { 0, 2, };
static struct ccu_div tcon1_clk = {
.enable = BIT(31),
.div = _SUNXI_CCU_DIV(0, 4),
.mux = _SUNXI_CCU_MUX_TABLE(24, 2, tcon1_table),
.common = {
.reg = 0x11c,
.hw.init = CLK_HW_INIT_PARENTS("tcon1",
tcon1_parents,
&ccu_div_ops,
CLK_SET_RATE_PARENT),
},
};
static const char * const deinterlace_parents[] = { "pll-periph0", "pll-periph1" };
static SUNXI_CCU_M_WITH_MUX_GATE(deinterlace_clk, "deinterlace", deinterlace_parents,
0x124, 0, 4, 24, 3, BIT(31), 0);
static SUNXI_CCU_GATE(csi_misc_clk, "csi-misc", "osc24M",
0x130, BIT(31), 0);
static const char * const csi_sclk_parents[] = { "pll-periph0", "pll-periph1" };
static SUNXI_CCU_M_WITH_MUX_GATE(csi_sclk_clk, "csi-sclk", csi_sclk_parents,
0x134, 16, 4, 24, 3, BIT(31), 0);
static const char * const csi_mclk_parents[] = { "osc24M", "pll-video1", "pll-periph1" };
static SUNXI_CCU_M_WITH_MUX_GATE(csi_mclk_clk, "csi-mclk", csi_mclk_parents,
0x134, 0, 5, 8, 3, BIT(15), 0);
static SUNXI_CCU_M_WITH_GATE(ve_clk, "ve", "pll-ve",
0x13c, 16, 3, BIT(31), CLK_SET_RATE_PARENT);
static SUNXI_CCU_GATE(ac_dig_clk, "ac-dig", "pll-audio",
0x140, BIT(31), CLK_SET_RATE_PARENT);
static SUNXI_CCU_GATE(ac_dig_4x_clk, "ac-dig-4x", "pll-audio-4x",
0x140, BIT(30), CLK_SET_RATE_PARENT);
static SUNXI_CCU_GATE(avs_clk, "avs", "osc24M",
0x144, BIT(31), 0);
static const char * const hdmi_parents[] = { "pll-video0", "pll-video1" };
static SUNXI_CCU_M_WITH_MUX_GATE(hdmi_clk, "hdmi", hdmi_parents,
0x150, 0, 4, 24, 2, BIT(31), CLK_SET_RATE_PARENT);
static SUNXI_CCU_GATE(hdmi_ddc_clk, "hdmi-ddc", "osc24M",
0x154, BIT(31), 0);
static const char * const mbus_parents[] = { "osc24M", "pll-periph0-2x",
"pll-ddr0", "pll-ddr1" };
static SUNXI_CCU_M_WITH_MUX_GATE(mbus_clk, "mbus", mbus_parents,
0x15c, 0, 3, 24, 2, BIT(31), CLK_IS_CRITICAL);
static const char * const dsi_dphy_parents[] = { "pll-video0", "pll-periph0" };
static const u8 dsi_dphy_table[] = { 0, 2, };
static SUNXI_CCU_M_WITH_MUX_TABLE_GATE(dsi_dphy_clk, "dsi-dphy",
dsi_dphy_parents, dsi_dphy_table,
0x168, 0, 4, 8, 2, BIT(15), CLK_SET_RATE_PARENT);
static SUNXI_CCU_M_WITH_GATE(gpu_clk, "gpu", "pll-gpu",
0x1a0, 0, 3, BIT(31), CLK_SET_RATE_PARENT);
/* Fixed Factor clocks */
static CLK_FIXED_FACTOR_FW_NAME(osc12M_clk, "osc12M", "hosc", 2, 1, 0);
static const struct clk_hw *clk_parent_pll_audio[] = {
&pll_audio_base_clk.common.hw
};
/* We hardcode the divider to 1 for now */
static CLK_FIXED_FACTOR_HWS(pll_audio_clk, "pll-audio",
clk_parent_pll_audio,
1, 1, CLK_SET_RATE_PARENT);
static CLK_FIXED_FACTOR_HWS(pll_audio_2x_clk, "pll-audio-2x",
clk_parent_pll_audio,
2, 1, CLK_SET_RATE_PARENT);
static CLK_FIXED_FACTOR_HWS(pll_audio_4x_clk, "pll-audio-4x",
clk_parent_pll_audio,
1, 1, CLK_SET_RATE_PARENT);
static CLK_FIXED_FACTOR_HWS(pll_audio_8x_clk, "pll-audio-8x",
clk_parent_pll_audio,
1, 2, CLK_SET_RATE_PARENT);
static CLK_FIXED_FACTOR_HW(pll_periph0_2x_clk, "pll-periph0-2x",
&pll_periph0_clk.common.hw,
1, 2, 0);
static CLK_FIXED_FACTOR_HW(pll_periph1_2x_clk, "pll-periph1-2x",
&pll_periph1_clk.common.hw,
1, 2, 0);
static CLK_FIXED_FACTOR_HW(pll_video0_2x_clk, "pll-video0-2x",
&pll_video0_clk.common.hw,
1, 2, CLK_SET_RATE_PARENT);
static struct ccu_common *sun50i_a64_ccu_clks[] = {
&pll_cpux_clk.common,
&pll_audio_base_clk.common,
&pll_video0_clk.common,
&pll_ve_clk.common,
&pll_ddr0_clk.common,
&pll_periph0_clk.common,
&pll_periph1_clk.common,
&pll_video1_clk.common,
&pll_gpu_clk.common,
&pll_mipi_clk.common,
&pll_hsic_clk.common,
&pll_de_clk.common,
&pll_ddr1_clk.common,
&cpux_clk.common,
&axi_clk.common,
&ahb1_clk.common,
&apb1_clk.common,
&apb2_clk.common,
&ahb2_clk.common,
&bus_mipi_dsi_clk.common,
&bus_ce_clk.common,
&bus_dma_clk.common,
&bus_mmc0_clk.common,
&bus_mmc1_clk.common,
&bus_mmc2_clk.common,
&bus_nand_clk.common,
&bus_dram_clk.common,
&bus_emac_clk.common,
&bus_ts_clk.common,
&bus_hstimer_clk.common,
&bus_spi0_clk.common,
&bus_spi1_clk.common,
&bus_otg_clk.common,
&bus_ehci0_clk.common,
&bus_ehci1_clk.common,
&bus_ohci0_clk.common,
&bus_ohci1_clk.common,
&bus_ve_clk.common,
&bus_tcon0_clk.common,
&bus_tcon1_clk.common,
&bus_deinterlace_clk.common,
&bus_csi_clk.common,
&bus_hdmi_clk.common,
&bus_de_clk.common,
&bus_gpu_clk.common,
&bus_msgbox_clk.common,
&bus_spinlock_clk.common,
&bus_codec_clk.common,
&bus_spdif_clk.common,
&bus_pio_clk.common,
&bus_ths_clk.common,
&bus_i2s0_clk.common,
&bus_i2s1_clk.common,
&bus_i2s2_clk.common,
&bus_i2c0_clk.common,
&bus_i2c1_clk.common,
&bus_i2c2_clk.common,
&bus_scr_clk.common,
&bus_uart0_clk.common,
&bus_uart1_clk.common,
&bus_uart2_clk.common,
&bus_uart3_clk.common,
&bus_uart4_clk.common,
&bus_dbg_clk.common,
&ths_clk.common,
&nand_clk.common,
&mmc0_clk.common,
&mmc1_clk.common,
&mmc2_clk.common,
&ts_clk.common,
&ce_clk.common,
&spi0_clk.common,
&spi1_clk.common,
&i2s0_clk.common,
&i2s1_clk.common,
&i2s2_clk.common,
&spdif_clk.common,
&usb_phy0_clk.common,
&usb_phy1_clk.common,
&usb_hsic_clk.common,
&usb_hsic_12m_clk.common,
&usb_ohci0_clk.common,
&usb_ohci1_clk.common,
&dram_clk.common,
&dram_ve_clk.common,
&dram_csi_clk.common,
&dram_deinterlace_clk.common,
&dram_ts_clk.common,
&de_clk.common,
&tcon0_clk.common,
&tcon1_clk.common,
&deinterlace_clk.common,
&csi_misc_clk.common,
&csi_sclk_clk.common,
&csi_mclk_clk.common,
&ve_clk.common,
&ac_dig_clk.common,
&ac_dig_4x_clk.common,
&avs_clk.common,
&hdmi_clk.common,
&hdmi_ddc_clk.common,
&mbus_clk.common,
&dsi_dphy_clk.common,
&gpu_clk.common,
};
static struct clk_hw_onecell_data sun50i_a64_hw_clks = {
.hws = {
[CLK_OSC_12M] = &osc12M_clk.hw,
[CLK_PLL_CPUX] = &pll_cpux_clk.common.hw,
[CLK_PLL_AUDIO_BASE] = &pll_audio_base_clk.common.hw,
[CLK_PLL_AUDIO] = &pll_audio_clk.hw,
[CLK_PLL_AUDIO_2X] = &pll_audio_2x_clk.hw,
[CLK_PLL_AUDIO_4X] = &pll_audio_4x_clk.hw,
[CLK_PLL_AUDIO_8X] = &pll_audio_8x_clk.hw,
[CLK_PLL_VIDEO0] = &pll_video0_clk.common.hw,
[CLK_PLL_VIDEO0_2X] = &pll_video0_2x_clk.hw,
[CLK_PLL_VE] = &pll_ve_clk.common.hw,
[CLK_PLL_DDR0] = &pll_ddr0_clk.common.hw,
[CLK_PLL_PERIPH0] = &pll_periph0_clk.common.hw,
[CLK_PLL_PERIPH0_2X] = &pll_periph0_2x_clk.hw,
[CLK_PLL_PERIPH1] = &pll_periph1_clk.common.hw,
[CLK_PLL_PERIPH1_2X] = &pll_periph1_2x_clk.hw,
[CLK_PLL_VIDEO1] = &pll_video1_clk.common.hw,
[CLK_PLL_GPU] = &pll_gpu_clk.common.hw,
[CLK_PLL_MIPI] = &pll_mipi_clk.common.hw,
[CLK_PLL_HSIC] = &pll_hsic_clk.common.hw,
[CLK_PLL_DE] = &pll_de_clk.common.hw,
[CLK_PLL_DDR1] = &pll_ddr1_clk.common.hw,
[CLK_CPUX] = &cpux_clk.common.hw,
[CLK_AXI] = &axi_clk.common.hw,
[CLK_AHB1] = &ahb1_clk.common.hw,
[CLK_APB1] = &apb1_clk.common.hw,
[CLK_APB2] = &apb2_clk.common.hw,
[CLK_AHB2] = &ahb2_clk.common.hw,
[CLK_BUS_MIPI_DSI] = &bus_mipi_dsi_clk.common.hw,
[CLK_BUS_CE] = &bus_ce_clk.common.hw,
[CLK_BUS_DMA] = &bus_dma_clk.common.hw,
[CLK_BUS_MMC0] = &bus_mmc0_clk.common.hw,
[CLK_BUS_MMC1] = &bus_mmc1_clk.common.hw,
[CLK_BUS_MMC2] = &bus_mmc2_clk.common.hw,
[CLK_BUS_NAND] = &bus_nand_clk.common.hw,
[CLK_BUS_DRAM] = &bus_dram_clk.common.hw,
[CLK_BUS_EMAC] = &bus_emac_clk.common.hw,
[CLK_BUS_TS] = &bus_ts_clk.common.hw,
[CLK_BUS_HSTIMER] = &bus_hstimer_clk.common.hw,
[CLK_BUS_SPI0] = &bus_spi0_clk.common.hw,
[CLK_BUS_SPI1] = &bus_spi1_clk.common.hw,
[CLK_BUS_OTG] = &bus_otg_clk.common.hw,
[CLK_BUS_EHCI0] = &bus_ehci0_clk.common.hw,
[CLK_BUS_EHCI1] = &bus_ehci1_clk.common.hw,
[CLK_BUS_OHCI0] = &bus_ohci0_clk.common.hw,
[CLK_BUS_OHCI1] = &bus_ohci1_clk.common.hw,
[CLK_BUS_VE] = &bus_ve_clk.common.hw,
[CLK_BUS_TCON0] = &bus_tcon0_clk.common.hw,
[CLK_BUS_TCON1] = &bus_tcon1_clk.common.hw,
[CLK_BUS_DEINTERLACE] = &bus_deinterlace_clk.common.hw,
[CLK_BUS_CSI] = &bus_csi_clk.common.hw,
[CLK_BUS_HDMI] = &bus_hdmi_clk.common.hw,
[CLK_BUS_DE] = &bus_de_clk.common.hw,
[CLK_BUS_GPU] = &bus_gpu_clk.common.hw,
[CLK_BUS_MSGBOX] = &bus_msgbox_clk.common.hw,
[CLK_BUS_SPINLOCK] = &bus_spinlock_clk.common.hw,
[CLK_BUS_CODEC] = &bus_codec_clk.common.hw,
[CLK_BUS_SPDIF] = &bus_spdif_clk.common.hw,
[CLK_BUS_PIO] = &bus_pio_clk.common.hw,
[CLK_BUS_THS] = &bus_ths_clk.common.hw,
[CLK_BUS_I2S0] = &bus_i2s0_clk.common.hw,
[CLK_BUS_I2S1] = &bus_i2s1_clk.common.hw,
[CLK_BUS_I2S2] = &bus_i2s2_clk.common.hw,
[CLK_BUS_I2C0] = &bus_i2c0_clk.common.hw,
[CLK_BUS_I2C1] = &bus_i2c1_clk.common.hw,
[CLK_BUS_I2C2] = &bus_i2c2_clk.common.hw,
[CLK_BUS_UART0] = &bus_uart0_clk.common.hw,
[CLK_BUS_UART1] = &bus_uart1_clk.common.hw,
[CLK_BUS_UART2] = &bus_uart2_clk.common.hw,
[CLK_BUS_UART3] = &bus_uart3_clk.common.hw,
[CLK_BUS_UART4] = &bus_uart4_clk.common.hw,
[CLK_BUS_SCR] = &bus_scr_clk.common.hw,
[CLK_BUS_DBG] = &bus_dbg_clk.common.hw,
[CLK_THS] = &ths_clk.common.hw,
[CLK_NAND] = &nand_clk.common.hw,
[CLK_MMC0] = &mmc0_clk.common.hw,
[CLK_MMC1] = &mmc1_clk.common.hw,
[CLK_MMC2] = &mmc2_clk.common.hw,
[CLK_TS] = &ts_clk.common.hw,
[CLK_CE] = &ce_clk.common.hw,
[CLK_SPI0] = &spi0_clk.common.hw,
[CLK_SPI1] = &spi1_clk.common.hw,
[CLK_I2S0] = &i2s0_clk.common.hw,
[CLK_I2S1] = &i2s1_clk.common.hw,
[CLK_I2S2] = &i2s2_clk.common.hw,
[CLK_SPDIF] = &spdif_clk.common.hw,
[CLK_USB_PHY0] = &usb_phy0_clk.common.hw,
[CLK_USB_PHY1] = &usb_phy1_clk.common.hw,
[CLK_USB_HSIC] = &usb_hsic_clk.common.hw,
[CLK_USB_HSIC_12M] = &usb_hsic_12m_clk.common.hw,
[CLK_USB_OHCI0] = &usb_ohci0_clk.common.hw,
[CLK_USB_OHCI1] = &usb_ohci1_clk.common.hw,
[CLK_DRAM] = &dram_clk.common.hw,
[CLK_DRAM_VE] = &dram_ve_clk.common.hw,
[CLK_DRAM_CSI] = &dram_csi_clk.common.hw,
[CLK_DRAM_DEINTERLACE] = &dram_deinterlace_clk.common.hw,
[CLK_DRAM_TS] = &dram_ts_clk.common.hw,
[CLK_DE] = &de_clk.common.hw,
[CLK_TCON0] = &tcon0_clk.common.hw,
[CLK_TCON1] = &tcon1_clk.common.hw,
[CLK_DEINTERLACE] = &deinterlace_clk.common.hw,
[CLK_CSI_MISC] = &csi_misc_clk.common.hw,
[CLK_CSI_SCLK] = &csi_sclk_clk.common.hw,
[CLK_CSI_MCLK] = &csi_mclk_clk.common.hw,
[CLK_VE] = &ve_clk.common.hw,
[CLK_AC_DIG] = &ac_dig_clk.common.hw,
[CLK_AC_DIG_4X] = &ac_dig_4x_clk.common.hw,
[CLK_AVS] = &avs_clk.common.hw,
[CLK_HDMI] = &hdmi_clk.common.hw,
[CLK_HDMI_DDC] = &hdmi_ddc_clk.common.hw,
[CLK_MBUS] = &mbus_clk.common.hw,
[CLK_DSI_DPHY] = &dsi_dphy_clk.common.hw,
[CLK_GPU] = &gpu_clk.common.hw,
},
.num = CLK_NUMBER,
};
static struct ccu_reset_map sun50i_a64_ccu_resets[] = {
[RST_USB_PHY0] = { 0x0cc, BIT(0) },
[RST_USB_PHY1] = { 0x0cc, BIT(1) },
[RST_USB_HSIC] = { 0x0cc, BIT(2) },
[RST_DRAM] = { 0x0f4, BIT(31) },
[RST_MBUS] = { 0x0fc, BIT(31) },
[RST_BUS_MIPI_DSI] = { 0x2c0, BIT(1) },
[RST_BUS_CE] = { 0x2c0, BIT(5) },
[RST_BUS_DMA] = { 0x2c0, BIT(6) },
[RST_BUS_MMC0] = { 0x2c0, BIT(8) },
[RST_BUS_MMC1] = { 0x2c0, BIT(9) },
[RST_BUS_MMC2] = { 0x2c0, BIT(10) },
[RST_BUS_NAND] = { 0x2c0, BIT(13) },
[RST_BUS_DRAM] = { 0x2c0, BIT(14) },
[RST_BUS_EMAC] = { 0x2c0, BIT(17) },
[RST_BUS_TS] = { 0x2c0, BIT(18) },
[RST_BUS_HSTIMER] = { 0x2c0, BIT(19) },
[RST_BUS_SPI0] = { 0x2c0, BIT(20) },
[RST_BUS_SPI1] = { 0x2c0, BIT(21) },
[RST_BUS_OTG] = { 0x2c0, BIT(23) },
[RST_BUS_EHCI0] = { 0x2c0, BIT(24) },
[RST_BUS_EHCI1] = { 0x2c0, BIT(25) },
[RST_BUS_OHCI0] = { 0x2c0, BIT(28) },
[RST_BUS_OHCI1] = { 0x2c0, BIT(29) },
[RST_BUS_VE] = { 0x2c4, BIT(0) },
[RST_BUS_TCON0] = { 0x2c4, BIT(3) },
[RST_BUS_TCON1] = { 0x2c4, BIT(4) },
[RST_BUS_DEINTERLACE] = { 0x2c4, BIT(5) },
[RST_BUS_CSI] = { 0x2c4, BIT(8) },
[RST_BUS_HDMI0] = { 0x2c4, BIT(10) },
[RST_BUS_HDMI1] = { 0x2c4, BIT(11) },
[RST_BUS_DE] = { 0x2c4, BIT(12) },
[RST_BUS_GPU] = { 0x2c4, BIT(20) },
[RST_BUS_MSGBOX] = { 0x2c4, BIT(21) },
[RST_BUS_SPINLOCK] = { 0x2c4, BIT(22) },
[RST_BUS_DBG] = { 0x2c4, BIT(31) },
[RST_BUS_LVDS] = { 0x2c8, BIT(0) },
[RST_BUS_CODEC] = { 0x2d0, BIT(0) },
[RST_BUS_SPDIF] = { 0x2d0, BIT(1) },
[RST_BUS_THS] = { 0x2d0, BIT(8) },
[RST_BUS_I2S0] = { 0x2d0, BIT(12) },
[RST_BUS_I2S1] = { 0x2d0, BIT(13) },
[RST_BUS_I2S2] = { 0x2d0, BIT(14) },
[RST_BUS_I2C0] = { 0x2d8, BIT(0) },
[RST_BUS_I2C1] = { 0x2d8, BIT(1) },
[RST_BUS_I2C2] = { 0x2d8, BIT(2) },
[RST_BUS_SCR] = { 0x2d8, BIT(5) },
[RST_BUS_UART0] = { 0x2d8, BIT(16) },
[RST_BUS_UART1] = { 0x2d8, BIT(17) },
[RST_BUS_UART2] = { 0x2d8, BIT(18) },
[RST_BUS_UART3] = { 0x2d8, BIT(19) },
[RST_BUS_UART4] = { 0x2d8, BIT(20) },
};
static const struct sunxi_ccu_desc sun50i_a64_ccu_desc = {
.ccu_clks = sun50i_a64_ccu_clks,
.num_ccu_clks = ARRAY_SIZE(sun50i_a64_ccu_clks),
.hw_clks = &sun50i_a64_hw_clks,
.resets = sun50i_a64_ccu_resets,
.num_resets = ARRAY_SIZE(sun50i_a64_ccu_resets),
};
static struct ccu_pll_nb sun50i_a64_pll_cpu_nb = {
.common = &pll_cpux_clk.common,
/* copy from pll_cpux_clk */
.enable = BIT(31),
.lock = BIT(28),
};
static struct ccu_mux_nb sun50i_a64_cpu_nb = {
.common = &cpux_clk.common,
.cm = &cpux_clk.mux,
.delay_us = 1, /* > 8 clock cycles at 24 MHz */
.bypass_index = 1, /* index of 24 MHz oscillator */
};
static int sun50i_a64_ccu_probe(struct platform_device *pdev)
{
struct resource *res;
void __iomem *reg;
u32 val;
int ret;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
reg = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(reg))
return PTR_ERR(reg);
/* Force the PLL-Audio-1x divider to 1 */
val = readl(reg + SUN50I_A64_PLL_AUDIO_REG);
val &= ~GENMASK(19, 16);
writel(val | (0 << 16), reg + SUN50I_A64_PLL_AUDIO_REG);
writel(0x515, reg + SUN50I_A64_PLL_MIPI_REG);
ret = sunxi_ccu_probe(pdev->dev.of_node, reg, &sun50i_a64_ccu_desc);
if (ret)
return ret;
/* Gate then ungate PLL CPU after any rate changes */
ccu_pll_notifier_register(&sun50i_a64_pll_cpu_nb);
/* Reparent CPU during PLL CPU rate changes */
ccu_mux_notifier_register(pll_cpux_clk.common.hw.clk,
&sun50i_a64_cpu_nb);
return 0;
}
static const struct of_device_id sun50i_a64_ccu_ids[] = {
{ .compatible = "allwinner,sun50i-a64-ccu" },
{ }
};
static struct platform_driver sun50i_a64_ccu_driver = {
.probe = sun50i_a64_ccu_probe,
.driver = {
.name = "sun50i-a64-ccu",
.of_match_table = sun50i_a64_ccu_ids,
},
};
builtin_platform_driver(sun50i_a64_ccu_driver);
| {
"language": "C"
} |
/*
**********************************************************************
* Copyright (C) 1997-2013, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*
* File USCRIPT.H
*
* Modification History:
*
* Date Name Description
* 07/06/2001 Ram Creation.
******************************************************************************
*/
#ifndef USCRIPT_H
#define USCRIPT_H
#include "unicode/utypes.h"
/**
* \file
* \brief C API: Unicode Script Information
*/
/**
* Constants for ISO 15924 script codes.
*
* Many of these script codes - those from Unicode's ScriptNames.txt -
* are character property values for Unicode's Script property.
* See UAX #24 Script Names (http://www.unicode.org/reports/tr24/).
*
* Starting with ICU 3.6, constants for most ISO 15924 script codes
* are included (currently excluding private-use codes Qaaa..Qabx).
* For scripts for which there are codes in ISO 15924 but which are not
* used in the Unicode Character Database (UCD), there are no Unicode characters
* associated with those scripts.
*
* For example, there are no characters that have a UCD script code of
* Hans or Hant. All Han ideographs have the Hani script code.
* The Hans and Hant script codes are used with CLDR data.
*
* ISO 15924 script codes are included for use with CLDR and similar.
*
* @stable ICU 2.2
*/
typedef enum UScriptCode {
/*
* Note: UScriptCode constants and their ISO script code comments
* are parsed by preparseucd.py.
* It matches lines like
* USCRIPT_<Unicode Script value name> = <integer>, / * <ISO script code> * /
*/
/** @stable ICU 2.2 */
USCRIPT_INVALID_CODE = -1,
/** @stable ICU 2.2 */
USCRIPT_COMMON = 0, /* Zyyy */
/** @stable ICU 2.2 */
USCRIPT_INHERITED = 1, /* Zinh */ /* "Code for inherited script", for non-spacing combining marks; also Qaai */
/** @stable ICU 2.2 */
USCRIPT_ARABIC = 2, /* Arab */
/** @stable ICU 2.2 */
USCRIPT_ARMENIAN = 3, /* Armn */
/** @stable ICU 2.2 */
USCRIPT_BENGALI = 4, /* Beng */
/** @stable ICU 2.2 */
USCRIPT_BOPOMOFO = 5, /* Bopo */
/** @stable ICU 2.2 */
USCRIPT_CHEROKEE = 6, /* Cher */
/** @stable ICU 2.2 */
USCRIPT_COPTIC = 7, /* Copt */
/** @stable ICU 2.2 */
USCRIPT_CYRILLIC = 8, /* Cyrl */
/** @stable ICU 2.2 */
USCRIPT_DESERET = 9, /* Dsrt */
/** @stable ICU 2.2 */
USCRIPT_DEVANAGARI = 10, /* Deva */
/** @stable ICU 2.2 */
USCRIPT_ETHIOPIC = 11, /* Ethi */
/** @stable ICU 2.2 */
USCRIPT_GEORGIAN = 12, /* Geor */
/** @stable ICU 2.2 */
USCRIPT_GOTHIC = 13, /* Goth */
/** @stable ICU 2.2 */
USCRIPT_GREEK = 14, /* Grek */
/** @stable ICU 2.2 */
USCRIPT_GUJARATI = 15, /* Gujr */
/** @stable ICU 2.2 */
USCRIPT_GURMUKHI = 16, /* Guru */
/** @stable ICU 2.2 */
USCRIPT_HAN = 17, /* Hani */
/** @stable ICU 2.2 */
USCRIPT_HANGUL = 18, /* Hang */
/** @stable ICU 2.2 */
USCRIPT_HEBREW = 19, /* Hebr */
/** @stable ICU 2.2 */
USCRIPT_HIRAGANA = 20, /* Hira */
/** @stable ICU 2.2 */
USCRIPT_KANNADA = 21, /* Knda */
/** @stable ICU 2.2 */
USCRIPT_KATAKANA = 22, /* Kana */
/** @stable ICU 2.2 */
USCRIPT_KHMER = 23, /* Khmr */
/** @stable ICU 2.2 */
USCRIPT_LAO = 24, /* Laoo */
/** @stable ICU 2.2 */
USCRIPT_LATIN = 25, /* Latn */
/** @stable ICU 2.2 */
USCRIPT_MALAYALAM = 26, /* Mlym */
/** @stable ICU 2.2 */
USCRIPT_MONGOLIAN = 27, /* Mong */
/** @stable ICU 2.2 */
USCRIPT_MYANMAR = 28, /* Mymr */
/** @stable ICU 2.2 */
USCRIPT_OGHAM = 29, /* Ogam */
/** @stable ICU 2.2 */
USCRIPT_OLD_ITALIC = 30, /* Ital */
/** @stable ICU 2.2 */
USCRIPT_ORIYA = 31, /* Orya */
/** @stable ICU 2.2 */
USCRIPT_RUNIC = 32, /* Runr */
/** @stable ICU 2.2 */
USCRIPT_SINHALA = 33, /* Sinh */
/** @stable ICU 2.2 */
USCRIPT_SYRIAC = 34, /* Syrc */
/** @stable ICU 2.2 */
USCRIPT_TAMIL = 35, /* Taml */
/** @stable ICU 2.2 */
USCRIPT_TELUGU = 36, /* Telu */
/** @stable ICU 2.2 */
USCRIPT_THAANA = 37, /* Thaa */
/** @stable ICU 2.2 */
USCRIPT_THAI = 38, /* Thai */
/** @stable ICU 2.2 */
USCRIPT_TIBETAN = 39, /* Tibt */
/** Canadian_Aboriginal script. @stable ICU 2.6 */
USCRIPT_CANADIAN_ABORIGINAL = 40, /* Cans */
/** Canadian_Aboriginal script (alias). @stable ICU 2.2 */
USCRIPT_UCAS = USCRIPT_CANADIAN_ABORIGINAL,
/** @stable ICU 2.2 */
USCRIPT_YI = 41, /* Yiii */
/* New scripts in Unicode 3.2 */
/** @stable ICU 2.2 */
USCRIPT_TAGALOG = 42, /* Tglg */
/** @stable ICU 2.2 */
USCRIPT_HANUNOO = 43, /* Hano */
/** @stable ICU 2.2 */
USCRIPT_BUHID = 44, /* Buhd */
/** @stable ICU 2.2 */
USCRIPT_TAGBANWA = 45, /* Tagb */
/* New scripts in Unicode 4 */
/** @stable ICU 2.6 */
USCRIPT_BRAILLE = 46, /* Brai */
/** @stable ICU 2.6 */
USCRIPT_CYPRIOT = 47, /* Cprt */
/** @stable ICU 2.6 */
USCRIPT_LIMBU = 48, /* Limb */
/** @stable ICU 2.6 */
USCRIPT_LINEAR_B = 49, /* Linb */
/** @stable ICU 2.6 */
USCRIPT_OSMANYA = 50, /* Osma */
/** @stable ICU 2.6 */
USCRIPT_SHAVIAN = 51, /* Shaw */
/** @stable ICU 2.6 */
USCRIPT_TAI_LE = 52, /* Tale */
/** @stable ICU 2.6 */
USCRIPT_UGARITIC = 53, /* Ugar */
/** New script code in Unicode 4.0.1 @stable ICU 3.0 */
USCRIPT_KATAKANA_OR_HIRAGANA = 54,/*Hrkt */
/* New scripts in Unicode 4.1 */
/** @stable ICU 3.4 */
USCRIPT_BUGINESE = 55, /* Bugi */
/** @stable ICU 3.4 */
USCRIPT_GLAGOLITIC = 56, /* Glag */
/** @stable ICU 3.4 */
USCRIPT_KHAROSHTHI = 57, /* Khar */
/** @stable ICU 3.4 */
USCRIPT_SYLOTI_NAGRI = 58, /* Sylo */
/** @stable ICU 3.4 */
USCRIPT_NEW_TAI_LUE = 59, /* Talu */
/** @stable ICU 3.4 */
USCRIPT_TIFINAGH = 60, /* Tfng */
/** @stable ICU 3.4 */
USCRIPT_OLD_PERSIAN = 61, /* Xpeo */
/* New script codes from ISO 15924 */
/** @stable ICU 3.6 */
USCRIPT_BALINESE = 62, /* Bali */
/** @stable ICU 3.6 */
USCRIPT_BATAK = 63, /* Batk */
/** @stable ICU 3.6 */
USCRIPT_BLISSYMBOLS = 64, /* Blis */
/** @stable ICU 3.6 */
USCRIPT_BRAHMI = 65, /* Brah */
/** @stable ICU 3.6 */
USCRIPT_CHAM = 66, /* Cham */
/** @stable ICU 3.6 */
USCRIPT_CIRTH = 67, /* Cirt */
/** @stable ICU 3.6 */
USCRIPT_OLD_CHURCH_SLAVONIC_CYRILLIC = 68, /* Cyrs */
/** @stable ICU 3.6 */
USCRIPT_DEMOTIC_EGYPTIAN = 69, /* Egyd */
/** @stable ICU 3.6 */
USCRIPT_HIERATIC_EGYPTIAN = 70, /* Egyh */
/** @stable ICU 3.6 */
USCRIPT_EGYPTIAN_HIEROGLYPHS = 71, /* Egyp */
/** @stable ICU 3.6 */
USCRIPT_KHUTSURI = 72, /* Geok */
/** @stable ICU 3.6 */
USCRIPT_SIMPLIFIED_HAN = 73, /* Hans */
/** @stable ICU 3.6 */
USCRIPT_TRADITIONAL_HAN = 74, /* Hant */
/** @stable ICU 3.6 */
USCRIPT_PAHAWH_HMONG = 75, /* Hmng */
/** @stable ICU 3.6 */
USCRIPT_OLD_HUNGARIAN = 76, /* Hung */
/** @stable ICU 3.6 */
USCRIPT_HARAPPAN_INDUS = 77, /* Inds */
/** @stable ICU 3.6 */
USCRIPT_JAVANESE = 78, /* Java */
/** @stable ICU 3.6 */
USCRIPT_KAYAH_LI = 79, /* Kali */
/** @stable ICU 3.6 */
USCRIPT_LATIN_FRAKTUR = 80, /* Latf */
/** @stable ICU 3.6 */
USCRIPT_LATIN_GAELIC = 81, /* Latg */
/** @stable ICU 3.6 */
USCRIPT_LEPCHA = 82, /* Lepc */
/** @stable ICU 3.6 */
USCRIPT_LINEAR_A = 83, /* Lina */
/** @stable ICU 4.6 */
USCRIPT_MANDAIC = 84, /* Mand */
/** @stable ICU 3.6 */
USCRIPT_MANDAEAN = USCRIPT_MANDAIC,
/** @stable ICU 3.6 */
USCRIPT_MAYAN_HIEROGLYPHS = 85, /* Maya */
/** @stable ICU 4.6 */
USCRIPT_MEROITIC_HIEROGLYPHS = 86, /* Mero */
/** @stable ICU 3.6 */
USCRIPT_MEROITIC = USCRIPT_MEROITIC_HIEROGLYPHS,
/** @stable ICU 3.6 */
USCRIPT_NKO = 87, /* Nkoo */
/** @stable ICU 3.6 */
USCRIPT_ORKHON = 88, /* Orkh */
/** @stable ICU 3.6 */
USCRIPT_OLD_PERMIC = 89, /* Perm */
/** @stable ICU 3.6 */
USCRIPT_PHAGS_PA = 90, /* Phag */
/** @stable ICU 3.6 */
USCRIPT_PHOENICIAN = 91, /* Phnx */
/** @stable ICU 3.6 */
USCRIPT_PHONETIC_POLLARD = 92, /* Plrd */
/** @stable ICU 3.6 */
USCRIPT_RONGORONGO = 93, /* Roro */
/** @stable ICU 3.6 */
USCRIPT_SARATI = 94, /* Sara */
/** @stable ICU 3.6 */
USCRIPT_ESTRANGELO_SYRIAC = 95, /* Syre */
/** @stable ICU 3.6 */
USCRIPT_WESTERN_SYRIAC = 96, /* Syrj */
/** @stable ICU 3.6 */
USCRIPT_EASTERN_SYRIAC = 97, /* Syrn */
/** @stable ICU 3.6 */
USCRIPT_TENGWAR = 98, /* Teng */
/** @stable ICU 3.6 */
USCRIPT_VAI = 99, /* Vaii */
/** @stable ICU 3.6 */
USCRIPT_VISIBLE_SPEECH = 100,/* Visp */
/** @stable ICU 3.6 */
USCRIPT_CUNEIFORM = 101,/* Xsux */
/** @stable ICU 3.6 */
USCRIPT_UNWRITTEN_LANGUAGES = 102,/* Zxxx */
/** @stable ICU 3.6 */
USCRIPT_UNKNOWN = 103,/* Zzzz */ /* Unknown="Code for uncoded script", for unassigned code points */
/* New script codes from ISO 15924 */
/** @stable ICU 3.8 */
USCRIPT_CARIAN = 104,/* Cari */
/** @stable ICU 3.8 */
USCRIPT_JAPANESE = 105,/* Jpan */
/** @stable ICU 3.8 */
USCRIPT_LANNA = 106,/* Lana */
/** @stable ICU 3.8 */
USCRIPT_LYCIAN = 107,/* Lyci */
/** @stable ICU 3.8 */
USCRIPT_LYDIAN = 108,/* Lydi */
/** @stable ICU 3.8 */
USCRIPT_OL_CHIKI = 109,/* Olck */
/** @stable ICU 3.8 */
USCRIPT_REJANG = 110,/* Rjng */
/** @stable ICU 3.8 */
USCRIPT_SAURASHTRA = 111,/* Saur */
/** @stable ICU 3.8 */
USCRIPT_SIGN_WRITING = 112,/* Sgnw */
/** @stable ICU 3.8 */
USCRIPT_SUNDANESE = 113,/* Sund */
/** @stable ICU 3.8 */
USCRIPT_MOON = 114,/* Moon */
/** @stable ICU 3.8 */
USCRIPT_MEITEI_MAYEK = 115,/* Mtei */
/* New script codes from ISO 15924 */
/** @stable ICU 4.0 */
USCRIPT_IMPERIAL_ARAMAIC = 116,/* Armi */
/** @stable ICU 4.0 */
USCRIPT_AVESTAN = 117,/* Avst */
/** @stable ICU 4.0 */
USCRIPT_CHAKMA = 118,/* Cakm */
/** @stable ICU 4.0 */
USCRIPT_KOREAN = 119,/* Kore */
/** @stable ICU 4.0 */
USCRIPT_KAITHI = 120,/* Kthi */
/** @stable ICU 4.0 */
USCRIPT_MANICHAEAN = 121,/* Mani */
/** @stable ICU 4.0 */
USCRIPT_INSCRIPTIONAL_PAHLAVI = 122,/* Phli */
/** @stable ICU 4.0 */
USCRIPT_PSALTER_PAHLAVI = 123,/* Phlp */
/** @stable ICU 4.0 */
USCRIPT_BOOK_PAHLAVI = 124,/* Phlv */
/** @stable ICU 4.0 */
USCRIPT_INSCRIPTIONAL_PARTHIAN = 125,/* Prti */
/** @stable ICU 4.0 */
USCRIPT_SAMARITAN = 126,/* Samr */
/** @stable ICU 4.0 */
USCRIPT_TAI_VIET = 127,/* Tavt */
/** @stable ICU 4.0 */
USCRIPT_MATHEMATICAL_NOTATION = 128,/* Zmth */
/** @stable ICU 4.0 */
USCRIPT_SYMBOLS = 129,/* Zsym */
/* New script codes from ISO 15924 */
/** @stable ICU 4.4 */
USCRIPT_BAMUM = 130,/* Bamu */
/** @stable ICU 4.4 */
USCRIPT_LISU = 131,/* Lisu */
/** @stable ICU 4.4 */
USCRIPT_NAKHI_GEBA = 132,/* Nkgb */
/** @stable ICU 4.4 */
USCRIPT_OLD_SOUTH_ARABIAN = 133,/* Sarb */
/* New script codes from ISO 15924 */
/** @stable ICU 4.6 */
USCRIPT_BASSA_VAH = 134,/* Bass */
/** @stable ICU 4.6 */
USCRIPT_DUPLOYAN_SHORTAND = 135,/* Dupl */
/** @stable ICU 4.6 */
USCRIPT_ELBASAN = 136,/* Elba */
/** @stable ICU 4.6 */
USCRIPT_GRANTHA = 137,/* Gran */
/** @stable ICU 4.6 */
USCRIPT_KPELLE = 138,/* Kpel */
/** @stable ICU 4.6 */
USCRIPT_LOMA = 139,/* Loma */
/** @stable ICU 4.6 */
USCRIPT_MENDE = 140,/* Mend */
/** @stable ICU 4.6 */
USCRIPT_MEROITIC_CURSIVE = 141,/* Merc */
/** @stable ICU 4.6 */
USCRIPT_OLD_NORTH_ARABIAN = 142,/* Narb */
/** @stable ICU 4.6 */
USCRIPT_NABATAEAN = 143,/* Nbat */
/** @stable ICU 4.6 */
USCRIPT_PALMYRENE = 144,/* Palm */
/** @stable ICU 4.6 */
USCRIPT_SINDHI = 145,/* Sind */
/** @stable ICU 4.6 */
USCRIPT_WARANG_CITI = 146,/* Wara */
/** @stable ICU 4.8 */
USCRIPT_AFAKA = 147,/* Afak */
/** @stable ICU 4.8 */
USCRIPT_JURCHEN = 148,/* Jurc */
/** @stable ICU 4.8 */
USCRIPT_MRO = 149,/* Mroo */
/** @stable ICU 4.8 */
USCRIPT_NUSHU = 150,/* Nshu */
/** @stable ICU 4.8 */
USCRIPT_SHARADA = 151,/* Shrd */
/** @stable ICU 4.8 */
USCRIPT_SORA_SOMPENG = 152,/* Sora */
/** @stable ICU 4.8 */
USCRIPT_TAKRI = 153,/* Takr */
/** @stable ICU 4.8 */
USCRIPT_TANGUT = 154,/* Tang */
/** @stable ICU 4.8 */
USCRIPT_WOLEAI = 155,/* Wole */
/** @stable ICU 49 */
USCRIPT_ANATOLIAN_HIEROGLYPHS = 156,/* Hluw */
/** @stable ICU 49 */
USCRIPT_KHOJKI = 157,/* Khoj */
/** @stable ICU 49 */
USCRIPT_TIRHUTA = 158,/* Tirh */
/* Private use codes from Qaaa - Qabx are not supported */
/** @stable ICU 2.2 */
USCRIPT_CODE_LIMIT = 159
} UScriptCode;
/**
* Gets script codes associated with the given locale or ISO 15924 abbreviation or name.
* Fills in USCRIPT_MALAYALAM given "Malayam" OR "Mlym".
* Fills in USCRIPT_LATIN given "en" OR "en_US"
* If required capacity is greater than capacity of the destination buffer then the error code
* is set to U_BUFFER_OVERFLOW_ERROR and the required capacity is returned
*
* <p>Note: To search by short or long script alias only, use
* u_getPropertyValueEnum(UCHAR_SCRIPT, alias) instead. This does
* a fast lookup with no access of the locale data.
* @param nameOrAbbrOrLocale name of the script, as given in
* PropertyValueAliases.txt, or ISO 15924 code or locale
* @param fillIn the UScriptCode buffer to fill in the script code
* @param capacity the capacity (size) fo UScriptCode buffer passed in.
* @param err the error status code.
* @return The number of script codes filled in the buffer passed in
* @stable ICU 2.4
*/
U_STABLE int32_t U_EXPORT2
uscript_getCode(const char* nameOrAbbrOrLocale,UScriptCode* fillIn,int32_t capacity,UErrorCode *err);
/**
* Gets a script name associated with the given script code.
* Returns "Malayam" given USCRIPT_MALAYALAM
* @param scriptCode UScriptCode enum
* @return script long name as given in
* PropertyValueAliases.txt, or NULL if scriptCode is invalid
* @stable ICU 2.4
*/
U_STABLE const char* U_EXPORT2
uscript_getName(UScriptCode scriptCode);
/**
* Gets a script name associated with the given script code.
* Returns "Mlym" given USCRIPT_MALAYALAM
* @param scriptCode UScriptCode enum
* @return script abbreviated name as given in
* PropertyValueAliases.txt, or NULL if scriptCode is invalid
* @stable ICU 2.4
*/
U_STABLE const char* U_EXPORT2
uscript_getShortName(UScriptCode scriptCode);
/**
* Gets the script code associated with the given codepoint.
* Returns USCRIPT_MALAYALAM given 0x0D02
* @param codepoint UChar32 codepoint
* @param err the error status code.
* @return The UScriptCode, or 0 if codepoint is invalid
* @stable ICU 2.4
*/
U_STABLE UScriptCode U_EXPORT2
uscript_getScript(UChar32 codepoint, UErrorCode *err);
/**
* Do the Script_Extensions of code point c contain script sc?
* If c does not have explicit Script_Extensions, then this tests whether
* c has the Script property value sc.
*
* Some characters are commonly used in multiple scripts.
* For more information, see UAX #24: http://www.unicode.org/reports/tr24/.
*
* The Script_Extensions property is provisional. It may be modified or removed
* in future versions of the Unicode Standard, and thus in ICU.
* @param c code point
* @param sc script code
* @return TRUE if sc is in Script_Extensions(c)
* @stable ICU 49
*/
U_STABLE UBool U_EXPORT2
uscript_hasScript(UChar32 c, UScriptCode sc);
/**
* Writes code point c's Script_Extensions as a list of UScriptCode values
* to the output scripts array and returns the number of script codes.
* - If c does have Script_Extensions, then the Script property value
* (normally Common or Inherited) is not included.
* - If c does not have Script_Extensions, then the one Script code is written to the output array.
* - If c is not a valid code point, then the one USCRIPT_UNKNOWN code is written.
* In other words, if the return value is 1,
* then the output array contains exactly c's single Script code.
* If the return value is n>=2, then the output array contains c's n Script_Extensions script codes.
*
* Some characters are commonly used in multiple scripts.
* For more information, see UAX #24: http://www.unicode.org/reports/tr24/.
*
* If there are more than capacity script codes to be written, then
* U_BUFFER_OVERFLOW_ERROR is set and the number of Script_Extensions is returned.
* (Usual ICU buffer handling behavior.)
*
* The Script_Extensions property is provisional. It may be modified or removed
* in future versions of the Unicode Standard, and thus in ICU.
* @param c code point
* @param scripts output script code array
* @param capacity capacity of the scripts array
* @param errorCode Standard ICU error code. Its input value must
* pass the U_SUCCESS() test, or else the function returns
* immediately. Check for U_FAILURE() on output or use with
* function chaining. (See User Guide for details.)
* @return number of script codes in c's Script_Extensions, or 1 for the single Script value,
* written to scripts unless U_BUFFER_OVERFLOW_ERROR indicates insufficient capacity
* @stable ICU 49
*/
U_STABLE int32_t U_EXPORT2
uscript_getScriptExtensions(UChar32 c,
UScriptCode *scripts, int32_t capacity,
UErrorCode *errorCode);
#ifndef U_HIDE_DRAFT_API
/**
* Script usage constants.
* See UAX #31 Unicode Identifier and Pattern Syntax.
* http://www.unicode.org/reports/tr31/#Table_Candidate_Characters_for_Exclusion_from_Identifiers
*
* @draft ICU 51
*/
typedef enum UScriptUsage {
/** Not encoded in Unicode. @draft ICU 51 */
USCRIPT_USAGE_NOT_ENCODED,
/** Unknown script usage. @draft ICU 51 */
USCRIPT_USAGE_UNKNOWN,
/** Candidate for Exclusion from Identifiers. @draft ICU 51 */
USCRIPT_USAGE_EXCLUDED,
/** Limited Use script. @draft ICU 51 */
USCRIPT_USAGE_LIMITED_USE,
/** Aspirational Use script. @draft ICU 51 */
USCRIPT_USAGE_ASPIRATIONAL,
/** Recommended script. @draft ICU 51 */
USCRIPT_USAGE_RECOMMENDED
} UScriptUsage;
/**
* Writes the script sample character string.
* This string normally consists of one code point but might be longer.
* The string is empty if the script is not encoded.
*
* @param script script code
* @param dest output string array
* @param capacity number of UChars in the dest array
* @param pErrorCode standard ICU in/out error code, must pass U_SUCCESS() on input
* @return the string length, even if U_BUFFER_OVERFLOW_ERROR
* @draft ICU 51
*/
U_DRAFT int32_t U_EXPORT2
uscript_getSampleString(UScriptCode script, UChar *dest, int32_t capacity, UErrorCode *pErrorCode);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
class UnicodeString;
U_NAMESPACE_END
/**
* Returns the script sample character string.
* This string normally consists of one code point but might be longer.
* The string is empty if the script is not encoded.
*
* @param script script code
* @return the sample character string
* @draft ICU 51
*/
U_COMMON_API icu::UnicodeString U_EXPORT2
uscript_getSampleUnicodeString(UScriptCode script);
#endif
/**
* Returns the script usage according to UAX #31 Unicode Identifier and Pattern Syntax.
* Returns USCRIPT_USAGE_NOT_ENCODED if the script is not encoded in Unicode.
*
* @param script script code
* @return script usage
* @see UScriptUsage
* @draft ICU 51
*/
U_DRAFT UScriptUsage U_EXPORT2
uscript_getUsage(UScriptCode script);
/**
* Returns TRUE if the script is written right-to-left.
* For example, Arab and Hebr.
*
* @param script script code
* @return TRUE if the script is right-to-left
* @draft ICU 51
*/
U_DRAFT UBool U_EXPORT2
uscript_isRightToLeft(UScriptCode script);
/**
* Returns TRUE if the script allows line breaks between letters (excluding hyphenation).
* Such a script typically requires dictionary-based line breaking.
* For example, Hani and Thai.
*
* @param script script code
* @return TRUE if the script allows line breaks between letters
* @draft ICU 51
*/
U_DRAFT UBool U_EXPORT2
uscript_breaksBetweenLetters(UScriptCode script);
/**
* Returns TRUE if in modern (or most recent) usage of the script case distinctions are customary.
* For example, Latn and Cyrl.
*
* @param script script code
* @return TRUE if the script is cased
* @draft ICU 51
*/
U_DRAFT UBool U_EXPORT2
uscript_isCased(UScriptCode script);
#endif /* U_HIDE_DRAFT_API */
#endif
| {
"language": "C"
} |
/******************************************************************************
*
* (c) Copyright 2008, RealTEK Technologies Inc. All Rights Reserved.
*
* Module: Efuse.c ( Source C File)
*
* Note: Copy from WMAC for the first version!!!!
*
*
* Function:
*
* Export:
*
* Abbrev:
*
* History:
* Data Who Remark
*
* 09/23/2008 MHC Porting Efuse R/W API from WMAC.
* 11/10/2008 MHC 1. Porting from 8712 EFUSE.
* 2. Add description and reorganize code arch.
* 11/16/2008 MHC 1. Reorganize code architecture.
* 2. Rename for some API and change extern or static type.
*
******************************************************************************/
#include "r8192U.h"
#include "r8192S_hw.h"
#include "r8192S_phy.h"
#include "r8192S_phyreg.h"
#include "r8192S_Efuse.h"
#include <linux/types.h>
//typedef int INT32;
//
// In the future, we will always support EFUSE!!
//
/*---------------------------Define Local Constant---------------------------*/
#define _POWERON_DELAY_
#define _PRE_EXECUTE_READ_CMD_
#define EFUSE_REPEAT_THRESHOLD_ 3
#define EFUSE_ERROE_HANDLE 1
// From 8712!!!!!
typedef struct _EFUSE_MAP_A{
u8 offset; //0~15
u8 word_start; //0~3
u8 byte_start; //0 or 1
u8 byte_cnts;
}EFUSE_MAP, *PEFUSE_MAP;
typedef struct PG_PKT_STRUCT_A{
u8 offset;
u8 word_en;
u8 data[8];
}PGPKT_STRUCT,*PPGPKT_STRUCT;
typedef enum _EFUSE_DATA_ITEM{
EFUSE_CHIP_ID=0,
EFUSE_LDO_SETTING,
EFUSE_CLK_SETTING,
EFUSE_SDIO_SETTING,
EFUSE_CCCR,
EFUSE_SDIO_MODE,
EFUSE_OCR,
EFUSE_F0CIS,
EFUSE_F1CIS,
EFUSE_MAC_ADDR,
EFUSE_EEPROM_VER,
EFUSE_CHAN_PLAN,
EFUSE_TXPW_TAB
} EFUSE_DATA_ITEM;
struct efuse_priv
{
u8 id[2];
u8 ldo_setting[2];
u8 clk_setting[2];
u8 cccr;
u8 sdio_mode;
u8 ocr[3];
u8 cis0[17];
u8 cis1[48];
u8 mac_addr[6];
u8 eeprom_verno;
u8 channel_plan;
u8 tx_power_b[14];
u8 tx_power_g[14];
};
/*---------------------------Define Local Constant---------------------------*/
/*------------------------Define global variable-----------------------------*/
const u8 MAX_PGPKT_SIZE = 9; //header+ 2* 4 words (BYTES)
const u8 PGPKT_DATA_SIZE = 8; //BYTES sizeof(u8)*8
const u32 EFUSE_MAX_SIZE = 512;
const EFUSE_MAP RTL8712_SDIO_EFUSE_TABLE[]={
//offset word_s byte_start byte_cnts
/*ID*/ {0 ,0 ,0 ,2 }, // 00~01h
/*LDO Setting*/ {0 ,1 ,0 ,2 }, // 02~03h
/*CLK Setting*/ {0 ,2 ,0 ,2 }, // 04~05h
/*SDIO Setting*/ {1 ,0 ,0 ,1 }, // 08h
/*CCCR*/ {1 ,0 ,1 ,1 }, // 09h
/*SDIO MODE*/ {1 ,1 ,0 ,1 }, // 0Ah
/*OCR*/ {1 ,1 ,1 ,3 }, // 0B~0Dh
/*CCIS*/ {1 ,3 ,0 ,17 }, // 0E~1Eh 2...1
/*F1CIS*/ {3 ,3 ,1 ,48 }, // 1F~4Eh 6...0
/*MAC Addr*/ {10 ,0 ,0 ,6 }, // 50~55h
/*EEPROM ver*/ {10 ,3 ,0 ,1 }, // 56h
/*Channel plan*/ {10 ,3 ,1 ,1 }, // 57h
/*TxPwIndex */ {11 ,0 ,0 ,28 } // 58~73h 3...4
};
/*------------------------Define global variable-----------------------------*/
/*------------------------Define local variable------------------------------*/
/*------------------------Define local variable------------------------------*/
/*--------------------Define function prototype-----------------------*/
//
// From WMAC Efuse one byte R/W
//
extern void
EFUSE_Initialize(struct net_device* dev);
extern u8
EFUSE_Read1Byte(struct net_device* dev, u16 Address);
extern void
EFUSE_Write1Byte(struct net_device* dev, u16 Address,u8 Value);
//
// Efuse Shadow Area operation
//
static void
efuse_ShadowRead1Byte(struct net_device* dev,u16 Offset,u8 *Value);
static void
efuse_ShadowRead2Byte(struct net_device* dev, u16 Offset,u16 *Value );
static void
efuse_ShadowRead4Byte(struct net_device* dev, u16 Offset,u32 *Value );
static void
efuse_ShadowWrite1Byte(struct net_device* dev, u16 Offset, u8 Value);
static void
efuse_ShadowWrite2Byte(struct net_device* dev, u16 Offset,u16 Value);
static void
efuse_ShadowWrite4Byte(struct net_device* dev, u16 Offset,u32 Value);
//
// Real Efuse operation
//
static u8
efuse_OneByteRead(struct net_device* dev,u16 addr,u8 *data);
static u8
efuse_OneByteWrite(struct net_device* dev,u16 addr, u8 data);
//
// HW setting map file operation
//
static void
efuse_ReadAllMap(struct net_device* dev,u8 *Efuse);
#ifdef TO_DO_LIST
static void
efuse_WriteAllMap(struct net_device* dev,u8 *eeprom,u32 eeprom_size);
static bool
efuse_ParsingMap(char* szStr,u32* pu4bVal,u32* pu4bMove);
#endif
//
// Reald Efuse R/W or other operation API.
//
static u8
efuse_PgPacketRead( struct net_device* dev,u8 offset,u8 *data);
static u8
efuse_PgPacketWrite(struct net_device* dev,u8 offset,u8 word_en,u8 *data);
static void
efuse_WordEnableDataRead( u8 word_en,u8 *sourdata,u8 *targetdata);
static u8
efuse_WordEnableDataWrite( struct net_device* dev, u16 efuse_addr, u8 word_en, u8 *data);
static void
efuse_PowerSwitch(struct net_device* dev,u8 PwrState);
static u16
efuse_GetCurrentSize(struct net_device* dev);
static u8
efuse_CalculateWordCnts(u8 word_en);
//
// API for power on power off!!!
//
#ifdef TO_DO_LIST
static void efuse_reg_ctrl(struct net_device* dev, u8 bPowerOn);
#endif
/*--------------------Define function prototype-----------------------*/
/*-----------------------------------------------------------------------------
* Function: EFUSE_Initialize
*
* Overview: Copy from WMAC fot EFUSE testing setting init.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 09/23/2008 MHC Copy from WMAC.
*
*---------------------------------------------------------------------------*/
extern void
EFUSE_Initialize(struct net_device* dev)
{
u8 Bytetemp = {0x00};
u8 temp = {0x00};
//Enable Digital Core Vdd : 0x2[13]=1
Bytetemp = read_nic_byte(dev, SYS_FUNC_EN+1);
temp = Bytetemp | 0x20;
write_nic_byte(dev, SYS_FUNC_EN+1, temp);
//EE loader to retention path1: attach 0x0[8]=0
Bytetemp = read_nic_byte(dev, SYS_ISO_CTRL+1);
temp = Bytetemp & 0xFE;
write_nic_byte(dev, SYS_ISO_CTRL+1, temp);
//Enable E-fuse use 2.5V LDO : 0x37[7]=1
Bytetemp = read_nic_byte(dev, EFUSE_TEST+3);
temp = Bytetemp | 0x80;
write_nic_byte(dev, EFUSE_TEST+3, temp);
//E-fuse clk switch from 500k to 40M : 0x2F8[1:0]=11b
write_nic_byte(dev, 0x2F8, 0x3);
//Set E-fuse program time & read time : 0x30[30:24]=1110010b
write_nic_byte(dev, EFUSE_CTRL+3, 0x72);
} /* EFUSE_Initialize */
/*-----------------------------------------------------------------------------
* Function: EFUSE_Read1Byte
*
* Overview: Copy from WMAC fot EFUSE read 1 byte.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 09/23/2008 MHC Copy from WMAC.
*
*---------------------------------------------------------------------------*/
extern u8
EFUSE_Read1Byte(struct net_device* dev, u16 Address)
{
u8 data;
u8 Bytetemp = {0x00};
u8 temp = {0x00};
u32 k=0;
if (Address < EFUSE_MAC_LEN) //E-fuse 512Byte
{
//Write E-fuse Register address bit0~7
temp = Address & 0xFF;
write_nic_byte(dev, EFUSE_CTRL+1, temp);
Bytetemp = read_nic_byte(dev, EFUSE_CTRL+2);
//Write E-fuse Register address bit8~9
temp = ((Address >> 8) & 0x03) | (Bytetemp & 0xFC);
write_nic_byte(dev, EFUSE_CTRL+2, temp);
//Write 0x30[31]=0
Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
temp = Bytetemp & 0x7F;
write_nic_byte(dev, EFUSE_CTRL+3, temp);
//Wait Write-ready (0x30[31]=1)
Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
while(!(Bytetemp & 0x80))
{
Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
k++;
if(k==1000)
{
k=0;
break;
}
}
data=read_nic_byte(dev, EFUSE_CTRL);
return data;
}
else
return 0xFF;
} /* EFUSE_Read1Byte */
/*-----------------------------------------------------------------------------
* Function: EFUSE_Write1Byte
*
* Overview: Copy from WMAC fot EFUSE write 1 byte.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 09/23/2008 MHC Copy from WMAC.
*
*---------------------------------------------------------------------------*/
extern void
EFUSE_Write1Byte(struct net_device* dev, u16 Address,u8 Value)
{
//u8 data;
u8 Bytetemp = {0x00};
u8 temp = {0x00};
u32 k=0;
//RT_TRACE(COMP_EFUSE, "Addr=%x Data =%x\n", Address, Value);
if( Address < EFUSE_MAC_LEN) //E-fuse 512Byte
{
write_nic_byte(dev, EFUSE_CTRL, Value);
//Write E-fuse Register address bit0~7
temp = Address & 0xFF;
write_nic_byte(dev, EFUSE_CTRL+1, temp);
Bytetemp = read_nic_byte(dev, EFUSE_CTRL+2);
//Write E-fuse Register address bit8~9
temp = ((Address >> 8) & 0x03) | (Bytetemp & 0xFC);
write_nic_byte(dev, EFUSE_CTRL+2, temp);
//Write 0x30[31]=1
Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
temp = Bytetemp | 0x80;
write_nic_byte(dev, EFUSE_CTRL+3, temp);
//Wait Write-ready (0x30[31]=0)
Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
while(Bytetemp & 0x80)
{
Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
k++;
if(k==100)
{
k=0;
break;
}
}
}
} /* EFUSE_Write1Byte */
#ifdef EFUSE_FOR_92SU
//
// Description:
// 1. Process CR93C46 Data polling cycle.
// 2. Refered from SD1 Richard.
//
// Assumption:
// 1. Boot from E-Fuse and successfully auto-load.
// 2. PASSIVE_LEVEL (USB interface)
//
// Created by Roger, 2008.10.21.
//
void do_93c46(struct net_device* dev, u8 addorvalue)
{
//u8 clear[1] = {0x0}; // cs=0 , sk=0 , di=0 , do=0
u8 cs[1] = {0x88}; // cs=1 , sk=0 , di=0 , do=0
u8 cssk[1] = {0x8c}; // cs=1 , sk=1 , di=0 , do=0
u8 csdi[1] = {0x8a}; // cs=1 , sk=0 , di=1 , do=0
u8 csskdi[1] = {0x8e}; // cs=1 , sk=1 , di=1 , do=0
//u8 di[1] = {0x82}; // cs=0 , sk=0 , di=1 , do=0
u8 count;
for(count=0 ; count<8 ; count++)
{
if((addorvalue&0x80)!=0)
{
write_nic_byte(dev, EPROM_CMD, csdi[0]);
write_nic_byte(dev, EPROM_CMD, csskdi[0]);
}
else
{
write_nic_byte(dev, EPROM_CMD, cs[0]);
write_nic_byte(dev, EPROM_CMD, cssk[0]);
}
addorvalue = addorvalue << 1;
}
}
//
// Description:
// Process CR93C46 Data read polling cycle.
// Refered from SD1 Richard.
//
// Assumption:
// 1. Boot from E-Fuse and successfully auto-load.
// 2. PASSIVE_LEVEL (USB interface)
//
// Created by Roger, 2008.10.21.
//
u16 Read93C46(struct net_device* dev, u16 Reg )
{
u8 clear[1] = {0x0}; // cs=0 , sk=0 , di=0 , do=0
u8 cs[1] = {0x88}; // cs=1 , sk=0 , di=0 , do=0
u8 cssk[1] = {0x8c}; // cs=1 , sk=1 , di=0 , do=0
u8 csdi[1] = {0x8a}; // cs=1 , sk=0 , di=1 , do=0
u8 csskdi[1] = {0x8e}; // cs=1 , sk=1 , di=1 , do=0
//u8 di[1] = {0x82}; // cs=0 , sk=0 , di=1 , do=0
u8 EepromSEL[1]={0x00};
u8 address;
u16 storedataF[1] = {0x0}; //93c46 data packet for 16bits
u8 t,data[1],storedata[1];
address = (u8)Reg;
// Suggested by SD1 Alex, 2008.10.20. Revised by Roger.
*EepromSEL= read_nic_byte(dev, EPROM_CMD);
if((*EepromSEL & 0x10) == 0x10) // select 93c46
{
address = address | 0x80;
write_nic_byte(dev, EPROM_CMD, csdi[0]);
write_nic_byte(dev, EPROM_CMD, csskdi[0]);
do_93c46(dev, address);
}
for(t=0 ; t<16 ; t++) //if read 93c46 , t=16
{
write_nic_byte(dev, EPROM_CMD, cs[0]);
write_nic_byte(dev, EPROM_CMD, cssk[0]);
*data= read_nic_byte(dev, EPROM_CMD);
if(*data & 0x8d) //original code
{
*data = *data & 0x01;
*storedata = *data;
}
else
{
*data = *data & 0x01 ;
*storedata = *data;
}
*storedataF = (*storedataF << 1 ) + *storedata;
}
write_nic_byte(dev, EPROM_CMD, cs[0]);
write_nic_byte(dev, EPROM_CMD, clear[0]);
return *storedataF;
}
//
// Description:
// Execute E-Fuse read byte operation.
// Refered from SD1 Richard.
//
// Assumption:
// 1. Boot from E-Fuse and successfully auto-load.
// 2. PASSIVE_LEVEL (USB interface)
//
// Created by Roger, 2008.10.21.
//
void
ReadEFuseByte(struct net_device* dev,u16 _offset, u8 *pbuf)
{
//u16 indexk=0;
u32 value32;
u8 readbyte;
u16 retry;
//Write Address
write_nic_byte(dev, EFUSE_CTRL+1, (_offset & 0xff));
readbyte = read_nic_byte(dev, EFUSE_CTRL+2);
write_nic_byte(dev, EFUSE_CTRL+2, ((_offset >> 8) & 0x03) | (readbyte & 0xfc));
//Write bit 32 0
readbyte = read_nic_byte(dev, EFUSE_CTRL+3);
write_nic_byte(dev, EFUSE_CTRL+3, (readbyte & 0x7f));
//Check bit 32 read-ready
retry = 0;
value32 = read_nic_dword(dev, EFUSE_CTRL);
//while(!(((value32 >> 24) & 0xff) & 0x80) && (retry<10))
while(!(((value32 >> 24) & 0xff) & 0x80) && (retry<10000))
{
value32 = read_nic_dword(dev, EFUSE_CTRL);
retry++;
}
*pbuf = (u8)(value32 & 0xff);
}
#define EFUSE_READ_SWITCH 1
//
// Description:
// 1. Execute E-Fuse read byte operation according as map offset and
// save to E-Fuse table.
// 2. Refered from SD1 Richard.
//
// Assumption:
// 1. Boot from E-Fuse and successfully auto-load.
// 2. PASSIVE_LEVEL (USB interface)
//
// Created by Roger, 2008.10.21.
//
void
ReadEFuse(struct net_device* dev, u16 _offset, u16 _size_byte, u8 *pbuf)
{
u8 efuseTbl[128];
u8 rtemp8[1];
u16 eFuse_Addr = 0;
u8 offset, wren;
u16 i, j;
u16 eFuseWord[16][4];// = {0xFF};//FIXLZM
for(i=0; i<16; i++)
for(j=0; j<4; j++)
eFuseWord[i][j]=0xFF;
// Do NOT excess total size of EFuse table. Added by Roger, 2008.11.10.
if((_offset + _size_byte)>128)
{// total E-Fuse table is 128bytes
//RT_TRACE(COMP_EFUSE, "ReadEFuse(): Invalid offset(%#x) with read bytes(%#x)!!\n",_offset, _size_byte);
printk("ReadEFuse(): Invalid offset with read bytes!!\n");
return;
}
// Refresh efuse init map as all oxFF.
for (i = 0; i < 128; i++)
efuseTbl[i] = 0xFF;
#if (EFUSE_READ_SWITCH == 1)
ReadEFuseByte(dev, eFuse_Addr, rtemp8);
#else
rtemp8[0] = EFUSE_Read1Byte(dev, eFuse_Addr);
#endif
if(*rtemp8 != 0xFF) eFuse_Addr++;
while((*rtemp8 != 0xFF) && (eFuse_Addr < 512)){
offset = ((*rtemp8 >> 4) & 0x0f);
if(offset <= 0x0F){
wren = (*rtemp8 & 0x0f);
for(i=0; i<4; i++){
if(!(wren & 0x01)){
#if (EFUSE_READ_SWITCH == 1)
ReadEFuseByte(dev, eFuse_Addr, rtemp8); eFuse_Addr++;
#else
rtemp8[0] = EFUSE_Read1Byte(dev, eFuse_Addr); eFuse_Addr++;
#endif
eFuseWord[offset][i] = (*rtemp8 & 0xff);
if(eFuse_Addr >= 512) break;
#if (EFUSE_READ_SWITCH == 1)
ReadEFuseByte(dev, eFuse_Addr, rtemp8); eFuse_Addr++;
#else
rtemp8[0] = EFUSE_Read1Byte(dev, eFuse_Addr); eFuse_Addr++;
#endif
eFuseWord[offset][i] |= (((u16)*rtemp8 << 8) & 0xff00);
if(eFuse_Addr >= 512) break;
}
wren >>= 1;
}
}
#if (EFUSE_READ_SWITCH == 1)
ReadEFuseByte(dev, eFuse_Addr, rtemp8);
#else
rtemp8[0] = EFUSE_Read1Byte(dev, eFuse_Addr); eFuse_Addr++;
#endif
if(*rtemp8 != 0xFF && (eFuse_Addr < 512)) eFuse_Addr++;
}
for(i=0; i<16; i++){
for(j=0; j<4; j++){
efuseTbl[(i*8)+(j*2)]=(eFuseWord[i][j] & 0xff);
efuseTbl[(i*8)+((j*2)+1)]=((eFuseWord[i][j] >> 8) & 0xff);
}
}
for(i=0; i<_size_byte; i++)
pbuf[i] = efuseTbl[_offset+i];
}
#endif // #if (EFUSE_FOR_92SU == 1)
/*-----------------------------------------------------------------------------
* Function: EFUSE_ShadowRead
*
* Overview: Read from efuse init map !!!!!
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/12/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
extern void
EFUSE_ShadowRead( struct net_device* dev, u8 Type, u16 Offset, u32 *Value)
{
//HAL_DATA_TYPE *pHalData = GET_HAL_DATA(pAdapter);
if (Type == 1)
efuse_ShadowRead1Byte(dev, Offset, (u8 *)Value);
else if (Type == 2)
efuse_ShadowRead2Byte(dev, Offset, (u16 *)Value);
else if (Type == 4)
efuse_ShadowRead4Byte(dev, Offset, (u32 *)Value);
} // EFUSE_ShadowRead
/*-----------------------------------------------------------------------------
* Function: EFUSE_ShadowWrite
*
* Overview: Write efuse modify map for later update operation to use!!!!!
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/12/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
extern void
EFUSE_ShadowWrite( struct net_device* dev, u8 Type, u16 Offset,u32 Value)
{
//HAL_DATA_TYPE *pHalData = GET_HAL_DATA(pAdapter);
if (Offset >= 0x18 && Offset <= 0x1F)
return;
if (Type == 1)
efuse_ShadowWrite1Byte(dev, Offset, (u8)Value);
else if (Type == 2)
efuse_ShadowWrite2Byte(dev, Offset, (u16)Value);
else if (Type == 4)
efuse_ShadowWrite4Byte(dev, Offset, (u32)Value);
} // EFUSE_ShadowWrite
/*-----------------------------------------------------------------------------
* Function: EFUSE_ShadowUpdate
*
* Overview: Compare init and modify map to update Efuse!!!!!
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/12/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
extern void
EFUSE_ShadowUpdate(struct net_device* dev)
{
//HAL_DATA_TYPE *pHalData = GET_HAL_DATA(pAdapter);
struct r8192_priv *priv = ieee80211_priv(dev);
u16 i, offset, base = 0;
u8 word_en = 0x0F;
bool first_pg = false;
// For Efuse write action, we must enable LDO2.5V and 40MHZ clk.
efuse_PowerSwitch(dev, TRUE);
//
// Efuse support 16 write are with PG header packet!!!!
//
for (offset = 0; offset < 16; offset++)
{
// Offset 0x18-1F are reserved now!!!
word_en = 0x0F;
base = offset * 8;
//
// Decide Word Enable Bit for the Efuse section
// One section contain 4 words = 8 bytes!!!!!
//
for (i = 0; i < 8; i++)
{
if (offset == 0 && priv->EfuseMap[EFUSE_INIT_MAP][base+i] == 0xFF)
{
first_pg = TRUE;
}
// 2008/12/11 MH HW autoload fail workaround for A/BCUT.
if (first_pg == TRUE)
{
word_en &= ~(1<<(i/2));
priv->EfuseMap[EFUSE_INIT_MAP][base+i] =
priv->EfuseMap[EFUSE_MODIFY_MAP][base+i];
}else
{
if ( priv->EfuseMap[EFUSE_INIT_MAP][base+i] !=
priv->EfuseMap[EFUSE_MODIFY_MAP][base+i])
{
word_en &= ~(EFUSE_BIT(i/2));
//RT_TRACE(COMP_EFUSE, "Offset=%d Addr%x %x ==> %x Word_En=%02x\n",
//offset, base+i, priv->EfuseMap[0][base+i], priv->EfuseMap[1][base+i],word_en);
// Update init table!!!
priv->EfuseMap[EFUSE_INIT_MAP][base+i] =
priv->EfuseMap[EFUSE_MODIFY_MAP][base+i];
}
}
}
//
// Call Efuse real write section !!!!
//
if (word_en != 0x0F)
{
u8 tmpdata[8];
//FIXLZM
memcpy(tmpdata, &(priv->EfuseMap[EFUSE_MODIFY_MAP][base]), 8);
//RT_PRINT_DATA(COMP_INIT, DBG_LOUD, ("U-EFUSE\n"), tmpdata, 8);
efuse_PgPacketWrite(dev,(u8)offset,word_en,tmpdata);
}
}
// 2008/12/01 MH For Efuse HW load bug workarounf method!!!!
// We will force write 0x10EC into address 10&11 after all Efuse content.
//
// For warm reboot, we must resume Efuse clock to 500K.
efuse_PowerSwitch(dev, FALSE);
// 2008/12/01 MH We update shadow content again!!!!
EFUSE_ShadowMapUpdate(dev);
} // EFUSE_ShadowUpdate
/*-----------------------------------------------------------------------------
* Function: EFUSE_ShadowMapUpdate
*
* Overview: Transfer current EFUSE content to shadow init and modify map.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/13/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
extern void EFUSE_ShadowMapUpdate(struct net_device* dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
if (priv->AutoloadFailFlag == true){
memset(&(priv->EfuseMap[EFUSE_INIT_MAP][0]), 0xff, 128);
}else{
efuse_ReadAllMap(dev, &priv->EfuseMap[EFUSE_INIT_MAP][0]);
}
//PlatformMoveMemory(&priv->EfuseMap[EFUSE_MODIFY_MAP][0],
//&priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);//FIXLZM
memcpy(&priv->EfuseMap[EFUSE_MODIFY_MAP][0],
&priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);
} // EFUSE_ShadowMapUpdate
extern void
EFUSE_ForceWriteVendorId( struct net_device* dev)
{
u8 tmpdata[8] = {0xFF, 0xFF, 0xEC, 0x10, 0xFF, 0xFF, 0xFF, 0xFF};
efuse_PowerSwitch(dev, TRUE);
efuse_PgPacketWrite(dev, 1, 0xD, tmpdata);
efuse_PowerSwitch(dev, FALSE);
} // EFUSE_ForceWriteVendorId
/*-----------------------------------------------------------------------------
* Function: efuse_ShadowRead1Byte
* efuse_ShadowRead2Byte
* efuse_ShadowRead4Byte
*
* Overview: Read from efuse init map by one/two/four bytes !!!!!
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/12/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
static void
efuse_ShadowRead1Byte(struct net_device* dev, u16 Offset, u8 *Value)
{
struct r8192_priv *priv = ieee80211_priv(dev);
*Value = priv->EfuseMap[EFUSE_MODIFY_MAP][Offset];
} // EFUSE_ShadowRead1Byte
//---------------Read Two Bytes
static void
efuse_ShadowRead2Byte(struct net_device* dev, u16 Offset, u16 *Value)
{
struct r8192_priv *priv = ieee80211_priv(dev);
*Value = priv->EfuseMap[EFUSE_MODIFY_MAP][Offset];
*Value |= priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+1]<<8;
} // EFUSE_ShadowRead2Byte
//---------------Read Four Bytes
static void
efuse_ShadowRead4Byte(struct net_device* dev, u16 Offset, u32 *Value)
{
struct r8192_priv *priv = ieee80211_priv(dev);
*Value = priv->EfuseMap[EFUSE_MODIFY_MAP][Offset];
*Value |= priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+1]<<8;
*Value |= priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+2]<<16;
*Value |= priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+3]<<24;
} // efuse_ShadowRead4Byte
/*-----------------------------------------------------------------------------
* Function: efuse_ShadowWrite1Byte
* efuse_ShadowWrite2Byte
* efuse_ShadowWrite4Byte
*
* Overview: Write efuse modify map by one/two/four byte.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/12/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
static void
efuse_ShadowWrite1Byte(struct net_device* dev, u16 Offset, u8 Value)
{
struct r8192_priv *priv = ieee80211_priv(dev);
priv->EfuseMap[EFUSE_MODIFY_MAP][Offset] = Value;
} // efuse_ShadowWrite1Byte
//---------------Write Two Bytes
static void
efuse_ShadowWrite2Byte(struct net_device* dev, u16 Offset, u16 Value)
{
struct r8192_priv *priv = ieee80211_priv(dev);
priv->EfuseMap[EFUSE_MODIFY_MAP][Offset] = Value&0x00FF;
priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+1] = Value>>8;
} // efuse_ShadowWrite1Byte
//---------------Write Four Bytes
static void
efuse_ShadowWrite4Byte(struct net_device* dev, u16 Offset, u32 Value)
{
struct r8192_priv *priv = ieee80211_priv(dev);
priv->EfuseMap[EFUSE_MODIFY_MAP][Offset] = (u8)(Value&0x000000FF);
priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+1] = (u8)((Value>>8)&0x0000FF);
priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+2] = (u8)((Value>>16)&0x00FF);
priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+3] = (u8)((Value>>24)&0xFF);
} // efuse_ShadowWrite1Byte
/* 11/16/2008 MH Read one byte from real Efuse. */
static u8
efuse_OneByteRead(struct net_device* dev, u16 addr,u8 *data)
{
u8 tmpidx = 0;
u8 bResult;
// -----------------e-fuse reg ctrl ---------------------------------
//address
write_nic_byte(dev, EFUSE_CTRL+1, (u8)(addr&0xff));
write_nic_byte(dev, EFUSE_CTRL+2, ((u8)((addr>>8) &0x03) ) |
(read_nic_byte(dev, EFUSE_CTRL+2)&0xFC ));
write_nic_byte(dev, EFUSE_CTRL+3, 0x72);//read cmd
while(!(0x80 &read_nic_byte(dev, EFUSE_CTRL+3))&&(tmpidx<100))
{
tmpidx++;
}
if(tmpidx<100)
{
*data=read_nic_byte(dev, EFUSE_CTRL);
bResult = TRUE;
}
else
{
*data = 0xff;
bResult = FALSE;
}
return bResult;
} // efuse_OneByteRead
/* 11/16/2008 MH Write one byte to reald Efuse. */
static u8
efuse_OneByteWrite(struct net_device* dev, u16 addr, u8 data)
{
u8 tmpidx = 0;
u8 bResult;
//RT_TRACE(COMP_EFUSE, "Addr = %x Data=%x\n", addr, data);
//return 0;
// -----------------e-fuse reg ctrl ---------------------------------
//address
write_nic_byte(dev, EFUSE_CTRL+1, (u8)(addr&0xff));
write_nic_byte(dev, EFUSE_CTRL+2,
read_nic_byte(dev, EFUSE_CTRL+2)|(u8)((addr>>8)&0x03) );
write_nic_byte(dev, EFUSE_CTRL, data);//data
write_nic_byte(dev, EFUSE_CTRL+3, 0xF2);//write cmd
while((0x80 & read_nic_byte(dev, EFUSE_CTRL+3)) && (tmpidx<100) ){
tmpidx++;
}
if(tmpidx<100)
{
bResult = TRUE;
}
else
{
bResult = FALSE;
}
return bResult;
} // efuse_OneByteWrite
/*-----------------------------------------------------------------------------
* Function: efuse_ReadAllMap
*
* Overview: Read All Efuse content
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/11/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
static void
efuse_ReadAllMap(struct net_device* dev, u8 *Efuse)
{
//u8 pg_data[8];
//u8 offset = 0;
//u8 tmpidx;
//static u8 index = 0;
//
// We must enable clock and LDO 2.5V otherwise, read all map will be fail!!!!
//
efuse_PowerSwitch(dev, TRUE);
ReadEFuse(dev, 0, 128, Efuse);
efuse_PowerSwitch(dev, FALSE);
} // efuse_ReadAllMap
/*-----------------------------------------------------------------------------
* Function: efuse_WriteAllMap
*
* Overview: Write All Efuse content
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/11/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
#ifdef TO_DO_LIST
static void
efuse_WriteAllMap(struct net_device* dev,u8 *eeprom, u32 eeprom_size)
{
unsigned char word_en = 0x00;
unsigned char tmpdata[8];
unsigned char offset;
// For Efuse write action, we must enable LDO2.5V and 40MHZ clk.
efuse_PowerSwitch(dev, TRUE);
//sdio contents
for(offset=0 ; offset< eeprom_size/PGPKT_DATA_SIZE ; offset++)
{
// 92S will only reserv 0x18-1F 8 bytes now. The 3rd efuse write area!
if (IS_HARDWARE_TYPE_8192SE(dev))
{
// Refer to
// 0x18-1f Reserve >0x50 Reserve for tx power
if (offset == 3/* || offset > 9*/)
continue;//word_en = 0x0F;
//else if (offset == 9) // 0x4c-4f Reserve
//word_en = 0x0C;
else
word_en = 0x00;
}
//RT_TRACE(COMP_EFUSE, ("Addr=%d size=%d Word_En=%02x\n", offset, eeprom_size, word_en));
//memcpy(tmpdata,eeprom+(offset*PGPKT_DATA_SIZE),8);
memcpy(tmpdata, (eeprom+(offset*PGPKT_DATA_SIZE)), 8);
//RT_PRINT_DATA(COMP_INIT, DBG_LOUD, ("EFUSE\t"), tmpdata, 8);
efuse_PgPacketWrite(dev,offset,word_en,tmpdata);
}
// For warm reboot, we must resume Efuse clock to 500K.
efuse_PowerSwitch(dev, FALSE);
} // efuse_WriteAllMap
#endif
/*-----------------------------------------------------------------------------
* Function: efuse_PgPacketRead
*
* Overview: Receive dedicated Efuse are content. For92s, we support 16
* area now. It will return 8 bytes content for every area.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/16/2008 MHC Reorganize code Arch and assign as local API.
*
*---------------------------------------------------------------------------*/
static u8
efuse_PgPacketRead( struct net_device* dev, u8 offset, u8 *data)
{
u8 ReadState = PG_STATE_HEADER;
bool bContinual = TRUE;
bool bDataEmpty = TRUE ;
u8 efuse_data,word_cnts=0;
u16 efuse_addr = 0;
u8 hoffset=0,hworden=0;
u8 tmpidx=0;
u8 tmpdata[8];
if(data==NULL) return FALSE;
if(offset>15) return FALSE;
//FIXLZM
//PlatformFillMemory((PVOID)data, sizeof(u8)*PGPKT_DATA_SIZE, 0xff);
//PlatformFillMemory((PVOID)tmpdata, sizeof(u8)*PGPKT_DATA_SIZE, 0xff);
memset(data, 0xff, sizeof(u8)*PGPKT_DATA_SIZE);
memset(tmpdata, 0xff, sizeof(u8)*PGPKT_DATA_SIZE);
//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("efuse_PgPacketRead-1\n"), data, 8);
//efuse_reg_ctrl(pAdapter,TRUE);//power on
while(bContinual && (efuse_addr < EFUSE_MAX_SIZE) )
{
//------- Header Read -------------
if(ReadState & PG_STATE_HEADER)
{
if(efuse_OneByteRead(dev, efuse_addr ,&efuse_data)&&(efuse_data!=0xFF)){
hoffset = (efuse_data>>4) & 0x0F;
hworden = efuse_data & 0x0F;
word_cnts = efuse_CalculateWordCnts(hworden);
bDataEmpty = TRUE ;
if(hoffset==offset){
for(tmpidx = 0;tmpidx< word_cnts*2 ;tmpidx++){
if(efuse_OneByteRead(dev, efuse_addr+1+tmpidx ,&efuse_data) ){
tmpdata[tmpidx] = efuse_data;
if(efuse_data!=0xff){
bDataEmpty = FALSE;
}
}
}
if(bDataEmpty==FALSE){
ReadState = PG_STATE_DATA;
}else{//read next header
efuse_addr = efuse_addr + (word_cnts*2)+1;
ReadState = PG_STATE_HEADER;
}
}
else{//read next header
efuse_addr = efuse_addr + (word_cnts*2)+1;
ReadState = PG_STATE_HEADER;
}
}
else{
bContinual = FALSE ;
}
}
//------- Data section Read -------------
else if(ReadState & PG_STATE_DATA)
{
efuse_WordEnableDataRead(hworden,tmpdata,data);
efuse_addr = efuse_addr + (word_cnts*2)+1;
ReadState = PG_STATE_HEADER;
}
}
//efuse_reg_ctrl(pAdapter,FALSE);//power off
//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("efuse_PgPacketRead-2\n"), data, 8);
if( (data[0]==0xff) &&(data[1]==0xff) && (data[2]==0xff) && (data[3]==0xff) &&
(data[4]==0xff) &&(data[5]==0xff) && (data[6]==0xff) && (data[7]==0xff))
return FALSE;
else
return TRUE;
} // efuse_PgPacketRead
/*-----------------------------------------------------------------------------
* Function: efuse_PgPacketWrite
*
* Overview: Send A G package for different section in real efuse area.
* For 92S, One PG package contain 8 bytes content and 4 word
* unit. PG header = 0x[bit7-4=offset][bit3-0word enable]
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/16/2008 MHC Reorganize code Arch and assign as local API.
*
*---------------------------------------------------------------------------*/
static u8 efuse_PgPacketWrite(struct net_device* dev, u8 offset, u8 word_en,u8 *data)
{
u8 WriteState = PG_STATE_HEADER;
bool bContinual = TRUE,bDataEmpty=TRUE, bResult = TRUE;
u16 efuse_addr = 0;
u8 efuse_data;
u8 pg_header = 0;
//u16 tmp_addr=0;
u8 tmp_word_cnts=0,target_word_cnts=0;
u8 tmp_header,match_word_en,tmp_word_en;
//u8 efuse_clk_ori,efuse_clk_new;
PGPKT_STRUCT target_pkt;
PGPKT_STRUCT tmp_pkt;
u8 originaldata[sizeof(u8)*8];
u8 tmpindex = 0,badworden = 0x0F;
static u32 repeat_times = 0;
if( efuse_GetCurrentSize(dev) >= EFUSE_MAX_SIZE)
{
printk("efuse_PgPacketWrite error \n");
return FALSE;
}
// Init the 8 bytes content as 0xff
target_pkt.offset = offset;
target_pkt.word_en= word_en;
//PlatformFillMemory((PVOID)target_pkt.data, sizeof(u8)*8, 0xFF);
memset(target_pkt.data,0xFF,sizeof(u8)*8);
efuse_WordEnableDataRead(word_en,data,target_pkt.data);
target_word_cnts = efuse_CalculateWordCnts(target_pkt.word_en);
//efuse_reg_ctrl(pAdapter,TRUE);//power on
printk("EFUSE Power ON\n");
while( bContinual && (efuse_addr < EFUSE_MAX_SIZE) )
{
if(WriteState==PG_STATE_HEADER)
{
bDataEmpty=TRUE;
badworden = 0x0F;
//************ so *******************
printk("EFUSE PG_STATE_HEADER\n");
if ( efuse_OneByteRead(dev, efuse_addr ,&efuse_data) &&
(efuse_data!=0xFF))
{
tmp_header = efuse_data;
tmp_pkt.offset = (tmp_header>>4) & 0x0F;
tmp_pkt.word_en = tmp_header & 0x0F;
tmp_word_cnts = efuse_CalculateWordCnts(tmp_pkt.word_en);
//************ so-1 *******************
if(tmp_pkt.offset != target_pkt.offset)
{
efuse_addr = efuse_addr + (tmp_word_cnts*2) +1; //Next pg_packet
#if (EFUSE_ERROE_HANDLE == 1)
WriteState = PG_STATE_HEADER;
#endif
}
else
{
//************ so-2 *******************
for(tmpindex=0 ; tmpindex<(tmp_word_cnts*2) ; tmpindex++)
{
if(efuse_OneByteRead(dev, (efuse_addr+1+tmpindex) ,&efuse_data)&&(efuse_data != 0xFF)){
bDataEmpty = FALSE;
}
}
//************ so-2-1 *******************
if(bDataEmpty == FALSE)
{
efuse_addr = efuse_addr + (tmp_word_cnts*2) +1; //Next pg_packet
#if (EFUSE_ERROE_HANDLE == 1)
WriteState=PG_STATE_HEADER;
#endif
}
else
{//************ so-2-2 *******************
match_word_en = 0x0F;
if( !( (target_pkt.word_en&BIT0)|(tmp_pkt.word_en&BIT0) ))
{
match_word_en &= (~BIT0);
}
if( !( (target_pkt.word_en&BIT1)|(tmp_pkt.word_en&BIT1) ))
{
match_word_en &= (~BIT1);
}
if( !( (target_pkt.word_en&BIT2)|(tmp_pkt.word_en&BIT2) ))
{
match_word_en &= (~BIT2);
}
if( !( (target_pkt.word_en&BIT3)|(tmp_pkt.word_en&BIT3) ))
{
match_word_en &= (~BIT3);
}
//************ so-2-2-A *******************
if((match_word_en&0x0F)!=0x0F)
{
badworden = efuse_WordEnableDataWrite(dev,efuse_addr+1, tmp_pkt.word_en ,target_pkt.data);
//************ so-2-2-A-1 *******************
//############################
if(0x0F != (badworden&0x0F))
{
u8 reorg_offset = offset;
u8 reorg_worden=badworden;
efuse_PgPacketWrite(dev,reorg_offset,reorg_worden,originaldata);
}
//############################
tmp_word_en = 0x0F;
if( (target_pkt.word_en&BIT0)^(match_word_en&BIT0) )
{
tmp_word_en &= (~BIT0);
}
if( (target_pkt.word_en&BIT1)^(match_word_en&BIT1) )
{
tmp_word_en &= (~BIT1);
}
if( (target_pkt.word_en&BIT2)^(match_word_en&BIT2) )
{
tmp_word_en &= (~BIT2);
}
if( (target_pkt.word_en&BIT3)^(match_word_en&BIT3) )
{
tmp_word_en &=(~BIT3);
}
//************ so-2-2-A-2 *******************
if((tmp_word_en&0x0F)!=0x0F){
//reorganize other pg packet
//efuse_addr = efuse_addr + (2*tmp_word_cnts) +1;//next pg packet addr
efuse_addr = efuse_GetCurrentSize(dev);
//===========================
target_pkt.offset = offset;
target_pkt.word_en= tmp_word_en;
//===========================
}else{
bContinual = FALSE;
}
#if (EFUSE_ERROE_HANDLE == 1)
WriteState=PG_STATE_HEADER;
repeat_times++;
if(repeat_times>EFUSE_REPEAT_THRESHOLD_){
bContinual = FALSE;
bResult = FALSE;
}
#endif
}
else{//************ so-2-2-B *******************
//reorganize other pg packet
efuse_addr = efuse_addr + (2*tmp_word_cnts) +1;//next pg packet addr
//===========================
target_pkt.offset = offset;
target_pkt.word_en= target_pkt.word_en;
//===========================
#if (EFUSE_ERROE_HANDLE == 1)
WriteState=PG_STATE_HEADER;
#endif
}
}
}
printk("EFUSE PG_STATE_HEADER-1\n");
}
else //************ s1: header == oxff *******************
{
pg_header = ((target_pkt.offset << 4)&0xf0) |target_pkt.word_en;
efuse_OneByteWrite(dev,efuse_addr, pg_header);
efuse_OneByteRead(dev,efuse_addr, &tmp_header);
if(tmp_header == pg_header)
{ //************ s1-1*******************
WriteState = PG_STATE_DATA;
}
#if (EFUSE_ERROE_HANDLE == 1)
else if(tmp_header == 0xFF){//************ s1-3: if Write or read func doesn't work *******************
//efuse_addr doesn't change
WriteState = PG_STATE_HEADER;
repeat_times++;
if(repeat_times>EFUSE_REPEAT_THRESHOLD_){
bContinual = FALSE;
bResult = FALSE;
}
}
#endif
else
{//************ s1-2 : fixed the header procedure *******************
tmp_pkt.offset = (tmp_header>>4) & 0x0F;
tmp_pkt.word_en= tmp_header & 0x0F;
tmp_word_cnts = efuse_CalculateWordCnts(tmp_pkt.word_en);
//************ s1-2-A :cover the exist data *******************
memset(originaldata,0xff,sizeof(u8)*8);
//PlatformFillMemory((PVOID)originaldata, sizeof(u8)*8, 0xff);
if(efuse_PgPacketRead( dev, tmp_pkt.offset,originaldata))
{ //check if data exist
//efuse_reg_ctrl(pAdapter,TRUE);//power on
badworden = efuse_WordEnableDataWrite(dev,efuse_addr+1,tmp_pkt.word_en,originaldata);
//############################
if(0x0F != (badworden&0x0F))
{
u8 reorg_offset = tmp_pkt.offset;
u8 reorg_worden=badworden;
efuse_PgPacketWrite(dev,reorg_offset,reorg_worden,originaldata);
efuse_addr = efuse_GetCurrentSize(dev);
}
//############################
else{
efuse_addr = efuse_addr + (tmp_word_cnts*2) +1; //Next pg_packet
}
}
//************ s1-2-B: wrong address*******************
else
{
efuse_addr = efuse_addr + (tmp_word_cnts*2) +1; //Next pg_packet
}
#if (EFUSE_ERROE_HANDLE == 1)
WriteState=PG_STATE_HEADER;
repeat_times++;
if(repeat_times>EFUSE_REPEAT_THRESHOLD_){
bContinual = FALSE;
bResult = FALSE;
}
#endif
printk("EFUSE PG_STATE_HEADER-2\n");
}
}
}
//write data state
else if(WriteState==PG_STATE_DATA)
{ //************ s1-1 *******************
printk("EFUSE PG_STATE_DATA\n");
badworden = 0x0f;
badworden = efuse_WordEnableDataWrite(dev,efuse_addr+1,target_pkt.word_en,target_pkt.data);
if((badworden&0x0F)==0x0F)
{ //************ s1-1-A *******************
bContinual = FALSE;
}
else
{//reorganize other pg packet //************ s1-1-B *******************
efuse_addr = efuse_addr + (2*target_word_cnts) +1;//next pg packet addr
//===========================
target_pkt.offset = offset;
target_pkt.word_en= badworden;
target_word_cnts = efuse_CalculateWordCnts(target_pkt.word_en);
//===========================
#if (EFUSE_ERROE_HANDLE == 1)
WriteState=PG_STATE_HEADER;
repeat_times++;
if(repeat_times>EFUSE_REPEAT_THRESHOLD_){
bContinual = FALSE;
bResult = FALSE;
}
#endif
printk("EFUSE PG_STATE_HEADER-3\n");
}
}
}
//efuse_reg_ctrl(pAdapter,FALSE);//power off
return TRUE;
} // efuse_PgPacketWrite
/*-----------------------------------------------------------------------------
* Function: efuse_WordEnableDataRead
*
* Overview: Read allowed word in current efuse section data.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/16/2008 MHC Create Version 0.
* 11/21/2008 MHC Fix Write bug when we only enable late word.
*
*---------------------------------------------------------------------------*/
static void
efuse_WordEnableDataRead( u8 word_en,u8 *sourdata,u8 *targetdata)
{
//u8 tmpindex = 0;
//DbgPrint("efuse_WordEnableDataRead word_en = %x\n", word_en);
//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("sourdata\n"), sourdata, 8);
//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("targetdata\n"), targetdata, 8);
if (!(word_en&BIT0))
{
targetdata[0] = sourdata[0];//sourdata[tmpindex++];
targetdata[1] = sourdata[1];//sourdata[tmpindex++];
}
if (!(word_en&BIT1))
{
targetdata[2] = sourdata[2];//sourdata[tmpindex++];
targetdata[3] = sourdata[3];//sourdata[tmpindex++];
}
if (!(word_en&BIT2))
{
targetdata[4] = sourdata[4];//sourdata[tmpindex++];
targetdata[5] = sourdata[5];//sourdata[tmpindex++];
}
if (!(word_en&BIT3))
{
targetdata[6] = sourdata[6];//sourdata[tmpindex++];
targetdata[7] = sourdata[7];//sourdata[tmpindex++];
}
} // efuse_WordEnableDataRead
/*-----------------------------------------------------------------------------
* Function: efuse_WordEnableDataWrite
*
* Overview: Write necessary word unit into current efuse section!
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/16/2008 MHC Reorganize Efuse operate flow!!.
*
*---------------------------------------------------------------------------*/
static u8
efuse_WordEnableDataWrite( struct net_device* dev, u16 efuse_addr, u8 word_en, u8 *data)
{
u16 tmpaddr = 0;
u16 start_addr = efuse_addr;
u8 badworden = 0x0F;
//u8 NextState;
u8 tmpdata[8];
memset(tmpdata,0xff,PGPKT_DATA_SIZE);
//PlatformFillMemory((PVOID)tmpdata, PGPKT_DATA_SIZE, 0xff);
//RT_TRACE(COMP_EFUSE, "word_en = %x efuse_addr=%x\n", word_en, efuse_addr);
//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("U-EFUSE\n"), data, 8);
if(!(word_en&BIT0))
{
tmpaddr = start_addr;
efuse_OneByteWrite(dev,start_addr++, data[0]);
efuse_OneByteWrite(dev,start_addr++, data[1]);
efuse_OneByteRead(dev,tmpaddr, &tmpdata[0]);
efuse_OneByteRead(dev,tmpaddr+1, &tmpdata[1]);
if((data[0]!=tmpdata[0])||(data[1]!=tmpdata[1])){
badworden &= (~BIT0);
}
}
if(!(word_en&BIT1))
{
tmpaddr = start_addr;
efuse_OneByteWrite(dev,start_addr++, data[2]);
efuse_OneByteWrite(dev,start_addr++, data[3]);
efuse_OneByteRead(dev,tmpaddr , &tmpdata[2]);
efuse_OneByteRead(dev,tmpaddr+1, &tmpdata[3]);
if((data[2]!=tmpdata[2])||(data[3]!=tmpdata[3])){
badworden &=( ~BIT1);
}
}
if(!(word_en&BIT2))
{
tmpaddr = start_addr;
efuse_OneByteWrite(dev,start_addr++, data[4]);
efuse_OneByteWrite(dev,start_addr++, data[5]);
efuse_OneByteRead(dev,tmpaddr, &tmpdata[4]);
efuse_OneByteRead(dev,tmpaddr+1, &tmpdata[5]);
if((data[4]!=tmpdata[4])||(data[5]!=tmpdata[5])){
badworden &=( ~BIT2);
}
}
if(!(word_en&BIT3))
{
tmpaddr = start_addr;
efuse_OneByteWrite(dev,start_addr++, data[6]);
efuse_OneByteWrite(dev,start_addr++, data[7]);
efuse_OneByteRead(dev,tmpaddr, &tmpdata[6]);
efuse_OneByteRead(dev,tmpaddr+1, &tmpdata[7]);
if((data[6]!=tmpdata[6])||(data[7]!=tmpdata[7])){
badworden &=( ~BIT3);
}
}
return badworden;
} // efuse_WordEnableDataWrite
/*-----------------------------------------------------------------------------
* Function: efuse_PowerSwitch
*
* Overview: When we want to enable write operation, we should change to
* pwr on state. When we stop write, we should switch to 500k mode
* and disable LDO 2.5V.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/17/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
static void
efuse_PowerSwitch(struct net_device* dev, u8 PwrState)
{
u8 tempval;
if (PwrState == TRUE)
{
// Enable LDO 2.5V for write action
tempval = read_nic_byte(dev, EFUSE_TEST+3);
write_nic_byte(dev, EFUSE_TEST+3, (tempval | 0x80));
// Change Efuse Clock for write action to 40MHZ
write_nic_byte(dev, EFUSE_CLK, 0x03);
}
else
{
// Enable LDO 2.5V for write action
tempval = read_nic_byte(dev, EFUSE_TEST+3);
write_nic_byte(dev, EFUSE_TEST+3, (tempval & 0x7F));
// Change Efuse Clock for write action to 500K
write_nic_byte(dev, EFUSE_CLK, 0x02);
}
} /* efuse_PowerSwitch */
/*-----------------------------------------------------------------------------
* Function: efuse_GetCurrentSize
*
* Overview: Get current efuse size!!!
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/16/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
static u16
efuse_GetCurrentSize(struct net_device* dev)
{
bool bContinual = TRUE;
u16 efuse_addr = 0;
u8 hoffset=0,hworden=0;
u8 efuse_data,word_cnts=0;
//efuse_reg_ctrl(pAdapter,TRUE);//power on
while ( bContinual &&
efuse_OneByteRead(dev, efuse_addr ,&efuse_data) &&
(efuse_addr < EFUSE_MAX_SIZE) )
{
if(efuse_data!=0xFF)
{
hoffset = (efuse_data>>4) & 0x0F;
hworden = efuse_data & 0x0F;
word_cnts = efuse_CalculateWordCnts(hworden);
//read next header
efuse_addr = efuse_addr + (word_cnts*2)+1;
}
else
{
bContinual = FALSE ;
}
}
//efuse_reg_ctrl(pAdapter,FALSE);//power off
return efuse_addr;
} // efuse_GetCurrentSize}
/* 11/16/2008 MH Add description. Get current efuse area enabled word!!. */
static u8
efuse_CalculateWordCnts(u8 word_en)
{
u8 word_cnts = 0;
if(!(word_en & BIT0)) word_cnts++; // 0 : write enable
if(!(word_en & BIT1)) word_cnts++;
if(!(word_en & BIT2)) word_cnts++;
if(!(word_en & BIT3)) word_cnts++;
return word_cnts;
} // efuse_CalculateWordCnts
/*-----------------------------------------------------------------------------
* Function: EFUSE_ProgramMap
*
* Overview: Read EFUSE map file and execute PG.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/10/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
#ifdef TO_DO_LIST
extern bool // 0=Shadow 1=Real Efuse
EFUSE_ProgramMap(struct net_device* dev, char* pFileName,u8 TableType)
{
struct r8192_priv *priv = ieee80211_priv(dev);
s4Byte nLinesRead, ithLine;
RT_STATUS rtStatus = RT_STATUS_SUCCESS;
char* szLine;
u32 u4bRegValue, u4RegMask;
u32 u4bMove;
u16 index = 0;
u16 i;
u8 eeprom[HWSET_MAX_SIZE_92S];
rtStatus = PlatformReadFile(
dev,
pFileName,
(u8*)(priv->BufOfLines),
MAX_LINES_HWCONFIG_TXT,
MAX_BYTES_LINE_HWCONFIG_TXT,
&nLinesRead
);
if(rtStatus == RT_STATUS_SUCCESS)
{
memcp(pHalData->BufOfLines3, pHalData->BufOfLines,
nLinesRead*MAX_BYTES_LINE_HWCONFIG_TXT);
pHalData->nLinesRead3 = nLinesRead;
}
if(rtStatus == RT_STATUS_SUCCESS)
{
printk("szEepromFile(): read %s ok\n", pFileName);
for(ithLine = 0; ithLine < nLinesRead; ithLine++)
{
szLine = pHalData->BufOfLines[ithLine];
printk("Line-%d String =%s\n", ithLine, szLine);
if(!IsCommentString(szLine))
{
// EEPROM map one line has 8 words content.
for (i = 0; i < 8; i++)
{
u32 j;
//GetHexValueFromString(szLine, &u4bRegValue, &u4bMove);
efuse_ParsingMap(szLine, &u4bRegValue, &u4bMove);
// Get next hex value as EEPROM value.
szLine += u4bMove;
//WriteEEprom(dev, (u16)(ithLine*8+i), (u16)u4bRegValue);
eeprom[index++] = (u8)(u4bRegValue&0xff);
eeprom[index++] = (u8)((u4bRegValue>>8)&0xff);
printk("Addr-%d = %x\n", (ithLine*8+i), u4bRegValue);
}
}
}
}
else
{
printk("szEepromFile(): Fail read%s\n", pFileName);
return RT_STATUS_FAILURE;
}
//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("EFUSE "), eeprom, HWSET_MAX_SIZE_92S);
// Use map file to update real Efuse or shadow modify table.
if (TableType == 1)
{
efuse_WriteAllMap(dev, eeprom, HWSET_MAX_SIZE_92S);
}
else
{
// Modify shadow table.
for (i = 0; i < HWSET_MAX_SIZE_92S; i++)
EFUSE_ShadowWrite(dev, 1, i, (u32)eeprom[i]);
}
return rtStatus;
} /* EFUSE_ProgramMap */
#endif
//
// Description:
// Return TRUE if chTmp is represent for hex digit and
// FALSE otherwise.
//
//
bool IsHexDigit( char chTmp)
{
if( (chTmp >= '0' && chTmp <= '9') ||
(chTmp >= 'a' && chTmp <= 'f') ||
(chTmp >= 'A' && chTmp <= 'F') )
{
return TRUE;
}
else
{
return FALSE;
}
}
//
// Description:
// Translate a character to hex digit.
//
u32 MapCharToHexDigit(char chTmp)
{
if(chTmp >= '0' && chTmp <= '9')
return (chTmp - '0');
else if(chTmp >= 'a' && chTmp <= 'f')
return (10 + (chTmp - 'a'));
else if(chTmp >= 'A' && chTmp <= 'F')
return (10 + (chTmp - 'A'));
else
return 0;
}
/*-----------------------------------------------------------------------------
* Function: efuse_ParsingMap
*
* Overview:
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 11/08/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
#ifdef TO_DO_LIST
static bool
efuse_ParsingMap(char* szStr,u32* pu4bVal,u32* pu4bMove)
{
char* szScan = szStr;
// Check input parameter.
if(szStr == NULL || pu4bVal == NULL || pu4bMove == NULL)
{
//RT_TRACE(COMP_EFUSE,
//"eeprom_ParsingMap(): Invalid IN args! szStr: %p, pu4bVal: %p, pu4bMove: %p\n",
//szStr, pu4bVal, pu4bMove);
return FALSE;
}
// Initialize output.
*pu4bMove = 0;
*pu4bVal = 0;
// Skip leading space.
while( *szScan != '\0' &&
(*szScan == ' ' || *szScan == '\t') )
{
szScan++;
(*pu4bMove)++;
}
// Check if szScan is now pointer to a character for hex digit,
// if not, it means this is not a valid hex number.
if(!IsHexDigit(*szScan))
{
return FALSE;
}
// Parse each digit.
do
{
(*pu4bVal) <<= 4;
*pu4bVal += MapCharToHexDigit(*szScan);
szScan++;
(*pu4bMove)++;
} while(IsHexDigit(*szScan));
return TRUE;
} /* efuse_ParsingMap */
#endif
//
// Useless Section Code Now!!!!!!
//
// Porting from 8712 SDIO
int efuse_one_byte_rw(struct net_device* dev, u8 bRead, u16 addr, u8 *data)
{
u32 bResult;
//u8 efuse_ctlreg,tmpidx = 0;
u8 tmpidx = 0;
u8 tmpv8=0;
// -----------------e-fuse reg ctrl ---------------------------------
write_nic_byte(dev, EFUSE_CTRL+1, (u8)(addr&0xff)); //address
tmpv8 = ((u8)((addr>>8) &0x03) ) | (read_nic_byte(dev, EFUSE_CTRL+2)&0xFC );
write_nic_byte(dev, EFUSE_CTRL+2, tmpv8);
if(TRUE==bRead){
write_nic_byte(dev, EFUSE_CTRL+3, 0x72);//read cmd
while(!(0x80 & read_nic_byte(dev, EFUSE_CTRL+3)) && (tmpidx<100) ){
tmpidx++;
}
if(tmpidx<100){
*data=read_nic_byte(dev, EFUSE_CTRL);
bResult = TRUE;
}
else
{
*data = 0;
bResult = FALSE;
}
}
else{
//return 0;
write_nic_byte(dev, EFUSE_CTRL, *data);//data
write_nic_byte(dev, EFUSE_CTRL+3, 0xF2);//write cmd
while((0x80 & read_nic_byte(dev, EFUSE_CTRL+3)) && (tmpidx<100) ){
tmpidx++;
}
if(tmpidx<100)
{
*data=read_nic_byte(dev, EFUSE_CTRL);
bResult = TRUE;
}
else
{
*data = 0;
bResult = FALSE;
}
}
return bResult;
}
//------------------------------------------------------------------------------
void efuse_access(struct net_device* dev, u8 bRead,u16 start_addr, u8 cnts, u8 *data)
{
u8 efuse_clk_ori,efuse_clk_new;//,tmp8;
u32 i = 0;
if(start_addr>0x200) return;
//RT_TRACE(_module_rtl871x_mp_ioctl_c_,_drv_err_,
// ("\n ===> efuse_access [start_addr=0x%x cnts:%d dataarray:0x%08x Query Efuse].\n",start_addr,cnts,data));
// -----------------SYS_FUNC_EN Digital Core Vdd enable ---------------------------------
efuse_clk_ori = read_nic_byte(dev,SYS_FUNC_EN+1);
efuse_clk_new = efuse_clk_ori|0x20;
if(efuse_clk_new!= efuse_clk_ori){
//RT_TRACE(_module_rtl871x_mp_ioctl_c_,_drv_err_,("====write 0x10250003=====\n"));
write_nic_byte(dev, SYS_FUNC_EN+1, efuse_clk_new);
}
#ifdef _POWERON_DELAY_
mdelay(10);
#endif
// -----------------e-fuse pwr & clk reg ctrl ---------------------------------
write_nic_byte(dev, EFUSE_TEST+3, (read_nic_byte(dev, EFUSE_TEST+3)|0x80));
write_nic_byte(dev, EFUSE_CLK_CTRL, (read_nic_byte(dev, EFUSE_CLK_CTRL)|0x03));
#ifdef _PRE_EXECUTE_READ_CMD_
{
unsigned char tmpdata;
efuse_OneByteRead(dev, 0,&tmpdata);
}
#endif
//-----------------e-fuse one byte read / write ------------------------------
for(i=0;i<cnts;i++){
efuse_one_byte_rw(dev,bRead, start_addr+i , data+i);
////RT_TRACE(_module_rtl871x_mp_ioctl_c_,_drv_err_,("==>efuse_access addr:0x%02x value:0x%02x\n",data+i,*(data+i)));
}
// -----------------e-fuse pwr & clk reg ctrl ---------------------------------
write_nic_byte(dev, EFUSE_TEST+3, read_nic_byte(dev, EFUSE_TEST+3)&0x7f);
write_nic_byte(dev, EFUSE_CLK_CTRL, read_nic_byte(dev, EFUSE_CLK_CTRL)&0xfd);
// -----------------SYS_FUNC_EN Digital Core Vdd disable ---------------------------------
if(efuse_clk_new != efuse_clk_ori) write_nic_byte(dev, 0x10250003, efuse_clk_ori);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#ifdef TO_DO_LIST
static void efuse_reg_ctrl(struct net_device* dev, u8 bPowerOn)
{
if(TRUE==bPowerOn){
// -----------------SYS_FUNC_EN Digital Core Vdd enable ---------------------------------
write_nic_byte(dev, SYS_FUNC_EN+1, read_nic_byte(dev,SYS_FUNC_EN+1)|0x20);
#ifdef _POWERON_DELAY_
mdelay(10);
#endif
// -----------------e-fuse pwr & clk reg ctrl ---------------------------------
write_nic_byte(dev, EFUSE_TEST+4, (read_nic_byte(dev, EFUSE_TEST+4)|0x80));
write_nic_byte(dev, EFUSE_CLK_CTRL, (read_nic_byte(dev, EFUSE_CLK_CTRL)|0x03));
#ifdef _PRE_EXECUTE_READ_CMD_
{
unsigned char tmpdata;
efuse_OneByteRead(dev, 0,&tmpdata);
}
#endif
}
else{
// -----------------e-fuse pwr & clk reg ctrl ---------------------------------
write_nic_byte(dev, EFUSE_TEST+4, read_nic_byte(dev, EFUSE_TEST+4)&0x7f);
write_nic_byte(dev, EFUSE_CLK_CTRL, read_nic_byte(dev, EFUSE_CLK_CTRL)&0xfd);
// -----------------SYS_FUNC_EN Digital Core Vdd disable ---------------------------------
//write_nic_byte(pAdapter, SYS_FUNC_EN+1, read_nic_byte(pAdapter,SYS_FUNC_EN+1)&0xDF);
}
}
#endif
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void efuse_read_data(struct net_device* dev,u8 efuse_read_item,u8 *data,u32 data_size)
{
u8 offset, word_start,byte_start,byte_cnts;
u8 efusedata[EFUSE_MAC_LEN];
u8 *tmpdata = NULL;
u8 pg_pkt_cnts ;
u8 tmpidx;
u8 pg_data[8];
//u8 temp_value[8] = {0xff};
if(efuse_read_item> (sizeof(RTL8712_SDIO_EFUSE_TABLE)/sizeof(EFUSE_MAP))){
//error msg
return ;
}
offset = RTL8712_SDIO_EFUSE_TABLE[efuse_read_item].offset ;
word_start = RTL8712_SDIO_EFUSE_TABLE[efuse_read_item].word_start;
byte_start = RTL8712_SDIO_EFUSE_TABLE[efuse_read_item].byte_start;
byte_cnts = RTL8712_SDIO_EFUSE_TABLE[efuse_read_item].byte_cnts;
if(data_size!=byte_cnts){
//error msg
return;
}
pg_pkt_cnts = (byte_cnts /PGPKT_DATA_SIZE) +1;
if(pg_pkt_cnts > 1){
//tmpdata = _malloc(pg_pkt_cnts*PGPKT_DATA_SIZE);
tmpdata = efusedata;
if(tmpdata!=NULL)
{
memset(tmpdata,0xff,pg_pkt_cnts*PGPKT_DATA_SIZE);
//PlatformFillMemory((PVOID)pg_data, pg_pkt_cnts*PGPKT_DATA_SIZE, 0xff);
for(tmpidx=0;tmpidx<pg_pkt_cnts;tmpidx++)
{
memset(pg_data,0xff,PGPKT_DATA_SIZE);
//PlatformFillMemory((PVOID)pg_data, PGPKT_DATA_SIZE, 0xff);
if(TRUE== efuse_PgPacketRead(dev,offset+tmpidx,pg_data))
{
memcpy(tmpdata+(PGPKT_DATA_SIZE*tmpidx),pg_data,PGPKT_DATA_SIZE);
//PlatformMoveMemory((PVOID)(tmpdata+(PGPKT_DATA_SIZE*tmpidx)), (PVOID)pg_data, PGPKT_DATA_SIZE);
}
}
memcpy(data,(tmpdata+ (2*word_start)+byte_start ),data_size);
//PlatformMoveMemory((PVOID)data, (PVOID)(tmpdata+ (2*word_start)+byte_start ), data_size);
//_mfree(tmpdata, pg_pkt_cnts*PGPKT_DATA_SIZE);
}
}
else
{
memset(pg_data,0xff,PGPKT_DATA_SIZE);
//PlatformFillMemory((PVOID)pg_data, PGPKT_DATA_SIZE, 0xff);
if(TRUE==efuse_PgPacketRead(dev,offset,pg_data)){
memcpy(data,pg_data+ (2*word_start)+byte_start ,data_size);
//PlatformMoveMemory((PVOID)data, (PVOID)(pg_data+ (2*word_start)+byte_start), data_size);
}
}
}
//------------------------------------------------------------------------------
//per interface doesn't alike
void efuse_write_data(struct net_device* dev,u8 efuse_write_item,u8 *data,u32 data_size,u32 bWordUnit)
{
u8 offset, word_start,byte_start,byte_cnts;
u8 word_en = 0x0f,word_cnts;
u8 pg_pkt_cnts ;
u8 tmpidx,tmpbitmask;
u8 pg_data[8],tmpbytes=0;
if(efuse_write_item> (sizeof(RTL8712_SDIO_EFUSE_TABLE)/sizeof(EFUSE_MAP))){
//error msg
return ;
}
offset = RTL8712_SDIO_EFUSE_TABLE[efuse_write_item].offset ;
word_start = RTL8712_SDIO_EFUSE_TABLE[efuse_write_item].word_start;
byte_start = RTL8712_SDIO_EFUSE_TABLE[efuse_write_item].byte_start;
byte_cnts = RTL8712_SDIO_EFUSE_TABLE[efuse_write_item].byte_cnts;
if(data_size > byte_cnts){
//error msg
return;
}
pg_pkt_cnts = (byte_cnts /PGPKT_DATA_SIZE) +1;
word_cnts = byte_cnts /2 ;
if(byte_cnts %2){
word_cnts+=1;
}
if((byte_start==1)||((byte_cnts%2)==1)){//situation A
if((efuse_write_item==EFUSE_F0CIS)||(efuse_write_item==EFUSE_F1CIS)){
memset(pg_data,0xff,PGPKT_DATA_SIZE);
//PlatformFillMemory((PVOID)pg_data, PGPKT_DATA_SIZE, 0xff);
efuse_PgPacketRead(dev,offset,pg_data);
if(efuse_write_item==EFUSE_F0CIS){
word_en = 0x07;
memcpy(pg_data+word_start*2+byte_start,data,sizeof(u8)*2);
//PlatformMoveMemory((PVOID)(pg_data+word_start*2+byte_start), (PVOID)data, sizeof(u8)*2);
efuse_PgPacketWrite(dev,offset,word_en,pg_data+(word_start*2));
word_en = 0x00;
efuse_PgPacketWrite(dev,(offset+1),word_en,data+2);
word_en = 0x00;
efuse_PgPacketRead(dev,offset+2,pg_data);
memcpy(pg_data,data+2+8,sizeof(u8)*7);
//PlatformMoveMemory((PVOID)(pg_data), (PVOID)(data+2+8), sizeof(u8)*7);
efuse_PgPacketWrite(dev,(offset+2),word_en,pg_data);
}
else if(efuse_write_item==EFUSE_F1CIS){
word_en = 0x07;
efuse_PgPacketRead(dev,offset,pg_data);
pg_data[7] = data[0];
efuse_PgPacketWrite(dev,offset,word_en,pg_data+(word_start*2));
word_en = 0x00;
for(tmpidx = 0 ;tmpidx<(word_cnts/4);tmpidx++){
efuse_PgPacketWrite(dev,(offset+1+tmpidx),word_en,data+1+(tmpidx*PGPKT_DATA_SIZE));
}
}
}
else{
memset(pg_data,0xff,PGPKT_DATA_SIZE);
//PlatformFillMemory((PVOID)pg_data, PGPKT_DATA_SIZE, 0xff);
if((efuse_write_item==EFUSE_SDIO_SETTING)||(efuse_write_item==EFUSE_CCCR)){
word_en = 0x0e ;
tmpbytes = 2;
}
else if(efuse_write_item == EFUSE_SDIO_MODE){
word_en = 0x0d ;
tmpbytes = 2;
}
else if(efuse_write_item == EFUSE_OCR){
word_en = 0x09 ;
tmpbytes = 4;
}
else if((efuse_write_item == EFUSE_EEPROM_VER)||(efuse_write_item==EFUSE_CHAN_PLAN)){
word_en = 0x07 ;
tmpbytes = 2;
}
if(bWordUnit==TRUE){
memcpy(pg_data+word_start*2 ,data,sizeof(u8)*tmpbytes);
//PlatformMoveMemory((PVOID)(pg_data+word_start*2), (PVOID)(data), sizeof(u8)*tmpbytes);
}
else{
efuse_PgPacketRead(dev,offset,pg_data);
memcpy(pg_data+(2*word_start)+byte_start,data,sizeof(u8)*byte_cnts);
//PlatformMoveMemory((PVOID)(pg_data+(2*word_start)+byte_start), (PVOID)(data), sizeof(u8)*byte_cnts);
}
efuse_PgPacketWrite(dev,offset,word_en,pg_data+(word_start*2));
}
}
//========================================================================
else if(pg_pkt_cnts>1){//situation B
if(word_start==0){
word_en = 0x00;
for(tmpidx = 0 ;tmpidx<(word_cnts/4);tmpidx++)
{
efuse_PgPacketWrite(dev,(offset+tmpidx),word_en,data+(tmpidx*PGPKT_DATA_SIZE));
}
word_en = 0x0f;
for(tmpidx= 0; tmpidx<(word_cnts%4) ; tmpidx++)
{
tmpbitmask =tmpidx;
word_en &= (~(EFUSE_BIT(tmpbitmask)));
//BIT0
}
efuse_PgPacketWrite(dev,offset+(word_cnts/4),word_en,data+((word_cnts/4)*PGPKT_DATA_SIZE));
}else
{
}
}
//========================================================================
else{//situation C
word_en = 0x0f;
for(tmpidx= 0; tmpidx<word_cnts ; tmpidx++)
{
tmpbitmask = word_start + tmpidx ;
word_en &= (~(EFUSE_BIT(tmpbitmask)));
}
efuse_PgPacketWrite(dev,offset,word_en,data);
}
}
//------------------------------------------------------------------------------
void efuset_test_func_read(struct net_device* dev)
{
u8 chipid[2];
u8 ocr[3];
u8 macaddr[6];
u8 txpowertable[28];
memset(chipid,0,sizeof(u8)*2);
efuse_read_data(dev,EFUSE_CHIP_ID,chipid,sizeof(chipid));
memset(ocr,0,sizeof(u8)*3);
efuse_read_data(dev,EFUSE_CCCR,ocr,sizeof(ocr));
memset(macaddr,0,sizeof(u8)*6);
efuse_read_data(dev,EFUSE_MAC_ADDR,macaddr,sizeof(macaddr));
memset(txpowertable,0,sizeof(u8)*28);
efuse_read_data(dev,EFUSE_TXPW_TAB,txpowertable,sizeof(txpowertable));
}
//------------------------------------------------------------------------------
void efuset_test_func_write(struct net_device* dev)
{
u32 bWordUnit = TRUE;
u8 CCCR=0x02,SDIO_SETTING = 0xFF;
u8 tmpdata[2];
u8 macaddr[6] = {0x00,0xe0,0x4c,0x87,0x12,0x66};
efuse_write_data(dev,EFUSE_MAC_ADDR,macaddr,sizeof(macaddr),bWordUnit);
bWordUnit = FALSE;
efuse_write_data(dev,EFUSE_CCCR,&CCCR,sizeof(u8),bWordUnit);
bWordUnit = FALSE;
efuse_write_data(dev,EFUSE_SDIO_SETTING,&SDIO_SETTING,sizeof(u8),bWordUnit);
bWordUnit = TRUE;
tmpdata[0] =SDIO_SETTING ;
tmpdata[1] =CCCR ;
efuse_write_data(dev,EFUSE_SDIO_SETTING,tmpdata,sizeof(tmpdata),bWordUnit);
}
//------------------------------------------------------------------------------
/* End of Efuse.c */
| {
"language": "C"
} |
/*
* linux/drivers/pcmcia/sa1100_badge4.c
*
* BadgePAD 4 PCMCIA specific routines
*
* Christopher Hoover <ch@hpl.hp.com>
*
* Copyright (C) 2002 Hewlett-Packard Company
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <mach/badge4.h>
#include <asm/hardware/sa1111.h>
#include "sa1111_generic.h"
/*
* BadgePAD 4 Details
*
* PCM Vcc:
*
* PCM Vcc on BadgePAD 4 can be jumpered for 3v3 (short pins 1 and 3
* on JP6) or 5v0 (short pins 3 and 5 on JP6).
*
* PCM Vpp:
*
* PCM Vpp on BadgePAD 4 can be jumpered for 12v0 (short pins 4 and 6
* on JP6) or tied to PCM Vcc (short pins 2 and 4 on JP6). N.B.,
* 12v0 operation requires that the power supply actually supply 12v0
* via pin 7 of JP7.
*
* CF Vcc:
*
* CF Vcc on BadgePAD 4 can be jumpered either for 3v3 (short pins 1
* and 2 on JP10) or 5v0 (short pins 2 and 3 on JP10).
*
* Unfortunately there's no way programmatically to determine how a
* given board is jumpered. This code assumes a default jumpering
* as described below.
*
* If the defaults aren't correct, you may override them with a pcmv
* setup argument: pcmv=<pcm vcc>,<pcm vpp>,<cf vcc>. The units are
* tenths of volts; e.g. pcmv=33,120,50 indicates 3v3 PCM Vcc, 12v0
* PCM Vpp, and 5v0 CF Vcc.
*
*/
static int badge4_pcmvcc = 50; /* pins 3 and 5 jumpered on JP6 */
static int badge4_pcmvpp = 50; /* pins 2 and 4 jumpered on JP6 */
static int badge4_cfvcc = 33; /* pins 1 and 2 jumpered on JP10 */
static void complain_about_jumpering(const char *whom,
const char *supply,
int given, int wanted)
{
printk(KERN_ERR
"%s: %s %d.%dV wanted but board is jumpered for %s %d.%dV operation"
"; re-jumper the board and/or use pcmv=xx,xx,xx\n",
whom, supply,
wanted / 10, wanted % 10,
supply,
given / 10, given % 10);
}
static int
badge4_pcmcia_configure_socket(struct soc_pcmcia_socket *skt, const socket_state_t *state)
{
int ret;
switch (skt->nr) {
case 0:
if ((state->Vcc != 0) &&
(state->Vcc != badge4_pcmvcc)) {
complain_about_jumpering(__func__, "pcmvcc",
badge4_pcmvcc, state->Vcc);
// Apply power regardless of the jumpering.
// return -1;
}
if ((state->Vpp != 0) &&
(state->Vpp != badge4_pcmvpp)) {
complain_about_jumpering(__func__, "pcmvpp",
badge4_pcmvpp, state->Vpp);
return -1;
}
break;
case 1:
if ((state->Vcc != 0) &&
(state->Vcc != badge4_cfvcc)) {
complain_about_jumpering(__func__, "cfvcc",
badge4_cfvcc, state->Vcc);
return -1;
}
break;
default:
return -1;
}
ret = sa1111_pcmcia_configure_socket(skt, state);
if (ret == 0) {
unsigned long flags;
int need5V;
local_irq_save(flags);
need5V = ((state->Vcc == 50) || (state->Vpp == 50));
badge4_set_5V(BADGE4_5V_PCMCIA_SOCK(skt->nr), need5V);
local_irq_restore(flags);
}
return ret;
}
static struct pcmcia_low_level badge4_pcmcia_ops = {
.owner = THIS_MODULE,
.configure_socket = badge4_pcmcia_configure_socket,
.first = 0,
.nr = 2,
};
int pcmcia_badge4_init(struct sa1111_dev *dev)
{
int ret = -ENODEV;
if (machine_is_badge4()) {
printk(KERN_INFO
"%s: badge4_pcmvcc=%d, badge4_pcmvpp=%d, badge4_cfvcc=%d\n",
__func__,
badge4_pcmvcc, badge4_pcmvpp, badge4_cfvcc);
sa11xx_drv_pcmcia_ops(&badge4_pcmcia_ops);
ret = sa1111_pcmcia_add(dev, &badge4_pcmcia_ops,
sa11xx_drv_pcmcia_add_one);
}
return ret;
}
static int __init pcmv_setup(char *s)
{
int v[4];
s = get_options(s, ARRAY_SIZE(v), v);
if (v[0] >= 1) badge4_pcmvcc = v[1];
if (v[0] >= 2) badge4_pcmvpp = v[2];
if (v[0] >= 3) badge4_cfvcc = v[3];
return 1;
}
__setup("pcmv=", pcmv_setup);
| {
"language": "C"
} |
/**
* @file ps.h
* @brief PS service.
*/
#pragma once
/// PS AES algorithms.
typedef enum
{
PS_ALGORITHM_CBC_ENC, ///< CBC encoding.
PS_ALGORITHM_CBC_DEC, ///< CBC decoding.
PS_ALGORITHM_CTR_ENC, ///< CTR encoding.
PS_ALGORITHM_CTR_DEC, ///< CTR decoding.
PS_ALGORITHM_CCM_ENC, ///< CCM encoding.
PS_ALGORITHM_CCM_DEC, ///< CCM decoding.
} PS_AESAlgorithm;
/// PS key slots.
typedef enum
{
PS_KEYSLOT_0D, ///< Key slot 0x0D.
PS_KEYSLOT_2D, ///< Key slot 0x2D.
PS_KEYSLOT_31, ///< Key slot 0x31.
PS_KEYSLOT_38, ///< Key slot 0x38.
PS_KEYSLOT_32, ///< Key slot 0x32.
PS_KEYSLOT_39_DLP, ///< Key slot 0x39. (DLP)
PS_KEYSLOT_2E, ///< Key slot 0x2E.
PS_KEYSLOT_INVALID, ///< Invalid key slot.
PS_KEYSLOT_36, ///< Key slot 0x36.
PS_KEYSLOT_39_NFC ///< Key slot 0x39. (NFC)
} PS_AESKeyType;
/// Initializes PS.
Result psInit(void);
/// Exits PS.
void psExit(void);
/**
* @brief Encrypts/Decrypts AES data. Does not support AES CCM.
* @param size Size of the data.
* @param in Input buffer.
* @param out Output buffer.
* @param aes_algo AES algorithm to use.
* @param key_type Key type to use.
* @param iv Pointer to the CTR/IV.
*/
Result PS_EncryptDecryptAes(u32 size, u8* in, u8* out, PS_AESAlgorithm aes_algo, PS_AESKeyType key_type, u8* iv);
/**
* @brief Encrypts/Decrypts signed AES CCM data.
* When decrypting, if the MAC is invalid, 0xC9010401 is returned. After encrypting the MAC is located at inputbufptr.
* @param in Input buffer.
* @param in_size Size of the input buffer. Must include MAC size when decrypting.
* @param out Output buffer.
* @param out_size Size of the output buffer. Must include MAC size when encrypting.
* @param data_len Length of the data to be encrypted/decrypted.
* @param mac_data_len Length of the MAC data.
* @param mac_len Length of the MAC.
* @param aes_algo AES algorithm to use.
* @param key_type Key type to use.
* @param nonce Pointer to the nonce.
*/
Result PS_EncryptSignDecryptVerifyAesCcm(u8* in, u32 in_size, u8* out, u32 out_size, u32 data_len, u32 mac_data_len, u32 mac_len, PS_AESAlgorithm aes_algo, PS_AESKeyType key_type, u8* nonce);
/**
* @brief Gets the 64-bit console friend code seed.
* @param seed Pointer to write the friend code seed to.
*/
Result PS_GetLocalFriendCodeSeed(u64* seed);
/**
* @brief Gets the 32-bit device ID.
* @param device_id Pointer to write the device ID to.
*/
Result PS_GetDeviceId(u32* device_id);
| {
"language": "C"
} |
/*
* Copyright 2005-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include "rsa_local.h"
static const unsigned char zeroes[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
#if defined(_MSC_VER) && defined(_ARM_)
# pragma optimize("g", off)
#endif
int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash,
const EVP_MD *Hash, const unsigned char *EM,
int sLen)
{
return RSA_verify_PKCS1_PSS_mgf1(rsa, mHash, Hash, NULL, EM, sLen);
}
int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash,
const EVP_MD *Hash, const EVP_MD *mgf1Hash,
const unsigned char *EM, int sLen)
{
int i;
int ret = 0;
int hLen, maskedDBLen, MSBits, emLen;
const unsigned char *H;
unsigned char *DB = NULL;
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
unsigned char H_[EVP_MAX_MD_SIZE];
if (ctx == NULL)
goto err;
if (mgf1Hash == NULL)
mgf1Hash = Hash;
hLen = EVP_MD_size(Hash);
if (hLen < 0)
goto err;
/*-
* Negative sLen has special meanings:
* -1 sLen == hLen
* -2 salt length is autorecovered from signature
* -3 salt length is maximized
* -N reserved
*/
if (sLen == RSA_PSS_SALTLEN_DIGEST) {
sLen = hLen;
} else if (sLen < RSA_PSS_SALTLEN_MAX) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
MSBits = (BN_num_bits(rsa->n) - 1) & 0x7;
emLen = RSA_size(rsa);
if (EM[0] & (0xFF << MSBits)) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_FIRST_OCTET_INVALID);
goto err;
}
if (MSBits == 0) {
EM++;
emLen--;
}
if (emLen < hLen + 2) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_DATA_TOO_LARGE);
goto err;
}
if (sLen == RSA_PSS_SALTLEN_MAX) {
sLen = emLen - hLen - 2;
} else if (sLen > emLen - hLen - 2) { /* sLen can be small negative */
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_DATA_TOO_LARGE);
goto err;
}
if (EM[emLen - 1] != 0xbc) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_LAST_OCTET_INVALID);
goto err;
}
maskedDBLen = emLen - hLen - 1;
H = EM + maskedDBLen;
DB = OPENSSL_malloc(maskedDBLen);
if (DB == NULL) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, ERR_R_MALLOC_FAILURE);
goto err;
}
if (PKCS1_MGF1(DB, maskedDBLen, H, hLen, mgf1Hash) < 0)
goto err;
for (i = 0; i < maskedDBLen; i++)
DB[i] ^= EM[i];
if (MSBits)
DB[0] &= 0xFF >> (8 - MSBits);
for (i = 0; DB[i] == 0 && i < (maskedDBLen - 1); i++) ;
if (DB[i++] != 0x1) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_RECOVERY_FAILED);
goto err;
}
if (sLen != RSA_PSS_SALTLEN_AUTO && (maskedDBLen - i) != sLen) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
if (!EVP_DigestInit_ex(ctx, Hash, NULL)
|| !EVP_DigestUpdate(ctx, zeroes, sizeof(zeroes))
|| !EVP_DigestUpdate(ctx, mHash, hLen))
goto err;
if (maskedDBLen - i) {
if (!EVP_DigestUpdate(ctx, DB + i, maskedDBLen - i))
goto err;
}
if (!EVP_DigestFinal_ex(ctx, H_, NULL))
goto err;
if (memcmp(H_, H, hLen)) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_BAD_SIGNATURE);
ret = 0;
} else {
ret = 1;
}
err:
OPENSSL_free(DB);
EVP_MD_CTX_free(ctx);
return ret;
}
int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM,
const unsigned char *mHash,
const EVP_MD *Hash, int sLen)
{
return RSA_padding_add_PKCS1_PSS_mgf1(rsa, EM, mHash, Hash, NULL, sLen);
}
int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM,
const unsigned char *mHash,
const EVP_MD *Hash, const EVP_MD *mgf1Hash,
int sLen)
{
int i;
int ret = 0;
int hLen, maskedDBLen, MSBits, emLen;
unsigned char *H, *salt = NULL, *p;
EVP_MD_CTX *ctx = NULL;
if (mgf1Hash == NULL)
mgf1Hash = Hash;
hLen = EVP_MD_size(Hash);
if (hLen < 0)
goto err;
/*-
* Negative sLen has special meanings:
* -1 sLen == hLen
* -2 salt length is maximized
* -3 same as above (on signing)
* -N reserved
*/
if (sLen == RSA_PSS_SALTLEN_DIGEST) {
sLen = hLen;
} else if (sLen == RSA_PSS_SALTLEN_MAX_SIGN) {
sLen = RSA_PSS_SALTLEN_MAX;
} else if (sLen < RSA_PSS_SALTLEN_MAX) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
MSBits = (BN_num_bits(rsa->n) - 1) & 0x7;
emLen = RSA_size(rsa);
if (MSBits == 0) {
*EM++ = 0;
emLen--;
}
if (emLen < hLen + 2) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
goto err;
}
if (sLen == RSA_PSS_SALTLEN_MAX) {
sLen = emLen - hLen - 2;
} else if (sLen > emLen - hLen - 2) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
goto err;
}
if (sLen > 0) {
salt = OPENSSL_malloc(sLen);
if (salt == NULL) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
ERR_R_MALLOC_FAILURE);
goto err;
}
if (RAND_bytes(salt, sLen) <= 0)
goto err;
}
maskedDBLen = emLen - hLen - 1;
H = EM + maskedDBLen;
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
goto err;
if (!EVP_DigestInit_ex(ctx, Hash, NULL)
|| !EVP_DigestUpdate(ctx, zeroes, sizeof(zeroes))
|| !EVP_DigestUpdate(ctx, mHash, hLen))
goto err;
if (sLen && !EVP_DigestUpdate(ctx, salt, sLen))
goto err;
if (!EVP_DigestFinal_ex(ctx, H, NULL))
goto err;
/* Generate dbMask in place then perform XOR on it */
if (PKCS1_MGF1(EM, maskedDBLen, H, hLen, mgf1Hash))
goto err;
p = EM;
/*
* Initial PS XORs with all zeroes which is a NOP so just update pointer.
* Note from a test above this value is guaranteed to be non-negative.
*/
p += emLen - sLen - hLen - 2;
*p++ ^= 0x1;
if (sLen > 0) {
for (i = 0; i < sLen; i++)
*p++ ^= salt[i];
}
if (MSBits)
EM[0] &= 0xFF >> (8 - MSBits);
/* H is already in place so just set final 0xbc */
EM[emLen - 1] = 0xbc;
ret = 1;
err:
EVP_MD_CTX_free(ctx);
OPENSSL_clear_free(salt, (size_t)sLen); /* salt != NULL implies sLen > 0 */
return ret;
}
#if defined(_MSC_VER)
# pragma optimize("",on)
#endif
| {
"language": "C"
} |
/*
* Copyright (c) 2008, Technische Universitaet Berlin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the Technische Universitaet Berlin nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* - Revision -------------------------------------------------------------
* $Revision: 1.3 $
* $Date: 2009-03-04 18:31:46 $
* @author Jan Hauer <hauer@tkn.tu-berlin.de>
* ========================================================================
*/
/**
* The IEEE154Frame interface allows to access the content of a IEEE 802.15.4
* frame.
*/
#include <TKN154.h>
#include <message.h>
interface IEEE154Frame
{
/**
* Returns the source addressing mode of the frame.
*
* @param frame the frame
* @return source addressing mode of the frame; either
* ADDR_MODE_NOT_PRESENT, ADDR_MODE_RESERVED,
* ADDR_MODE_SHORT_ADDRESS or ADDR_MODE_EXTENDED_ADDRESS
*/
command uint8_t getSrcAddrMode(message_t* frame);
/**
* Reads the source address (to be interpreted
* as specified by the source addressing mode) of the frame.
*
* @param frame the frame
* @param address a pointer to where the source address
* will be written
* @return SUCCESS, if the source address is present
* and was written to "address",
* FAIL otherwise (source address remains
* unmodified)
*/
command error_t getSrcAddr(message_t* frame, ieee154_address_t *address);
/**
* Reads the source PAN identifier of the frame.
*
* @param frame the frame
* @param PANID a pointer to where the source PAN identifier
* will be written
* @return SUCCESS, if the source PAN identifier is present
* and was written to "PANID",
* FAIL otherwise (PANID remains unmodified)
*/
command error_t getSrcPANId(message_t* frame, uint16_t* PANID);
/**
* Returns the destination addressing mode of the frame.
*
* @param frame the frame
* @return destination addressing mode of the frame; either
* ADDR_MODE_NOT_PRESENT, ADDR_MODE_RESERVED,
* ADDR_MODE_SHORT_ADDRESS or ADDR_MODE_EXTENDED_ADDRESS
*/
command uint8_t getDstAddrMode(message_t* frame);
/**
* Reads the destination address (to be interpreted
* as specified by the destination addressing mode) of the frame.
*
* @param frame the frame
* @param address a pointer to where the destination address
* will be written
* @return SUCCESS, if the destination address is present
* and was written to "address",
* FAIL otherwise (destination address
* remains unmodified)
*/
command error_t getDstAddr(message_t* frame, ieee154_address_t *address);
/**
* Reads the destination PAN identifier of the frame.
*
* @param PANID a pointer to where the destination
* PAN identifier should be written
* @param frame the frame
* @return SUCCESS, if the destination PAN identifier
* is present and was copied to "PANID",
* FAIL otherwise (PANID remains unmodified)
*/
command error_t getDstPANId(message_t* frame, uint16_t* PANID);
/**
* Sets the addressing fields in the MAC header of a frame. The source
* PAN identifier and the source address will be set automatically, their
* values depend on the <tt>SrcAddrMode</tt> parameter: if
* <tt>SrcAddrMode</tt> is a short or extended address, then
* the current PIB attributes <tt>macShortAddress</tt> or
* <tt>aExtendedAddress</tt> and <tt>macPANId</tt> are used.
*
* @param frame the frame
* @param srcAddrMode the source addressing mode
* @param dstAddrMode the destination addressing mode
* @param dstPANID the 16 bit PAN identifier of the destination
* @param dstAddr individual device address of the destination as per
* the dstAddrMode
* @param security the security options (NULL means security is
* disabled)
*
* @return SUCCESS if the addressing fields where written,
* FAIL if an incorrect addressing mode was specified
*/
command error_t setAddressingFields(message_t* frame,
uint8_t SrcAddrMode,
uint8_t DstAddrMode,
uint16_t DstPANID,
ieee154_address_t *DstAddr,
ieee154_security_t *security);
/**
* Returns a pointer to the MAC payload portion of a frame.
*
* @param frame the frame
* @return a pointer to the frame's payload
*/
command void* getPayload(message_t* frame);
/**
* Returns the length of the MAC payload portion of the frame (in byte).
*
* @param frame the frame
* @return the length of the frame's payload (in byte)
*/
command uint8_t getPayloadLength(message_t* frame);
/**
* Returns the point in time when the first bit (of the PHY preamble) of the
* frame was received or transmitted. Time is expressed in symbols as local
* time (which can also be accessed via the LocalTime<T62500hz> interface
* provided by your platform, e.g.
* tos/platforms/telosb/mac/tkn154/timer/LocalTime62500hzC). If
* <tt>isTimestampValid()</tt> returns FALSE then the timestamp is not valid
* and must be ignored.
*
* @param frame the frame
* @return timestamp of the frame
*/
command uint32_t getTimestamp(message_t* frame);
/**
* Tells whether the timestamp is valid.
*
* @return TRUE if timestamp is valid, FALSE otherwise.
*/
command bool isTimestampValid(message_t* frame);
/**
* Returns the sequence number of the frame.
*
* @param frame the frame
* @return sequence number of the frame
*/
command uint8_t getDSN(message_t* frame);
/**
* Returns the link quality level of a received frame, where
* "link quality level" is defined in Sect. 6.9.8 of the
* IEEE 802.15.4-2006 standard. For the CC2420 radio it is
* identical with the LQI.
*
* @param frame the frame
* @return link quality level
*/
command uint8_t getLinkQuality(message_t* frame);
/**
* Returns the average RSSI (in dBm) of a received frame. The
* IEEE 802.15.4-2006 standard does not specify that a radio
* must provide RSSI, so this command is optional: if a
* radio does not provide per-frame RSSI then this call will
* return a value of +127.
*
* @param frame the frame
* @return RSSI
*/
command int8_t getRSSI(message_t* frame);
/**
* Returns the type of the frame
* BEACON=0, DATA=1, ACK=2, COMMAND=3.
*
* Note: For beacon frames one can use the <tt>IEEE154BeaconFrame</tt>
* interface to inspect additional fields of the frame.
*
* @param frame the frame
* @return the type of the frame
*/
command uint8_t getFrameType(message_t* frame);
/**
* Returns a pointer to the MAC header (i.e. to the first byte of
* the Frame Control field).
*
* @param frame the frame
* @return a pointer to the frame's header
*/
command void* getHeader(message_t* frame);
/**
* Returns the length of the MAC header.
*
* @param frame the frame
* @return the length of the MAC header (in byte)
*/
command uint8_t getHeaderLength(message_t* frame);
/**
* Tells whether or not the frame was received while
* promiscuous mode was enabled.
*
* @param frame the frame
* @return TRUE if frame was received while in promiscuous
* mode, FALSE otherwise
*/
command bool wasPromiscuousModeEnabled(message_t* frame);
/**
* Tells whether or not the frame has a standard compliant
* IEEE 802.15.4 header - this will only be relevant for frames
* received while in promiscuous mode, because then no filtering
* (except CRC check) was applied. Note: if this command returns
* FALSE, then all other commands in this interface (except
* <tt>wasPromiscuousModeEnabled()</tt>) and the
* <tt>IEEE154BeaconFrame</tt> interface return undefined values!
*
* @param frame the frame
* @return TRUE if frame has a standard compliant header,
* FALSE otherwise
*/
command bool hasStandardCompliantHeader(message_t* frame);
}
| {
"language": "C"
} |
#include "../include/apue.h"
int main(int argc,char *argv[]){
int i;
char **ptr;
extern **environ;
for(i=0;i<argc;i++)
printf("argv[%d]:%s\n",i,argv[i]);
for(ptr = environ;*ptr!=0;ptr++)
printf("%s\n",*ptr);
exit(0);
} | {
"language": "C"
} |
/**
* \file
*
* \brief Component description for ADC
*
* Copyright (c) 2018 Microchip Technology Inc.
*
* \asf_license_start
*
* \page License
*
* SPDX-License-Identifier: Apache-2.0
*
* 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 Licence 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.
*
* \asf_license_stop
*
*/
#ifndef _SAMD11_ADC_COMPONENT_
#define _SAMD11_ADC_COMPONENT_
/* ========================================================================== */
/** SOFTWARE API DEFINITION FOR ADC */
/* ========================================================================== */
/** \addtogroup SAMD11_ADC Analog Digital Converter */
/*@{*/
#define ADC_U2204
#define REV_ADC 0x120
/* -------- ADC_CTRLA : (ADC Offset: 0x00) (R/W 8) Control A -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t SWRST:1; /*!< bit: 0 Software Reset */
uint8_t ENABLE:1; /*!< bit: 1 Enable */
uint8_t RUNSTDBY:1; /*!< bit: 2 Run in Standby */
uint8_t :5; /*!< bit: 3.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_CTRLA_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_CTRLA_OFFSET 0x00 /**< \brief (ADC_CTRLA offset) Control A */
#define ADC_CTRLA_RESETVALUE _U_(0x00) /**< \brief (ADC_CTRLA reset_value) Control A */
#define ADC_CTRLA_SWRST_Pos 0 /**< \brief (ADC_CTRLA) Software Reset */
#define ADC_CTRLA_SWRST (_U_(0x1) << ADC_CTRLA_SWRST_Pos)
#define ADC_CTRLA_ENABLE_Pos 1 /**< \brief (ADC_CTRLA) Enable */
#define ADC_CTRLA_ENABLE (_U_(0x1) << ADC_CTRLA_ENABLE_Pos)
#define ADC_CTRLA_RUNSTDBY_Pos 2 /**< \brief (ADC_CTRLA) Run in Standby */
#define ADC_CTRLA_RUNSTDBY (_U_(0x1) << ADC_CTRLA_RUNSTDBY_Pos)
#define ADC_CTRLA_MASK _U_(0x07) /**< \brief (ADC_CTRLA) MASK Register */
/* -------- ADC_REFCTRL : (ADC Offset: 0x01) (R/W 8) Reference Control -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t REFSEL:4; /*!< bit: 0.. 3 Reference Selection */
uint8_t :3; /*!< bit: 4.. 6 Reserved */
uint8_t REFCOMP:1; /*!< bit: 7 Reference Buffer Offset Compensation Enable */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_REFCTRL_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_REFCTRL_OFFSET 0x01 /**< \brief (ADC_REFCTRL offset) Reference Control */
#define ADC_REFCTRL_RESETVALUE _U_(0x00) /**< \brief (ADC_REFCTRL reset_value) Reference Control */
#define ADC_REFCTRL_REFSEL_Pos 0 /**< \brief (ADC_REFCTRL) Reference Selection */
#define ADC_REFCTRL_REFSEL_Msk (_U_(0xF) << ADC_REFCTRL_REFSEL_Pos)
#define ADC_REFCTRL_REFSEL(value) (ADC_REFCTRL_REFSEL_Msk & ((value) << ADC_REFCTRL_REFSEL_Pos))
#define ADC_REFCTRL_REFSEL_INT1V_Val _U_(0x0) /**< \brief (ADC_REFCTRL) 1.0V voltage reference */
#define ADC_REFCTRL_REFSEL_INTVCC0_Val _U_(0x1) /**< \brief (ADC_REFCTRL) 1/1.48 VDDANA */
#define ADC_REFCTRL_REFSEL_INTVCC1_Val _U_(0x2) /**< \brief (ADC_REFCTRL) 1/2 VDDANA (only for VDDANA > 2.0V) */
#define ADC_REFCTRL_REFSEL_AREFA_Val _U_(0x3) /**< \brief (ADC_REFCTRL) External reference */
#define ADC_REFCTRL_REFSEL_AREFB_Val _U_(0x4) /**< \brief (ADC_REFCTRL) External reference */
#define ADC_REFCTRL_REFSEL_INT1V (ADC_REFCTRL_REFSEL_INT1V_Val << ADC_REFCTRL_REFSEL_Pos)
#define ADC_REFCTRL_REFSEL_INTVCC0 (ADC_REFCTRL_REFSEL_INTVCC0_Val << ADC_REFCTRL_REFSEL_Pos)
#define ADC_REFCTRL_REFSEL_INTVCC1 (ADC_REFCTRL_REFSEL_INTVCC1_Val << ADC_REFCTRL_REFSEL_Pos)
#define ADC_REFCTRL_REFSEL_AREFA (ADC_REFCTRL_REFSEL_AREFA_Val << ADC_REFCTRL_REFSEL_Pos)
#define ADC_REFCTRL_REFSEL_AREFB (ADC_REFCTRL_REFSEL_AREFB_Val << ADC_REFCTRL_REFSEL_Pos)
#define ADC_REFCTRL_REFCOMP_Pos 7 /**< \brief (ADC_REFCTRL) Reference Buffer Offset Compensation Enable */
#define ADC_REFCTRL_REFCOMP (_U_(0x1) << ADC_REFCTRL_REFCOMP_Pos)
#define ADC_REFCTRL_MASK _U_(0x8F) /**< \brief (ADC_REFCTRL) MASK Register */
/* -------- ADC_AVGCTRL : (ADC Offset: 0x02) (R/W 8) Average Control -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t SAMPLENUM:4; /*!< bit: 0.. 3 Number of Samples to be Collected */
uint8_t ADJRES:3; /*!< bit: 4.. 6 Adjusting Result / Division Coefficient */
uint8_t :1; /*!< bit: 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_AVGCTRL_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_AVGCTRL_OFFSET 0x02 /**< \brief (ADC_AVGCTRL offset) Average Control */
#define ADC_AVGCTRL_RESETVALUE _U_(0x00) /**< \brief (ADC_AVGCTRL reset_value) Average Control */
#define ADC_AVGCTRL_SAMPLENUM_Pos 0 /**< \brief (ADC_AVGCTRL) Number of Samples to be Collected */
#define ADC_AVGCTRL_SAMPLENUM_Msk (_U_(0xF) << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM(value) (ADC_AVGCTRL_SAMPLENUM_Msk & ((value) << ADC_AVGCTRL_SAMPLENUM_Pos))
#define ADC_AVGCTRL_SAMPLENUM_1_Val _U_(0x0) /**< \brief (ADC_AVGCTRL) 1 sample */
#define ADC_AVGCTRL_SAMPLENUM_2_Val _U_(0x1) /**< \brief (ADC_AVGCTRL) 2 samples */
#define ADC_AVGCTRL_SAMPLENUM_4_Val _U_(0x2) /**< \brief (ADC_AVGCTRL) 4 samples */
#define ADC_AVGCTRL_SAMPLENUM_8_Val _U_(0x3) /**< \brief (ADC_AVGCTRL) 8 samples */
#define ADC_AVGCTRL_SAMPLENUM_16_Val _U_(0x4) /**< \brief (ADC_AVGCTRL) 16 samples */
#define ADC_AVGCTRL_SAMPLENUM_32_Val _U_(0x5) /**< \brief (ADC_AVGCTRL) 32 samples */
#define ADC_AVGCTRL_SAMPLENUM_64_Val _U_(0x6) /**< \brief (ADC_AVGCTRL) 64 samples */
#define ADC_AVGCTRL_SAMPLENUM_128_Val _U_(0x7) /**< \brief (ADC_AVGCTRL) 128 samples */
#define ADC_AVGCTRL_SAMPLENUM_256_Val _U_(0x8) /**< \brief (ADC_AVGCTRL) 256 samples */
#define ADC_AVGCTRL_SAMPLENUM_512_Val _U_(0x9) /**< \brief (ADC_AVGCTRL) 512 samples */
#define ADC_AVGCTRL_SAMPLENUM_1024_Val _U_(0xA) /**< \brief (ADC_AVGCTRL) 1024 samples */
#define ADC_AVGCTRL_SAMPLENUM_1 (ADC_AVGCTRL_SAMPLENUM_1_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_2 (ADC_AVGCTRL_SAMPLENUM_2_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_4 (ADC_AVGCTRL_SAMPLENUM_4_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_8 (ADC_AVGCTRL_SAMPLENUM_8_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_16 (ADC_AVGCTRL_SAMPLENUM_16_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_32 (ADC_AVGCTRL_SAMPLENUM_32_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_64 (ADC_AVGCTRL_SAMPLENUM_64_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_128 (ADC_AVGCTRL_SAMPLENUM_128_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_256 (ADC_AVGCTRL_SAMPLENUM_256_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_512 (ADC_AVGCTRL_SAMPLENUM_512_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_SAMPLENUM_1024 (ADC_AVGCTRL_SAMPLENUM_1024_Val << ADC_AVGCTRL_SAMPLENUM_Pos)
#define ADC_AVGCTRL_ADJRES_Pos 4 /**< \brief (ADC_AVGCTRL) Adjusting Result / Division Coefficient */
#define ADC_AVGCTRL_ADJRES_Msk (_U_(0x7) << ADC_AVGCTRL_ADJRES_Pos)
#define ADC_AVGCTRL_ADJRES(value) (ADC_AVGCTRL_ADJRES_Msk & ((value) << ADC_AVGCTRL_ADJRES_Pos))
#define ADC_AVGCTRL_MASK _U_(0x7F) /**< \brief (ADC_AVGCTRL) MASK Register */
/* -------- ADC_SAMPCTRL : (ADC Offset: 0x03) (R/W 8) Sampling Time Control -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t SAMPLEN:6; /*!< bit: 0.. 5 Sampling Time Length */
uint8_t :2; /*!< bit: 6.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_SAMPCTRL_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_SAMPCTRL_OFFSET 0x03 /**< \brief (ADC_SAMPCTRL offset) Sampling Time Control */
#define ADC_SAMPCTRL_RESETVALUE _U_(0x00) /**< \brief (ADC_SAMPCTRL reset_value) Sampling Time Control */
#define ADC_SAMPCTRL_SAMPLEN_Pos 0 /**< \brief (ADC_SAMPCTRL) Sampling Time Length */
#define ADC_SAMPCTRL_SAMPLEN_Msk (_U_(0x3F) << ADC_SAMPCTRL_SAMPLEN_Pos)
#define ADC_SAMPCTRL_SAMPLEN(value) (ADC_SAMPCTRL_SAMPLEN_Msk & ((value) << ADC_SAMPCTRL_SAMPLEN_Pos))
#define ADC_SAMPCTRL_MASK _U_(0x3F) /**< \brief (ADC_SAMPCTRL) MASK Register */
/* -------- ADC_CTRLB : (ADC Offset: 0x04) (R/W 16) Control B -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint16_t DIFFMODE:1; /*!< bit: 0 Differential Mode */
uint16_t LEFTADJ:1; /*!< bit: 1 Left-Adjusted Result */
uint16_t FREERUN:1; /*!< bit: 2 Free Running Mode */
uint16_t CORREN:1; /*!< bit: 3 Digital Correction Logic Enabled */
uint16_t RESSEL:2; /*!< bit: 4.. 5 Conversion Result Resolution */
uint16_t :2; /*!< bit: 6.. 7 Reserved */
uint16_t PRESCALER:3; /*!< bit: 8..10 Prescaler Configuration */
uint16_t :5; /*!< bit: 11..15 Reserved */
} bit; /*!< Structure used for bit access */
uint16_t reg; /*!< Type used for register access */
} ADC_CTRLB_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_CTRLB_OFFSET 0x04 /**< \brief (ADC_CTRLB offset) Control B */
#define ADC_CTRLB_RESETVALUE _U_(0x0000) /**< \brief (ADC_CTRLB reset_value) Control B */
#define ADC_CTRLB_DIFFMODE_Pos 0 /**< \brief (ADC_CTRLB) Differential Mode */
#define ADC_CTRLB_DIFFMODE (_U_(0x1) << ADC_CTRLB_DIFFMODE_Pos)
#define ADC_CTRLB_LEFTADJ_Pos 1 /**< \brief (ADC_CTRLB) Left-Adjusted Result */
#define ADC_CTRLB_LEFTADJ (_U_(0x1) << ADC_CTRLB_LEFTADJ_Pos)
#define ADC_CTRLB_FREERUN_Pos 2 /**< \brief (ADC_CTRLB) Free Running Mode */
#define ADC_CTRLB_FREERUN (_U_(0x1) << ADC_CTRLB_FREERUN_Pos)
#define ADC_CTRLB_CORREN_Pos 3 /**< \brief (ADC_CTRLB) Digital Correction Logic Enabled */
#define ADC_CTRLB_CORREN (_U_(0x1) << ADC_CTRLB_CORREN_Pos)
#define ADC_CTRLB_RESSEL_Pos 4 /**< \brief (ADC_CTRLB) Conversion Result Resolution */
#define ADC_CTRLB_RESSEL_Msk (_U_(0x3) << ADC_CTRLB_RESSEL_Pos)
#define ADC_CTRLB_RESSEL(value) (ADC_CTRLB_RESSEL_Msk & ((value) << ADC_CTRLB_RESSEL_Pos))
#define ADC_CTRLB_RESSEL_12BIT_Val _U_(0x0) /**< \brief (ADC_CTRLB) 12-bit result */
#define ADC_CTRLB_RESSEL_16BIT_Val _U_(0x1) /**< \brief (ADC_CTRLB) For averaging mode output */
#define ADC_CTRLB_RESSEL_10BIT_Val _U_(0x2) /**< \brief (ADC_CTRLB) 10-bit result */
#define ADC_CTRLB_RESSEL_8BIT_Val _U_(0x3) /**< \brief (ADC_CTRLB) 8-bit result */
#define ADC_CTRLB_RESSEL_12BIT (ADC_CTRLB_RESSEL_12BIT_Val << ADC_CTRLB_RESSEL_Pos)
#define ADC_CTRLB_RESSEL_16BIT (ADC_CTRLB_RESSEL_16BIT_Val << ADC_CTRLB_RESSEL_Pos)
#define ADC_CTRLB_RESSEL_10BIT (ADC_CTRLB_RESSEL_10BIT_Val << ADC_CTRLB_RESSEL_Pos)
#define ADC_CTRLB_RESSEL_8BIT (ADC_CTRLB_RESSEL_8BIT_Val << ADC_CTRLB_RESSEL_Pos)
#define ADC_CTRLB_PRESCALER_Pos 8 /**< \brief (ADC_CTRLB) Prescaler Configuration */
#define ADC_CTRLB_PRESCALER_Msk (_U_(0x7) << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_PRESCALER(value) (ADC_CTRLB_PRESCALER_Msk & ((value) << ADC_CTRLB_PRESCALER_Pos))
#define ADC_CTRLB_PRESCALER_DIV4_Val _U_(0x0) /**< \brief (ADC_CTRLB) Peripheral clock divided by 4 */
#define ADC_CTRLB_PRESCALER_DIV8_Val _U_(0x1) /**< \brief (ADC_CTRLB) Peripheral clock divided by 8 */
#define ADC_CTRLB_PRESCALER_DIV16_Val _U_(0x2) /**< \brief (ADC_CTRLB) Peripheral clock divided by 16 */
#define ADC_CTRLB_PRESCALER_DIV32_Val _U_(0x3) /**< \brief (ADC_CTRLB) Peripheral clock divided by 32 */
#define ADC_CTRLB_PRESCALER_DIV64_Val _U_(0x4) /**< \brief (ADC_CTRLB) Peripheral clock divided by 64 */
#define ADC_CTRLB_PRESCALER_DIV128_Val _U_(0x5) /**< \brief (ADC_CTRLB) Peripheral clock divided by 128 */
#define ADC_CTRLB_PRESCALER_DIV256_Val _U_(0x6) /**< \brief (ADC_CTRLB) Peripheral clock divided by 256 */
#define ADC_CTRLB_PRESCALER_DIV512_Val _U_(0x7) /**< \brief (ADC_CTRLB) Peripheral clock divided by 512 */
#define ADC_CTRLB_PRESCALER_DIV4 (ADC_CTRLB_PRESCALER_DIV4_Val << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_PRESCALER_DIV8 (ADC_CTRLB_PRESCALER_DIV8_Val << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_PRESCALER_DIV16 (ADC_CTRLB_PRESCALER_DIV16_Val << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_PRESCALER_DIV32 (ADC_CTRLB_PRESCALER_DIV32_Val << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_PRESCALER_DIV64 (ADC_CTRLB_PRESCALER_DIV64_Val << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_PRESCALER_DIV128 (ADC_CTRLB_PRESCALER_DIV128_Val << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_PRESCALER_DIV256 (ADC_CTRLB_PRESCALER_DIV256_Val << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_PRESCALER_DIV512 (ADC_CTRLB_PRESCALER_DIV512_Val << ADC_CTRLB_PRESCALER_Pos)
#define ADC_CTRLB_MASK _U_(0x073F) /**< \brief (ADC_CTRLB) MASK Register */
/* -------- ADC_WINCTRL : (ADC Offset: 0x08) (R/W 8) Window Monitor Control -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t WINMODE:3; /*!< bit: 0.. 2 Window Monitor Mode */
uint8_t :5; /*!< bit: 3.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_WINCTRL_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_WINCTRL_OFFSET 0x08 /**< \brief (ADC_WINCTRL offset) Window Monitor Control */
#define ADC_WINCTRL_RESETVALUE _U_(0x00) /**< \brief (ADC_WINCTRL reset_value) Window Monitor Control */
#define ADC_WINCTRL_WINMODE_Pos 0 /**< \brief (ADC_WINCTRL) Window Monitor Mode */
#define ADC_WINCTRL_WINMODE_Msk (_U_(0x7) << ADC_WINCTRL_WINMODE_Pos)
#define ADC_WINCTRL_WINMODE(value) (ADC_WINCTRL_WINMODE_Msk & ((value) << ADC_WINCTRL_WINMODE_Pos))
#define ADC_WINCTRL_WINMODE_DISABLE_Val _U_(0x0) /**< \brief (ADC_WINCTRL) No window mode (default) */
#define ADC_WINCTRL_WINMODE_MODE1_Val _U_(0x1) /**< \brief (ADC_WINCTRL) Mode 1: RESULT > WINLT */
#define ADC_WINCTRL_WINMODE_MODE2_Val _U_(0x2) /**< \brief (ADC_WINCTRL) Mode 2: RESULT < WINUT */
#define ADC_WINCTRL_WINMODE_MODE3_Val _U_(0x3) /**< \brief (ADC_WINCTRL) Mode 3: WINLT < RESULT < WINUT */
#define ADC_WINCTRL_WINMODE_MODE4_Val _U_(0x4) /**< \brief (ADC_WINCTRL) Mode 4: !(WINLT < RESULT < WINUT) */
#define ADC_WINCTRL_WINMODE_DISABLE (ADC_WINCTRL_WINMODE_DISABLE_Val << ADC_WINCTRL_WINMODE_Pos)
#define ADC_WINCTRL_WINMODE_MODE1 (ADC_WINCTRL_WINMODE_MODE1_Val << ADC_WINCTRL_WINMODE_Pos)
#define ADC_WINCTRL_WINMODE_MODE2 (ADC_WINCTRL_WINMODE_MODE2_Val << ADC_WINCTRL_WINMODE_Pos)
#define ADC_WINCTRL_WINMODE_MODE3 (ADC_WINCTRL_WINMODE_MODE3_Val << ADC_WINCTRL_WINMODE_Pos)
#define ADC_WINCTRL_WINMODE_MODE4 (ADC_WINCTRL_WINMODE_MODE4_Val << ADC_WINCTRL_WINMODE_Pos)
#define ADC_WINCTRL_MASK _U_(0x07) /**< \brief (ADC_WINCTRL) MASK Register */
/* -------- ADC_SWTRIG : (ADC Offset: 0x0C) (R/W 8) Software Trigger -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t FLUSH:1; /*!< bit: 0 ADC Conversion Flush */
uint8_t START:1; /*!< bit: 1 ADC Start Conversion */
uint8_t :6; /*!< bit: 2.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_SWTRIG_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_SWTRIG_OFFSET 0x0C /**< \brief (ADC_SWTRIG offset) Software Trigger */
#define ADC_SWTRIG_RESETVALUE _U_(0x00) /**< \brief (ADC_SWTRIG reset_value) Software Trigger */
#define ADC_SWTRIG_FLUSH_Pos 0 /**< \brief (ADC_SWTRIG) ADC Conversion Flush */
#define ADC_SWTRIG_FLUSH (_U_(0x1) << ADC_SWTRIG_FLUSH_Pos)
#define ADC_SWTRIG_START_Pos 1 /**< \brief (ADC_SWTRIG) ADC Start Conversion */
#define ADC_SWTRIG_START (_U_(0x1) << ADC_SWTRIG_START_Pos)
#define ADC_SWTRIG_MASK _U_(0x03) /**< \brief (ADC_SWTRIG) MASK Register */
/* -------- ADC_INPUTCTRL : (ADC Offset: 0x10) (R/W 32) Input Control -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint32_t MUXPOS:5; /*!< bit: 0.. 4 Positive Mux Input Selection */
uint32_t :3; /*!< bit: 5.. 7 Reserved */
uint32_t MUXNEG:5; /*!< bit: 8..12 Negative Mux Input Selection */
uint32_t :3; /*!< bit: 13..15 Reserved */
uint32_t INPUTSCAN:4; /*!< bit: 16..19 Number of Input Channels Included in Scan */
uint32_t INPUTOFFSET:4; /*!< bit: 20..23 Positive Mux Setting Offset */
uint32_t GAIN:4; /*!< bit: 24..27 Gain Factor Selection */
uint32_t :4; /*!< bit: 28..31 Reserved */
} bit; /*!< Structure used for bit access */
uint32_t reg; /*!< Type used for register access */
} ADC_INPUTCTRL_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_INPUTCTRL_OFFSET 0x10 /**< \brief (ADC_INPUTCTRL offset) Input Control */
#define ADC_INPUTCTRL_RESETVALUE _U_(0x00000000) /**< \brief (ADC_INPUTCTRL reset_value) Input Control */
#define ADC_INPUTCTRL_MUXPOS_Pos 0 /**< \brief (ADC_INPUTCTRL) Positive Mux Input Selection */
#define ADC_INPUTCTRL_MUXPOS_Msk (_U_(0x1F) << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS(value) (ADC_INPUTCTRL_MUXPOS_Msk & ((value) << ADC_INPUTCTRL_MUXPOS_Pos))
#define ADC_INPUTCTRL_MUXPOS_PIN0_Val _U_(0x0) /**< \brief (ADC_INPUTCTRL) ADC AIN0 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN1_Val _U_(0x1) /**< \brief (ADC_INPUTCTRL) ADC AIN1 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN2_Val _U_(0x2) /**< \brief (ADC_INPUTCTRL) ADC AIN2 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN3_Val _U_(0x3) /**< \brief (ADC_INPUTCTRL) ADC AIN3 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN4_Val _U_(0x4) /**< \brief (ADC_INPUTCTRL) ADC AIN4 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN5_Val _U_(0x5) /**< \brief (ADC_INPUTCTRL) ADC AIN5 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN6_Val _U_(0x6) /**< \brief (ADC_INPUTCTRL) ADC AIN6 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN7_Val _U_(0x7) /**< \brief (ADC_INPUTCTRL) ADC AIN7 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN8_Val _U_(0x8) /**< \brief (ADC_INPUTCTRL) ADC AIN8 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN9_Val _U_(0x9) /**< \brief (ADC_INPUTCTRL) ADC AIN9 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN10_Val _U_(0xA) /**< \brief (ADC_INPUTCTRL) ADC AIN10 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN11_Val _U_(0xB) /**< \brief (ADC_INPUTCTRL) ADC AIN11 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN12_Val _U_(0xC) /**< \brief (ADC_INPUTCTRL) ADC AIN12 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN13_Val _U_(0xD) /**< \brief (ADC_INPUTCTRL) ADC AIN13 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN14_Val _U_(0xE) /**< \brief (ADC_INPUTCTRL) ADC AIN14 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN15_Val _U_(0xF) /**< \brief (ADC_INPUTCTRL) ADC AIN15 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN16_Val _U_(0x10) /**< \brief (ADC_INPUTCTRL) ADC AIN16 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN17_Val _U_(0x11) /**< \brief (ADC_INPUTCTRL) ADC AIN17 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN18_Val _U_(0x12) /**< \brief (ADC_INPUTCTRL) ADC AIN18 Pin */
#define ADC_INPUTCTRL_MUXPOS_PIN19_Val _U_(0x13) /**< \brief (ADC_INPUTCTRL) ADC AIN19 Pin */
#define ADC_INPUTCTRL_MUXPOS_TEMP_Val _U_(0x18) /**< \brief (ADC_INPUTCTRL) Temperature Reference */
#define ADC_INPUTCTRL_MUXPOS_BANDGAP_Val _U_(0x19) /**< \brief (ADC_INPUTCTRL) Bandgap Voltage */
#define ADC_INPUTCTRL_MUXPOS_SCALEDCOREVCC_Val _U_(0x1A) /**< \brief (ADC_INPUTCTRL) 1/4 Scaled Core Supply */
#define ADC_INPUTCTRL_MUXPOS_SCALEDIOVCC_Val _U_(0x1B) /**< \brief (ADC_INPUTCTRL) 1/4 Scaled I/O Supply */
#define ADC_INPUTCTRL_MUXPOS_DAC_Val _U_(0x1C) /**< \brief (ADC_INPUTCTRL) DAC Output */
#define ADC_INPUTCTRL_MUXPOS_PIN0 (ADC_INPUTCTRL_MUXPOS_PIN0_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN1 (ADC_INPUTCTRL_MUXPOS_PIN1_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN2 (ADC_INPUTCTRL_MUXPOS_PIN2_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN3 (ADC_INPUTCTRL_MUXPOS_PIN3_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN4 (ADC_INPUTCTRL_MUXPOS_PIN4_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN5 (ADC_INPUTCTRL_MUXPOS_PIN5_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN6 (ADC_INPUTCTRL_MUXPOS_PIN6_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN7 (ADC_INPUTCTRL_MUXPOS_PIN7_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN8 (ADC_INPUTCTRL_MUXPOS_PIN8_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN9 (ADC_INPUTCTRL_MUXPOS_PIN9_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN10 (ADC_INPUTCTRL_MUXPOS_PIN10_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN11 (ADC_INPUTCTRL_MUXPOS_PIN11_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN12 (ADC_INPUTCTRL_MUXPOS_PIN12_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN13 (ADC_INPUTCTRL_MUXPOS_PIN13_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN14 (ADC_INPUTCTRL_MUXPOS_PIN14_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN15 (ADC_INPUTCTRL_MUXPOS_PIN15_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN16 (ADC_INPUTCTRL_MUXPOS_PIN16_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN17 (ADC_INPUTCTRL_MUXPOS_PIN17_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN18 (ADC_INPUTCTRL_MUXPOS_PIN18_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_PIN19 (ADC_INPUTCTRL_MUXPOS_PIN19_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_TEMP (ADC_INPUTCTRL_MUXPOS_TEMP_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_BANDGAP (ADC_INPUTCTRL_MUXPOS_BANDGAP_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_SCALEDCOREVCC (ADC_INPUTCTRL_MUXPOS_SCALEDCOREVCC_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_SCALEDIOVCC (ADC_INPUTCTRL_MUXPOS_SCALEDIOVCC_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXPOS_DAC (ADC_INPUTCTRL_MUXPOS_DAC_Val << ADC_INPUTCTRL_MUXPOS_Pos)
#define ADC_INPUTCTRL_MUXNEG_Pos 8 /**< \brief (ADC_INPUTCTRL) Negative Mux Input Selection */
#define ADC_INPUTCTRL_MUXNEG_Msk (_U_(0x1F) << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG(value) (ADC_INPUTCTRL_MUXNEG_Msk & ((value) << ADC_INPUTCTRL_MUXNEG_Pos))
#define ADC_INPUTCTRL_MUXNEG_PIN0_Val _U_(0x0) /**< \brief (ADC_INPUTCTRL) ADC AIN0 Pin */
#define ADC_INPUTCTRL_MUXNEG_PIN1_Val _U_(0x1) /**< \brief (ADC_INPUTCTRL) ADC AIN1 Pin */
#define ADC_INPUTCTRL_MUXNEG_PIN2_Val _U_(0x2) /**< \brief (ADC_INPUTCTRL) ADC AIN2 Pin */
#define ADC_INPUTCTRL_MUXNEG_PIN3_Val _U_(0x3) /**< \brief (ADC_INPUTCTRL) ADC AIN3 Pin */
#define ADC_INPUTCTRL_MUXNEG_PIN4_Val _U_(0x4) /**< \brief (ADC_INPUTCTRL) ADC AIN4 Pin */
#define ADC_INPUTCTRL_MUXNEG_PIN5_Val _U_(0x5) /**< \brief (ADC_INPUTCTRL) ADC AIN5 Pin */
#define ADC_INPUTCTRL_MUXNEG_PIN6_Val _U_(0x6) /**< \brief (ADC_INPUTCTRL) ADC AIN6 Pin */
#define ADC_INPUTCTRL_MUXNEG_PIN7_Val _U_(0x7) /**< \brief (ADC_INPUTCTRL) ADC AIN7 Pin */
#define ADC_INPUTCTRL_MUXNEG_GND_Val _U_(0x18) /**< \brief (ADC_INPUTCTRL) Internal Ground */
#define ADC_INPUTCTRL_MUXNEG_IOGND_Val _U_(0x19) /**< \brief (ADC_INPUTCTRL) I/O Ground */
#define ADC_INPUTCTRL_MUXNEG_PIN0 (ADC_INPUTCTRL_MUXNEG_PIN0_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_PIN1 (ADC_INPUTCTRL_MUXNEG_PIN1_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_PIN2 (ADC_INPUTCTRL_MUXNEG_PIN2_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_PIN3 (ADC_INPUTCTRL_MUXNEG_PIN3_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_PIN4 (ADC_INPUTCTRL_MUXNEG_PIN4_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_PIN5 (ADC_INPUTCTRL_MUXNEG_PIN5_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_PIN6 (ADC_INPUTCTRL_MUXNEG_PIN6_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_PIN7 (ADC_INPUTCTRL_MUXNEG_PIN7_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_GND (ADC_INPUTCTRL_MUXNEG_GND_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_MUXNEG_IOGND (ADC_INPUTCTRL_MUXNEG_IOGND_Val << ADC_INPUTCTRL_MUXNEG_Pos)
#define ADC_INPUTCTRL_INPUTSCAN_Pos 16 /**< \brief (ADC_INPUTCTRL) Number of Input Channels Included in Scan */
#define ADC_INPUTCTRL_INPUTSCAN_Msk (_U_(0xF) << ADC_INPUTCTRL_INPUTSCAN_Pos)
#define ADC_INPUTCTRL_INPUTSCAN(value) (ADC_INPUTCTRL_INPUTSCAN_Msk & ((value) << ADC_INPUTCTRL_INPUTSCAN_Pos))
#define ADC_INPUTCTRL_INPUTOFFSET_Pos 20 /**< \brief (ADC_INPUTCTRL) Positive Mux Setting Offset */
#define ADC_INPUTCTRL_INPUTOFFSET_Msk (_U_(0xF) << ADC_INPUTCTRL_INPUTOFFSET_Pos)
#define ADC_INPUTCTRL_INPUTOFFSET(value) (ADC_INPUTCTRL_INPUTOFFSET_Msk & ((value) << ADC_INPUTCTRL_INPUTOFFSET_Pos))
#define ADC_INPUTCTRL_GAIN_Pos 24 /**< \brief (ADC_INPUTCTRL) Gain Factor Selection */
#define ADC_INPUTCTRL_GAIN_Msk (_U_(0xF) << ADC_INPUTCTRL_GAIN_Pos)
#define ADC_INPUTCTRL_GAIN(value) (ADC_INPUTCTRL_GAIN_Msk & ((value) << ADC_INPUTCTRL_GAIN_Pos))
#define ADC_INPUTCTRL_GAIN_1X_Val _U_(0x0) /**< \brief (ADC_INPUTCTRL) 1x */
#define ADC_INPUTCTRL_GAIN_2X_Val _U_(0x1) /**< \brief (ADC_INPUTCTRL) 2x */
#define ADC_INPUTCTRL_GAIN_4X_Val _U_(0x2) /**< \brief (ADC_INPUTCTRL) 4x */
#define ADC_INPUTCTRL_GAIN_8X_Val _U_(0x3) /**< \brief (ADC_INPUTCTRL) 8x */
#define ADC_INPUTCTRL_GAIN_16X_Val _U_(0x4) /**< \brief (ADC_INPUTCTRL) 16x */
#define ADC_INPUTCTRL_GAIN_DIV2_Val _U_(0xF) /**< \brief (ADC_INPUTCTRL) 1/2x */
#define ADC_INPUTCTRL_GAIN_1X (ADC_INPUTCTRL_GAIN_1X_Val << ADC_INPUTCTRL_GAIN_Pos)
#define ADC_INPUTCTRL_GAIN_2X (ADC_INPUTCTRL_GAIN_2X_Val << ADC_INPUTCTRL_GAIN_Pos)
#define ADC_INPUTCTRL_GAIN_4X (ADC_INPUTCTRL_GAIN_4X_Val << ADC_INPUTCTRL_GAIN_Pos)
#define ADC_INPUTCTRL_GAIN_8X (ADC_INPUTCTRL_GAIN_8X_Val << ADC_INPUTCTRL_GAIN_Pos)
#define ADC_INPUTCTRL_GAIN_16X (ADC_INPUTCTRL_GAIN_16X_Val << ADC_INPUTCTRL_GAIN_Pos)
#define ADC_INPUTCTRL_GAIN_DIV2 (ADC_INPUTCTRL_GAIN_DIV2_Val << ADC_INPUTCTRL_GAIN_Pos)
#define ADC_INPUTCTRL_MASK _U_(0x0FFF1F1F) /**< \brief (ADC_INPUTCTRL) MASK Register */
/* -------- ADC_EVCTRL : (ADC Offset: 0x14) (R/W 8) Event Control -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t STARTEI:1; /*!< bit: 0 Start Conversion Event In */
uint8_t SYNCEI:1; /*!< bit: 1 Synchronization Event In */
uint8_t :2; /*!< bit: 2.. 3 Reserved */
uint8_t RESRDYEO:1; /*!< bit: 4 Result Ready Event Out */
uint8_t WINMONEO:1; /*!< bit: 5 Window Monitor Event Out */
uint8_t :2; /*!< bit: 6.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_EVCTRL_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_EVCTRL_OFFSET 0x14 /**< \brief (ADC_EVCTRL offset) Event Control */
#define ADC_EVCTRL_RESETVALUE _U_(0x00) /**< \brief (ADC_EVCTRL reset_value) Event Control */
#define ADC_EVCTRL_STARTEI_Pos 0 /**< \brief (ADC_EVCTRL) Start Conversion Event In */
#define ADC_EVCTRL_STARTEI (_U_(0x1) << ADC_EVCTRL_STARTEI_Pos)
#define ADC_EVCTRL_SYNCEI_Pos 1 /**< \brief (ADC_EVCTRL) Synchronization Event In */
#define ADC_EVCTRL_SYNCEI (_U_(0x1) << ADC_EVCTRL_SYNCEI_Pos)
#define ADC_EVCTRL_RESRDYEO_Pos 4 /**< \brief (ADC_EVCTRL) Result Ready Event Out */
#define ADC_EVCTRL_RESRDYEO (_U_(0x1) << ADC_EVCTRL_RESRDYEO_Pos)
#define ADC_EVCTRL_WINMONEO_Pos 5 /**< \brief (ADC_EVCTRL) Window Monitor Event Out */
#define ADC_EVCTRL_WINMONEO (_U_(0x1) << ADC_EVCTRL_WINMONEO_Pos)
#define ADC_EVCTRL_MASK _U_(0x33) /**< \brief (ADC_EVCTRL) MASK Register */
/* -------- ADC_INTENCLR : (ADC Offset: 0x16) (R/W 8) Interrupt Enable Clear -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t RESRDY:1; /*!< bit: 0 Result Ready Interrupt Enable */
uint8_t OVERRUN:1; /*!< bit: 1 Overrun Interrupt Enable */
uint8_t WINMON:1; /*!< bit: 2 Window Monitor Interrupt Enable */
uint8_t SYNCRDY:1; /*!< bit: 3 Synchronization Ready Interrupt Enable */
uint8_t :4; /*!< bit: 4.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_INTENCLR_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_INTENCLR_OFFSET 0x16 /**< \brief (ADC_INTENCLR offset) Interrupt Enable Clear */
#define ADC_INTENCLR_RESETVALUE _U_(0x00) /**< \brief (ADC_INTENCLR reset_value) Interrupt Enable Clear */
#define ADC_INTENCLR_RESRDY_Pos 0 /**< \brief (ADC_INTENCLR) Result Ready Interrupt Enable */
#define ADC_INTENCLR_RESRDY (_U_(0x1) << ADC_INTENCLR_RESRDY_Pos)
#define ADC_INTENCLR_OVERRUN_Pos 1 /**< \brief (ADC_INTENCLR) Overrun Interrupt Enable */
#define ADC_INTENCLR_OVERRUN (_U_(0x1) << ADC_INTENCLR_OVERRUN_Pos)
#define ADC_INTENCLR_WINMON_Pos 2 /**< \brief (ADC_INTENCLR) Window Monitor Interrupt Enable */
#define ADC_INTENCLR_WINMON (_U_(0x1) << ADC_INTENCLR_WINMON_Pos)
#define ADC_INTENCLR_SYNCRDY_Pos 3 /**< \brief (ADC_INTENCLR) Synchronization Ready Interrupt Enable */
#define ADC_INTENCLR_SYNCRDY (_U_(0x1) << ADC_INTENCLR_SYNCRDY_Pos)
#define ADC_INTENCLR_MASK _U_(0x0F) /**< \brief (ADC_INTENCLR) MASK Register */
/* -------- ADC_INTENSET : (ADC Offset: 0x17) (R/W 8) Interrupt Enable Set -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t RESRDY:1; /*!< bit: 0 Result Ready Interrupt Enable */
uint8_t OVERRUN:1; /*!< bit: 1 Overrun Interrupt Enable */
uint8_t WINMON:1; /*!< bit: 2 Window Monitor Interrupt Enable */
uint8_t SYNCRDY:1; /*!< bit: 3 Synchronization Ready Interrupt Enable */
uint8_t :4; /*!< bit: 4.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_INTENSET_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_INTENSET_OFFSET 0x17 /**< \brief (ADC_INTENSET offset) Interrupt Enable Set */
#define ADC_INTENSET_RESETVALUE _U_(0x00) /**< \brief (ADC_INTENSET reset_value) Interrupt Enable Set */
#define ADC_INTENSET_RESRDY_Pos 0 /**< \brief (ADC_INTENSET) Result Ready Interrupt Enable */
#define ADC_INTENSET_RESRDY (_U_(0x1) << ADC_INTENSET_RESRDY_Pos)
#define ADC_INTENSET_OVERRUN_Pos 1 /**< \brief (ADC_INTENSET) Overrun Interrupt Enable */
#define ADC_INTENSET_OVERRUN (_U_(0x1) << ADC_INTENSET_OVERRUN_Pos)
#define ADC_INTENSET_WINMON_Pos 2 /**< \brief (ADC_INTENSET) Window Monitor Interrupt Enable */
#define ADC_INTENSET_WINMON (_U_(0x1) << ADC_INTENSET_WINMON_Pos)
#define ADC_INTENSET_SYNCRDY_Pos 3 /**< \brief (ADC_INTENSET) Synchronization Ready Interrupt Enable */
#define ADC_INTENSET_SYNCRDY (_U_(0x1) << ADC_INTENSET_SYNCRDY_Pos)
#define ADC_INTENSET_MASK _U_(0x0F) /**< \brief (ADC_INTENSET) MASK Register */
/* -------- ADC_INTFLAG : (ADC Offset: 0x18) (R/W 8) Interrupt Flag Status and Clear -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union { // __I to avoid read-modify-write on write-to-clear register
struct {
__I uint8_t RESRDY:1; /*!< bit: 0 Result Ready */
__I uint8_t OVERRUN:1; /*!< bit: 1 Overrun */
__I uint8_t WINMON:1; /*!< bit: 2 Window Monitor */
__I uint8_t SYNCRDY:1; /*!< bit: 3 Synchronization Ready */
__I uint8_t :4; /*!< bit: 4.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_INTFLAG_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_INTFLAG_OFFSET 0x18 /**< \brief (ADC_INTFLAG offset) Interrupt Flag Status and Clear */
#define ADC_INTFLAG_RESETVALUE _U_(0x00) /**< \brief (ADC_INTFLAG reset_value) Interrupt Flag Status and Clear */
#define ADC_INTFLAG_RESRDY_Pos 0 /**< \brief (ADC_INTFLAG) Result Ready */
#define ADC_INTFLAG_RESRDY (_U_(0x1) << ADC_INTFLAG_RESRDY_Pos)
#define ADC_INTFLAG_OVERRUN_Pos 1 /**< \brief (ADC_INTFLAG) Overrun */
#define ADC_INTFLAG_OVERRUN (_U_(0x1) << ADC_INTFLAG_OVERRUN_Pos)
#define ADC_INTFLAG_WINMON_Pos 2 /**< \brief (ADC_INTFLAG) Window Monitor */
#define ADC_INTFLAG_WINMON (_U_(0x1) << ADC_INTFLAG_WINMON_Pos)
#define ADC_INTFLAG_SYNCRDY_Pos 3 /**< \brief (ADC_INTFLAG) Synchronization Ready */
#define ADC_INTFLAG_SYNCRDY (_U_(0x1) << ADC_INTFLAG_SYNCRDY_Pos)
#define ADC_INTFLAG_MASK _U_(0x0F) /**< \brief (ADC_INTFLAG) MASK Register */
/* -------- ADC_STATUS : (ADC Offset: 0x19) (R/ 8) Status -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t :7; /*!< bit: 0.. 6 Reserved */
uint8_t SYNCBUSY:1; /*!< bit: 7 Synchronization Busy */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_STATUS_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_STATUS_OFFSET 0x19 /**< \brief (ADC_STATUS offset) Status */
#define ADC_STATUS_RESETVALUE _U_(0x00) /**< \brief (ADC_STATUS reset_value) Status */
#define ADC_STATUS_SYNCBUSY_Pos 7 /**< \brief (ADC_STATUS) Synchronization Busy */
#define ADC_STATUS_SYNCBUSY (_U_(0x1) << ADC_STATUS_SYNCBUSY_Pos)
#define ADC_STATUS_MASK _U_(0x80) /**< \brief (ADC_STATUS) MASK Register */
/* -------- ADC_RESULT : (ADC Offset: 0x1A) (R/ 16) Result -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint16_t RESULT:16; /*!< bit: 0..15 Result Conversion Value */
} bit; /*!< Structure used for bit access */
uint16_t reg; /*!< Type used for register access */
} ADC_RESULT_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_RESULT_OFFSET 0x1A /**< \brief (ADC_RESULT offset) Result */
#define ADC_RESULT_RESETVALUE _U_(0x0000) /**< \brief (ADC_RESULT reset_value) Result */
#define ADC_RESULT_RESULT_Pos 0 /**< \brief (ADC_RESULT) Result Conversion Value */
#define ADC_RESULT_RESULT_Msk (_U_(0xFFFF) << ADC_RESULT_RESULT_Pos)
#define ADC_RESULT_RESULT(value) (ADC_RESULT_RESULT_Msk & ((value) << ADC_RESULT_RESULT_Pos))
#define ADC_RESULT_MASK _U_(0xFFFF) /**< \brief (ADC_RESULT) MASK Register */
/* -------- ADC_WINLT : (ADC Offset: 0x1C) (R/W 16) Window Monitor Lower Threshold -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint16_t WINLT:16; /*!< bit: 0..15 Window Lower Threshold */
} bit; /*!< Structure used for bit access */
uint16_t reg; /*!< Type used for register access */
} ADC_WINLT_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_WINLT_OFFSET 0x1C /**< \brief (ADC_WINLT offset) Window Monitor Lower Threshold */
#define ADC_WINLT_RESETVALUE _U_(0x0000) /**< \brief (ADC_WINLT reset_value) Window Monitor Lower Threshold */
#define ADC_WINLT_WINLT_Pos 0 /**< \brief (ADC_WINLT) Window Lower Threshold */
#define ADC_WINLT_WINLT_Msk (_U_(0xFFFF) << ADC_WINLT_WINLT_Pos)
#define ADC_WINLT_WINLT(value) (ADC_WINLT_WINLT_Msk & ((value) << ADC_WINLT_WINLT_Pos))
#define ADC_WINLT_MASK _U_(0xFFFF) /**< \brief (ADC_WINLT) MASK Register */
/* -------- ADC_WINUT : (ADC Offset: 0x20) (R/W 16) Window Monitor Upper Threshold -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint16_t WINUT:16; /*!< bit: 0..15 Window Upper Threshold */
} bit; /*!< Structure used for bit access */
uint16_t reg; /*!< Type used for register access */
} ADC_WINUT_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_WINUT_OFFSET 0x20 /**< \brief (ADC_WINUT offset) Window Monitor Upper Threshold */
#define ADC_WINUT_RESETVALUE _U_(0x0000) /**< \brief (ADC_WINUT reset_value) Window Monitor Upper Threshold */
#define ADC_WINUT_WINUT_Pos 0 /**< \brief (ADC_WINUT) Window Upper Threshold */
#define ADC_WINUT_WINUT_Msk (_U_(0xFFFF) << ADC_WINUT_WINUT_Pos)
#define ADC_WINUT_WINUT(value) (ADC_WINUT_WINUT_Msk & ((value) << ADC_WINUT_WINUT_Pos))
#define ADC_WINUT_MASK _U_(0xFFFF) /**< \brief (ADC_WINUT) MASK Register */
/* -------- ADC_GAINCORR : (ADC Offset: 0x24) (R/W 16) Gain Correction -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint16_t GAINCORR:12; /*!< bit: 0..11 Gain Correction Value */
uint16_t :4; /*!< bit: 12..15 Reserved */
} bit; /*!< Structure used for bit access */
uint16_t reg; /*!< Type used for register access */
} ADC_GAINCORR_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_GAINCORR_OFFSET 0x24 /**< \brief (ADC_GAINCORR offset) Gain Correction */
#define ADC_GAINCORR_RESETVALUE _U_(0x0000) /**< \brief (ADC_GAINCORR reset_value) Gain Correction */
#define ADC_GAINCORR_GAINCORR_Pos 0 /**< \brief (ADC_GAINCORR) Gain Correction Value */
#define ADC_GAINCORR_GAINCORR_Msk (_U_(0xFFF) << ADC_GAINCORR_GAINCORR_Pos)
#define ADC_GAINCORR_GAINCORR(value) (ADC_GAINCORR_GAINCORR_Msk & ((value) << ADC_GAINCORR_GAINCORR_Pos))
#define ADC_GAINCORR_MASK _U_(0x0FFF) /**< \brief (ADC_GAINCORR) MASK Register */
/* -------- ADC_OFFSETCORR : (ADC Offset: 0x26) (R/W 16) Offset Correction -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint16_t OFFSETCORR:12; /*!< bit: 0..11 Offset Correction Value */
uint16_t :4; /*!< bit: 12..15 Reserved */
} bit; /*!< Structure used for bit access */
uint16_t reg; /*!< Type used for register access */
} ADC_OFFSETCORR_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_OFFSETCORR_OFFSET 0x26 /**< \brief (ADC_OFFSETCORR offset) Offset Correction */
#define ADC_OFFSETCORR_RESETVALUE _U_(0x0000) /**< \brief (ADC_OFFSETCORR reset_value) Offset Correction */
#define ADC_OFFSETCORR_OFFSETCORR_Pos 0 /**< \brief (ADC_OFFSETCORR) Offset Correction Value */
#define ADC_OFFSETCORR_OFFSETCORR_Msk (_U_(0xFFF) << ADC_OFFSETCORR_OFFSETCORR_Pos)
#define ADC_OFFSETCORR_OFFSETCORR(value) (ADC_OFFSETCORR_OFFSETCORR_Msk & ((value) << ADC_OFFSETCORR_OFFSETCORR_Pos))
#define ADC_OFFSETCORR_MASK _U_(0x0FFF) /**< \brief (ADC_OFFSETCORR) MASK Register */
/* -------- ADC_CALIB : (ADC Offset: 0x28) (R/W 16) Calibration -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint16_t LINEARITY_CAL:8; /*!< bit: 0.. 7 Linearity Calibration Value */
uint16_t BIAS_CAL:3; /*!< bit: 8..10 Bias Calibration Value */
uint16_t :5; /*!< bit: 11..15 Reserved */
} bit; /*!< Structure used for bit access */
uint16_t reg; /*!< Type used for register access */
} ADC_CALIB_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_CALIB_OFFSET 0x28 /**< \brief (ADC_CALIB offset) Calibration */
#define ADC_CALIB_RESETVALUE _U_(0x0000) /**< \brief (ADC_CALIB reset_value) Calibration */
#define ADC_CALIB_LINEARITY_CAL_Pos 0 /**< \brief (ADC_CALIB) Linearity Calibration Value */
#define ADC_CALIB_LINEARITY_CAL_Msk (_U_(0xFF) << ADC_CALIB_LINEARITY_CAL_Pos)
#define ADC_CALIB_LINEARITY_CAL(value) (ADC_CALIB_LINEARITY_CAL_Msk & ((value) << ADC_CALIB_LINEARITY_CAL_Pos))
#define ADC_CALIB_BIAS_CAL_Pos 8 /**< \brief (ADC_CALIB) Bias Calibration Value */
#define ADC_CALIB_BIAS_CAL_Msk (_U_(0x7) << ADC_CALIB_BIAS_CAL_Pos)
#define ADC_CALIB_BIAS_CAL(value) (ADC_CALIB_BIAS_CAL_Msk & ((value) << ADC_CALIB_BIAS_CAL_Pos))
#define ADC_CALIB_MASK _U_(0x07FF) /**< \brief (ADC_CALIB) MASK Register */
/* -------- ADC_DBGCTRL : (ADC Offset: 0x2A) (R/W 8) Debug Control -------- */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef union {
struct {
uint8_t DBGRUN:1; /*!< bit: 0 Debug Run */
uint8_t :7; /*!< bit: 1.. 7 Reserved */
} bit; /*!< Structure used for bit access */
uint8_t reg; /*!< Type used for register access */
} ADC_DBGCTRL_Type;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#define ADC_DBGCTRL_OFFSET 0x2A /**< \brief (ADC_DBGCTRL offset) Debug Control */
#define ADC_DBGCTRL_RESETVALUE _U_(0x00) /**< \brief (ADC_DBGCTRL reset_value) Debug Control */
#define ADC_DBGCTRL_DBGRUN_Pos 0 /**< \brief (ADC_DBGCTRL) Debug Run */
#define ADC_DBGCTRL_DBGRUN (_U_(0x1) << ADC_DBGCTRL_DBGRUN_Pos)
#define ADC_DBGCTRL_MASK _U_(0x01) /**< \brief (ADC_DBGCTRL) MASK Register */
/** \brief ADC hardware registers */
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
typedef struct {
__IO ADC_CTRLA_Type CTRLA; /**< \brief Offset: 0x00 (R/W 8) Control A */
__IO ADC_REFCTRL_Type REFCTRL; /**< \brief Offset: 0x01 (R/W 8) Reference Control */
__IO ADC_AVGCTRL_Type AVGCTRL; /**< \brief Offset: 0x02 (R/W 8) Average Control */
__IO ADC_SAMPCTRL_Type SAMPCTRL; /**< \brief Offset: 0x03 (R/W 8) Sampling Time Control */
__IO ADC_CTRLB_Type CTRLB; /**< \brief Offset: 0x04 (R/W 16) Control B */
RoReg8 Reserved1[0x2];
__IO ADC_WINCTRL_Type WINCTRL; /**< \brief Offset: 0x08 (R/W 8) Window Monitor Control */
RoReg8 Reserved2[0x3];
__IO ADC_SWTRIG_Type SWTRIG; /**< \brief Offset: 0x0C (R/W 8) Software Trigger */
RoReg8 Reserved3[0x3];
__IO ADC_INPUTCTRL_Type INPUTCTRL; /**< \brief Offset: 0x10 (R/W 32) Input Control */
__IO ADC_EVCTRL_Type EVCTRL; /**< \brief Offset: 0x14 (R/W 8) Event Control */
RoReg8 Reserved4[0x1];
__IO ADC_INTENCLR_Type INTENCLR; /**< \brief Offset: 0x16 (R/W 8) Interrupt Enable Clear */
__IO ADC_INTENSET_Type INTENSET; /**< \brief Offset: 0x17 (R/W 8) Interrupt Enable Set */
__IO ADC_INTFLAG_Type INTFLAG; /**< \brief Offset: 0x18 (R/W 8) Interrupt Flag Status and Clear */
__I ADC_STATUS_Type STATUS; /**< \brief Offset: 0x19 (R/ 8) Status */
__I ADC_RESULT_Type RESULT; /**< \brief Offset: 0x1A (R/ 16) Result */
__IO ADC_WINLT_Type WINLT; /**< \brief Offset: 0x1C (R/W 16) Window Monitor Lower Threshold */
RoReg8 Reserved5[0x2];
__IO ADC_WINUT_Type WINUT; /**< \brief Offset: 0x20 (R/W 16) Window Monitor Upper Threshold */
RoReg8 Reserved6[0x2];
__IO ADC_GAINCORR_Type GAINCORR; /**< \brief Offset: 0x24 (R/W 16) Gain Correction */
__IO ADC_OFFSETCORR_Type OFFSETCORR; /**< \brief Offset: 0x26 (R/W 16) Offset Correction */
__IO ADC_CALIB_Type CALIB; /**< \brief Offset: 0x28 (R/W 16) Calibration */
__IO ADC_DBGCTRL_Type DBGCTRL; /**< \brief Offset: 0x2A (R/W 8) Debug Control */
} Adc;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
/*@}*/
#endif /* _SAMD11_ADC_COMPONENT_ */
| {
"language": "C"
} |
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* Copyright (C) International Business Machines Corp., 2000-2001
* Portions Copyright (C) Christoph Hellwig, 2001-2002
*/
#ifndef _H_JFS_LOCK
#define _H_JFS_LOCK
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/sched.h>
/*
* jfs_lock.h
*/
/*
* Conditional sleep where condition is protected by spinlock
*
* lock_cmd and unlock_cmd take and release the spinlock
*/
#define __SLEEP_COND(wq, cond, lock_cmd, unlock_cmd) \
do { \
DECLARE_WAITQUEUE(__wait, current); \
\
add_wait_queue(&wq, &__wait); \
for (;;) { \
set_current_state(TASK_UNINTERRUPTIBLE);\
if (cond) \
break; \
unlock_cmd; \
io_schedule(); \
lock_cmd; \
} \
__set_current_state(TASK_RUNNING); \
remove_wait_queue(&wq, &__wait); \
} while (0)
#endif /* _H_JFS_LOCK */
| {
"language": "C"
} |
/**HEADER********************************************************************
*
* Copyright (c) 2008, 2013 - 2015 Freescale Semiconductor;
* All Rights Reserved
*
* Copyright (c) 1989-2008 ARC International;
* All Rights Reserved
*
***************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED 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 FREESCALE OR ITS 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.
*
**************************************************************************
*
* $FileName: usb_msc.c$
* $Version :
* $Date :
*
* Comments:
*
* @brief The file contains USB stack MSC layer implementation.
*
*****************************************************************************/
/******************************************************************************
* Includes
*****************************************************************************/
#include "usb_device_config.h"
#include "usb.h"
#include "usb_device_stack_interface.h"
#if USBCFG_DEV_MSC
#include "usb_class_internal.h"
#include "usb_msc.h"
#include "usb_opt.h"
/*****************************************************************************
* Constant and Macro's
*****************************************************************************/
/****************************************************************************
* Global Variables
****************************************************************************/
msc_device_struct_t g_msc_class[MAX_MSC_DEVICE];
#if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_BM) || ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK)))
cbw_t g_msc_class_cbw;
csw_t g_msc_class_csw;
#endif
/*****************************************************************************
* Local Types - None
*****************************************************************************/
/*****************************************************************************
* Local Functions Prototypes
*****************************************************************************/
usb_status process_mass_storage_command (msc_device_struct_t * msc_obj_ptr,
cbw_t * cbw_ptr,
uint32_t* csw_residue_ptr,
uint8_t* csw_status_ptr);
/*****************************************************************************
* Local Variables - None
*****************************************************************************/
/*****************************************************************************
* Local Functions
*****************************************************************************/
/*************************************************************************//*!
*
* @name USB_Msd_Allocate_Handle
*
* @brief The function reserves entry in device array and returns the index.
*
* @param none.
* @return returns the reserved handle or if no entry found device busy.
*
*****************************************************************************/
static usb_status USB_Msd_Allocate_Handle(msc_device_struct_t** handle)
{
uint32_t cnt = 0;
for (;cnt< MAX_MSC_DEVICE;cnt++)
{
if (g_msc_class[cnt].controller_handle == NULL)
{
*handle = (msc_device_struct_t*)&g_msc_class[cnt];
return USB_OK;
}
}
return USBERR_DEVICE_BUSY;
}
/*************************************************************************//*!
*
* @name USB_Msd_Free_Handle
*
* @brief The function releases entry in device array .
*
* @param handle index in device array to be released..
* @return returns and error code or USB_OK.
*
*****************************************************************************/
static usb_status USB_Msd_Free_Handle(msc_device_struct_t* handle)
{
int32_t cnt = 0;
for (;cnt< MAX_MSC_DEVICE;cnt++)
{
if ((&g_msc_class[cnt]) == handle)
{
OS_Mem_zero((void*)handle, sizeof(msc_device_struct_t));
return USB_OK;
}
}
return USBERR_INVALID_PARAM;
}
/*************************************************************************//*!
*
* @name USB_Msd_Get_Device_Ptr
*
* @brief The function gets the device pointer from device array .
*
* @param handle index in device array.
* @return returns returns pointer to MSD device structure..
*
*****************************************************************************/
static msc_device_struct_t * USB_Msd_Get_Device_Ptr(msd_handle_t handle)
{
return (msc_device_struct_t *)handle;
}
/*************************************************************************//*!
*
* @name USB_Msd_Get_Desc_Info
*
* @brief The function gets the info of the descriptors. .
*
* @param handle index in device array.
* @param type descriptor type.
* @param object store the returned value.
* @return returns USB_OK if successful.
*
*****************************************************************************/
static usb_status USB_Msd_Get_Desc_Info(msc_device_struct_t * msc_dev_ptr,USB_MSD_DESC_INFO_T type, uint32_t * object)
{
#if USBCFG_DEV_COMPOSITE
uint32_t interface_index = 0xFF;
#endif
/* Get class info */
switch(type)
{
case USB_MSD_INTERFACE_COUNT:
#if USBCFG_DEV_COMPOSITE
*object = MAX_MSC_SUPPORTED_INTERFACES + 2;
#else
*object = MAX_MSC_SUPPORTED_INTERFACES;
#endif
break;
#if USBCFG_DEV_COMPOSITE
case USB_MSD_CLASS_INFO:
{
uint32_t class_i;
usb_composite_info_struct_t* usbcompinfoPtr;
/* Get class info */
msc_dev_ptr->desc_callback.get_desc_entity((uint32_t)msc_dev_ptr->controller_handle,
USB_COMPOSITE_INFO,
(uint32_t *)&usbcompinfoPtr);
msc_dev_ptr->desc_callback.get_desc_entity((uint32_t)msc_dev_ptr,
USB_CLASS_INTERFACE_INDEX_INFO,
(uint32_t *)&interface_index);
*object = 0;
for (class_i = 0; class_i < usbcompinfoPtr->count; class_i++)
{
if ((USB_CLASS_MSC == usbcompinfoPtr->class_handle[class_i].type) && (class_i == interface_index))
{
*object = (uint32_t)&(usbcompinfoPtr->class_handle[class_i]);
break;
}
}
}
break;
#endif
default :
break;
}
return USB_OK;
}
/**************************************************************************//*!
*
* @name process_mass_storage_command
*
* @brief Process a Mass storage class command
* This function is added here to add more sub class specific commands)
*
* @param msc_device_struct_t *
* @param cbw_ptr : pointer to Command Block Wrapper sent by host
* @param csw_residue_ptr: pointer to dCSWDataResidue of Command Status Wrapper
* @param csw_status_ptr : pointer to bCSWStatus of Command Status Wrapper
*
* @return error
*
*****************************************************************************/
usb_status process_mass_storage_command
(
msc_device_struct_t * msc_obj_ptr,
cbw_t * cbw_ptr,
uint32_t* csw_residue_ptr,
uint8_t* csw_status_ptr
)
{
usb_status error = USBERR_ERROR;/* initializing to error value */
switch (cbw_ptr->command_block[0])
{
/* commands to be supported by all devices */
case INQUIRY_COMMAND : /*opcode : 0x12*/
error = msc_inquiry_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case READ_10_COMMAND : /*opcode : 0x28 */
case READ_12_COMMAND : /*opcode : 0xA8 */
error = msc_read_command(msc_obj_ptr,
cbw_ptr,csw_residue_ptr,csw_status_ptr);
break;
case REQUEST_SENSE_COMMAND : /*opcode : 0x03*/
error = msc_request_sense_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case TEST_UNIT_READY_COMMAND : /*opcode : 0x00 */
error = msc_test_unit_ready_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case WRITE_10_COMMAND : /*opcode : 0x2A */
case WRITE_12_COMMAND : /*opcode : 0xAA */
error = msc_write_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case PREVENT_ALLOW_MEDIUM_REM_COMMAND : /*opcode :0x1E */
error = msc_prevent_allow_medium_removal(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case FORMAT_UNIT_COMMAND : /*opcode : 0x04*/
error = msc_format_unit_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case READ_CAPACITY_10_COMMAND : /*opcode : 0x25*/
case READ_CAPACITY_16_COMMAND : /*opcode : 0x9E*/
error = msc_read_capacity_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case MODE_SENSE_10_COMMAND : /* opcode :0x5A*/
case MODE_SENSE_6_COMMAND : /* opcode : 0x1A */
error = msc_mode_sense_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case MODE_SELECT_10_COMMAND : /*opcode : 0x55 */
case MODE_SELECT_6_COMMAND : /*opcode : 0x15 */
error = msc_mode_select_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case READ_FORMAT_CAPACITIES_COMMAND : /*opcode : 0x23 */
error = msc_read_format_capacity_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case SEND_DIAGNOSTIC_COMMAND : /*opcode : 0x1D*/
error = msc_send_diagnostic_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case VERIFY_COMMAND : /*opcode : 0x2F*/
error = msc_verify_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
case START_STOP_UNIT_COMMAND : /*opcode : 0x1B*/
error = msc_start_stop_unit_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
break;
default: /* for all unsupported commands */
error = msc_unsupported_command(msc_obj_ptr, cbw_ptr,csw_residue_ptr,
csw_status_ptr);
msc_obj_ptr->out_flag = FALSE;
msc_obj_ptr->in_flag = FALSE;
msc_obj_ptr->out_stall_flag = FALSE;
msc_obj_ptr->in_stall_flag = FALSE;
msc_obj_ptr->need_out_stall_flag = FALSE;
msc_obj_ptr->need_in_stall_flag = FALSE;
break;
}
return error;
}
/**************************************************************************//*!
*
* @name USB_Service_Bulk_In
*
* @brief The function is callback function of DIC Bulk In Endpoint
*
* @param event
* @param arg
* @return None
*
*****************************************************************************/
void USB_Service_Bulk_In(usb_event_struct_t* event, void* arg)
{
//uint8_t event_type;
csw_t * csw_ptr;
msc_device_struct_t * msc_obj_ptr;
msc_obj_ptr = (msc_device_struct_t *)arg;
if (NULL == msc_obj_ptr)
{
#if _DEBUG
USB_PRINTF("USB_Service_Bulk_In: msc_obj_ptr is NULL\n");
#endif
return;
}
if (event->len == 0xFFFFFFFF)
{
if((msc_obj_ptr->in_flag) && (msc_obj_ptr->class_specific_callback.callback != NULL)
&& ((READ_10_COMMAND == msc_obj_ptr->cbw_ptr->command_block[0])
|| (READ_12_COMMAND == msc_obj_ptr->cbw_ptr->command_block[0])))
{
lba_app_struct_t lba_data;
lba_data.size = 0;
lba_data.buff_ptr = event->buffer_ptr;
lba_data.offset = 0;
msc_obj_ptr->class_specific_callback.callback(USB_DEV_EVENT_SEND_COMPLETE,
USB_REQ_VAL_INVALID, NULL, (uint32_t *)&lba_data, msc_obj_ptr->class_specific_callback.arg);
}
return;
}
if(msc_obj_ptr->transfer_remaining >= event->len)
{ /* decrement the global count */
msc_obj_ptr->transfer_remaining -= event->len;
}
/* check if there is need to stall BULK IN ENDPOINT And
there isn't any transfer in progress*/
if( (msc_obj_ptr->need_in_stall_flag == TRUE)&&
(!msc_obj_ptr->transfer_remaining))
{
msc_obj_ptr->need_in_stall_flag = FALSE; /* clear the flag */
msc_obj_ptr->in_stall_flag = TRUE;
msc_obj_ptr->in_flag = FALSE; /* clear send flag */
usb_device_stall_endpoint(msc_obj_ptr->controller_handle,event->ep_num,USB_SEND);
return;
}
/* If its not a data phase on bulk endpoint */
if ((!msc_obj_ptr->in_flag) && (event->len == MSC_CSW_LENGTH))
{
csw_ptr = (csw_t *)(event->buffer_ptr);
}
if(msc_obj_ptr->in_flag) /* bulk in transaction has occurred before CSW */
{
if(msc_obj_ptr->class_specific_callback.callback != NULL)
{
lba_app_struct_t lba_data;
lba_data.size = event->len;
lba_data.buff_ptr = event->buffer_ptr;
lba_data.offset = msc_obj_ptr->current_offset;
if((READ_10_COMMAND == msc_obj_ptr->cbw_ptr->command_block[0])
|| (READ_12_COMMAND == msc_obj_ptr->cbw_ptr->command_block[0])
)
{
msc_obj_ptr->class_specific_callback.callback(USB_DEV_EVENT_SEND_COMPLETE,
USB_REQ_VAL_INVALID,NULL,(uint32_t *)&lba_data, msc_obj_ptr->class_specific_callback.arg);
}
if(msc_obj_ptr->transfer_remaining)
{
msc_obj_ptr->current_offset += event->len;
lba_data.offset = msc_obj_ptr->current_offset;
lba_data.size = (msc_obj_ptr->msd_buff.msc_bulk_in_size > MSD_SEND_MAX_TRANS_LENGTH ?
MSD_SEND_MAX_TRANS_LENGTH : msc_obj_ptr->msd_buff.msc_bulk_in_size); /* whichever is smaller */
lba_data.size = (msc_obj_ptr->transfer_remaining > lba_data.size ?
lba_data.size : msc_obj_ptr->transfer_remaining); /* whichever is smaller */
lba_data.buff_ptr = NULL; //msc_obj_ptr->msd_buff.msc_bulk_in_ptr;
/* fetch data from MSD App(e.g)ram disk or Sd card, etc*/
msc_obj_ptr->class_specific_callback.callback(USB_MSC_DEVICE_READ_REQUEST,
USB_REQ_VAL_INVALID,&msc_obj_ptr->msd_buff.msc_bulk_in_ptr,(uint32_t *)&lba_data, msc_obj_ptr->class_specific_callback.arg);
lba_data.buff_ptr = msc_obj_ptr->msd_buff.msc_bulk_in_ptr; //msc_obj_ptr->msd_buff.msc_disk_buff_ptr + msc_obj_ptr->current_offset;
if(msc_obj_ptr->current_offset < (msc_obj_ptr->device_info.total_lba_device_supports * msc_obj_ptr->device_info.length_of_each_lab_of_device))
{
/* Send data on USB Bus */
(void)USB_MSC_Bulk_Send_Data(msc_obj_ptr->msc_handle,
(uint8_t *)lba_data.buff_ptr,lba_data.size);
}
else
{
msc_obj_ptr->need_in_stall_flag = FALSE; /* clear the flag */
msc_obj_ptr->in_stall_flag = TRUE;
msc_obj_ptr->in_flag = FALSE; /* clear send flag */
msc_obj_ptr->stall_status = (uint8_t)STALL_IN_DATA_PHASE;
usb_device_stall_endpoint(msc_obj_ptr->controller_handle,msc_obj_ptr->bulk_in_endpoint,USB_SEND);
}
}
}
if(!msc_obj_ptr->transfer_remaining)
{ /* marks the end of data phase */
msc_obj_ptr->in_flag = FALSE; /* clear the flag for next CBW */
//if(msc_obj_ptr->csw_prime_flag == FALSE)
{
/* Send the command status information */
(void)USB_MSC_Bulk_Send_Data(msc_obj_ptr->msc_handle,
(uint8_t *)msc_obj_ptr->csw_ptr, MSC_CSW_LENGTH);
msc_obj_ptr->csw_prime_flag = TRUE;
}
}
}
else if ((event->len == MSC_CSW_LENGTH) /* CSW is 13 bytes in length */
&& (csw_ptr->signature == USB_DCSWSIGNATURE)) /*valid CSW signature*/
{
/* this flag will now be set on reset or after CSW being sent */
msc_obj_ptr->cbw_valid_flag = TRUE;
msc_obj_ptr->csw_prime_flag = FALSE;
/* prepare for next CBW */
//if (msc_obj_ptr->cbw_prime_flag == FALSE)
{
(void)USB_MSC_Bulk_Recv_Data(msc_obj_ptr->controller_handle,
(uint8_t*)msc_obj_ptr->cbw_ptr, MSC_CBW_LENGTH);
msc_obj_ptr->cbw_prime_flag = TRUE;
}
}
}
/**************************************************************************//*!
*
* @name USB_Service_Bulk_Out
*
* @brief The function is callback function of DIC Bulk Out Endpoint
*
* @param event
* @param arg
* @return None
*
*****************************************************************************/
void USB_Service_Bulk_Out(usb_event_struct_t* event,void* arg)
{
//uint8_t event_type;
cbw_t * cbw_ptr = NULL;
uint8_t error;
msc_device_struct_t * msc_obj_ptr;
//uint32_t signature = USB_DCBWSIGNATURE;
//USB_PRINTF("\nsignature is :%x",signature);
#if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && (!USE_RTOS)) || (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_BM)
uint8_t have_transfer = 0;
#endif
msc_obj_ptr = (msc_device_struct_t *)arg;
if (NULL == msc_obj_ptr)
{
#if _DEBUG
USB_PRINTF("USB_Service_Bulk_Out: msc_dev_ptr is NULL\n");
#endif
return;
}
if (event->len == 0xFFFFFFFF)
{
/* need to notify app that receives data Successfully and size is 0, app can release buffer */
if ((msc_obj_ptr->out_flag) && (msc_obj_ptr->class_specific_callback.callback != NULL)
&& ((WRITE_10_COMMAND == msc_obj_ptr->cbw_ptr->command_block[0])
|| (WRITE_12_COMMAND == msc_obj_ptr->cbw_ptr->command_block[0])))
{
lba_app_struct_t lba_data1;
lba_data1.offset = 0;
lba_data1.size = 0;
lba_data1.buff_ptr = msc_obj_ptr->msd_buff.msc_bulk_out_ptr;
msc_obj_ptr->class_specific_callback.callback(USB_DEV_EVENT_DATA_RECEIVED,
USB_REQ_VAL_INVALID,NULL,(uint32_t *)&lba_data1, msc_obj_ptr->class_specific_callback.arg);
}
return;
}
if(msc_obj_ptr->transfer_remaining >= event->len)
{ /* decrement the global count */
msc_obj_ptr->transfer_remaining -= event->len;
}
/* check if there is need to stall BULK IN ENDPOINT */
if( (msc_obj_ptr->need_out_stall_flag == TRUE)&&
(!msc_obj_ptr->transfer_remaining))
{
//uint8_t component = (uint8_t)(event->ep_num |
// (USB_RECV<<COMPONENT_PREPARE_SHIFT));
msc_obj_ptr->need_out_stall_flag = FALSE; /* clear the flag */
msc_obj_ptr->out_stall_flag = TRUE; /* clear the flag */
msc_obj_ptr->out_flag = FALSE; /* clear send flag */
msc_obj_ptr->cbw_prime_flag = FALSE;
usb_device_stall_endpoint(msc_obj_ptr->controller_handle,event->ep_num,USB_RECV);
return;
}
/* If its not a data phase on bulk endpoint */
if ((!msc_obj_ptr->out_flag) && (event->len == MSC_CBW_LENGTH))
{
cbw_ptr = (cbw_t *)(event->buffer_ptr);
}
if(msc_obj_ptr->out_flag) /* bulk out transaction has occurred after CBW */
{
// if(msc_obj_ptr->transfer_remaining >= event->len)
// { /* decrement the global count */
// msc_obj_ptr->transfer_remaining -= event->len;
// }
if(msc_obj_ptr->class_specific_callback.callback != NULL)
{
lba_app_struct_t lba_data1;
lba_data1.size = event->len;
lba_data1.buff_ptr = msc_obj_ptr->msd_buff.msc_bulk_out_ptr;
lba_data1.offset = msc_obj_ptr->current_offset;
if((WRITE_10_COMMAND == msc_obj_ptr->cbw_ptr->command_block[0])
|| (WRITE_12_COMMAND == msc_obj_ptr->cbw_ptr->command_block[0])
)
{
//#ifdef MUTILE_BUFFER
#if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && (!USE_RTOS)) || (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_BM)
lba_app_struct_t lba_data2;
if (msc_obj_ptr->transfer_remaining)
{
msc_obj_ptr->class_specific_callback.callback(USB_MSC_DEVICE_WRITE_REQUEST,
USB_REQ_VAL_INVALID,&msc_obj_ptr->msd_buff.msc_bulk_out_ptr, NULL, msc_obj_ptr->class_specific_callback.arg);
if (msc_obj_ptr->msd_buff.msc_bulk_out_ptr != NULL)
{
have_transfer = 1;
msc_obj_ptr->current_offset += event->len;
lba_data2.offset = msc_obj_ptr->current_offset;
lba_data2.size = (msc_obj_ptr->msd_buff.msc_bulk_out_size > MSD_RECV_MAX_TRANS_LENGTH) ?
MSD_RECV_MAX_TRANS_LENGTH : msc_obj_ptr->msd_buff.msc_bulk_out_size; /* whichever is smaller */
lba_data2.size = (msc_obj_ptr->transfer_remaining > lba_data2.size) ?
lba_data2.size : msc_obj_ptr->transfer_remaining; /* whichever is smaller */
lba_data2.buff_ptr = msc_obj_ptr->msd_buff.msc_bulk_out_ptr;
if(msc_obj_ptr->current_offset < (msc_obj_ptr->device_info.total_lba_device_supports * msc_obj_ptr->device_info.length_of_each_lab_of_device))
{
(void)USB_MSC_Bulk_Recv_Data(msc_obj_ptr->controller_handle,
lba_data2.buff_ptr,lba_data2.size);
}
else
{
msc_obj_ptr->need_out_stall_flag = FALSE; /* clear the flag */
msc_obj_ptr->out_stall_flag = TRUE; /* clear the flag */
msc_obj_ptr->out_flag = FALSE; /* clear send flag */
msc_obj_ptr->stall_status = (uint8_t)STALL_IN_DATA_PHASE;
usb_device_stall_endpoint(msc_obj_ptr->controller_handle,msc_obj_ptr->bulk_out_endpoint,USB_RECV);
}
}
}
#endif
msc_obj_ptr->class_specific_callback.callback(USB_DEV_EVENT_DATA_RECEIVED,
USB_REQ_VAL_INVALID,NULL,(uint32_t *)&lba_data1, msc_obj_ptr->class_specific_callback.arg);
}
#if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && (!USE_RTOS)) || (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_BM)
if((msc_obj_ptr->transfer_remaining) && (have_transfer == 0))
#else
if(msc_obj_ptr->transfer_remaining)
#endif
{
msc_obj_ptr->current_offset += event->len;
lba_data1.offset = msc_obj_ptr->current_offset;
lba_data1.size = (msc_obj_ptr->msd_buff.msc_bulk_out_size > MSD_RECV_MAX_TRANS_LENGTH) ?
MSD_RECV_MAX_TRANS_LENGTH : msc_obj_ptr->msd_buff.msc_bulk_out_size; /* whichever is smaller */
lba_data1.size = (msc_obj_ptr->transfer_remaining > lba_data1.size) ?
lba_data1.size : msc_obj_ptr->transfer_remaining; /* whichever is smaller */
lba_data1.buff_ptr = NULL; //msc_obj_ptr->msd_buff.msc_bulk_out_ptr;
/* copy the data received on USB Bus, to MSD Disk
(e.g.) CD/DVD or SD Card, etc */
msc_obj_ptr->class_specific_callback.callback(USB_MSC_DEVICE_WRITE_REQUEST,
USB_REQ_VAL_INVALID,&msc_obj_ptr->msd_buff.msc_bulk_out_ptr,(uint32_t *)&lba_data1, msc_obj_ptr->class_specific_callback.arg);
lba_data1.buff_ptr = msc_obj_ptr->msd_buff.msc_bulk_out_ptr;
if(msc_obj_ptr->current_offset < (msc_obj_ptr->device_info.total_lba_device_supports * msc_obj_ptr->device_info.length_of_each_lab_of_device))
{
(void)USB_MSC_Bulk_Recv_Data(msc_obj_ptr->controller_handle,
lba_data1.buff_ptr,lba_data1.size);
}
else
{
msc_obj_ptr->need_out_stall_flag = FALSE; /* clear the flag */
msc_obj_ptr->out_stall_flag = TRUE; /* clear the flag */
msc_obj_ptr->out_flag = FALSE; /* clear send flag */
msc_obj_ptr->stall_status = (uint8_t)STALL_IN_DATA_PHASE;
usb_device_stall_endpoint(msc_obj_ptr->controller_handle,msc_obj_ptr->bulk_out_endpoint,USB_RECV);
}
}
}
// if((msc_obj_ptr->need_out_stall_flag == TRUE)&&
// (!msc_obj_ptr->transfer_remaining))
// {
// msc_obj_ptr->need_out_stall_flag = FALSE; /* clear the flag */
// msc_obj_ptr->out_stall_flag = TRUE; /* clear the flag */
// msc_obj_ptr->out_flag = FALSE; /* clear send flag */
// usb_device_stall_endpoint(msc_obj_ptr->controller_handle,event->ep_num,USB_SEND);
// return;
// }
if(!msc_obj_ptr->transfer_remaining)
{ /* marks the end of data phase */
msc_obj_ptr->out_flag = FALSE; /* clear the flag for next CBW */
/* Send the command status information */
//if(msc_obj_ptr->csw_prime_flag == FALSE)
{
(void)USB_MSC_Bulk_Send_Data(msc_obj_ptr->msc_handle,
(uint8_t *)msc_obj_ptr->csw_ptr, MSC_CSW_LENGTH);
msc_obj_ptr->csw_prime_flag = TRUE;
}
}
}
else if(/* check for valid and meaningful CBW */
/* CBW received after device had sent a CSW or after a reset */
(msc_obj_ptr->cbw_valid_flag)
/* CBW is 31 bytes in length */
&& (event->len == MSC_CBW_LENGTH)
/* valid CBW signature*/
&& (cbw_ptr != NULL) && (cbw_ptr->signature == USB_DCBWSIGNATURE)
/* all reserved bits should be zero*/
&& (!((cbw_ptr->lun & 0xF0) || (cbw_ptr->cb_length & 0xE0)))
/* host should send command to valid LUN */
&& (cbw_ptr->lun<msc_obj_ptr->device_info.num_lun_supported)
/* valid cbwcb length*/
&& ((cbw_ptr->cb_length >= 0x01)&&(cbw_ptr->cb_length <= 0x10))
)
{
msc_obj_ptr->re_stall_flag = TRUE;
msc_obj_ptr->cbw_prime_flag = FALSE;
msc_obj_ptr->transfer_remaining = 0;
/* A valid CBW was received */
msc_obj_ptr->csw_ptr->signature = USB_DCSWSIGNATURE;
msc_obj_ptr->csw_ptr->residue = 0;
msc_obj_ptr->csw_ptr->tag = cbw_ptr->tag;
/*this flag will now be set on reset or after CSW being sent */
msc_obj_ptr->cbw_valid_flag = FALSE;
cbw_ptr->data_length = USB_LONG_LE_TO_HOST(cbw_ptr->data_length);
/* set flag if device is going to recv data in coming transaction */
msc_obj_ptr->out_flag = (bool)(( (!(cbw_ptr->flag & USB_CBW_DIRECTION_BIT))
&& (cbw_ptr->data_length))?TRUE:FALSE);
/* set flag if send is going to send data in coming transaction */
msc_obj_ptr->in_flag = (bool)(( (cbw_ptr->flag & USB_CBW_DIRECTION_BIT)
&& (cbw_ptr->data_length))?TRUE:FALSE);
/* Process the command */
error = process_mass_storage_command(msc_obj_ptr, cbw_ptr,
&(msc_obj_ptr->csw_ptr->residue), &(msc_obj_ptr->csw_ptr->csw_status));
if (error == USBERR_ENDPOINT_STALLED)
{
if (msc_obj_ptr->out_flag==TRUE)
{
if (msc_obj_ptr->out_stall_flag == FALSE)
{
msc_obj_ptr->need_out_stall_flag = TRUE;
}
msc_obj_ptr->out_flag = FALSE; /* so as to send status phase */
}
else if (msc_obj_ptr->in_flag==TRUE)
{
if (msc_obj_ptr->in_stall_flag == FALSE)
{
msc_obj_ptr->need_in_stall_flag = TRUE;
}
msc_obj_ptr->in_flag = FALSE;
}
msc_obj_ptr->stall_status = (uint8_t)STALL_IN_DATA_PHASE;
}
/* if there is no data phase on bulk endpoints*/
/* even if need_out_stall_flag or need_in_stall_flag */
if(!((msc_obj_ptr->out_flag) || ((msc_obj_ptr->in_flag) || (msc_obj_ptr->need_in_stall_flag))))
{
/* Send the command status information */
(void)USB_MSC_Bulk_Send_Data(msc_obj_ptr->msc_handle,
(uint8_t *)msc_obj_ptr->csw_ptr, MSC_CSW_LENGTH);
msc_obj_ptr->csw_prime_flag = TRUE;
}
}
else /* Invalid/NMreceived */
{
//uint8_t direction;
//uint8_t ep_num;
/* prepare the component to be sent in lower layer with
endpoint number and direction*/
//uint8_t component;
//direction = USB_RECV;
//ep_num = msc_obj_ptr->bulk_out_endpoint;
//component = (uint8_t)(ep_num | (direction<<COMPONENT_PREPARE_SHIFT));
usb_device_stall_endpoint(msc_obj_ptr->controller_handle,msc_obj_ptr->bulk_out_endpoint,USB_RECV);
usb_device_stall_endpoint(msc_obj_ptr->controller_handle,msc_obj_ptr->bulk_in_endpoint,USB_SEND);
msc_obj_ptr->cbw_valid_flag = FALSE;
msc_obj_ptr->out_stall_flag = TRUE;
msc_obj_ptr->in_stall_flag = TRUE;
msc_obj_ptr->stall_status = (uint8_t)STALL_IN_CBW;
msc_obj_ptr->wait_for_reset_recovery = TRUE;
}
}
/**************************************************************************//*!
*
* @name USB_Class_MSC_Event
*
* @brief The function initializes MSC endpoints
*
* @param arg handle to Identify class object.
* @param event pointer to event structure
* @param val gives the configuration value
*
* @return None
*
*****************************************************************************/
void USB_Class_MSC_Event(uint8_t event, void* val,void* arg)
{
usb_class_struct_t* usbclassPtr;
msc_device_struct_t * msc_dev_ptr;
usb_endpoints_t *usb_ep_data;
//uint8_t error;
//USB_PRINTF("\n USB_Class_MSD_Event: event: 0x%x", event);
msc_dev_ptr = (msc_device_struct_t *)arg;
if (NULL == msc_dev_ptr)
{
#if _DEBUG
USB_PRINTF("USB_Class_MSC_Event: msc_dev_ptr is NULL\n");
#endif
return;
}
if(event == USB_DEV_EVENT_CONFIG_CHANGED)
{
uint8_t count = 0;
//USB_PRINTF("\n 000, count: 0x%x", count);
//USB_PRINTF("\nUSB_DEV_EVENT_CONFIG_CHANGED");
if (*(uint16_t*)val == 0)
{
#if _DEBUG
USB_PRINTF("only config change!\n");
#endif
return;
}
#if USBCFG_DEV_COMPOSITE
/* Get class info */
USB_Msd_Get_Desc_Info(msc_dev_ptr, USB_MSD_CLASS_INFO, (uint32_t *)&usbclassPtr);
USB_Msd_Get_Desc_Info(msc_dev_ptr, USB_MSD_INTERFACE_COUNT, &msc_dev_ptr->usb_max_suported_interfaces);
#else
msc_dev_ptr->desc_callback.get_desc_entity((uint32_t)msc_dev_ptr->controller_handle,
USB_CLASS_INFO, (uint32_t*)&usbclassPtr);
USB_Msd_Get_Desc_Info(msc_dev_ptr, USB_MSD_INTERFACE_COUNT, &msc_dev_ptr->usb_max_suported_interfaces);
#endif
if(usbclassPtr == NULL)
{
USB_PRINTF("not find msd interface\n");
return;
}
usb_ep_data = &(usbclassPtr[*(uint16_t*)val - 1].interfaces.interface[0].endpoints);
msc_dev_ptr->ep_desc_data = usb_ep_data;
msc_dev_ptr->msc_endpoint_data.count = usbclassPtr->interfaces.interface->endpoints.count;
if (msc_dev_ptr->msc_endpoint_data.count > MAX_MSC_CLASS_EP_NUM)
{
USB_PRINTF("too many msc endpoint for the class driver\n");
return;
}
for (int epindex = 0; epindex < usbclassPtr->interfaces.interface->endpoints.count; ++epindex)
{
if (usbclassPtr->interfaces.interface->endpoints.ep[epindex].direction == USB_SEND)
{
msc_dev_ptr->bulk_in_endpoint = usbclassPtr->interfaces.interface->endpoints.ep[epindex].ep_num;
msc_dev_ptr->bulk_in_endpoint_packet_size = usbclassPtr->interfaces.interface->endpoints.ep[epindex].size;
}
else if (usbclassPtr->interfaces.interface->endpoints.ep[epindex].direction == USB_RECV)
{
msc_dev_ptr->bulk_out_endpoint = usbclassPtr->interfaces.interface->endpoints.ep[epindex].ep_num;
}
}
/* initialize all non control endpoints */
while(count < usb_ep_data->count)
{
#if _DEBUG
USB_PRINTF("\n 222, count: 0x%x", count);
#endif
usb_ep_struct_t* ep_struct_ptr=
(usb_ep_struct_t*) (&usb_ep_data->ep[count]);
(void)usb_device_init_endpoint(msc_dev_ptr->controller_handle,
ep_struct_ptr, TRUE);
/* register callback service for Non Control EndPoints */
if(ep_struct_ptr->type == USB_BULK_PIPE)
{
if(ep_struct_ptr->direction == USB_RECV)
{
(void)usb_device_register_service(msc_dev_ptr->controller_handle,
(uint8_t)((uint8_t)(USB_SERVICE_EP0+ep_struct_ptr->ep_num) | ((uint8_t)(ep_struct_ptr->direction << 7))),
USB_Service_Bulk_Out,(void *)msc_dev_ptr);
}
else
{
(void)usb_device_register_service(msc_dev_ptr->controller_handle,
(uint8_t)((uint8_t)(USB_SERVICE_EP0+ep_struct_ptr->ep_num) | ((uint8_t)(ep_struct_ptr->direction << 7))),
USB_Service_Bulk_In,(void *)msc_dev_ptr);
}
}
count++;
}
msc_dev_ptr->re_stall_flag = FALSE;
msc_dev_ptr->out_flag = FALSE;
msc_dev_ptr->in_flag = FALSE;
msc_dev_ptr->out_stall_flag = FALSE;
msc_dev_ptr->in_stall_flag = FALSE;
msc_dev_ptr->need_out_stall_flag = FALSE;
msc_dev_ptr->need_in_stall_flag = FALSE;
msc_dev_ptr->cbw_valid_flag = TRUE; /*making the first CBW valid */
msc_dev_ptr->transfer_remaining = 0;
msc_dev_ptr->wait_for_reset_recovery = FALSE;
msc_dev_ptr->need_to_prepare_next = FALSE;
msc_dev_ptr->stall_status = 0;
}
else if(event == USB_DEV_EVENT_ENUM_COMPLETE)
{
/* To Do */
if(NULL == msc_dev_ptr->cbw_ptr)
{
USB_PRINTF("msc cbw buff error\n");
return;
}
//msc_dev_ptr->cbw_ptr = (cbw_t *)OS_Mem_alloc_uncached(MSC_CBW_LENGTH);
if(msc_dev_ptr->cbw_prime_flag == TRUE)
{
#if USBCFG_DEV_ADVANCED_CANCEL_ENABLE
usb_device_cancel_transfer(msc_dev_ptr->controller_handle, msc_dev_ptr->bulk_out_endpoint, USB_RECV);
#endif
}
usb_device_recv_data(msc_dev_ptr->controller_handle,
msc_dev_ptr->bulk_out_endpoint, (uint8_t*)msc_dev_ptr->cbw_ptr, MSC_CBW_LENGTH);
msc_dev_ptr->cbw_prime_flag = TRUE;
#if _DEBUG
USB_PRINTF("\nUSB_MSC_Bulk_Recv_Data");
#endif
//msc_dev_ptr->csw_ptr = (csw_t *)OS_mem_alloc_uncached(MSC_CSW_LENGTH);
//USB_Class_MSC_Send_Data(msc_dev_ptr->controller_handle,1,(uint8_t *)msc_dev_ptr->csw_ptr,MSC_CSW_LENGTH);
}
else if(event == USB_DEV_EVENT_BUS_RESET)
{
}
else if(event == USB_DEV_EVENT_EP_UNSTALLED)
{
uint8_t value;
value = *((uint8_t *)val);
if( (msc_dev_ptr->re_stall_flag == TRUE)
&&
(((value & 0x0F) == msc_dev_ptr->bulk_in_endpoint) ||
((value & 0x0F) == msc_dev_ptr->bulk_out_endpoint)))
{ /* For MASS Storage Class BULK ENDPOINTS have to be unstalled
only on receiving Bulk Only Reset.
Therefore, if Host sends clear feature to unstall these
endpoints, re-stall them
*/
usb_device_stall_endpoint(msc_dev_ptr->controller_handle,value & 0x0F, (uint8_t)(value & 0x80) >> 7);
}
}
else if(event == USB_DEV_EVENT_EP_STALLED)
{
/* Code to be added here,
if there is some action needed at app level */
}
else if (event == USB_DEV_EVENT_TYPE_CLR_EP_HALT)
{
uint8_t value;
value = *((uint8_t *)val);
if (msc_dev_ptr->wait_for_reset_recovery != TRUE)
{
if (((value & 0x0F) == msc_dev_ptr->bulk_in_endpoint) && (msc_dev_ptr->in_stall_flag == TRUE))
{
usb_device_unstall_endpoint(msc_dev_ptr->controller_handle,value & 0x0F, (uint8_t)(value & 0x80) >> 7);
msc_dev_ptr->in_stall_flag = FALSE;
}
if (((value & 0x0F) == msc_dev_ptr->bulk_out_endpoint) && (msc_dev_ptr->out_stall_flag == TRUE))
{
usb_device_unstall_endpoint(msc_dev_ptr->controller_handle,value & 0x0F, (uint8_t)(value & 0x80) >> 7);
msc_dev_ptr->out_stall_flag = FALSE;
}
if ((msc_dev_ptr->need_to_prepare_next != TRUE) && ((msc_dev_ptr->stall_status == STALL_IN_DATA_PHASE) || (msc_dev_ptr->stall_status == STALL_IN_CSW)))
{
if (msc_dev_ptr->csw_prime_flag == TRUE)
{
#if USBCFG_DEV_ADVANCED_CANCEL_ENABLE
usb_device_cancel_transfer(msc_dev_ptr->controller_handle, msc_dev_ptr->bulk_in_endpoint, USB_SEND);
#endif
}
/* Send the command status information */
usb_device_send_data(msc_dev_ptr->controller_handle,
msc_dev_ptr->bulk_in_endpoint, (uint8_t*)msc_dev_ptr->csw_ptr, MSC_CSW_LENGTH);
msc_dev_ptr->csw_prime_flag = TRUE;
msc_dev_ptr->stall_status = 0;
}
if ((msc_dev_ptr->need_to_prepare_next == TRUE) && (msc_dev_ptr->out_stall_flag == FALSE) && (msc_dev_ptr->in_stall_flag == FALSE))
{
msc_dev_ptr->need_to_prepare_next = FALSE;
if (msc_dev_ptr->cbw_prime_flag == TRUE)
{
#if USBCFG_DEV_ADVANCED_CANCEL_ENABLE
usb_device_cancel_transfer(msc_dev_ptr->controller_handle, msc_dev_ptr->bulk_out_endpoint, USB_RECV);
#endif
}
usb_device_recv_data(msc_dev_ptr->controller_handle,
msc_dev_ptr->bulk_out_endpoint, (uint8_t*)msc_dev_ptr->cbw_ptr, MSC_CBW_LENGTH);
msc_dev_ptr->cbw_prime_flag = TRUE;
msc_dev_ptr->stall_status = 0;
}
}
}
else if(event == USB_DEV_EVENT_TYPE_SET_EP_HALT)
{
/* Code to be added here,
if there is some action needed at app level */
uint8_t value;
value = *((uint8_t *)val);
if (((value & 0x0F) == msc_dev_ptr->bulk_in_endpoint))
{
//usb_device_stall_endpoint(msc_dev_ptr->controller_handle,value & 0x0F, (value & 0x80) >> 7);
msc_dev_ptr->in_stall_flag = TRUE;
}
if (((value & 0x0F) == msc_dev_ptr->bulk_out_endpoint))
{
//usb_device_stall_endpoint(msc_dev_ptr->controller_handle,value & 0x0F, (value & 0x80) >> 7);
msc_dev_ptr->out_stall_flag = TRUE;
}
}
if(msc_dev_ptr->msc_application_callback.callback != NULL)
{
msc_dev_ptr->msc_application_callback.callback(event,val,
msc_dev_ptr->msc_application_callback.arg);
}
}
/**************************************************************************//*!
*
* @name USB_MSC_Other_Requests
*
* @brief The function provides flexibility to add class and vendor specific
* requests
*
* @param arg
* @param setup_packet: setup packet received
* @param data: data to be send back
* @param size: size to be returned
*
* @return status:
* USB_OK : When Successfully
* Others : When Error
*
*****************************************************************************/
usb_status USB_MSC_Requests
(
usb_setup_struct_t * setup_packet,
uint8_t * *data,
uint32_t *size,
void* arg
)
{
msc_device_struct_t * msc_dev_ptr;
usb_status error = USBERR_INVALID_REQ_TYPE;
msc_dev_ptr = (msc_device_struct_t *)arg;
//USB_PRINTF("\nsetup_packet->request: 0x%x", setup_packet->request);
if (NULL == msc_dev_ptr)
{
#if _DEBUG
USB_PRINTF("USB_MSC_Other_Requests: msc_dev_ptr is NULL\n");
#endif
return USBERR_ERROR;
}
*size=0;
if((setup_packet->request_type & USB_DEV_REQ_STD_REQUEST_TYPE_TYPE_POS) ==
USB_DEV_REQ_STD_REQUEST_TYPE_TYPE_CLASS)
{ /* class request so handle it here */
error = USB_OK;
/* call for class/subclass specific requests */
switch(setup_packet->request)
{
case GET_MAX_LUN :
if((setup_packet->index < msc_dev_ptr->usb_max_suported_interfaces) &&
(!setup_packet->value) && (setup_packet->length <= 0x0001) &&
((setup_packet->request_type & USB_DEV_REQ_STD_REQUEST_TYPE_DIR_POS) == USB_DEV_REQ_STD_REQUEST_TYPE_DIR_IN)
)
{
/* return the maximum number of logical units supported */
*data = &msc_dev_ptr->lun;
*size= (uint32_t)setup_packet->length;
msc_dev_ptr->re_stall_flag = TRUE;
}
else
{ /* for Get Max LUN request with invalid wIndex parameter,
host expects stall */
error = USBERR_INVALID_REQ_TYPE;
}
break;
case BULK_ONLY_MASS_STORAGE_RESET :
/* Steps to be taken in this command :
1) ready the device for the next CBW from the host
2) preserve the value of its bulk data toggle bits
3) preserve the value of its bulk endpoint STALL conditions
4) device shall NAK the status stage of device request until
command is complete*/
if( (setup_packet->index < msc_dev_ptr->usb_max_suported_interfaces) &&
(!setup_packet->value)&&(!setup_packet->length) &&
((setup_packet->request_type & USB_DEV_REQ_STD_REQUEST_TYPE_DIR_POS) == USB_DEV_REQ_STD_REQUEST_TYPE_DIR_OUT)
)
{
/* get the endpoints from the descriptor module */
usb_endpoints_t *usb_ep_data = msc_dev_ptr->ep_desc_data;
uint8_t count = 0;
/* de-initialize and initialize bulk endpoints */
while(count < usb_ep_data->count)
{
usb_ep_struct_t* ep_struct_ptr=
(usb_ep_struct_t*) (&usb_ep_data->ep[count]);
if(ep_struct_ptr->type == USB_BULK_PIPE)
{
(void)usb_device_deinit_endpoint(msc_dev_ptr->controller_handle,
ep_struct_ptr->ep_num, ep_struct_ptr->direction);
(void)usb_device_init_endpoint(msc_dev_ptr->controller_handle,
ep_struct_ptr, TRUE);
}
count++;
}
msc_dev_ptr->out_flag = FALSE;
msc_dev_ptr->in_flag = FALSE;
msc_dev_ptr->need_out_stall_flag = FALSE;
msc_dev_ptr->need_in_stall_flag = FALSE;
/*making the first CBW valid */
msc_dev_ptr->cbw_valid_flag = TRUE;
msc_dev_ptr->re_stall_flag = FALSE;
msc_dev_ptr->transfer_remaining = 0;
msc_dev_ptr->wait_for_reset_recovery = FALSE;
msc_dev_ptr->cbw_prime_flag = FALSE;
msc_dev_ptr->csw_prime_flag = FALSE;
msc_dev_ptr->need_to_prepare_next = TRUE;
// usb_device_recv_data(msc_dev_ptr->controller_handle,
// msc_dev_ptr->bulk_out_endpoint, (uint8_t*)msc_dev_ptr->cbw_ptr, MSC_CBW_LENGTH);
}
else
{ /* for Get Max LUN request with invalid wIndex parameter,
host expects stall */
error = USBERR_INVALID_REQ_TYPE;
}
break;
default :break;
}
}
else if((setup_packet->request_type & USB_DEV_REQ_STD_REQUEST_TYPE_TYPE_POS) ==
USB_DEV_REQ_STD_REQUEST_TYPE_TYPE_VENDOR)
{ /* vendor specific request */
if(msc_dev_ptr->vendor_req_callback.callback != NULL)
{
error = msc_dev_ptr->vendor_req_callback.callback(setup_packet,
data,size,msc_dev_ptr->vendor_req_callback.arg);
}
}
return error;
}
/*****************************************************************************
* Global Functions
*****************************************************************************/
/**************************************************************************//*!
*
* @name USB_Class_MSC_Init
*
* @brief The function initializes the Device and Controller layer
*
* @param msd_config_ptr : Configuration parameter structure pointer
* passed by APP.
* @return status
* MSD Handle : When Successfully
* Others : Errors
******************************************************************************
*
*This function initializes the MSC Class layer and layers it is dependent on
******************************************************************************/
usb_status USB_Class_MSC_Init
(
uint8_t controller_id,
msc_config_struct_t* msd_config_ptr,
msd_handle_t * msd_handle
)
{
#if _DEBUG
USB_PRINTF("Enter USB_Class_MSC_Init\n");
#endif
usb_status error = USBERR_ERROR;
uint32_t implementing_disk_drive = IMPLEMENTING_DISK_DRIVE;
msc_device_struct_t * devicePtr = NULL;
usb_class_specific_callback_struct_t* scsi_cb_ptr;
device_lba_info_struct_t* usb_msd_lba_info_ptr = NULL;
if (msd_config_ptr == NULL)
{
return USBERR_ERROR;
}
error = USB_Msd_Allocate_Handle(&devicePtr);
if (USB_OK != error)
{
return error;
}
#if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_BM) || ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK)))
devicePtr->cbw_ptr = &g_msc_class_cbw; /* Initializing */
devicePtr->csw_ptr = &g_msc_class_csw;
#elif (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_MQX)
devicePtr->cbw_ptr = (cbw_t *)OS_Mem_alloc_uncached_align(sizeof(cbw_t), 32);
if (NULL == devicePtr->cbw_ptr)
{
#if _DEBUG
USB_PRINTF("6: USB_Class_MSC_Init: Memalloc failed\n");
#endif
error = USBERR_ALLOC;
if(NULL != devicePtr->csw_ptr)
{
OS_Mem_free(devicePtr->csw_ptr);
devicePtr->csw_ptr = NULL;
}
if(NULL != devicePtr->cbw_ptr)
{
OS_Mem_free(devicePtr->cbw_ptr);
devicePtr->cbw_ptr = NULL;
}
*msd_handle = (unsigned long)0;
return error;
}
devicePtr->csw_ptr = (csw_t *)OS_Mem_alloc_uncached_align(sizeof(csw_t), 32);
if (NULL == devicePtr->csw_ptr)
{
#if _DEBUG
USB_PRINTF("7: USB_Class_MSC_Init: Memalloc failed\n");
#endif
error = USBERR_ALLOC;
if(NULL != devicePtr->csw_ptr)
{
OS_Mem_free(devicePtr->csw_ptr);
devicePtr->csw_ptr = NULL;
}
if(NULL != devicePtr->cbw_ptr)
{
OS_Mem_free(devicePtr->cbw_ptr);
devicePtr->cbw_ptr = NULL;
}
*msd_handle = (unsigned long)0;
return error;
}
#endif
OS_Mem_zero(devicePtr->cbw_ptr, MSC_CBW_LENGTH);
OS_Mem_zero(devicePtr->csw_ptr, MSC_CSW_LENGTH);
OS_Mem_copy(msd_config_ptr->desc_callback_ptr,&devicePtr->desc_callback,sizeof(usb_desc_request_notify_struct_t));
/* save the callback pointer */
devicePtr->msc_application_callback.callback = msd_config_ptr->msc_application_callback.callback;
devicePtr->msc_application_callback.arg = msd_config_ptr->msc_application_callback.arg;
/* save the callback pointer */
devicePtr->vendor_req_callback.callback =
msd_config_ptr->vendor_req_callback.callback;
devicePtr->vendor_req_callback.arg = msd_config_ptr->vendor_req_callback.arg;
/* save the callback pointer */
devicePtr->class_specific_callback.callback = msd_config_ptr->class_specific_callback.callback;
devicePtr->class_specific_callback.arg = msd_config_ptr->class_specific_callback.arg;
if(devicePtr->msc_application_callback.callback)
{
devicePtr->msc_application_callback.callback(USB_MSC_DEVICE_GET_SEND_BUFF_INFO, &devicePtr->msd_buff.msc_bulk_in_size , NULL);
devicePtr->msc_application_callback.callback(USB_MSC_DEVICE_GET_RECV_BUFF_INFO, &devicePtr->msd_buff.msc_bulk_out_size , NULL);
}
#if USBCFG_DEV_COMPOSITE
devicePtr->class_handle = USB_Class_Get_Class_Handle();
devicePtr->controller_handle = (usb_device_handle)USB_Class_Get_Ctrler_Handle(devicePtr->class_handle);
if(NULL == devicePtr->controller_handle)
{
#if _DEBUG
USB_PRINTF("4: USB_Class_MSC_Init: call USB_Class_Get_Ctrler_Handle failed\n");
#endif
#if (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_MQX)
if(NULL != devicePtr->csw_ptr)
{
OS_Mem_free(devicePtr->csw_ptr);
devicePtr->csw_ptr = NULL;
}
if(NULL != devicePtr->cbw_ptr)
{
OS_Mem_free(devicePtr->cbw_ptr);
devicePtr->cbw_ptr = NULL;
}
#endif
*msd_handle = (unsigned long)0;
return error;
}
#else
/* Initialize the device layer*/
error = usb_device_init(controller_id,(&devicePtr->controller_handle));
/* +1 is for Control Endpoint */
if(error != USB_OK)
{
#if _DEBUG
USB_PRINTF("4: USB_Class_MSC_Init: call usb_device_init failed\n");
#endif
#if (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_MQX)
if(NULL != devicePtr->csw_ptr)
{
OS_Mem_free(devicePtr->csw_ptr);
devicePtr->csw_ptr = NULL;
}
if(NULL != devicePtr->cbw_ptr)
{
OS_Mem_free(devicePtr->cbw_ptr);
devicePtr->cbw_ptr = NULL;
}
#endif
*msd_handle = (unsigned long)0;
return error;
}
/* Initialize the generic class functions */
devicePtr->class_handle = USB_Class_Init(devicePtr->controller_handle,USB_Class_MSC_Event,
USB_MSC_Requests,(void *)devicePtr,msd_config_ptr->desc_callback_ptr);
#endif
devicePtr->desc_callback.get_desc_entity((uint32_t)devicePtr,USB_MSC_LBA_INFO, (uint32_t *)&usb_msd_lba_info_ptr);
if(NULL == usb_msd_lba_info_ptr)
{
#if _DEBUG
USB_PRINTF("9: USB_Class_MSC_Init: get msd lba info failed\n");
#endif
#if (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_MQX)
if(NULL != devicePtr->csw_ptr)
{
OS_Mem_free(devicePtr->csw_ptr);
devicePtr->csw_ptr = NULL;
}
if(NULL != devicePtr->cbw_ptr)
{
OS_Mem_free(devicePtr->cbw_ptr);
devicePtr->cbw_ptr = NULL;
}
#endif
*msd_handle = (unsigned long)0;
return error;
}
devicePtr->device_info.length_of_each_lab_of_device = usb_msd_lba_info_ptr->length_of_each_lab_of_device;
devicePtr->device_info.num_lun_supported = usb_msd_lba_info_ptr->num_lun_supported;
devicePtr->device_info.total_lba_device_supports = usb_msd_lba_info_ptr->total_lba_device_supports;
/* Initialize the scsi subclass functions */
//scsi_cb.callback = USB_Class_MSC_Event;
scsi_cb_ptr = &msd_config_ptr->class_specific_callback;
//scsi_cb.arg = devicePtr;
error = USB_MSC_SCSI_Init(devicePtr,scsi_cb_ptr, &devicePtr->device_info,
implementing_disk_drive);
if(error != USB_OK)
{
#if _DEBUG
USB_PRINTF("10: USB_Class_MSC_Init: call USB_MSC_SCSI_Init failed\n");
#endif
#if (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_MQX)
if(NULL != devicePtr->csw_ptr)
{
OS_Mem_free(devicePtr->csw_ptr);
devicePtr->csw_ptr = NULL;
}
if(NULL != devicePtr->cbw_ptr)
{
OS_Mem_free(devicePtr->cbw_ptr);
devicePtr->cbw_ptr = NULL;
}
#endif
*msd_handle = (unsigned long)0;
return error;
}
devicePtr->cbw_prime_flag = FALSE;
devicePtr->csw_prime_flag = FALSE;
*msd_handle = (unsigned long)devicePtr;
devicePtr->msc_handle = *msd_handle;
#if !USBCFG_DEV_COMPOSITE
usb_device_postinit(controller_id,devicePtr->controller_handle);
#endif
return USB_OK;
}
/**************************************************************************//*!
*
* @name USB_Class_MSC_Deinit
*
* @brief The function initializes the Device and Controller layer
*
* @param cdc_handle
*
* @return status
* USB_OK : When Successfully
* Others : Errors
******************************************************************************
*
*This function initializes the MSC Class layer and layers it is dependent on
*
*****************************************************************************/
usb_status USB_Class_MSC_Deinit
(
msd_handle_t msd_handle /*[IN]*/
)
{
usb_status error = USB_OK;
msc_device_struct_t * devicePtr = NULL;
if (msd_handle == 0)
{
return USBERR_ERROR;
}
devicePtr = USB_Msd_Get_Device_Ptr(msd_handle);
if(error == USB_OK)
{
/* De-initialize the scsi subclass functions */
error = USB_MSC_SCSI_Deinit(devicePtr);
}
#if !USBCFG_DEV_COMPOSITE
if(error == USB_OK)
{
/* De-initialize the generic class functions */
error = USB_Class_Deinit(devicePtr->controller_handle,devicePtr->class_handle);
}
if(error == USB_OK)
{
/* De-initialize the device layer*/
error = usb_device_deinit(devicePtr->controller_handle);
}
#endif
if(error == USB_OK)
{
#if (OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_MQX)
if(NULL != devicePtr->csw_ptr)
{
OS_Mem_free(devicePtr->csw_ptr);
devicePtr->csw_ptr = NULL;
}
if(NULL != devicePtr->cbw_ptr)
{
OS_Mem_free(devicePtr->cbw_ptr);
devicePtr->cbw_ptr = NULL;
}
#endif
USB_Msd_Free_Handle(devicePtr);
}
return error;
}
/**************************************************************************//*!
*
* @name USB_Class_MSC_Send_Data
*
* @brief
*
* @param msc_handle : handle returned from USB_Class_MSC_Init
* @param ep_num : endpoint num
* @param app_buff : buffer to send
* @param size : length of the transfer
*
* @return status
* USB_OK : When Successfully
* Others : Errors
*****************************************************************************/
usb_status USB_Class_MSC_Send_Data
(
msd_handle_t msc_handle, /*[IN]*/
uint8_t ep_num, /*[IN]*/
uint8_t * app_buff, /*[IN]*/
uint32_t size /*[IN]*/
)
{
msc_device_struct_t * devicePtr;
usb_status error = USB_OK;
devicePtr = USB_Msd_Get_Device_Ptr(msc_handle);
if (devicePtr == NULL)
{
return USBERR_ERROR;
}
error = USB_Class_Send_Data(devicePtr->class_handle,
ep_num, app_buff,size);
return error;
}
/**************************************************************************//*!
*
* @name USB_MSC_LBA_Transfer
*
* @brief
*
* @param msc_device_struct_t *
* @param direction : transfer direction
* @param lba_info_ptr : buffer to send
*
* @return status
* USB_OK : When Successfully
* Others : Errors
*****************************************************************************/
usb_status USB_MSC_LBA_Transfer
(
msc_device_struct_t * msc_obj_ptr,
bool direction,
lba_info_struct_t* lba_info_ptr
)
{
usb_status error;
lba_app_struct_t lba_data;
// if((!((lba_info_ptr->starting_lba<msc_obj_ptr->device_info.total_lba_device_supports)&&
// (lba_info_ptr->lba_transfer_num <= (msc_obj_ptr->device_info.total_lba_device_supports -
// lba_info_ptr->starting_lba)))) || (msc_obj_ptr->class_specific_callback.callback == NULL))
// {
// /* host trying to access region beyond MASS STORAGE SPACE
// Or no class_specific_callback is registered */
// //return(uint8_t)((direction?USBERR_TX_FAILED:USBERR_RX_FAILED));
// }
msc_obj_ptr->transfer_remaining = lba_info_ptr->lba_transfer_num *
msc_obj_ptr->device_info.length_of_each_lab_of_device;
msc_obj_ptr->current_offset = lba_info_ptr->starting_lba *
msc_obj_ptr->device_info.length_of_each_lab_of_device;
lba_data.offset = msc_obj_ptr->current_offset;
if(direction == USB_SEND)
{
lba_data.size = (msc_obj_ptr->msd_buff.msc_bulk_in_size > MSD_SEND_MAX_TRANS_LENGTH) ?
MSD_SEND_MAX_TRANS_LENGTH : msc_obj_ptr->msd_buff.msc_bulk_in_size; /* whichever is smaller */
lba_data.size = (msc_obj_ptr->transfer_remaining > lba_data.size) ?
lba_data.size : msc_obj_ptr->transfer_remaining; /* whichever is smaller */
lba_data.buff_ptr = NULL;
msc_obj_ptr->class_specific_callback.callback(USB_MSC_DEVICE_READ_REQUEST,
USB_REQ_VAL_INVALID,&msc_obj_ptr->msd_buff.msc_bulk_in_ptr,(uint32_t *)&lba_data, msc_obj_ptr->class_specific_callback.arg);
lba_data.buff_ptr = msc_obj_ptr->msd_buff.msc_bulk_in_ptr;
if(lba_info_ptr->starting_lba < msc_obj_ptr->device_info.total_lba_device_supports)
{
error = USB_MSC_Bulk_Send_Data(msc_obj_ptr->msc_handle,lba_data.buff_ptr,lba_data.size);
}
else
{
msc_obj_ptr->need_in_stall_flag = FALSE; /* clear the flag */
msc_obj_ptr->in_stall_flag = TRUE; /* clear the flag */
msc_obj_ptr->in_flag = FALSE; /* clear send flag */
msc_obj_ptr->stall_status = (uint8_t)STALL_IN_DATA_PHASE;
error = usb_device_stall_endpoint(msc_obj_ptr->controller_handle,msc_obj_ptr->bulk_in_endpoint,USB_SEND);
}
}
else
{
lba_data.size = (msc_obj_ptr->msd_buff.msc_bulk_out_size > MSD_RECV_MAX_TRANS_LENGTH) ?
MSD_RECV_MAX_TRANS_LENGTH : msc_obj_ptr->msd_buff.msc_bulk_out_size; /* whichever is smaller */
lba_data.size = (msc_obj_ptr->transfer_remaining > lba_data.size) ?
lba_data.size : msc_obj_ptr->transfer_remaining; /* whichever is smaller */
lba_data.buff_ptr = NULL;
msc_obj_ptr->class_specific_callback.callback(USB_MSC_DEVICE_WRITE_REQUEST,
USB_REQ_VAL_INVALID,&msc_obj_ptr->msd_buff.msc_bulk_out_ptr,(uint32_t *)&lba_data, msc_obj_ptr->class_specific_callback.arg);
lba_data.buff_ptr = msc_obj_ptr->msd_buff.msc_bulk_out_ptr;
if(lba_info_ptr->starting_lba < msc_obj_ptr->device_info.total_lba_device_supports)
{
error = USB_MSC_Bulk_Recv_Data(msc_obj_ptr->controller_handle,lba_data.buff_ptr,lba_data.size);
}
else
{
msc_obj_ptr->need_out_stall_flag = FALSE; /* clear the flag */
msc_obj_ptr->out_stall_flag = TRUE; /* clear the flag */
msc_obj_ptr->out_flag = FALSE; /* clear send flag */
msc_obj_ptr->stall_status = (uint8_t)STALL_IN_DATA_PHASE;
error = usb_device_stall_endpoint(msc_obj_ptr->controller_handle,msc_obj_ptr->bulk_out_endpoint,USB_RECV);
}
}
return error;
}
/**************************************************************************//*!
*
* @name USB_Class_MSC_Get_Speed
*
* @brief This functions get speed from Host.
*
* @param handle : handle returned by USB_Class_MSC_Init
* @param speed : speed
*
* @return status
* USB_OK : When Successfull
* Others : Errors
*****************************************************************************/
usb_status USB_Class_MSC_Get_Speed
(
msd_handle_t handle,
uint16_t * speed/* [OUT] the requested error */
)
{
msc_device_struct_t * msd_obj_ptr;
usb_status error = USB_OK;
msd_obj_ptr = (msc_device_struct_t *)handle;
if (NULL == msd_obj_ptr)
{
return USBERR_NO_DEVICE_CLASS;
}
error = USB_Class_Get_Status(msd_obj_ptr->class_handle, USB_STATUS_SPEED, speed);
return error;
}
#endif /*MSD_CONFIG*/
/* EOF */
| {
"language": "C"
} |
/*
* Copyright (c) 2012 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.
*/
#include "include/webrtc_vad.h"
#include <stdlib.h>
#include <string.h>
#include "../other/signal_processing_library.h"
#include "vad_core.h"
static const int kInitCheck = 42;
static const int kValidRates[] = { 8000, 16000, 32000, 48000 };
static const size_t kRatesSize = sizeof(kValidRates) / sizeof(*kValidRates);
static const int kMaxFrameLengthMs = 30;
int WebRtcVad_Create(VadInst** handle) {
VadInstT* self = NULL;
if (handle == NULL) {
return -1;
}
*handle = NULL;
self = (VadInstT*) malloc(sizeof(VadInstT));
*handle = (VadInst*) self;
if (self == NULL) {
return -1;
}
WebRtcSpl_Init();
self->init_flag = 0;
return 0;
}
void WebRtcVad_Free(VadInst* handle) {
free(handle);
}
// TODO(bjornv): Move WebRtcVad_InitCore() code here.
int WebRtcVad_Init(VadInst* handle) {
// Initialize the core VAD component.
return WebRtcVad_InitCore((VadInstT*) handle);
}
// TODO(bjornv): Move WebRtcVad_set_mode_core() code here.
int WebRtcVad_set_mode(VadInst* handle, int mode) {
VadInstT* self = (VadInstT*) handle;
if (handle == NULL) {
return -1;
}
if (self->init_flag != kInitCheck) {
return -1;
}
return WebRtcVad_set_mode_core(self, mode);
}
int WebRtcVad_Process(VadInst* handle, int fs, const int16_t* audio_frame,
int frame_length) {
int vad = -1;
VadInstT* self = (VadInstT*) handle;
if (handle == NULL) {
return -1;
}
if (self->init_flag != kInitCheck) {
return -1;
}
if (audio_frame == NULL) {
return -1;
}
if (WebRtcVad_ValidRateAndFrameLength(fs, frame_length) != 0) {
return -1;
}
if (fs == 48000) {
vad = WebRtcVad_CalcVad48khz(self, audio_frame, frame_length);
} else if (fs == 32000) {
vad = WebRtcVad_CalcVad32khz(self, audio_frame, frame_length);
} else if (fs == 16000) {
vad = WebRtcVad_CalcVad16khz(self, audio_frame, frame_length);
} else if (fs == 8000) {
vad = WebRtcVad_CalcVad8khz(self, audio_frame, frame_length);
}
if (vad > 0) {
vad = 1;
}
return vad;
}
int WebRtcVad_ValidRateAndFrameLength(int rate, int frame_length) {
int return_value = -1;
size_t i;
int valid_length_ms;
int valid_length;
// We only allow 10, 20 or 30 ms frames. Loop through valid frame rates and
// see if we have a matching pair.
for (i = 0; i < kRatesSize; i++) {
if (kValidRates[i] == rate) {
for (valid_length_ms = 10; valid_length_ms <= kMaxFrameLengthMs;
valid_length_ms += 10) {
valid_length = (kValidRates[i] / 1000 * valid_length_ms);
if (frame_length == valid_length) {
return_value = 0;
break;
}
}
break;
}
}
return return_value;
}
| {
"language": "C"
} |
/**************************************************************************//**
* @file core_sc300.h
* @brief CMSIS SC300 Core Peripheral Access Layer Header File
* @version V3.20
* @date 25. February 2013
*
* @note
*
******************************************************************************/
/* Copyright (c) 2009 - 2013 ARM LIMITED
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ARM nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND 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.
---------------------------------------------------------------------------*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __CORE_SC300_H_GENERIC
#define __CORE_SC300_H_GENERIC
/** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions
CMSIS violates the following MISRA-C:2004 rules:
\li Required Rule 8.5, object/function definition in header file.<br>
Function definitions in header files are used to allow 'inlining'.
\li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
Unions are used for effective representation of core registers.
\li Advisory Rule 19.7, Function-like macro defined.<br>
Function-like macros are used to allow more efficient code.
*/
/*******************************************************************************
* CMSIS definitions
******************************************************************************/
/** \ingroup SC3000
@{
*/
/* CMSIS SC300 definitions */
#define __SC300_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */
#define __SC300_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */
#define __SC300_CMSIS_VERSION ((__SC300_CMSIS_VERSION_MAIN << 16) | \
__SC300_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */
#define __CORTEX_SC (300) /*!< Cortex secure core */
#if defined ( __CC_ARM )
#define __ASM __asm /*!< asm keyword for ARM Compiler */
#define __INLINE __inline /*!< inline keyword for ARM Compiler */
#define __STATIC_INLINE static __inline
#elif defined ( __ICCARM__ )
#define __ASM __asm /*!< asm keyword for IAR Compiler */
#define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
#define __STATIC_INLINE static inline
#elif defined ( __GNUC__ )
#define __ASM __asm /*!< asm keyword for GNU Compiler */
#define __INLINE inline /*!< inline keyword for GNU Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __TASKING__ )
#define __ASM __asm /*!< asm keyword for TASKING Compiler */
#define __INLINE inline /*!< inline keyword for TASKING Compiler */
#define __STATIC_INLINE static inline
#endif
/** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all
*/
#define __FPU_USED 0
#if defined ( __CC_ARM )
#if defined __TARGET_FPU_VFP
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __ICCARM__ )
#if defined __ARMVFP__
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __GNUC__ )
#if defined (__VFP_FP__) && !defined(__SOFTFP__)
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TASKING__ )
#if defined __FPU_VFP__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#endif
#include <stdint.h> /* standard types definitions */
#include <core_cmInstr.h> /* Core Instruction Access */
#include <core_cmFunc.h> /* Core Function Access */
#endif /* __CORE_SC300_H_GENERIC */
#ifndef __CMSIS_GENERIC
#ifndef __CORE_SC300_H_DEPENDANT
#define __CORE_SC300_H_DEPENDANT
/* check device defines and use defaults */
#if defined __CHECK_DEVICE_DEFINES
#ifndef __SC300_REV
#define __SC300_REV 0x0000
#warning "__SC300_REV not defined in device header file; using default!"
#endif
#ifndef __MPU_PRESENT
#define __MPU_PRESENT 0
#warning "__MPU_PRESENT not defined in device header file; using default!"
#endif
#ifndef __NVIC_PRIO_BITS
#define __NVIC_PRIO_BITS 4
#warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
#endif
#ifndef __Vendor_SysTickConfig
#define __Vendor_SysTickConfig 0
#warning "__Vendor_SysTickConfig not defined in device header file; using default!"
#endif
#endif
/* IO definitions (access restrictions to peripheral registers) */
/**
\defgroup CMSIS_glob_defs CMSIS Global Defines
<strong>IO Type Qualifiers</strong> are used
\li to specify the access to peripheral variables.
\li for automatic generation of peripheral register debug information.
*/
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions */
#else
#define __I volatile const /*!< Defines 'read only' permissions */
#endif
#define __O volatile /*!< Defines 'write only' permissions */
#define __IO volatile /*!< Defines 'read / write' permissions */
/*@} end of group SC300 */
/*******************************************************************************
* Register Abstraction
Core Register contain:
- Core Register
- Core NVIC Register
- Core SCB Register
- Core SysTick Register
- Core Debug Register
- Core MPU Register
******************************************************************************/
/** \defgroup CMSIS_core_register Defines and Type Definitions
\brief Type definitions and defines for Cortex-M processor based devices.
*/
/** \ingroup CMSIS_core_register
\defgroup CMSIS_CORE Status and Control Registers
\brief Core Register type definitions.
@{
*/
/** \brief Union type to access the Application Program Status Register (APSR).
*/
typedef union
{
struct
{
#if (__CORTEX_M != 0x04)
uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */
#else
uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */
uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */
uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */
#endif
uint32_t Q:1; /*!< bit: 27 Saturation condition flag */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} APSR_Type;
/** \brief Union type to access the Interrupt Program Status Register (IPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} IPSR_Type;
/** \brief Union type to access the Special-Purpose Program Status Registers (xPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
#if (__CORTEX_M != 0x04)
uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */
#else
uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */
uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */
uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */
#endif
uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */
uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */
uint32_t Q:1; /*!< bit: 27 Saturation condition flag */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} xPSR_Type;
/** \brief Union type to access the Control Registers (CONTROL).
*/
typedef union
{
struct
{
uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */
uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */
uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */
uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} CONTROL_Type;
/*@} end of group CMSIS_CORE */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC)
\brief Type definitions for the NVIC Registers
@{
*/
/** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC).
*/
typedef struct
{
__IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */
uint32_t RESERVED0[24];
__IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */
uint32_t RSERVED1[24];
__IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */
uint32_t RESERVED2[24];
__IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */
uint32_t RESERVED3[24];
__IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */
uint32_t RESERVED4[56];
__IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */
uint32_t RESERVED5[644];
__O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */
} NVIC_Type;
/* Software Triggered Interrupt Register Definitions */
#define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */
#define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */
/*@} end of group CMSIS_NVIC */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SCB System Control Block (SCB)
\brief Type definitions for the System Control Block Registers
@{
*/
/** \brief Structure type to access the System Control Block (SCB).
*/
typedef struct
{
__I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */
__IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */
__IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */
__IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */
__IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */
__IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */
__IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */
__IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */
__IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */
__IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */
__IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */
__IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */
__IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */
__IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */
__I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */
__I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */
__I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */
__I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */
__I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */
uint32_t RESERVED0[5];
__IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */
} SCB_Type;
/* SCB CPUID Register Definitions */
#define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */
#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
#define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */
#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
#define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */
#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */
#define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */
#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
#define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */
#define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */
#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
#define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */
#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
#define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */
#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
#define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */
#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
#define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */
#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
#define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */
#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
#define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */
#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
#define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */
#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
#define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */
#define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */
#define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */
#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */
/* SCB Vector Table Offset Register Definitions */
#define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */
#define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */
#define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */
#define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */
/* SCB Application Interrupt and Reset Control Register Definitions */
#define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */
#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
#define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */
#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
#define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */
#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
#define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */
#define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */
#define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */
#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
#define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */
#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
#define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */
#define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */
/* SCB System Control Register Definitions */
#define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */
#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
#define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */
#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
#define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */
#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
/* SCB Configuration Control Register Definitions */
#define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */
#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
#define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */
#define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */
#define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */
#define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */
#define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */
#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
#define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */
#define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */
#define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */
#define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */
/* SCB System Handler Control and State Register Definitions */
#define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */
#define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */
#define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */
#define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */
#define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */
#define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */
#define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */
#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
#define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */
#define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */
#define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */
#define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */
#define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */
#define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */
#define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */
#define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */
#define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */
#define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */
#define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */
#define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */
#define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */
#define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */
#define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */
#define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */
#define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */
#define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */
#define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */
#define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */
/* SCB Configurable Fault Status Registers Definitions */
#define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */
#define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */
#define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */
#define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */
#define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */
#define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */
/* SCB Hard Fault Status Registers Definitions */
#define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */
#define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */
#define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */
#define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */
#define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */
#define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */
/* SCB Debug Fault Status Register Definitions */
#define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */
#define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */
#define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */
#define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */
#define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */
#define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */
#define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */
#define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */
#define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */
#define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */
/*@} end of group CMSIS_SCB */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
\brief Type definitions for the System Control and ID Register not in the SCB
@{
*/
/** \brief Structure type to access the System Control and ID Register not in the SCB.
*/
typedef struct
{
uint32_t RESERVED0[1];
__I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */
uint32_t RESERVED1[1];
} SCnSCB_Type;
/* Interrupt Controller Type Register Definitions */
#define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */
#define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */
/*@} end of group CMSIS_SCnotSCB */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SysTick System Tick Timer (SysTick)
\brief Type definitions for the System Timer Registers.
@{
*/
/** \brief Structure type to access the System Timer (SysTick).
*/
typedef struct
{
__IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
__IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
__IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
__I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
} SysTick_Type;
/* SysTick Control / Status Register Definitions */
#define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */
#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
#define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */
#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
#define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */
#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
#define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */
#define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */
/* SysTick Reload Register Definitions */
#define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */
#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */
/* SysTick Current Register Definitions */
#define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */
#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */
/* SysTick Calibration Register Definitions */
#define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */
#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
#define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */
#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
#define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */
#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */
/*@} end of group CMSIS_SysTick */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM)
\brief Type definitions for the Instrumentation Trace Macrocell (ITM)
@{
*/
/** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM).
*/
typedef struct
{
__O union
{
__O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */
__O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */
__O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */
} PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */
uint32_t RESERVED0[864];
__IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */
uint32_t RESERVED1[15];
__IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */
uint32_t RESERVED2[15];
__IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */
uint32_t RESERVED3[29];
__O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */
__I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */
__IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */
uint32_t RESERVED4[43];
__O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */
__I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */
uint32_t RESERVED5[6];
__I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */
__I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */
__I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */
__I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */
__I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */
__I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */
__I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */
__I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */
__I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */
__I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */
__I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */
__I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */
} ITM_Type;
/* ITM Trace Privilege Register Definitions */
#define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */
#define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */
/* ITM Trace Control Register Definitions */
#define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */
#define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */
#define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */
#define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */
#define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */
#define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */
#define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */
#define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */
#define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */
#define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */
#define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */
#define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */
#define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */
#define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */
#define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */
#define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */
#define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */
#define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */
/* ITM Integration Write Register Definitions */
#define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */
#define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */
/* ITM Integration Read Register Definitions */
#define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */
#define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */
/* ITM Integration Mode Control Register Definitions */
#define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */
#define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */
/* ITM Lock Status Register Definitions */
#define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */
#define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */
#define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */
#define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */
#define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */
#define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */
/*@}*/ /* end of group CMSIS_ITM */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_DWT Data Watchpoint and Trace (DWT)
\brief Type definitions for the Data Watchpoint and Trace (DWT)
@{
*/
/** \brief Structure type to access the Data Watchpoint and Trace Register (DWT).
*/
typedef struct
{
__IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */
__IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */
__IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */
__IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */
__IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */
__IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */
__IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */
__I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */
__IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */
__IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */
__IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */
uint32_t RESERVED0[1];
__IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */
__IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */
__IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */
uint32_t RESERVED1[1];
__IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */
__IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */
__IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */
uint32_t RESERVED2[1];
__IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */
__IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */
__IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */
} DWT_Type;
/* DWT Control Register Definitions */
#define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */
#define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */
#define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */
#define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */
#define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */
#define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */
#define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */
#define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */
#define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */
#define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */
#define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */
#define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */
#define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */
#define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */
#define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */
#define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */
#define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */
#define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */
#define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */
#define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */
#define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */
#define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */
#define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */
#define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */
#define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */
#define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */
#define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */
#define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */
#define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */
#define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */
#define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */
#define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */
#define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */
#define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */
#define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */
#define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */
/* DWT CPI Count Register Definitions */
#define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */
#define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */
/* DWT Exception Overhead Count Register Definitions */
#define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */
#define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */
/* DWT Sleep Count Register Definitions */
#define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */
#define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */
/* DWT LSU Count Register Definitions */
#define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */
#define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */
/* DWT Folded-instruction Count Register Definitions */
#define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */
#define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */
/* DWT Comparator Mask Register Definitions */
#define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */
#define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */
/* DWT Comparator Function Register Definitions */
#define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */
#define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */
#define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */
#define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */
#define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */
#define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */
#define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */
#define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */
#define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */
#define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */
#define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */
#define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */
#define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */
#define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */
#define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */
#define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */
#define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */
#define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */
/*@}*/ /* end of group CMSIS_DWT */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_TPI Trace Port Interface (TPI)
\brief Type definitions for the Trace Port Interface (TPI)
@{
*/
/** \brief Structure type to access the Trace Port Interface Register (TPI).
*/
typedef struct
{
__IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */
__IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */
uint32_t RESERVED0[2];
__IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */
uint32_t RESERVED1[55];
__IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */
uint32_t RESERVED2[131];
__I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */
__IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */
__I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */
uint32_t RESERVED3[759];
__I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */
__I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */
__I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */
uint32_t RESERVED4[1];
__I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */
__I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */
__IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */
uint32_t RESERVED5[39];
__IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */
__IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */
uint32_t RESERVED7[8];
__I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */
__I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */
} TPI_Type;
/* TPI Asynchronous Clock Prescaler Register Definitions */
#define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */
#define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */
/* TPI Selected Pin Protocol Register Definitions */
#define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */
#define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */
/* TPI Formatter and Flush Status Register Definitions */
#define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */
#define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */
#define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */
#define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */
#define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */
#define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */
#define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */
#define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */
/* TPI Formatter and Flush Control Register Definitions */
#define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */
#define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */
#define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */
#define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */
/* TPI TRIGGER Register Definitions */
#define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */
#define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */
/* TPI Integration ETM Data Register Definitions (FIFO0) */
#define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */
#define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */
#define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */
#define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */
#define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */
#define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */
#define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */
#define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */
#define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */
#define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */
#define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */
#define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */
#define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */
#define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */
/* TPI ITATBCTR2 Register Definitions */
#define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */
#define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */
/* TPI Integration ITM Data Register Definitions (FIFO1) */
#define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */
#define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */
#define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */
#define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */
#define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */
#define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */
#define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */
#define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */
#define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */
#define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */
#define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */
#define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */
#define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */
#define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */
/* TPI ITATBCTR0 Register Definitions */
#define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */
#define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */
/* TPI Integration Mode Control Register Definitions */
#define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */
#define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */
/* TPI DEVID Register Definitions */
#define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */
#define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */
#define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */
#define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */
#define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */
#define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */
#define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */
#define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */
#define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */
#define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */
#define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */
#define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */
/* TPI DEVTYPE Register Definitions */
#define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */
#define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */
#define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */
#define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */
/*@}*/ /* end of group CMSIS_TPI */
#if (__MPU_PRESENT == 1)
/** \ingroup CMSIS_core_register
\defgroup CMSIS_MPU Memory Protection Unit (MPU)
\brief Type definitions for the Memory Protection Unit (MPU)
@{
*/
/** \brief Structure type to access the Memory Protection Unit (MPU).
*/
typedef struct
{
__I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */
__IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */
__IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */
__IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */
__IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */
__IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */
__IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */
__IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */
__IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */
__IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */
__IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */
} MPU_Type;
/* MPU Type Register */
#define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */
#define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */
#define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */
#define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */
#define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */
#define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */
/* MPU Control Register */
#define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */
#define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */
#define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */
#define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */
#define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */
#define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */
/* MPU Region Number Register */
#define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */
#define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */
/* MPU Region Base Address Register */
#define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */
#define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */
#define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */
#define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */
#define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */
#define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */
/* MPU Region Attribute and Size Register */
#define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */
#define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */
#define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */
#define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */
#define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */
#define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */
#define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */
#define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */
#define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */
#define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */
#define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */
#define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */
#define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */
#define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */
#define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */
#define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */
#define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */
#define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */
#define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */
#define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */
/*@} end of group CMSIS_MPU */
#endif
/** \ingroup CMSIS_core_register
\defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug)
\brief Type definitions for the Core Debug Registers
@{
*/
/** \brief Structure type to access the Core Debug Register (CoreDebug).
*/
typedef struct
{
__IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */
__O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */
__IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */
__IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */
} CoreDebug_Type;
/* Debug Halting Control and Status Register */
#define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */
#define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */
#define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */
#define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */
#define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */
#define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */
#define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */
#define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */
#define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */
#define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */
#define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */
#define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */
#define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */
#define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */
#define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */
#define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */
#define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */
#define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */
#define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */
#define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */
#define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */
#define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */
#define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */
#define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */
/* Debug Core Register Selector Register */
#define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */
#define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */
#define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */
#define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */
/* Debug Exception and Monitor Control Register */
#define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */
#define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */
#define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */
#define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */
#define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */
#define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */
#define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */
#define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */
#define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */
#define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */
#define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */
#define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */
#define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */
#define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */
#define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */
#define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */
#define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */
#define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */
#define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */
#define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */
#define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */
#define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */
#define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */
#define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */
#define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */
#define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */
/*@} end of group CMSIS_CoreDebug */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_core_base Core Definitions
\brief Definitions for base addresses, unions, and structures.
@{
*/
/* Memory mapping of Cortex-M3 Hardware */
#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */
#define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */
#define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */
#define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */
#define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */
#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */
#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */
#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */
#define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */
#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */
#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */
#define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */
#define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */
#define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */
#define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */
#if (__MPU_PRESENT == 1)
#define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */
#define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */
#endif
/*@} */
/*******************************************************************************
* Hardware Abstraction Layer
Core Function Interface contains:
- Core NVIC Functions
- Core SysTick Functions
- Core Debug Functions
- Core Register Access Functions
******************************************************************************/
/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
*/
/* ########################## NVIC functions #################################### */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_NVICFunctions NVIC Functions
\brief Functions that manage interrupts and exceptions via the NVIC.
@{
*/
/** \brief Set Priority Grouping
The function sets the priority grouping field using the required unlock sequence.
The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field.
Only values from 0..7 are used.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set.
\param [in] PriorityGroup Priority grouping field.
*/
__STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
{
uint32_t reg_value;
uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */
reg_value = SCB->AIRCR; /* read old register configuration */
reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */
reg_value = (reg_value |
((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) |
(PriorityGroupTmp << 8)); /* Insert write key and priorty group */
SCB->AIRCR = reg_value;
}
/** \brief Get Priority Grouping
The function reads the priority grouping field from the NVIC Interrupt Controller.
\return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field).
*/
__STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void)
{
return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */
}
/** \brief Enable External Interrupt
The function enables a device-specific interrupt in the NVIC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
{
NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */
}
/** \brief Disable External Interrupt
The function disables a device-specific interrupt in the NVIC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
{
NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */
}
/** \brief Get Pending Interrupt
The function reads the pending register in the NVIC and returns the pending bit
for the specified interrupt.
\param [in] IRQn Interrupt number.
\return 0 Interrupt status is not pending.
\return 1 Interrupt status is pending.
*/
__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
{
return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */
}
/** \brief Set Pending Interrupt
The function sets the pending bit of an external interrupt.
\param [in] IRQn Interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
{
NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */
}
/** \brief Clear Pending Interrupt
The function clears the pending bit of an external interrupt.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */
}
/** \brief Get Active Interrupt
The function reads the active register in NVIC and returns the active bit.
\param [in] IRQn Interrupt number.
\return 0 Interrupt status is not active.
\return 1 Interrupt status is active.
*/
__STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn)
{
return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */
}
/** \brief Set Interrupt Priority
The function sets the priority of an interrupt.
\note The priority cannot be set for every core interrupt.
\param [in] IRQn Interrupt number.
\param [in] priority Priority to set.
*/
__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
if(IRQn < 0) {
SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */
else {
NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */
}
/** \brief Get Interrupt Priority
The function reads the priority of an interrupt. The interrupt
number can be positive to specify an external (device specific)
interrupt, or negative to specify an internal (core) interrupt.
\param [in] IRQn Interrupt number.
\return Interrupt Priority. Value is aligned automatically to the implemented
priority bits of the microcontroller.
*/
__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
{
if(IRQn < 0) {
return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */
else {
return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */
}
/** \brief Encode Priority
The function encodes the priority for an interrupt with the given priority group,
preemptive priority value, and subpriority value.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set.
\param [in] PriorityGroup Used priority group.
\param [in] PreemptPriority Preemptive priority value (starting from 0).
\param [in] SubPriority Subpriority value (starting from 0).
\return Encoded priority. Value can be used in the function \ref NVIC_SetPriority().
*/
__STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;
SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;
return (
((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) |
((SubPriority & ((1 << (SubPriorityBits )) - 1)))
);
}
/** \brief Decode Priority
The function decodes an interrupt priority value with a given priority group to
preemptive priority value and subpriority value.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set.
\param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority().
\param [in] PriorityGroup Used priority group.
\param [out] pPreemptPriority Preemptive priority value (starting from 0).
\param [out] pSubPriority Subpriority value (starting from 0).
*/
__STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;
SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;
*pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1);
*pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1);
}
/** \brief System Reset
The function initiates a system reset request to reset the MCU.
*/
__STATIC_INLINE void NVIC_SystemReset(void)
{
__DSB(); /* Ensure all outstanding memory accesses included
buffered write are completed before reset */
SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) |
(SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) |
SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */
__DSB(); /* Ensure completion of memory access */
while(1); /* wait until reset */
}
/*@} end of CMSIS_Core_NVICFunctions */
/* ################################## SysTick function ############################################ */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_SysTickFunctions SysTick Functions
\brief Functions that configure the System.
@{
*/
#if (__Vendor_SysTickConfig == 0)
/** \brief System Tick Configuration
The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
Counter is in free running mode to generate periodic interrupts.
\param [in] ticks Number of ticks between two interrupts.
\return 0 Function succeeded.
\return 1 Function failed.
\note When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
must contain a vendor-specific implementation of this function.
*/
__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */
SysTick->LOAD = ticks - 1; /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */
SysTick->VAL = 0; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0); /* Function successful */
}
#endif
/*@} end of CMSIS_Core_SysTickFunctions */
/* ##################################### Debug In/Output function ########################################### */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_core_DebugFunctions ITM Functions
\brief Functions that access the ITM debug interface.
@{
*/
extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */
#define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */
/** \brief ITM Send Character
The function transmits a character via the ITM channel 0, and
\li Just returns when no debugger is connected that has booked the output.
\li Is blocking when a debugger is connected, but the previous character sent has not been transmitted.
\param [in] ch Character to transmit.
\returns Character to transmit.
*/
__STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch)
{
if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */
(ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */
{
while (ITM->PORT[0].u32 == 0);
ITM->PORT[0].u8 = (uint8_t) ch;
}
return (ch);
}
/** \brief ITM Receive Character
The function inputs a character via the external variable \ref ITM_RxBuffer.
\return Received character.
\return -1 No character pending.
*/
__STATIC_INLINE int32_t ITM_ReceiveChar (void) {
int32_t ch = -1; /* no character available */
if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) {
ch = ITM_RxBuffer;
ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */
}
return (ch);
}
/** \brief ITM Check Character
The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer.
\return 0 No character available.
\return 1 Character available.
*/
__STATIC_INLINE int32_t ITM_CheckChar (void) {
if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) {
return (0); /* no character available */
} else {
return (1); /* character available */
}
}
/*@} end of CMSIS_core_DebugFunctions */
#endif /* __CORE_SC300_H_DEPENDANT */
#endif /* __CMSIS_GENERIC */
#ifdef __cplusplus
}
#endif
| {
"language": "C"
} |
/* This provides unification of code over SAM subfamilies */
/*
* This file is part of the libopencm3 project.
*
* Copyright (C) 2014 Felix Held <felix-libopencm3@felixheld.de>
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(SAM3A)
# include <libopencm3/sam/3a/gpio.h>
#elif defined(SAM3N)
# include <libopencm3/sam/3n/gpio.h>
#elif defined(SAM3S)
# include <libopencm3/sam/3s/gpio.h>
#elif defined(SAM3U)
# include <libopencm3/sam/3u/gpio.h>
#elif defined(SAM3X)
# include <libopencm3/sam/3x/gpio.h>
#elif defined(SAM4L)
# include <libopencm3/sam/4l/gpio.h>
#else
# error "sam family not defined."
#endif
| {
"language": "C"
} |
/*
* continuously incrementing 32 bit timer
*
* Copyright (c) 2009 Openmoko Inc.
*
* Authors Christopher Hall <hsw@openmoko.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(_TICK_H_)
#define _TICK_H_ 1
void Tick_initialise();
enum {
Tick_TicksPerMicroSecond = 60,
Tick_TicksPerMilliSecond = Tick_TicksPerMicroSecond * 1000,
Tick_TicksPerSecond = Tick_TicksPerMilliSecond * 1000,
};
unsigned long Tick_get(void);
#endif
| {
"language": "C"
} |
/*
* Self tests for device tree subsystem
*/
#define pr_fmt(fmt) "### dt-test ### " fmt
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/hashtable.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_fdt.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/of_platform.h>
#include <linux/i2c.h>
#include <linux/i2c-mux.h>
#include "of_private.h"
static struct selftest_results {
int passed;
int failed;
} selftest_results;
#define selftest(result, fmt, ...) ({ \
bool failed = !(result); \
if (failed) { \
selftest_results.failed++; \
pr_err("FAIL %s():%i " fmt, __func__, __LINE__, ##__VA_ARGS__); \
} else { \
selftest_results.passed++; \
pr_debug("pass %s():%i\n", __func__, __LINE__); \
} \
failed; \
})
static void __init of_selftest_find_node_by_name(void)
{
struct device_node *np;
const char *options;
np = of_find_node_by_path("/testcase-data");
selftest(np && !strcmp("/testcase-data", np->full_name),
"find /testcase-data failed\n");
of_node_put(np);
/* Test if trailing '/' works */
np = of_find_node_by_path("/testcase-data/");
selftest(!np, "trailing '/' on /testcase-data/ should fail\n");
np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a");
selftest(np && !strcmp("/testcase-data/phandle-tests/consumer-a", np->full_name),
"find /testcase-data/phandle-tests/consumer-a failed\n");
of_node_put(np);
np = of_find_node_by_path("testcase-alias");
selftest(np && !strcmp("/testcase-data", np->full_name),
"find testcase-alias failed\n");
of_node_put(np);
/* Test if trailing '/' works on aliases */
np = of_find_node_by_path("testcase-alias/");
selftest(!np, "trailing '/' on testcase-alias/ should fail\n");
np = of_find_node_by_path("testcase-alias/phandle-tests/consumer-a");
selftest(np && !strcmp("/testcase-data/phandle-tests/consumer-a", np->full_name),
"find testcase-alias/phandle-tests/consumer-a failed\n");
of_node_put(np);
np = of_find_node_by_path("/testcase-data/missing-path");
selftest(!np, "non-existent path returned node %s\n", np->full_name);
of_node_put(np);
np = of_find_node_by_path("missing-alias");
selftest(!np, "non-existent alias returned node %s\n", np->full_name);
of_node_put(np);
np = of_find_node_by_path("testcase-alias/missing-path");
selftest(!np, "non-existent alias with relative path returned node %s\n", np->full_name);
of_node_put(np);
np = of_find_node_opts_by_path("/testcase-data:testoption", &options);
selftest(np && !strcmp("testoption", options),
"option path test failed\n");
of_node_put(np);
np = of_find_node_opts_by_path("/testcase-data:test/option", &options);
selftest(np && !strcmp("test/option", options),
"option path test, subcase #1 failed\n");
of_node_put(np);
np = of_find_node_opts_by_path("/testcase-data/testcase-device1:test/option", &options);
selftest(np && !strcmp("test/option", options),
"option path test, subcase #2 failed\n");
of_node_put(np);
np = of_find_node_opts_by_path("/testcase-data:testoption", NULL);
selftest(np, "NULL option path test failed\n");
of_node_put(np);
np = of_find_node_opts_by_path("testcase-alias:testaliasoption",
&options);
selftest(np && !strcmp("testaliasoption", options),
"option alias path test failed\n");
of_node_put(np);
np = of_find_node_opts_by_path("testcase-alias:test/alias/option",
&options);
selftest(np && !strcmp("test/alias/option", options),
"option alias path test, subcase #1 failed\n");
of_node_put(np);
np = of_find_node_opts_by_path("testcase-alias:testaliasoption", NULL);
selftest(np, "NULL option alias path test failed\n");
of_node_put(np);
options = "testoption";
np = of_find_node_opts_by_path("testcase-alias", &options);
selftest(np && !options, "option clearing test failed\n");
of_node_put(np);
options = "testoption";
np = of_find_node_opts_by_path("/", &options);
selftest(np && !options, "option clearing root node test failed\n");
of_node_put(np);
}
static void __init of_selftest_dynamic(void)
{
struct device_node *np;
struct property *prop;
np = of_find_node_by_path("/testcase-data");
if (!np) {
pr_err("missing testcase data\n");
return;
}
/* Array of 4 properties for the purpose of testing */
prop = kzalloc(sizeof(*prop) * 4, GFP_KERNEL);
if (!prop) {
selftest(0, "kzalloc() failed\n");
return;
}
/* Add a new property - should pass*/
prop->name = "new-property";
prop->value = "new-property-data";
prop->length = strlen(prop->value);
selftest(of_add_property(np, prop) == 0, "Adding a new property failed\n");
/* Try to add an existing property - should fail */
prop++;
prop->name = "new-property";
prop->value = "new-property-data-should-fail";
prop->length = strlen(prop->value);
selftest(of_add_property(np, prop) != 0,
"Adding an existing property should have failed\n");
/* Try to modify an existing property - should pass */
prop->value = "modify-property-data-should-pass";
prop->length = strlen(prop->value);
selftest(of_update_property(np, prop) == 0,
"Updating an existing property should have passed\n");
/* Try to modify non-existent property - should pass*/
prop++;
prop->name = "modify-property";
prop->value = "modify-missing-property-data-should-pass";
prop->length = strlen(prop->value);
selftest(of_update_property(np, prop) == 0,
"Updating a missing property should have passed\n");
/* Remove property - should pass */
selftest(of_remove_property(np, prop) == 0,
"Removing a property should have passed\n");
/* Adding very large property - should pass */
prop++;
prop->name = "large-property-PAGE_SIZEx8";
prop->length = PAGE_SIZE * 8;
prop->value = kzalloc(prop->length, GFP_KERNEL);
selftest(prop->value != NULL, "Unable to allocate large buffer\n");
if (prop->value)
selftest(of_add_property(np, prop) == 0,
"Adding a large property should have passed\n");
}
static int __init of_selftest_check_node_linkage(struct device_node *np)
{
struct device_node *child;
int count = 0, rc;
for_each_child_of_node(np, child) {
if (child->parent != np) {
pr_err("Child node %s links to wrong parent %s\n",
child->name, np->name);
return -EINVAL;
}
rc = of_selftest_check_node_linkage(child);
if (rc < 0)
return rc;
count += rc;
}
return count + 1;
}
static void __init of_selftest_check_tree_linkage(void)
{
struct device_node *np;
int allnode_count = 0, child_count;
if (!of_root)
return;
for_each_of_allnodes(np)
allnode_count++;
child_count = of_selftest_check_node_linkage(of_root);
selftest(child_count > 0, "Device node data structure is corrupted\n");
selftest(child_count == allnode_count, "allnodes list size (%i) doesn't match"
"sibling lists size (%i)\n", allnode_count, child_count);
pr_debug("allnodes list size (%i); sibling lists size (%i)\n", allnode_count, child_count);
}
struct node_hash {
struct hlist_node node;
struct device_node *np;
};
static DEFINE_HASHTABLE(phandle_ht, 8);
static void __init of_selftest_check_phandles(void)
{
struct device_node *np;
struct node_hash *nh;
struct hlist_node *tmp;
int i, dup_count = 0, phandle_count = 0;
for_each_of_allnodes(np) {
if (!np->phandle)
continue;
hash_for_each_possible(phandle_ht, nh, node, np->phandle) {
if (nh->np->phandle == np->phandle) {
pr_info("Duplicate phandle! %i used by %s and %s\n",
np->phandle, nh->np->full_name, np->full_name);
dup_count++;
break;
}
}
nh = kzalloc(sizeof(*nh), GFP_KERNEL);
if (WARN_ON(!nh))
return;
nh->np = np;
hash_add(phandle_ht, &nh->node, np->phandle);
phandle_count++;
}
selftest(dup_count == 0, "Found %i duplicates in %i phandles\n",
dup_count, phandle_count);
/* Clean up */
hash_for_each_safe(phandle_ht, i, tmp, nh, node) {
hash_del(&nh->node);
kfree(nh);
}
}
static void __init of_selftest_parse_phandle_with_args(void)
{
struct device_node *np;
struct of_phandle_args args;
int i, rc;
np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a");
if (!np) {
pr_err("missing testcase data\n");
return;
}
rc = of_count_phandle_with_args(np, "phandle-list", "#phandle-cells");
selftest(rc == 7, "of_count_phandle_with_args() returned %i, expected 7\n", rc);
for (i = 0; i < 8; i++) {
bool passed = true;
rc = of_parse_phandle_with_args(np, "phandle-list",
"#phandle-cells", i, &args);
/* Test the values from tests-phandle.dtsi */
switch (i) {
case 0:
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == (i + 1));
break;
case 1:
passed &= !rc;
passed &= (args.args_count == 2);
passed &= (args.args[0] == (i + 1));
passed &= (args.args[1] == 0);
break;
case 2:
passed &= (rc == -ENOENT);
break;
case 3:
passed &= !rc;
passed &= (args.args_count == 3);
passed &= (args.args[0] == (i + 1));
passed &= (args.args[1] == 4);
passed &= (args.args[2] == 3);
break;
case 4:
passed &= !rc;
passed &= (args.args_count == 2);
passed &= (args.args[0] == (i + 1));
passed &= (args.args[1] == 100);
break;
case 5:
passed &= !rc;
passed &= (args.args_count == 0);
break;
case 6:
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == (i + 1));
break;
case 7:
passed &= (rc == -ENOENT);
break;
default:
passed = false;
}
selftest(passed, "index %i - data error on node %s rc=%i\n",
i, args.np->full_name, rc);
}
/* Check for missing list property */
rc = of_parse_phandle_with_args(np, "phandle-list-missing",
"#phandle-cells", 0, &args);
selftest(rc == -ENOENT, "expected:%i got:%i\n", -ENOENT, rc);
rc = of_count_phandle_with_args(np, "phandle-list-missing",
"#phandle-cells");
selftest(rc == -ENOENT, "expected:%i got:%i\n", -ENOENT, rc);
/* Check for missing cells property */
rc = of_parse_phandle_with_args(np, "phandle-list",
"#phandle-cells-missing", 0, &args);
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
rc = of_count_phandle_with_args(np, "phandle-list",
"#phandle-cells-missing");
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
/* Check for bad phandle in list */
rc = of_parse_phandle_with_args(np, "phandle-list-bad-phandle",
"#phandle-cells", 0, &args);
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
rc = of_count_phandle_with_args(np, "phandle-list-bad-phandle",
"#phandle-cells");
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
/* Check for incorrectly formed argument list */
rc = of_parse_phandle_with_args(np, "phandle-list-bad-args",
"#phandle-cells", 1, &args);
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
rc = of_count_phandle_with_args(np, "phandle-list-bad-args",
"#phandle-cells");
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
}
static void __init of_selftest_property_string(void)
{
const char *strings[4];
struct device_node *np;
int rc;
np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a");
if (!np) {
pr_err("No testcase data in device tree\n");
return;
}
rc = of_property_match_string(np, "phandle-list-names", "first");
selftest(rc == 0, "first expected:0 got:%i\n", rc);
rc = of_property_match_string(np, "phandle-list-names", "second");
selftest(rc == 1, "second expected:1 got:%i\n", rc);
rc = of_property_match_string(np, "phandle-list-names", "third");
selftest(rc == 2, "third expected:2 got:%i\n", rc);
rc = of_property_match_string(np, "phandle-list-names", "fourth");
selftest(rc == -ENODATA, "unmatched string; rc=%i\n", rc);
rc = of_property_match_string(np, "missing-property", "blah");
selftest(rc == -EINVAL, "missing property; rc=%i\n", rc);
rc = of_property_match_string(np, "empty-property", "blah");
selftest(rc == -ENODATA, "empty property; rc=%i\n", rc);
rc = of_property_match_string(np, "unterminated-string", "blah");
selftest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc);
/* of_property_count_strings() tests */
rc = of_property_count_strings(np, "string-property");
selftest(rc == 1, "Incorrect string count; rc=%i\n", rc);
rc = of_property_count_strings(np, "phandle-list-names");
selftest(rc == 3, "Incorrect string count; rc=%i\n", rc);
rc = of_property_count_strings(np, "unterminated-string");
selftest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc);
rc = of_property_count_strings(np, "unterminated-string-list");
selftest(rc == -EILSEQ, "unterminated string array; rc=%i\n", rc);
/* of_property_read_string_index() tests */
rc = of_property_read_string_index(np, "string-property", 0, strings);
selftest(rc == 0 && !strcmp(strings[0], "foobar"), "of_property_read_string_index() failure; rc=%i\n", rc);
strings[0] = NULL;
rc = of_property_read_string_index(np, "string-property", 1, strings);
selftest(rc == -ENODATA && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc);
rc = of_property_read_string_index(np, "phandle-list-names", 0, strings);
selftest(rc == 0 && !strcmp(strings[0], "first"), "of_property_read_string_index() failure; rc=%i\n", rc);
rc = of_property_read_string_index(np, "phandle-list-names", 1, strings);
selftest(rc == 0 && !strcmp(strings[0], "second"), "of_property_read_string_index() failure; rc=%i\n", rc);
rc = of_property_read_string_index(np, "phandle-list-names", 2, strings);
selftest(rc == 0 && !strcmp(strings[0], "third"), "of_property_read_string_index() failure; rc=%i\n", rc);
strings[0] = NULL;
rc = of_property_read_string_index(np, "phandle-list-names", 3, strings);
selftest(rc == -ENODATA && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc);
strings[0] = NULL;
rc = of_property_read_string_index(np, "unterminated-string", 0, strings);
selftest(rc == -EILSEQ && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc);
rc = of_property_read_string_index(np, "unterminated-string-list", 0, strings);
selftest(rc == 0 && !strcmp(strings[0], "first"), "of_property_read_string_index() failure; rc=%i\n", rc);
strings[0] = NULL;
rc = of_property_read_string_index(np, "unterminated-string-list", 2, strings); /* should fail */
selftest(rc == -EILSEQ && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc);
strings[1] = NULL;
/* of_property_read_string_array() tests */
rc = of_property_read_string_array(np, "string-property", strings, 4);
selftest(rc == 1, "Incorrect string count; rc=%i\n", rc);
rc = of_property_read_string_array(np, "phandle-list-names", strings, 4);
selftest(rc == 3, "Incorrect string count; rc=%i\n", rc);
rc = of_property_read_string_array(np, "unterminated-string", strings, 4);
selftest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc);
/* -- An incorrectly formed string should cause a failure */
rc = of_property_read_string_array(np, "unterminated-string-list", strings, 4);
selftest(rc == -EILSEQ, "unterminated string array; rc=%i\n", rc);
/* -- parsing the correctly formed strings should still work: */
strings[2] = NULL;
rc = of_property_read_string_array(np, "unterminated-string-list", strings, 2);
selftest(rc == 2 && strings[2] == NULL, "of_property_read_string_array() failure; rc=%i\n", rc);
strings[1] = NULL;
rc = of_property_read_string_array(np, "phandle-list-names", strings, 1);
selftest(rc == 1 && strings[1] == NULL, "Overwrote end of string array; rc=%i, str='%s'\n", rc, strings[1]);
}
#define propcmp(p1, p2) (((p1)->length == (p2)->length) && \
(p1)->value && (p2)->value && \
!memcmp((p1)->value, (p2)->value, (p1)->length) && \
!strcmp((p1)->name, (p2)->name))
static void __init of_selftest_property_copy(void)
{
#ifdef CONFIG_OF_DYNAMIC
struct property p1 = { .name = "p1", .length = 0, .value = "" };
struct property p2 = { .name = "p2", .length = 5, .value = "abcd" };
struct property *new;
new = __of_prop_dup(&p1, GFP_KERNEL);
selftest(new && propcmp(&p1, new), "empty property didn't copy correctly\n");
kfree(new->value);
kfree(new->name);
kfree(new);
new = __of_prop_dup(&p2, GFP_KERNEL);
selftest(new && propcmp(&p2, new), "non-empty property didn't copy correctly\n");
kfree(new->value);
kfree(new->name);
kfree(new);
#endif
}
static void __init of_selftest_changeset(void)
{
#ifdef CONFIG_OF_DYNAMIC
struct property *ppadd, padd = { .name = "prop-add", .length = 0, .value = "" };
struct property *ppupdate, pupdate = { .name = "prop-update", .length = 5, .value = "abcd" };
struct property *ppremove;
struct device_node *n1, *n2, *n21, *nremove, *parent, *np;
struct of_changeset chgset;
n1 = __of_node_dup(NULL, "/testcase-data/changeset/n1");
selftest(n1, "testcase setup failure\n");
n2 = __of_node_dup(NULL, "/testcase-data/changeset/n2");
selftest(n2, "testcase setup failure\n");
n21 = __of_node_dup(NULL, "%s/%s", "/testcase-data/changeset/n2", "n21");
selftest(n21, "testcase setup failure %p\n", n21);
nremove = of_find_node_by_path("/testcase-data/changeset/node-remove");
selftest(nremove, "testcase setup failure\n");
ppadd = __of_prop_dup(&padd, GFP_KERNEL);
selftest(ppadd, "testcase setup failure\n");
ppupdate = __of_prop_dup(&pupdate, GFP_KERNEL);
selftest(ppupdate, "testcase setup failure\n");
parent = nremove->parent;
n1->parent = parent;
n2->parent = parent;
n21->parent = n2;
n2->child = n21;
ppremove = of_find_property(parent, "prop-remove", NULL);
selftest(ppremove, "failed to find removal prop");
of_changeset_init(&chgset);
selftest(!of_changeset_attach_node(&chgset, n1), "fail attach n1\n");
selftest(!of_changeset_attach_node(&chgset, n2), "fail attach n2\n");
selftest(!of_changeset_detach_node(&chgset, nremove), "fail remove node\n");
selftest(!of_changeset_attach_node(&chgset, n21), "fail attach n21\n");
selftest(!of_changeset_add_property(&chgset, parent, ppadd), "fail add prop\n");
selftest(!of_changeset_update_property(&chgset, parent, ppupdate), "fail update prop\n");
selftest(!of_changeset_remove_property(&chgset, parent, ppremove), "fail remove prop\n");
mutex_lock(&of_mutex);
selftest(!of_changeset_apply(&chgset), "apply failed\n");
mutex_unlock(&of_mutex);
/* Make sure node names are constructed correctly */
selftest((np = of_find_node_by_path("/testcase-data/changeset/n2/n21")),
"'%s' not added\n", n21->full_name);
of_node_put(np);
mutex_lock(&of_mutex);
selftest(!of_changeset_revert(&chgset), "revert failed\n");
mutex_unlock(&of_mutex);
of_changeset_destroy(&chgset);
#endif
}
static void __init of_selftest_parse_interrupts(void)
{
struct device_node *np;
struct of_phandle_args args;
int i, rc;
np = of_find_node_by_path("/testcase-data/interrupts/interrupts0");
if (!np) {
pr_err("missing testcase data\n");
return;
}
for (i = 0; i < 4; i++) {
bool passed = true;
args.args_count = 0;
rc = of_irq_parse_one(np, i, &args);
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == (i + 1));
selftest(passed, "index %i - data error on node %s rc=%i\n",
i, args.np->full_name, rc);
}
of_node_put(np);
np = of_find_node_by_path("/testcase-data/interrupts/interrupts1");
if (!np) {
pr_err("missing testcase data\n");
return;
}
for (i = 0; i < 4; i++) {
bool passed = true;
args.args_count = 0;
rc = of_irq_parse_one(np, i, &args);
/* Test the values from tests-phandle.dtsi */
switch (i) {
case 0:
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == 9);
break;
case 1:
passed &= !rc;
passed &= (args.args_count == 3);
passed &= (args.args[0] == 10);
passed &= (args.args[1] == 11);
passed &= (args.args[2] == 12);
break;
case 2:
passed &= !rc;
passed &= (args.args_count == 2);
passed &= (args.args[0] == 13);
passed &= (args.args[1] == 14);
break;
case 3:
passed &= !rc;
passed &= (args.args_count == 2);
passed &= (args.args[0] == 15);
passed &= (args.args[1] == 16);
break;
default:
passed = false;
}
selftest(passed, "index %i - data error on node %s rc=%i\n",
i, args.np->full_name, rc);
}
of_node_put(np);
}
static void __init of_selftest_parse_interrupts_extended(void)
{
struct device_node *np;
struct of_phandle_args args;
int i, rc;
np = of_find_node_by_path("/testcase-data/interrupts/interrupts-extended0");
if (!np) {
pr_err("missing testcase data\n");
return;
}
for (i = 0; i < 7; i++) {
bool passed = true;
rc = of_irq_parse_one(np, i, &args);
/* Test the values from tests-phandle.dtsi */
switch (i) {
case 0:
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == 1);
break;
case 1:
passed &= !rc;
passed &= (args.args_count == 3);
passed &= (args.args[0] == 2);
passed &= (args.args[1] == 3);
passed &= (args.args[2] == 4);
break;
case 2:
passed &= !rc;
passed &= (args.args_count == 2);
passed &= (args.args[0] == 5);
passed &= (args.args[1] == 6);
break;
case 3:
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == 9);
break;
case 4:
passed &= !rc;
passed &= (args.args_count == 3);
passed &= (args.args[0] == 10);
passed &= (args.args[1] == 11);
passed &= (args.args[2] == 12);
break;
case 5:
passed &= !rc;
passed &= (args.args_count == 2);
passed &= (args.args[0] == 13);
passed &= (args.args[1] == 14);
break;
case 6:
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == 15);
break;
default:
passed = false;
}
selftest(passed, "index %i - data error on node %s rc=%i\n",
i, args.np->full_name, rc);
}
of_node_put(np);
}
static struct of_device_id match_node_table[] = {
{ .data = "A", .name = "name0", }, /* Name alone is lowest priority */
{ .data = "B", .type = "type1", }, /* followed by type alone */
{ .data = "Ca", .name = "name2", .type = "type1", }, /* followed by both together */
{ .data = "Cb", .name = "name2", }, /* Only match when type doesn't match */
{ .data = "Cc", .name = "name2", .type = "type2", },
{ .data = "E", .compatible = "compat3" },
{ .data = "G", .compatible = "compat2", },
{ .data = "H", .compatible = "compat2", .name = "name5", },
{ .data = "I", .compatible = "compat2", .type = "type1", },
{ .data = "J", .compatible = "compat2", .type = "type1", .name = "name8", },
{ .data = "K", .compatible = "compat2", .name = "name9", },
{}
};
static struct {
const char *path;
const char *data;
} match_node_tests[] = {
{ .path = "/testcase-data/match-node/name0", .data = "A", },
{ .path = "/testcase-data/match-node/name1", .data = "B", },
{ .path = "/testcase-data/match-node/a/name2", .data = "Ca", },
{ .path = "/testcase-data/match-node/b/name2", .data = "Cb", },
{ .path = "/testcase-data/match-node/c/name2", .data = "Cc", },
{ .path = "/testcase-data/match-node/name3", .data = "E", },
{ .path = "/testcase-data/match-node/name4", .data = "G", },
{ .path = "/testcase-data/match-node/name5", .data = "H", },
{ .path = "/testcase-data/match-node/name6", .data = "G", },
{ .path = "/testcase-data/match-node/name7", .data = "I", },
{ .path = "/testcase-data/match-node/name8", .data = "J", },
{ .path = "/testcase-data/match-node/name9", .data = "K", },
};
static void __init of_selftest_match_node(void)
{
struct device_node *np;
const struct of_device_id *match;
int i;
for (i = 0; i < ARRAY_SIZE(match_node_tests); i++) {
np = of_find_node_by_path(match_node_tests[i].path);
if (!np) {
selftest(0, "missing testcase node %s\n",
match_node_tests[i].path);
continue;
}
match = of_match_node(match_node_table, np);
if (!match) {
selftest(0, "%s didn't match anything\n",
match_node_tests[i].path);
continue;
}
if (strcmp(match->data, match_node_tests[i].data) != 0) {
selftest(0, "%s got wrong match. expected %s, got %s\n",
match_node_tests[i].path, match_node_tests[i].data,
(const char *)match->data);
continue;
}
selftest(1, "passed");
}
}
struct device test_bus = {
.init_name = "unittest-bus",
};
static void __init of_selftest_platform_populate(void)
{
int irq, rc;
struct device_node *np, *child, *grandchild;
struct platform_device *pdev;
struct of_device_id match[] = {
{ .compatible = "test-device", },
{}
};
np = of_find_node_by_path("/testcase-data");
of_platform_populate(np, of_default_bus_match_table, NULL, NULL);
/* Test that a missing irq domain returns -EPROBE_DEFER */
np = of_find_node_by_path("/testcase-data/testcase-device1");
pdev = of_find_device_by_node(np);
selftest(pdev, "device 1 creation failed\n");
irq = platform_get_irq(pdev, 0);
selftest(irq == -EPROBE_DEFER, "device deferred probe failed - %d\n", irq);
/* Test that a parsing failure does not return -EPROBE_DEFER */
np = of_find_node_by_path("/testcase-data/testcase-device2");
pdev = of_find_device_by_node(np);
selftest(pdev, "device 2 creation failed\n");
irq = platform_get_irq(pdev, 0);
selftest(irq < 0 && irq != -EPROBE_DEFER, "device parsing error failed - %d\n", irq);
if (selftest(np = of_find_node_by_path("/testcase-data/platform-tests"),
"No testcase data in device tree\n"));
return;
if (selftest(!(rc = device_register(&test_bus)),
"testbus registration failed; rc=%i\n", rc));
return;
for_each_child_of_node(np, child) {
of_platform_populate(child, match, NULL, &test_bus);
for_each_child_of_node(child, grandchild)
selftest(of_find_device_by_node(grandchild),
"Could not create device for node '%s'\n",
grandchild->name);
}
of_platform_depopulate(&test_bus);
for_each_child_of_node(np, child) {
for_each_child_of_node(child, grandchild)
selftest(!of_find_device_by_node(grandchild),
"device didn't get destroyed '%s'\n",
grandchild->name);
}
device_unregister(&test_bus);
of_node_put(np);
}
/**
* update_node_properties - adds the properties
* of np into dup node (present in live tree) and
* updates parent of children of np to dup.
*
* @np: node already present in live tree
* @dup: node present in live tree to be updated
*/
static void update_node_properties(struct device_node *np,
struct device_node *dup)
{
struct property *prop;
struct device_node *child;
for_each_property_of_node(np, prop)
of_add_property(dup, prop);
for_each_child_of_node(np, child)
child->parent = dup;
}
/**
* attach_node_and_children - attaches nodes
* and its children to live tree
*
* @np: Node to attach to live tree
*/
static int attach_node_and_children(struct device_node *np)
{
struct device_node *next, *dup, *child;
unsigned long flags;
dup = of_find_node_by_path(np->full_name);
if (dup) {
update_node_properties(np, dup);
return 0;
}
child = np->child;
np->child = NULL;
mutex_lock(&of_mutex);
raw_spin_lock_irqsave(&devtree_lock, flags);
np->sibling = np->parent->child;
np->parent->child = np;
of_node_clear_flag(np, OF_DETACHED);
raw_spin_unlock_irqrestore(&devtree_lock, flags);
__of_attach_node_sysfs(np);
mutex_unlock(&of_mutex);
while (child) {
next = child->sibling;
attach_node_and_children(child);
child = next;
}
return 0;
}
/**
* selftest_data_add - Reads, copies data from
* linked tree and attaches it to the live tree
*/
static int __init selftest_data_add(void)
{
void *selftest_data;
struct device_node *selftest_data_node, *np;
extern uint8_t __dtb_testcases_begin[];
extern uint8_t __dtb_testcases_end[];
const int size = __dtb_testcases_end - __dtb_testcases_begin;
int rc;
if (!size) {
pr_warn("%s: No testcase data to attach; not running tests\n",
__func__);
return -ENODATA;
}
/* creating copy */
selftest_data = kmemdup(__dtb_testcases_begin, size, GFP_KERNEL);
if (!selftest_data) {
pr_warn("%s: Failed to allocate memory for selftest_data; "
"not running tests\n", __func__);
return -ENOMEM;
}
of_fdt_unflatten_tree(selftest_data, &selftest_data_node);
if (!selftest_data_node) {
pr_warn("%s: No tree to attach; not running tests\n", __func__);
return -ENODATA;
}
of_node_set_flag(selftest_data_node, OF_DETACHED);
rc = of_resolve_phandles(selftest_data_node);
if (rc) {
pr_err("%s: Failed to resolve phandles (rc=%i)\n", __func__, rc);
return -EINVAL;
}
if (!of_root) {
of_root = selftest_data_node;
for_each_of_allnodes(np)
__of_attach_node_sysfs(np);
of_aliases = of_find_node_by_path("/aliases");
of_chosen = of_find_node_by_path("/chosen");
return 0;
}
/* attach the sub-tree to live tree */
np = selftest_data_node->child;
while (np) {
struct device_node *next = np->sibling;
np->parent = of_root;
attach_node_and_children(np);
np = next;
}
return 0;
}
#ifdef CONFIG_OF_OVERLAY
static int selftest_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
if (np == NULL) {
dev_err(dev, "No OF data for device\n");
return -EINVAL;
}
dev_dbg(dev, "%s for node @%s\n", __func__, np->full_name);
of_platform_populate(np, NULL, NULL, &pdev->dev);
return 0;
}
static int selftest_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
dev_dbg(dev, "%s for node @%s\n", __func__, np->full_name);
return 0;
}
static struct of_device_id selftest_match[] = {
{ .compatible = "selftest", },
{},
};
static struct platform_driver selftest_driver = {
.probe = selftest_probe,
.remove = selftest_remove,
.driver = {
.name = "selftest",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(selftest_match),
},
};
/* get the platform device instantiated at the path */
static struct platform_device *of_path_to_platform_device(const char *path)
{
struct device_node *np;
struct platform_device *pdev;
np = of_find_node_by_path(path);
if (np == NULL)
return NULL;
pdev = of_find_device_by_node(np);
of_node_put(np);
return pdev;
}
/* find out if a platform device exists at that path */
static int of_path_platform_device_exists(const char *path)
{
struct platform_device *pdev;
pdev = of_path_to_platform_device(path);
platform_device_put(pdev);
return pdev != NULL;
}
#if IS_BUILTIN(CONFIG_I2C)
/* get the i2c client device instantiated at the path */
static struct i2c_client *of_path_to_i2c_client(const char *path)
{
struct device_node *np;
struct i2c_client *client;
np = of_find_node_by_path(path);
if (np == NULL)
return NULL;
client = of_find_i2c_device_by_node(np);
of_node_put(np);
return client;
}
/* find out if a i2c client device exists at that path */
static int of_path_i2c_client_exists(const char *path)
{
struct i2c_client *client;
client = of_path_to_i2c_client(path);
if (client)
put_device(&client->dev);
return client != NULL;
}
#else
static int of_path_i2c_client_exists(const char *path)
{
return 0;
}
#endif
enum overlay_type {
PDEV_OVERLAY,
I2C_OVERLAY
};
static int of_path_device_type_exists(const char *path,
enum overlay_type ovtype)
{
switch (ovtype) {
case PDEV_OVERLAY:
return of_path_platform_device_exists(path);
case I2C_OVERLAY:
return of_path_i2c_client_exists(path);
}
return 0;
}
static const char *selftest_path(int nr, enum overlay_type ovtype)
{
const char *base;
static char buf[256];
switch (ovtype) {
case PDEV_OVERLAY:
base = "/testcase-data/overlay-node/test-bus";
break;
case I2C_OVERLAY:
base = "/testcase-data/overlay-node/test-bus/i2c-test-bus";
break;
default:
buf[0] = '\0';
return buf;
}
snprintf(buf, sizeof(buf) - 1, "%s/test-selftest%d", base, nr);
buf[sizeof(buf) - 1] = '\0';
return buf;
}
static int of_selftest_device_exists(int selftest_nr, enum overlay_type ovtype)
{
const char *path;
path = selftest_path(selftest_nr, ovtype);
switch (ovtype) {
case PDEV_OVERLAY:
return of_path_platform_device_exists(path);
case I2C_OVERLAY:
return of_path_i2c_client_exists(path);
}
return 0;
}
static const char *overlay_path(int nr)
{
static char buf[256];
snprintf(buf, sizeof(buf) - 1,
"/testcase-data/overlay%d", nr);
buf[sizeof(buf) - 1] = '\0';
return buf;
}
static const char *bus_path = "/testcase-data/overlay-node/test-bus";
static int of_selftest_apply_overlay(int selftest_nr, int overlay_nr,
int *overlay_id)
{
struct device_node *np = NULL;
int ret, id = -1;
np = of_find_node_by_path(overlay_path(overlay_nr));
if (np == NULL) {
selftest(0, "could not find overlay node @\"%s\"\n",
overlay_path(overlay_nr));
ret = -EINVAL;
goto out;
}
ret = of_overlay_create(np);
if (ret < 0) {
selftest(0, "could not create overlay from \"%s\"\n",
overlay_path(overlay_nr));
goto out;
}
id = ret;
ret = 0;
out:
of_node_put(np);
if (overlay_id)
*overlay_id = id;
return ret;
}
/* apply an overlay while checking before and after states */
static int of_selftest_apply_overlay_check(int overlay_nr, int selftest_nr,
int before, int after, enum overlay_type ovtype)
{
int ret;
/* selftest device must not be in before state */
if (of_selftest_device_exists(selftest_nr, ovtype) != before) {
selftest(0, "overlay @\"%s\" with device @\"%s\" %s\n",
overlay_path(overlay_nr),
selftest_path(selftest_nr, ovtype),
!before ? "enabled" : "disabled");
return -EINVAL;
}
ret = of_selftest_apply_overlay(overlay_nr, selftest_nr, NULL);
if (ret != 0) {
/* of_selftest_apply_overlay already called selftest() */
return ret;
}
/* selftest device must be to set to after state */
if (of_selftest_device_exists(selftest_nr, ovtype) != after) {
selftest(0, "overlay @\"%s\" failed to create @\"%s\" %s\n",
overlay_path(overlay_nr),
selftest_path(selftest_nr, ovtype),
!after ? "enabled" : "disabled");
return -EINVAL;
}
return 0;
}
/* apply an overlay and then revert it while checking before, after states */
static int of_selftest_apply_revert_overlay_check(int overlay_nr,
int selftest_nr, int before, int after,
enum overlay_type ovtype)
{
int ret, ov_id;
/* selftest device must be in before state */
if (of_selftest_device_exists(selftest_nr, ovtype) != before) {
selftest(0, "overlay @\"%s\" with device @\"%s\" %s\n",
overlay_path(overlay_nr),
selftest_path(selftest_nr, ovtype),
!before ? "enabled" : "disabled");
return -EINVAL;
}
/* apply the overlay */
ret = of_selftest_apply_overlay(overlay_nr, selftest_nr, &ov_id);
if (ret != 0) {
/* of_selftest_apply_overlay already called selftest() */
return ret;
}
/* selftest device must be in after state */
if (of_selftest_device_exists(selftest_nr, ovtype) != after) {
selftest(0, "overlay @\"%s\" failed to create @\"%s\" %s\n",
overlay_path(overlay_nr),
selftest_path(selftest_nr, ovtype),
!after ? "enabled" : "disabled");
return -EINVAL;
}
ret = of_overlay_destroy(ov_id);
if (ret != 0) {
selftest(0, "overlay @\"%s\" failed to be destroyed @\"%s\"\n",
overlay_path(overlay_nr),
selftest_path(selftest_nr, ovtype));
return ret;
}
/* selftest device must be again in before state */
if (of_selftest_device_exists(selftest_nr, PDEV_OVERLAY) != before) {
selftest(0, "overlay @\"%s\" with device @\"%s\" %s\n",
overlay_path(overlay_nr),
selftest_path(selftest_nr, ovtype),
!before ? "enabled" : "disabled");
return -EINVAL;
}
return 0;
}
/* test activation of device */
static void of_selftest_overlay_0(void)
{
int ret;
/* device should enable */
ret = of_selftest_apply_overlay_check(0, 0, 0, 1, PDEV_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 0);
}
/* test deactivation of device */
static void of_selftest_overlay_1(void)
{
int ret;
/* device should disable */
ret = of_selftest_apply_overlay_check(1, 1, 1, 0, PDEV_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 1);
}
/* test activation of device */
static void of_selftest_overlay_2(void)
{
int ret;
/* device should enable */
ret = of_selftest_apply_overlay_check(2, 2, 0, 1, PDEV_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 2);
}
/* test deactivation of device */
static void of_selftest_overlay_3(void)
{
int ret;
/* device should disable */
ret = of_selftest_apply_overlay_check(3, 3, 1, 0, PDEV_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 3);
}
/* test activation of a full device node */
static void of_selftest_overlay_4(void)
{
int ret;
/* device should disable */
ret = of_selftest_apply_overlay_check(4, 4, 0, 1, PDEV_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 4);
}
/* test overlay apply/revert sequence */
static void of_selftest_overlay_5(void)
{
int ret;
/* device should disable */
ret = of_selftest_apply_revert_overlay_check(5, 5, 0, 1, PDEV_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 5);
}
/* test overlay application in sequence */
static void of_selftest_overlay_6(void)
{
struct device_node *np;
int ret, i, ov_id[2];
int overlay_nr = 6, selftest_nr = 6;
int before = 0, after = 1;
/* selftest device must be in before state */
for (i = 0; i < 2; i++) {
if (of_selftest_device_exists(selftest_nr + i, PDEV_OVERLAY)
!= before) {
selftest(0, "overlay @\"%s\" with device @\"%s\" %s\n",
overlay_path(overlay_nr + i),
selftest_path(selftest_nr + i,
PDEV_OVERLAY),
!before ? "enabled" : "disabled");
return;
}
}
/* apply the overlays */
for (i = 0; i < 2; i++) {
np = of_find_node_by_path(overlay_path(overlay_nr + i));
if (np == NULL) {
selftest(0, "could not find overlay node @\"%s\"\n",
overlay_path(overlay_nr + i));
return;
}
ret = of_overlay_create(np);
if (ret < 0) {
selftest(0, "could not create overlay from \"%s\"\n",
overlay_path(overlay_nr + i));
return;
}
ov_id[i] = ret;
}
for (i = 0; i < 2; i++) {
/* selftest device must be in after state */
if (of_selftest_device_exists(selftest_nr + i, PDEV_OVERLAY)
!= after) {
selftest(0, "overlay @\"%s\" failed @\"%s\" %s\n",
overlay_path(overlay_nr + i),
selftest_path(selftest_nr + i,
PDEV_OVERLAY),
!after ? "enabled" : "disabled");
return;
}
}
for (i = 1; i >= 0; i--) {
ret = of_overlay_destroy(ov_id[i]);
if (ret != 0) {
selftest(0, "overlay @\"%s\" failed destroy @\"%s\"\n",
overlay_path(overlay_nr + i),
selftest_path(selftest_nr + i,
PDEV_OVERLAY));
return;
}
}
for (i = 0; i < 2; i++) {
/* selftest device must be again in before state */
if (of_selftest_device_exists(selftest_nr + i, PDEV_OVERLAY)
!= before) {
selftest(0, "overlay @\"%s\" with device @\"%s\" %s\n",
overlay_path(overlay_nr + i),
selftest_path(selftest_nr + i,
PDEV_OVERLAY),
!before ? "enabled" : "disabled");
return;
}
}
selftest(1, "overlay test %d passed\n", 6);
}
/* test overlay application in sequence */
static void of_selftest_overlay_8(void)
{
struct device_node *np;
int ret, i, ov_id[2];
int overlay_nr = 8, selftest_nr = 8;
/* we don't care about device state in this test */
/* apply the overlays */
for (i = 0; i < 2; i++) {
np = of_find_node_by_path(overlay_path(overlay_nr + i));
if (np == NULL) {
selftest(0, "could not find overlay node @\"%s\"\n",
overlay_path(overlay_nr + i));
return;
}
ret = of_overlay_create(np);
if (ret < 0) {
selftest(0, "could not create overlay from \"%s\"\n",
overlay_path(overlay_nr + i));
return;
}
ov_id[i] = ret;
}
/* now try to remove first overlay (it should fail) */
ret = of_overlay_destroy(ov_id[0]);
if (ret == 0) {
selftest(0, "overlay @\"%s\" was destroyed @\"%s\"\n",
overlay_path(overlay_nr + 0),
selftest_path(selftest_nr,
PDEV_OVERLAY));
return;
}
/* removing them in order should work */
for (i = 1; i >= 0; i--) {
ret = of_overlay_destroy(ov_id[i]);
if (ret != 0) {
selftest(0, "overlay @\"%s\" not destroyed @\"%s\"\n",
overlay_path(overlay_nr + i),
selftest_path(selftest_nr,
PDEV_OVERLAY));
return;
}
}
selftest(1, "overlay test %d passed\n", 8);
}
/* test insertion of a bus with parent devices */
static void of_selftest_overlay_10(void)
{
int ret;
char *child_path;
/* device should disable */
ret = of_selftest_apply_overlay_check(10, 10, 0, 1, PDEV_OVERLAY);
if (selftest(ret == 0,
"overlay test %d failed; overlay application\n", 10))
return;
child_path = kasprintf(GFP_KERNEL, "%s/test-selftest101",
selftest_path(10, PDEV_OVERLAY));
if (selftest(child_path, "overlay test %d failed; kasprintf\n", 10))
return;
ret = of_path_device_type_exists(child_path, PDEV_OVERLAY);
kfree(child_path);
if (selftest(ret, "overlay test %d failed; no child device\n", 10))
return;
}
/* test insertion of a bus with parent devices (and revert) */
static void of_selftest_overlay_11(void)
{
int ret;
/* device should disable */
ret = of_selftest_apply_revert_overlay_check(11, 11, 0, 1,
PDEV_OVERLAY);
if (selftest(ret == 0,
"overlay test %d failed; overlay application\n", 11))
return;
}
#if IS_BUILTIN(CONFIG_I2C) && IS_ENABLED(CONFIG_OF_OVERLAY)
struct selftest_i2c_bus_data {
struct platform_device *pdev;
struct i2c_adapter adap;
};
static int selftest_i2c_master_xfer(struct i2c_adapter *adap,
struct i2c_msg *msgs, int num)
{
struct selftest_i2c_bus_data *std = i2c_get_adapdata(adap);
(void)std;
return num;
}
static u32 selftest_i2c_functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm selftest_i2c_algo = {
.master_xfer = selftest_i2c_master_xfer,
.functionality = selftest_i2c_functionality,
};
static int selftest_i2c_bus_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
struct selftest_i2c_bus_data *std;
struct i2c_adapter *adap;
int ret;
if (np == NULL) {
dev_err(dev, "No OF data for device\n");
return -EINVAL;
}
dev_dbg(dev, "%s for node @%s\n", __func__, np->full_name);
std = devm_kzalloc(dev, sizeof(*std), GFP_KERNEL);
if (!std) {
dev_err(dev, "Failed to allocate selftest i2c data\n");
return -ENOMEM;
}
/* link them together */
std->pdev = pdev;
platform_set_drvdata(pdev, std);
adap = &std->adap;
i2c_set_adapdata(adap, std);
adap->nr = -1;
strlcpy(adap->name, pdev->name, sizeof(adap->name));
adap->class = I2C_CLASS_DEPRECATED;
adap->algo = &selftest_i2c_algo;
adap->dev.parent = dev;
adap->dev.of_node = dev->of_node;
adap->timeout = 5 * HZ;
adap->retries = 3;
ret = i2c_add_numbered_adapter(adap);
if (ret != 0) {
dev_err(dev, "Failed to add I2C adapter\n");
return ret;
}
return 0;
}
static int selftest_i2c_bus_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
struct selftest_i2c_bus_data *std = platform_get_drvdata(pdev);
dev_dbg(dev, "%s for node @%s\n", __func__, np->full_name);
i2c_del_adapter(&std->adap);
return 0;
}
static struct of_device_id selftest_i2c_bus_match[] = {
{ .compatible = "selftest-i2c-bus", },
{},
};
static struct platform_driver selftest_i2c_bus_driver = {
.probe = selftest_i2c_bus_probe,
.remove = selftest_i2c_bus_remove,
.driver = {
.name = "selftest-i2c-bus",
.of_match_table = of_match_ptr(selftest_i2c_bus_match),
},
};
static int selftest_i2c_dev_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct device *dev = &client->dev;
struct device_node *np = client->dev.of_node;
if (!np) {
dev_err(dev, "No OF node\n");
return -EINVAL;
}
dev_dbg(dev, "%s for node @%s\n", __func__, np->full_name);
return 0;
};
static int selftest_i2c_dev_remove(struct i2c_client *client)
{
struct device *dev = &client->dev;
struct device_node *np = client->dev.of_node;
dev_dbg(dev, "%s for node @%s\n", __func__, np->full_name);
return 0;
}
static const struct i2c_device_id selftest_i2c_dev_id[] = {
{ .name = "selftest-i2c-dev" },
{ }
};
static struct i2c_driver selftest_i2c_dev_driver = {
.driver = {
.name = "selftest-i2c-dev",
.owner = THIS_MODULE,
},
.probe = selftest_i2c_dev_probe,
.remove = selftest_i2c_dev_remove,
.id_table = selftest_i2c_dev_id,
};
#if IS_BUILTIN(CONFIG_I2C_MUX)
struct selftest_i2c_mux_data {
int nchans;
struct i2c_adapter *adap[];
};
static int selftest_i2c_mux_select_chan(struct i2c_adapter *adap,
void *client, u32 chan)
{
return 0;
}
static int selftest_i2c_mux_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret, i, nchans, size;
struct device *dev = &client->dev;
struct i2c_adapter *adap = to_i2c_adapter(dev->parent);
struct device_node *np = client->dev.of_node, *child;
struct selftest_i2c_mux_data *stm;
u32 reg, max_reg;
dev_dbg(dev, "%s for node @%s\n", __func__, np->full_name);
if (!np) {
dev_err(dev, "No OF node\n");
return -EINVAL;
}
max_reg = (u32)-1;
for_each_child_of_node(np, child) {
ret = of_property_read_u32(child, "reg", ®);
if (ret)
continue;
if (max_reg == (u32)-1 || reg > max_reg)
max_reg = reg;
}
nchans = max_reg == (u32)-1 ? 0 : max_reg + 1;
if (nchans == 0) {
dev_err(dev, "No channels\n");
return -EINVAL;
}
size = offsetof(struct selftest_i2c_mux_data, adap[nchans]);
stm = devm_kzalloc(dev, size, GFP_KERNEL);
if (!stm) {
dev_err(dev, "Out of memory\n");
return -ENOMEM;
}
stm->nchans = nchans;
for (i = 0; i < nchans; i++) {
stm->adap[i] = i2c_add_mux_adapter(adap, dev, client,
0, i, 0, selftest_i2c_mux_select_chan, NULL);
if (!stm->adap[i]) {
dev_err(dev, "Failed to register mux #%d\n", i);
for (i--; i >= 0; i--)
i2c_del_mux_adapter(stm->adap[i]);
return -ENODEV;
}
}
i2c_set_clientdata(client, stm);
return 0;
};
static int selftest_i2c_mux_remove(struct i2c_client *client)
{
struct device *dev = &client->dev;
struct device_node *np = client->dev.of_node;
struct selftest_i2c_mux_data *stm = i2c_get_clientdata(client);
int i;
dev_dbg(dev, "%s for node @%s\n", __func__, np->full_name);
for (i = stm->nchans - 1; i >= 0; i--)
i2c_del_mux_adapter(stm->adap[i]);
return 0;
}
static const struct i2c_device_id selftest_i2c_mux_id[] = {
{ .name = "selftest-i2c-mux" },
{ }
};
static struct i2c_driver selftest_i2c_mux_driver = {
.driver = {
.name = "selftest-i2c-mux",
.owner = THIS_MODULE,
},
.probe = selftest_i2c_mux_probe,
.remove = selftest_i2c_mux_remove,
.id_table = selftest_i2c_mux_id,
};
#endif
static int of_selftest_overlay_i2c_init(void)
{
int ret;
ret = i2c_add_driver(&selftest_i2c_dev_driver);
if (selftest(ret == 0,
"could not register selftest i2c device driver\n"))
return ret;
ret = platform_driver_register(&selftest_i2c_bus_driver);
if (selftest(ret == 0,
"could not register selftest i2c bus driver\n"))
return ret;
#if IS_BUILTIN(CONFIG_I2C_MUX)
ret = i2c_add_driver(&selftest_i2c_mux_driver);
if (selftest(ret == 0,
"could not register selftest i2c mux driver\n"))
return ret;
#endif
return 0;
}
static void of_selftest_overlay_i2c_cleanup(void)
{
#if IS_BUILTIN(CONFIG_I2C_MUX)
i2c_del_driver(&selftest_i2c_mux_driver);
#endif
platform_driver_unregister(&selftest_i2c_bus_driver);
i2c_del_driver(&selftest_i2c_dev_driver);
}
static void of_selftest_overlay_i2c_12(void)
{
int ret;
/* device should enable */
ret = of_selftest_apply_overlay_check(12, 12, 0, 1, I2C_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 12);
}
/* test deactivation of device */
static void of_selftest_overlay_i2c_13(void)
{
int ret;
/* device should disable */
ret = of_selftest_apply_overlay_check(13, 13, 1, 0, I2C_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 13);
}
/* just check for i2c mux existence */
static void of_selftest_overlay_i2c_14(void)
{
}
static void of_selftest_overlay_i2c_15(void)
{
int ret;
/* device should enable */
ret = of_selftest_apply_overlay_check(16, 15, 0, 1, I2C_OVERLAY);
if (ret != 0)
return;
selftest(1, "overlay test %d passed\n", 15);
}
#else
static inline void of_selftest_overlay_i2c_14(void) { }
static inline void of_selftest_overlay_i2c_15(void) { }
#endif
static void __init of_selftest_overlay(void)
{
struct device_node *bus_np = NULL;
int ret;
ret = platform_driver_register(&selftest_driver);
if (ret != 0) {
selftest(0, "could not register selftest driver\n");
goto out;
}
bus_np = of_find_node_by_path(bus_path);
if (bus_np == NULL) {
selftest(0, "could not find bus_path \"%s\"\n", bus_path);
goto out;
}
ret = of_platform_populate(bus_np, of_default_bus_match_table,
NULL, NULL);
if (ret != 0) {
selftest(0, "could not populate bus @ \"%s\"\n", bus_path);
goto out;
}
if (!of_selftest_device_exists(100, PDEV_OVERLAY)) {
selftest(0, "could not find selftest0 @ \"%s\"\n",
selftest_path(100, PDEV_OVERLAY));
goto out;
}
if (of_selftest_device_exists(101, PDEV_OVERLAY)) {
selftest(0, "selftest1 @ \"%s\" should not exist\n",
selftest_path(101, PDEV_OVERLAY));
goto out;
}
selftest(1, "basic infrastructure of overlays passed");
/* tests in sequence */
of_selftest_overlay_0();
of_selftest_overlay_1();
of_selftest_overlay_2();
of_selftest_overlay_3();
of_selftest_overlay_4();
of_selftest_overlay_5();
of_selftest_overlay_6();
of_selftest_overlay_8();
of_selftest_overlay_10();
of_selftest_overlay_11();
#if IS_BUILTIN(CONFIG_I2C)
if (selftest(of_selftest_overlay_i2c_init() == 0, "i2c init failed\n"))
goto out;
of_selftest_overlay_i2c_12();
of_selftest_overlay_i2c_13();
of_selftest_overlay_i2c_14();
of_selftest_overlay_i2c_15();
of_selftest_overlay_i2c_cleanup();
#endif
out:
of_node_put(bus_np);
}
#else
static inline void __init of_selftest_overlay(void) { }
#endif
static int __init of_selftest(void)
{
struct device_node *np;
int res;
/* adding data for selftest */
res = selftest_data_add();
if (res)
return res;
if (!of_aliases)
of_aliases = of_find_node_by_path("/aliases");
np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a");
if (!np) {
pr_info("No testcase data in device tree; not running tests\n");
return 0;
}
of_node_put(np);
pr_info("start of selftest - you will see error messages\n");
of_selftest_check_tree_linkage();
of_selftest_check_phandles();
of_selftest_find_node_by_name();
of_selftest_dynamic();
of_selftest_parse_phandle_with_args();
of_selftest_property_string();
of_selftest_property_copy();
of_selftest_changeset();
of_selftest_parse_interrupts();
of_selftest_parse_interrupts_extended();
of_selftest_match_node();
of_selftest_platform_populate();
of_selftest_overlay();
/* Double check linkage after removing testcase data */
of_selftest_check_tree_linkage();
pr_info("end of selftest - %i passed, %i failed\n",
selftest_results.passed, selftest_results.failed);
return 0;
}
late_initcall(of_selftest);
| {
"language": "C"
} |
/*-
* Copyright (c) 2016 Michal Meloun <mmel@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/bus.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/malloc.h>
#include <sys/rman.h>
#include <machine/bus.h>
#include <machine/fdt.h>
#include <dev/extres/hwreset/hwreset.h>
#include <dev/extres/phy/phy.h>
#include <dev/fdt/fdt_common.h>
#include <dev/fdt/fdt_pinctrl.h>
#include <dev/ofw/openfirm.h>
#include <dev/ofw/ofw_bus.h>
#include <dev/ofw/ofw_bus_subr.h>
#include <gnu/dts/include/dt-bindings/pinctrl/pinctrl-tegra-xusb.h>
#include "phy_if.h"
#define XUSB_PADCTL_USB2_PAD_MUX 0x004
#define XUSB_PADCTL_ELPG_PROGRAM 0x01C
#define ELPG_PROGRAM_AUX_MUX_LP0_VCORE_DOWN (1 << 26)
#define ELPG_PROGRAM_AUX_MUX_LP0_CLAMP_EN_EARLY (1 << 25)
#define ELPG_PROGRAM_AUX_MUX_LP0_CLAMP_EN (1 << 24)
#define XUSB_PADCTL_IOPHY_PLL_P0_CTL1 0x040
#define IOPHY_PLL_P0_CTL1_PLL0_LOCKDET (1 << 19)
#define IOPHY_PLL_P0_CTL1_REFCLK_SEL_MASK (0xf<< 12)
#define IOPHY_PLL_P0_CTL1_PLL_RST (1 << 1)
#define XUSB_PADCTL_IOPHY_PLL_P0_CTL2 0x044
#define IOPHY_PLL_P0_CTL2_REFCLKBUF_EN (1 << 6)
#define IOPHY_PLL_P0_CTL2_TXCLKREF_EN (1 << 5)
#define IOPHY_PLL_P0_CTL2_TXCLKREF_SEL (1 << 4)
#define XUSB_PADCTL_USB3_PAD_MUX 0x134
#define XUSB_PADCTL_IOPHY_PLL_S0_CTL1 0x138
#define IOPHY_PLL_S0_CTL1_PLL1_LOCKDET (1 << 27)
#define IOPHY_PLL_S0_CTL1_PLL1_MODE (1 << 24)
#define IOPHY_PLL_S0_CTL1_PLL_PWR_OVRD (1 << 3)
#define IOPHY_PLL_S0_CTL1_PLL_RST_L (1 << 1)
#define IOPHY_PLL_S0_CTL1_PLL_IDDQ (1 << 0)
#define XUSB_PADCTL_IOPHY_PLL_S0_CTL2 0x13C
#define XUSB_PADCTL_IOPHY_PLL_S0_CTL3 0x140
#define XUSB_PADCTL_IOPHY_PLL_S0_CTL4 0x144
#define XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL1 0x148
#define IOPHY_MISC_PAD_S0_CTL1_IDDQ_OVRD (1 << 1)
#define IOPHY_MISC_PAD_S0_CTL1_IDDQ (1 << 0)
#define XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL2 0x14C
#define XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL3 0x150
#define XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL4 0x154
#define XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL5 0x158
#define XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL6 0x15C
struct lane_cfg {
char *function;
char **lanes;
int iddq;
};
struct xusbpadctl_softc {
device_t dev;
struct resource *mem_res;
hwreset_t rst;
int phy_ena_cnt;
};
static struct ofw_compat_data compat_data[] = {
{"nvidia,tegra124-xusb-padctl", 1},
{NULL, 0},
};
struct padctl_lane {
const char *name;
bus_size_t reg;
uint32_t shift;
uint32_t mask;
int iddq;
char **mux;
int nmux;
};
static char *otg_mux[] = {"snps", "xusb", "uart", "rsvd"};
static char *usb_mux[] = {"snps", "xusb"};
static char *pci_mux[] = {"pcie", "usb3", "sata", "rsvd"};
#define LANE(n, r, s, m, i, mx) \
{ \
.name = n, \
.reg = r, \
.shift = s, \
.mask = m, \
.iddq = i, \
.mux = mx, \
.nmux = nitems(mx), \
}
static const struct padctl_lane lanes_tbl[] = {
LANE("otg-0", XUSB_PADCTL_USB2_PAD_MUX, 0, 0x3, -1, otg_mux),
LANE("otg-1", XUSB_PADCTL_USB2_PAD_MUX, 2, 0x3, -1, otg_mux),
LANE("otg-2", XUSB_PADCTL_USB2_PAD_MUX, 4, 0x3, -1, otg_mux),
LANE("ulpi-0", XUSB_PADCTL_USB2_PAD_MUX, 12, 0x1, -1, usb_mux),
LANE("hsic-0", XUSB_PADCTL_USB2_PAD_MUX, 14, 0x1, -1, usb_mux),
LANE("hsic-1", XUSB_PADCTL_USB2_PAD_MUX, 15, 0x1, -1, usb_mux),
LANE("pcie-0", XUSB_PADCTL_USB3_PAD_MUX, 16, 0x3, 1, pci_mux),
LANE("pcie-1", XUSB_PADCTL_USB3_PAD_MUX, 18, 0x3, 2, pci_mux),
LANE("pcie-2", XUSB_PADCTL_USB3_PAD_MUX, 20, 0x3, 3, pci_mux),
LANE("pcie-3", XUSB_PADCTL_USB3_PAD_MUX, 22, 0x3, 4, pci_mux),
LANE("pcie-4", XUSB_PADCTL_USB3_PAD_MUX, 24, 0x3, 5, pci_mux),
LANE("sata-0", XUSB_PADCTL_USB3_PAD_MUX, 26, 0x3, 6, pci_mux),
};
static int
xusbpadctl_mux_function(const struct padctl_lane *lane, char *fnc_name)
{
int i;
for (i = 0; i < lane->nmux; i++) {
if (strcmp(fnc_name, lane->mux[i]) == 0)
return (i);
}
return (-1);
}
static int
xusbpadctl_config_lane(struct xusbpadctl_softc *sc, char *lane_name,
const struct padctl_lane *lane, struct lane_cfg *cfg)
{
int tmp;
uint32_t reg;
reg = bus_read_4(sc->mem_res, lane->reg);
if (cfg->function != NULL) {
tmp = xusbpadctl_mux_function(lane, cfg->function);
if (tmp == -1) {
device_printf(sc->dev,
"Unknown function %s for lane %s\n", cfg->function,
lane_name);
return (EINVAL);
}
reg &= ~(lane->mask << lane->shift);
reg |= (tmp & lane->mask) << lane->shift;
}
if (cfg->iddq != -1) {
if (lane->iddq == -1) {
device_printf(sc->dev, "Invalid IDDQ for lane %s\n",
lane_name);
return (EINVAL);
}
if (cfg->iddq != 0)
reg &= ~(1 << lane->iddq);
else
reg |= 1 << lane->iddq;
}
bus_write_4(sc->mem_res, lane->reg, reg);
return (0);
}
static const struct padctl_lane *
xusbpadctl_search_lane(char *lane_name)
{
int i;
for (i = 0; i < nitems(lanes_tbl); i++) {
if (strcmp(lane_name, lanes_tbl[i].name) == 0)
return (&lanes_tbl[i]);
}
return (NULL);
}
static int
xusbpadctl_config_node(struct xusbpadctl_softc *sc, char *lane_name,
struct lane_cfg *cfg)
{
const struct padctl_lane *lane;
int rv;
lane = xusbpadctl_search_lane(lane_name);
if (lane == NULL) {
device_printf(sc->dev, "Unknown lane: %s\n", lane_name);
return (ENXIO);
}
rv = xusbpadctl_config_lane(sc, lane_name, lane, cfg);
return (rv);
}
static int
xusbpadctl_read_node(struct xusbpadctl_softc *sc, phandle_t node,
struct lane_cfg *cfg, char **lanes, int *llanes)
{
int rv;
*llanes = OF_getprop_alloc(node, "nvidia,lanes", 1, (void **)lanes);
if (*llanes <= 0)
return (ENOENT);
/* Read function (mux) settings. */
rv = OF_getprop_alloc(node, "nvidia,function", 1,
(void **)&cfg->function);
if (rv <= 0)
cfg->function = NULL;
/* Read numeric properties. */
rv = OF_getencprop(node, "nvidia,iddq", &cfg->iddq,
sizeof(cfg->iddq));
if (rv <= 0)
cfg->iddq = -1;
return (0);
}
static int
xusbpadctl_process_node(struct xusbpadctl_softc *sc, phandle_t node)
{
struct lane_cfg cfg;
char *lanes, *lname;
int i, len, llanes, rv;
rv = xusbpadctl_read_node(sc, node, &cfg, &lanes, &llanes);
if (rv != 0)
return (rv);
len = 0;
lname = lanes;
do {
i = strlen(lname) + 1;
rv = xusbpadctl_config_node(sc, lname, &cfg);
if (rv != 0)
device_printf(sc->dev,
"Cannot configure lane: %s: %d\n", lname, rv);
len += i;
lname += i;
} while (len < llanes);
if (lanes != NULL)
OF_prop_free(lanes);
if (cfg.function != NULL)
OF_prop_free(cfg.function);
return (rv);
}
static int
xusbpadctl_pinctrl_cfg(device_t dev, phandle_t cfgxref)
{
struct xusbpadctl_softc *sc;
phandle_t node, cfgnode;
int rv;
sc = device_get_softc(dev);
cfgnode = OF_node_from_xref(cfgxref);
rv = 0;
for (node = OF_child(cfgnode); node != 0; node = OF_peer(node)) {
if (!fdt_is_enabled(node))
continue;
rv = xusbpadctl_process_node(sc, node);
if (rv != 0)
return (rv);
}
return (rv);
}
static int
xusbpadctl_phy_pcie_powerup(struct xusbpadctl_softc *sc)
{
uint32_t reg;
int i;
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL1);
reg &= ~IOPHY_PLL_P0_CTL1_REFCLK_SEL_MASK;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL1, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL2);
reg |= IOPHY_PLL_P0_CTL2_REFCLKBUF_EN;
reg |= IOPHY_PLL_P0_CTL2_TXCLKREF_EN;
reg |= IOPHY_PLL_P0_CTL2_TXCLKREF_SEL;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL2, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL1);
reg |= IOPHY_PLL_P0_CTL1_PLL_RST;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL1, reg);
DELAY(100);
for (i = 0; i < 100; i++) {
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL1);
if (reg & IOPHY_PLL_P0_CTL1_PLL0_LOCKDET)
return (0);
DELAY(10);
}
return (ETIMEDOUT);
}
static int
xusbpadctl_phy_pcie_powerdown(struct xusbpadctl_softc *sc)
{
uint32_t reg;
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL1);
reg &= ~IOPHY_PLL_P0_CTL1_PLL_RST;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_P0_CTL1, reg);
DELAY(100);
return (0);
}
static int
xusbpadctl_phy_sata_powerup(struct xusbpadctl_softc *sc)
{
uint32_t reg;
int i;
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL1);
reg &= ~IOPHY_MISC_PAD_S0_CTL1_IDDQ_OVRD;
reg &= ~IOPHY_MISC_PAD_S0_CTL1_IDDQ;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL1, reg);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1);
reg &= ~IOPHY_PLL_S0_CTL1_PLL_PWR_OVRD;
reg &= ~IOPHY_PLL_S0_CTL1_PLL_IDDQ;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1, reg);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1);
reg |= IOPHY_PLL_S0_CTL1_PLL1_MODE;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1, reg);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1);
reg |= IOPHY_PLL_S0_CTL1_PLL_RST_L;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1, reg);
for (i = 100; i >= 0; i--) {
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1);
if (reg & IOPHY_PLL_S0_CTL1_PLL1_LOCKDET)
break;
DELAY(100);
}
if (i <= 0) {
device_printf(sc->dev, "Failed to power up SATA phy\n");
return (ETIMEDOUT);
}
return (0);
}
static int
xusbpadctl_phy_sata_powerdown(struct xusbpadctl_softc *sc)
{
uint32_t reg;
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1);
reg &= ~IOPHY_PLL_S0_CTL1_PLL_RST_L;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1);
reg &= ~IOPHY_PLL_S0_CTL1_PLL1_MODE;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1);
reg |= IOPHY_PLL_S0_CTL1_PLL_PWR_OVRD;
reg |= IOPHY_PLL_S0_CTL1_PLL_IDDQ;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_PLL_S0_CTL1, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL1);
reg |= IOPHY_MISC_PAD_S0_CTL1_IDDQ_OVRD;
reg |= IOPHY_MISC_PAD_S0_CTL1_IDDQ;
bus_write_4(sc->mem_res, XUSB_PADCTL_IOPHY_MISC_PAD_S0_CTL1, reg);
DELAY(100);
return (0);
}
static int
xusbpadctl_phy_powerup(struct xusbpadctl_softc *sc)
{
uint32_t reg;
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM);
reg &= ~ELPG_PROGRAM_AUX_MUX_LP0_CLAMP_EN;
bus_write_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM);
reg &= ~ELPG_PROGRAM_AUX_MUX_LP0_CLAMP_EN_EARLY;
bus_write_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM);
reg &= ~ELPG_PROGRAM_AUX_MUX_LP0_VCORE_DOWN;
bus_write_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM, reg);
DELAY(100);
return (0);
}
static int
xusbpadctl_phy_powerdown(struct xusbpadctl_softc *sc)
{
uint32_t reg;
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM);
reg |= ELPG_PROGRAM_AUX_MUX_LP0_VCORE_DOWN;
bus_write_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM);
reg |= ELPG_PROGRAM_AUX_MUX_LP0_CLAMP_EN_EARLY;
bus_write_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM, reg);
DELAY(100);
reg = bus_read_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM);
reg |= ELPG_PROGRAM_AUX_MUX_LP0_CLAMP_EN;
bus_write_4(sc->mem_res, XUSB_PADCTL_ELPG_PROGRAM, reg);
DELAY(100);
return (0);
}
static int
xusbpadctl_phy_enable(device_t dev, intptr_t id, bool enable)
{
struct xusbpadctl_softc *sc;
int rv;
sc = device_get_softc(dev);
if ((id != TEGRA_XUSB_PADCTL_PCIE) &&
(id != TEGRA_XUSB_PADCTL_SATA)) {
device_printf(dev, "Unknown phy: %d\n", id);
return (ENXIO);
}
rv = 0;
if (enable) {
if (sc->phy_ena_cnt == 0) {
rv = xusbpadctl_phy_powerup(sc);
if (rv != 0)
return (rv);
}
sc->phy_ena_cnt++;
}
if (id == TEGRA_XUSB_PADCTL_PCIE) {
if (enable)
rv = xusbpadctl_phy_pcie_powerup(sc);
else
rv = xusbpadctl_phy_pcie_powerdown(sc);
if (rv != 0)
return (rv);
} else if (id == TEGRA_XUSB_PADCTL_SATA) {
if (enable)
rv = xusbpadctl_phy_sata_powerup(sc);
else
rv = xusbpadctl_phy_sata_powerdown(sc);
if (rv != 0)
return (rv);
}
if (!enable) {
if (sc->phy_ena_cnt == 1) {
rv = xusbpadctl_phy_powerdown(sc);
if (rv != 0)
return (rv);
}
sc->phy_ena_cnt--;
}
return (0);
}
static int
xusbpadctl_probe(device_t dev)
{
if (!ofw_bus_status_okay(dev))
return (ENXIO);
if (!ofw_bus_search_compatible(dev, compat_data)->ocd_data)
return (ENXIO);
device_set_desc(dev, "Tegra XUSB phy");
return (BUS_PROBE_DEFAULT);
}
static int
xusbpadctl_detach(device_t dev)
{
/* This device is always present. */
return (EBUSY);
}
static int
xusbpadctl_attach(device_t dev)
{
struct xusbpadctl_softc * sc;
int rid, rv;
phandle_t node;
sc = device_get_softc(dev);
sc->dev = dev;
rid = 0;
sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
RF_ACTIVE);
if (sc->mem_res == NULL) {
device_printf(dev, "Cannot allocate memory resources\n");
return (ENXIO);
}
node = ofw_bus_get_node(dev);
rv = hwreset_get_by_ofw_name(dev, "padctl", &sc->rst);
if (rv != 0) {
device_printf(dev, "Cannot get 'padctl' reset: %d\n", rv);
return (rv);
}
rv = hwreset_deassert(sc->rst);
if (rv != 0) {
device_printf(dev, "Cannot unreset 'padctl' reset: %d\n", rv);
return (rv);
}
/* Register as a pinctrl device and use default configuration */
fdt_pinctrl_register(dev, NULL);
fdt_pinctrl_configure_by_name(dev, "default");
phy_register_provider(dev);
return (0);
}
static device_method_t tegra_xusbpadctl_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, xusbpadctl_probe),
DEVMETHOD(device_attach, xusbpadctl_attach),
DEVMETHOD(device_detach, xusbpadctl_detach),
/* fdt_pinctrl interface */
DEVMETHOD(fdt_pinctrl_configure, xusbpadctl_pinctrl_cfg),
/* phy interface */
DEVMETHOD(phy_enable, xusbpadctl_phy_enable),
DEVMETHOD_END
};
static driver_t tegra_xusbpadctl_driver = {
"tegra_xusbpadctl",
tegra_xusbpadctl_methods,
sizeof(struct xusbpadctl_softc),
};
static devclass_t tegra_xusbpadctl_devclass;
EARLY_DRIVER_MODULE(tegra_xusbpadctl, simplebus, tegra_xusbpadctl_driver,
tegra_xusbpadctl_devclass, 0, 0, 73);
| {
"language": "C"
} |
/* Copyright 2020
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "keymap.h"
// clang-format off
/*
* ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐
* │ ` │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 0 │ ' │ + │ │
* ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤
* │ │ Љ │ Њ │ Е │ Р │ Т │ З │ У │ И │ О │ П │ Ш │ Ђ │ │
* ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┐ │
* │ │ А │ С │ Д │ Ф │ Г │ Х │ Ј │ К │ Л │ Ч │ Ћ │ Ж │ │
* ├────┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴───┴────┤
* │ │ < │ Ѕ │ Џ │ Ц │ В │ Б │ Н │ М │ , │ . │ - │ │
* ├────┼───┴┬──┴─┬─┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤
* │ │ │ │ │ │ │ │ │
* └────┴────┴────┴────────────────────────┴────┴────┴────┴────┘
*/
// Row 1
#define RS_GRV KC_GRV // `
#define RS_1 KC_1 // 1
#define RS_2 KC_2 // 2
#define RS_3 KC_3 // 3
#define RS_4 KC_4 // 4
#define RS_5 KC_5 // 5
#define RS_6 KC_6 // 6
#define RS_7 KC_7 // 7
#define RS_8 KC_8 // 8
#define RS_9 KC_9 // 9
#define RS_0 KC_0 // 0
#define RS_QUOT KC_MINS // ' (dead)
#define RS_PLUS KC_EQL // +
// Row 2
#define RS_LJE KC_Q // Љ
#define RS_NJE KC_W // Њ
#define RS_IE KC_E // Е
#define RS_ER KC_R // Р
#define RS_TE KC_T // Т
#define RS_ZE KC_Y // З
#define RS_U KC_U // У
#define RS_I KC_I // И
#define RS_O KC_O // О
#define RS_PE KC_P // П
#define RS_SHA KC_LBRC // Ш
#define RS_DJE KC_RBRC // Ђ
// Row 3
#define RS_A KC_A // А
#define RS_ES KC_S // С
#define RS_DE KC_D // Д
#define RS_EF KC_F // Ф
#define RS_GHE KC_G // Г
#define RS_HA KC_H // Х
#define RS_JE KC_J // Ј
#define RS_KA KC_K // К
#define RS_EL KC_L // Л
#define RS_CHE KC_SCLN // Ч
#define RS_TSHE KC_QUOT // Ћ
#define RS_ZHE KC_NUHS // Ж
// Row 4
#define RS_LABK KC_NUBS // <
#define RS_DZE KC_Z // Ѕ
#define RS_DZHE KC_X // Џ
#define RS_TSE KC_C // Ц
#define RS_VE KC_V // В
#define RS_BE KC_B // Б
#define RS_EN KC_N // Н
#define RS_EM KC_M // М
#define RS_COMM KC_COMM // ,
#define RS_DOT KC_DOT // .
#define RS_MINS KC_SLSH // -
/* Shifted symbols
* ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐
* │ ~ │ ! │ " │ # │ $ │ % │ & │ / │ ( │ ) │ = │ ? │ * │ │
* ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤
* │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
* ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┐ │
* │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
* ├────┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴───┴────┤
* │ │ > │ │ │ │ │ │ │ │ ; │ : │ _ │ │
* ├────┼───┴┬──┴─┬─┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤
* │ │ │ │ │ │ │ │ │
* └────┴────┴────┴────────────────────────┴────┴────┴────┴────┘
*/
// Row 1
#define RS_TILD S(RS_GRV) // ~
#define RS_EXLM S(RS_1) // !
#define RS_DQUO S(RS_2) // "
#define RS_HASH S(RS_3) // #
#define RS_DLR S(RS_4) // $
#define RS_PERC S(RS_5) // %
#define RS_AMPR S(RS_6) // &
#define RS_SLSH S(RS_7) // /
#define RS_LPRN S(RS_8) // (
#define RS_RPRN S(RS_9) // )
#define RS_EQL S(RS_0) // =
#define RS_QUES S(RS_QUOT) // ?
#define RS_ASTR S(RS_PLUS) // *
// Row 4
#define RS_RABK S(RS_LABK) // >
#define RS_SCLN S(RS_COMM) // ;
#define RS_COLN S(RS_DOT) // :
#define RS_UNDS S(RS_MINS) // _
/* AltGr symbols
* ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐
* │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
* ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤
* │ │ │ │ € │ │ │ │ │ │ │ │ │ │ │
* ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┐ │
* │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
* ├────┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴───┴────┤
* │ │ │ │ │ │ │ │ │ │ │ │ │ │
* ├────┼───┴┬──┴─┬─┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤
* │ │ │ │ │ │ │ │ │
* └────┴────┴────┴────────────────────────┴────┴────┴────┴────┘
*/
// Row 2
#define RS_EURO ALGR(RS_IE) // €
| {
"language": "C"
} |
Support wincrypt for password encryption on Cygwin.
From: David Rothenberger <daveroth@acm.org>
---
build.conf | 5 +++++
subversion/include/svn_auth.h | 2 +-
subversion/libsvn_subr/auth.c | 2 +-
subversion/libsvn_subr/config_file.c | 2 +-
subversion/libsvn_subr/win32_crypto.c | 5 ++++-
subversion/tests/libsvn_subr/auth-test.c | 6 ++++--
6 files changed, 16 insertions(+), 6 deletions(-)
diff --git a/build.conf b/build.conf
index 33084f7..9222e57 100644
--- a/build.conf
+++ b/build.conf
@@ -376,6 +376,7 @@ path = subversion/libsvn_subr
sources = *.c lz4/*.c
libs = aprutil apriconv apr xml zlib apr_memcache
sqlite magic intl lz4 utf8proc macos-plist macos-keychain
+ wincrypt
msvc-libs = kernel32.lib advapi32.lib shfolder.lib ole32.lib
crypt32.lib version.lib
msvc-export =
@@ -1549,6 +1550,10 @@ type = lib
external-lib = $(SVN_FS_LIB_LINK)
libs = libsvn_fs_base libsvn_fs_fs libsvn_fs_x
+[wincrypt]
+type = lib
+external-lib = -lcrypt32
+
[__ALL__]
type = project
path = build/win32
diff --git a/subversion/include/svn_auth.h b/subversion/include/svn_auth.h
index ca3b703..7c3c56b 100644
--- a/subversion/include/svn_auth.h
+++ b/subversion/include/svn_auth.h
@@ -865,7 +865,7 @@ svn_auth_get_platform_specific_client_providers(
svn_config_t *config,
apr_pool_t *pool);
-#if (defined(WIN32) && !defined(__MINGW32__)) || defined(DOXYGEN)
+#if ((defined(WIN32) && !defined(__MINGW32__)) || defined(__CYGWIN__)) || defined(DOXYGEN)
/**
* Set @a *provider to an authentication provider of type @c
* svn_auth_cred_simple_t that gets/sets information from the user's
diff --git a/subversion/libsvn_subr/auth.c b/subversion/libsvn_subr/auth.c
index 9d58c73..ae1957e 100644
--- a/subversion/libsvn_subr/auth.c
+++ b/subversion/libsvn_subr/auth.c
@@ -578,7 +578,7 @@ svn_auth_get_platform_specific_provider(svn_auth_provider_object_t **provider,
}
#endif
-#if defined(WIN32) && !defined(__MINGW32__)
+#if (defined(WIN32) && !defined(__MINGW32__)) || defined(__CYGWIN__)
if (strcmp(provider_name, "windows") == 0 &&
strcmp(provider_type, "simple") == 0)
{
diff --git a/subversion/libsvn_subr/config_file.c b/subversion/libsvn_subr/config_file.c
index 9c0a83a..a6863a6 100644
--- a/subversion/libsvn_subr/config_file.c
+++ b/subversion/libsvn_subr/config_file.c
@@ -1371,7 +1371,7 @@ svn_config_ensure(const char *config_dir, apr_pool_t *pool)
"### windows-cryptoapi (Windows)" NL
#ifdef SVN_HAVE_KEYCHAIN_SERVICES
"# password-stores = keychain" NL
-#elif defined(WIN32) && !defined(__MINGW32__)
+#elif (defined(WIN32) && !defined(__MINGW32__)) || defined(__CYGWIN__)
"# password-stores = windows-cryptoapi" NL
#else
"# password-stores = gpg-agent,gnome-keyring,kwallet" NL
diff --git a/subversion/libsvn_subr/win32_crypto.c b/subversion/libsvn_subr/win32_crypto.c
index deead9f..f688676 100644
--- a/subversion/libsvn_subr/win32_crypto.c
+++ b/subversion/libsvn_subr/win32_crypto.c
@@ -26,7 +26,7 @@ typedef int win32_crypto__dummy;
/* ==================================================================== */
-#if defined(WIN32) && !defined(__MINGW32__)
+#if (defined(WIN32) && !defined(__MINGW32__)) || defined(__CYGWIN__)
/*** Includes. ***/
@@ -45,6 +45,9 @@ typedef int win32_crypto__dummy;
#include "svn_private_config.h"
+#ifdef __CYGWIN__
+#include <windows.h>
+#endif
#include <wincrypt.h>
diff --git a/subversion/tests/libsvn_subr/auth-test.c b/subversion/tests/libsvn_subr/auth-test.c
index c184442..383b572 100644
--- a/subversion/tests/libsvn_subr/auth-test.c
+++ b/subversion/tests/libsvn_subr/auth-test.c
@@ -62,7 +62,7 @@ test_platform_specific_auth_providers(apr_pool_t *pool)
#ifdef SVN_HAVE_KEYCHAIN_SERVICES
number_of_providers += 2;
#endif
-#if defined(WIN32) && !defined(__MINGW32__)
+#if (defined(WIN32) && !defined(__MINGW32__)) || defined(__CYGWIN__)
number_of_providers += 4;
#endif
if (providers->nelts != number_of_providers)
@@ -104,7 +104,7 @@ test_platform_specific_auth_providers(apr_pool_t *pool)
#endif
/* Test Windows auth providers */
-#if defined(WIN32) && !defined(__MINGW32__)
+#if (defined(WIN32) && !defined(__MINGW32__)) || defined(__CYGWIN__)
svn_auth_get_platform_specific_provider(&provider, "windows",
"simple", pool);
@@ -165,6 +165,7 @@ test_platform_specific_auth_providers(apr_pool_t *pool)
"'ssl_client_cert_pw') should not return NULL");
/* Make sure you do not get a Windows auth provider */
+#ifndef __CYGWIN__
SVN_ERR(svn_auth_get_platform_specific_provider(&provider, "windows",
"simple", pool));
@@ -173,6 +174,7 @@ test_platform_specific_auth_providers(apr_pool_t *pool)
(SVN_ERR_TEST_FAILED, NULL,
"svn_auth_get_platform_specific_provider('windows', 'simple') should " \
"return NULL");
+#endif
#endif
/* Test KWallet auth providers */
| {
"language": "C"
} |
/*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
#include "mpidimpl.h"
#include "ofi_impl.h"
#include "mpidu_bc.h"
#include "ofi_noinline.h"
int MPIDI_OFI_mpi_comm_commit_pre_hook(MPIR_Comm * comm)
{
int mpi_errno = MPI_SUCCESS;
MPIR_FUNC_VERBOSE_STATE_DECL(MPID_STATE_MPIDI_OFI_MPI_COMM_COMMIT_PRE_HOOK);
MPIR_FUNC_VERBOSE_ENTER(MPID_STATE_MPIDI_OFI_MPI_COMM_COMMIT_PRE_HOOK);
MPIDIU_map_create(&MPIDI_OFI_COMM(comm).huge_send_counters, MPL_MEM_COMM);
MPIDIU_map_create(&MPIDI_OFI_COMM(comm).huge_recv_counters, MPL_MEM_COMM);
/* no connection for non-dynamic or non-root-rank of intercomm */
MPIDI_OFI_COMM(comm).conn_id = -1;
/* eagain defaults to off */
if (comm->hints[MPIR_COMM_HINT_EAGAIN] == 0) {
comm->hints[MPIR_COMM_HINT_EAGAIN] = FALSE;
}
fn_exit:
MPIR_FUNC_VERBOSE_EXIT(MPID_STATE_MPIDI_OFI_MPI_COMM_COMMIT_PRE_HOOK);
return mpi_errno;
fn_fail:
goto fn_exit;
}
int MPIDI_OFI_mpi_comm_commit_post_hook(MPIR_Comm * comm)
{
int mpi_errno = MPI_SUCCESS;
MPIR_FUNC_VERBOSE_STATE_DECL(MPID_STATE_MPIDI_OFI_MPI_COMM_COMMIT_POST_HOOK);
MPIR_FUNC_VERBOSE_ENTER(MPID_STATE_MPIDI_OFI_MPI_COMM_COMMIT_POST_HOOK);
fn_exit:
MPIR_FUNC_VERBOSE_EXIT(MPID_STATE_MPIDI_OFI_MPI_COMM_COMMIT_POST_HOOK);
return mpi_errno;
fn_fail:
goto fn_exit;
}
int MPIDI_OFI_mpi_comm_free_hook(MPIR_Comm * comm)
{
int mpi_errno = MPI_SUCCESS;
MPIR_FUNC_VERBOSE_STATE_DECL(MPID_STATE_MPIDI_OFI_MPI_COMM_FREE_HOOK);
MPIR_FUNC_VERBOSE_ENTER(MPID_STATE_MPIDI_OFI_MPI_COMM_FREE_HOOK);
MPIDIU_map_destroy(MPIDI_OFI_COMM(comm).huge_send_counters);
MPIDIU_map_destroy(MPIDI_OFI_COMM(comm).huge_recv_counters);
MPIR_FUNC_VERBOSE_EXIT(MPID_STATE_MPIDI_OFI_MPI_COMM_FREE_HOOK);
return mpi_errno;
}
| {
"language": "C"
} |
#include "license_pbs.h" /* See here for the software license */
#ifndef _REQ_DELETEARRAY_CT_H
#define _REQ_DELETEARRAY_CT_H
#include <check.h>
#define REQ_DELETEARRAY_SUITE 1
Suite *req_deletearray_suite();
#define METH_2 2
Suite *meth_2_suite();
#endif /* _REQ_DELETEARRAY_CT_H */
| {
"language": "C"
} |
/*
* Copyright (c) 2003-2004, Artem B. Bityuckiy
* Copyright (c) 1999,2000, Konstantin Chuguev. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "cesbi.h"
#if defined (ICONV_TO_UCS_CES_TABLE) \
|| defined (ICONV_FROM_UCS_CES_TABLE)
#include <_ansi.h>
#include <reent.h>
#include <newlib.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/iconvnls.h>
#include "../lib/endian.h"
#include "../lib/local.h"
#include "../lib/ucsconv.h"
#include "../ccs/ccs.h"
/*
* Table-based CES converter is implemented here. Table-based CES converter
* deals with encodings with "null" CES, like KOI8-R. In this case it is
* possible to implement one generic algorithm which works with different
* CCS tables.
*
* Table-based CES converter deals with CCS tables placed into iconv/ccs
* subdirectory. First, converter tries to find needed CCS table among
* linked-in tables. If not found, it tries to load it from external file
* (only if corespondent capability was enabled in Newlib configuration).
*
* 16 bit encodings are assumed to be Big Endian.
*/
static ucs2_t
_EXFUN(find_code_size, (ucs2_t code, _CONST __uint16_t *tblp));
static __inline ucs2_t
_EXFUN(find_code_speed, (ucs2_t code, _CONST __uint16_t *tblp));
static __inline ucs2_t
_EXFUN(find_code_speed_8bit, (ucs2_t code, _CONST unsigned char *tblp));
#ifdef _ICONV_ENABLE_EXTERNAL_CCS
static _CONST iconv_ccs_desc_t *
_EXFUN(load_file, (struct _reent *rptr, _CONST char *name, int direction));
#endif
/*
* Interface data and functions implementation.
*/
static size_t
_DEFUN(table_close, (rptr, data),
struct _reent *rptr _AND
_VOID_PTR data)
{
_CONST iconv_ccs_desc_t *ccsp = (iconv_ccs_desc_t *)data;
if (ccsp->type == TABLE_EXTERNAL)
_free_r (rptr, (_VOID_PTR)ccsp->tbl);
_free_r( rptr, (_VOID_PTR)ccsp);
return 0;
}
#if defined (ICONV_FROM_UCS_CES_TABLE)
static _VOID_PTR
_DEFUN(table_init_from_ucs, (rptr, encoding),
struct _reent *rptr _AND
_CONST char *encoding)
{
int i;
_CONST iconv_ccs_t *biccsp = NULL;
iconv_ccs_desc_t *ccsp;
for (i = 0; _iconv_ccs[i] != NULL; i++)
if (strcmp (_iconv_ccs[i]->name, encoding) == 0)
{
biccsp = _iconv_ccs[i];
break;
}
if (biccsp != NULL)
{
if (biccsp->from_ucs == NULL
|| (ccsp = (iconv_ccs_desc_t *)
_malloc_r (rptr, sizeof (iconv_ccs_desc_t))) == NULL)
return NULL;
ccsp->type = TABLE_BUILTIN;
ccsp->bits = biccsp->bits;
ccsp->optimization = biccsp->from_ucs_type;
ccsp->tbl = biccsp->from_ucs;
return (_VOID_PTR)ccsp;
}
#ifdef _ICONV_ENABLE_EXTERNAL_CCS
return (_VOID_PTR)load_file (rptr, encoding, 1);
#else
return NULL;
#endif
}
static size_t
_DEFUN(table_convert_from_ucs, (data, in, outbuf, outbytesleft),
_VOID_PTR data _AND
ucs4_t in _AND
unsigned char **outbuf _AND
size_t *outbytesleft)
{
_CONST iconv_ccs_desc_t *ccsp = (iconv_ccs_desc_t *)data;
ucs2_t code;
if (in > 0xFFFF || in == INVALC)
return (size_t)ICONV_CES_INVALID_CHARACTER;
if (ccsp->bits == TABLE_8BIT)
{
code = find_code_speed_8bit ((ucs2_t)in,
(_CONST unsigned char *)ccsp->tbl);
if (code == INVALC)
return (size_t)ICONV_CES_INVALID_CHARACTER;
**outbuf = (unsigned char)code;
*outbuf += 1;
*outbytesleft -= 1;
return 1;
}
else if (ccsp->optimization == TABLE_SPEED_OPTIMIZED)
code = find_code_speed ((ucs2_t)in, ccsp->tbl);
else
code = find_code_size ((ucs2_t)in, ccsp->tbl);
if (code == INVALC)
return (size_t)ICONV_CES_INVALID_CHARACTER;
if (*outbytesleft < 2)
return (size_t)ICONV_CES_NOSPACE;
/* We can't store whole word since **outbuf may be not 2-byte aligned */
**outbuf = (unsigned char)((ucs2_t)code >> 8);
*(*outbuf + 1) = (unsigned char)code;
*outbuf += 2;
*outbytesleft -= 2;
return 2;
}
#endif /* ICONV_FROM_UCS_CES_TABLE */
#if defined (ICONV_TO_UCS_CES_TABLE)
static _VOID_PTR
_DEFUN(table_init_to_ucs, (rptr, encoding),
struct _reent *rptr _AND
_CONST char *encoding)
{
int i;
_CONST iconv_ccs_t *biccsp = NULL;
iconv_ccs_desc_t *ccsp;
for (i = 0; _iconv_ccs[i] != NULL; i++)
if (strcmp (_iconv_ccs[i]->name, encoding) == 0)
{
biccsp = _iconv_ccs[i];
break;
}
if (biccsp != NULL)
{
if (biccsp->to_ucs == NULL
|| (ccsp = (iconv_ccs_desc_t *)
_malloc_r (rptr, sizeof (iconv_ccs_desc_t))) == NULL)
return NULL;
ccsp->type = TABLE_BUILTIN;
ccsp->bits = biccsp->bits;
ccsp->optimization = biccsp->to_ucs_type;
ccsp->tbl = biccsp->to_ucs;
return (_VOID_PTR)ccsp;
}
#ifdef _ICONV_ENABLE_EXTERNAL_CCS
return (_VOID_PTR)load_file (rptr, encoding, 0);
#else
return NULL;
#endif
}
static ucs4_t
_DEFUN(table_convert_to_ucs, (data, inbuf, inbytesleft),
_VOID_PTR data _AND
_CONST unsigned char **inbuf _AND
size_t *inbytesleft)
{
_CONST iconv_ccs_desc_t *ccsp = (iconv_ccs_desc_t *)data;
ucs2_t ucs;
if (ccsp->bits == TABLE_8BIT)
{
if (*inbytesleft < 1)
return (ucs4_t)ICONV_CES_BAD_SEQUENCE;
ucs = (ucs2_t)ccsp->tbl[**inbuf];
if (ucs == INVALC)
return (ucs4_t)ICONV_CES_INVALID_CHARACTER;
*inbytesleft -= 1;
*inbuf += 1;
return (ucs4_t)ucs;
}
if (*inbytesleft < 2)
return (ucs4_t)ICONV_CES_BAD_SEQUENCE;
if (ccsp->optimization == TABLE_SIZE_OPTIMIZED)
ucs = find_code_size((ucs2_t)**inbuf << 8 | (ucs2_t)*(*inbuf + 1),
ccsp->tbl);
else
ucs = find_code_speed((ucs2_t)**inbuf << 8 | (ucs2_t)*(*inbuf + 1),
ccsp->tbl);
if (ucs == INVALC)
return (ucs4_t)ICONV_CES_INVALID_CHARACTER;
*inbuf += 2;
*inbytesleft -= 2;
return (ucs4_t)ucs;
}
#endif /* ICONV_TO_UCS_CES_TABLE */
static int
_DEFUN(table_get_mb_cur_max, (data),
_VOID_PTR data)
{
return ((iconv_ccs_desc_t *)data)->bits/8;
}
#if defined (ICONV_TO_UCS_CES_TABLE)
_CONST iconv_to_ucs_ces_handlers_t
_iconv_to_ucs_ces_handlers_table =
{
table_init_to_ucs,
table_close,
table_get_mb_cur_max,
NULL,
NULL,
NULL,
table_convert_to_ucs
};
#endif /* ICONV_FROM_UCS_CES_TABLE */
#if defined (ICONV_FROM_UCS_CES_TABLE)
_CONST iconv_from_ucs_ces_handlers_t
_iconv_from_ucs_ces_handlers_table =
{
table_init_from_ucs,
table_close,
table_get_mb_cur_max,
NULL,
NULL,
NULL,
table_convert_from_ucs
};
#endif /* ICONV_TO_UCS_CES_TABLE */
/*
* Supplementary functions.
*/
/*
* find_code_speed - find code in 16 bit speed-optimized table.
*
* PARAMETERS:
* ucs2_t code - code whose mapping to find.
* _CONST __uint16_t *tblp - table pointer.
*
* RETURN:
* Code that corresponds to 'code'.
*/
static __inline ucs2_t
_DEFUN(find_code_speed, (code, tblp),
ucs2_t code _AND
_CONST __uint16_t *tblp)
{
int idx = tblp[code >> 8];
if (idx == INVBLK)
return (ucs2_t)INVALC;
return (ucs2_t)tblp[(code & 0x00FF) + idx];
}
/*
* find_code_speed_8bit - find code in 8 bit speed-optimized table.
*
* PARAMETERS:
* ucs2_t code - code whose mapping to find.
* _CONST __uint16_t *tblp - table pointer.
*
* RETURN:
* Code that corresponds to 'code'.
*/
static __inline ucs2_t
_DEFUN(find_code_speed_8bit, (code, tblp),
ucs2_t code _AND
_CONST unsigned char *tblp)
{
int idx;
unsigned char ccs;
if (code == ((ucs2_t *)tblp)[0])
return (ucs2_t)0xFF;
idx = ((ucs2_t *)tblp)[1 + (code >> 8)];
if (idx == INVBLK)
return (ucs2_t)INVALC;
ccs = tblp[(code & 0x00FF) + idx];
return ccs == 0xFF ? (ucs2_t)INVALC : (ucs2_t)ccs;
}
/* Left range boundary */
#define RANGE_LEFT(n) (tblp[FIRST_RANGE_INDEX + (n)*3 + 0])
/* Right range boundary */
#define RANGE_RIGHT(n) (tblp[FIRST_RANGE_INDEX + (n)*3 + 1])
/* Range offset */
#define RANGE_INDEX(n) (tblp[FIRST_RANGE_INDEX + (n)*3 + 2])
/* Un-ranged offset */
#define UNRANGED_INDEX(n) (tblp[FIRST_UNRANGED_INDEX_INDEX] + (n)*2)
/*
* find_code_size - find code in 16 bit size-optimized table.
*
* PARAMETERS:
* ucs2_t code - code whose mapping to find.
* _CONST __uint16_t *tblp - table pointer.
*
* RETURN:
* Code that corresponds to 'code'.
*/
static ucs2_t
_DEFUN(find_code_size, (code, tblp),
ucs2_t code _AND
_CONST __uint16_t *tblp)
{
int first, last, cur, center;
if (tblp[RANGES_NUM_INDEX] > 0)
{
first = 0;
last = tblp[RANGES_NUM_INDEX] - 1;
do
{
center = (last - first)/2;
cur = center + first;
if (code > RANGE_RIGHT (cur))
first = cur;
else if (code < RANGE_LEFT (cur))
last = cur;
else
return (ucs2_t)tblp[RANGE_INDEX (cur) + code - RANGE_LEFT (cur)];
} while (center > 0);
if (last - first == 1)
{
if (code >= RANGE_LEFT (first) && code <= RANGE_RIGHT (first))
return (ucs2_t)tblp[RANGE_INDEX (first)
+ code - RANGE_LEFT (first)];
if (code >= RANGE_LEFT (last) && code <= RANGE_RIGHT (last))
return (ucs2_t)tblp[RANGE_INDEX (last)
+ code - RANGE_LEFT (last)];
}
}
if (tblp[UNRANGED_NUM_INDEX] > 0)
{
first = 0;
last = tblp[UNRANGED_NUM_INDEX] - 1;
do
{
int c;
center = (last - first)/2;
cur = center + first;
c = tblp[UNRANGED_INDEX (cur)];
if (code > c)
first = cur;
else if (code < c)
last = cur;
else
return (ucs2_t)tblp[UNRANGED_INDEX (cur) + 1];
} while (center > 0);
if (last - first == 1)
{
if (code == tblp[UNRANGED_INDEX (first)])
return (ucs2_t)tblp[UNRANGED_INDEX (first) + 1];
if (code == tblp[UNRANGED_INDEX (last)])
return (ucs2_t)tblp[UNRANGED_INDEX (last) + 1];
}
}
return (ucs2_t)INVALC;
}
#ifdef _ICONV_ENABLE_EXTERNAL_CCS
#define _16BIT_ELT(offset) \
ICONV_BETOHS(*((__uint16_t *)(buf + (offset))))
#define _32BIT_ELT(offset) \
ICONV_BETOHL(*((__uint32_t *)(buf + (offset))))
/*
* load_file - load conversion table from external file and initialize
* iconv_ccs_desc_t object.
*
* PARAMETERS:
* struct _reent *rptr - reent structure of current thread/process.
* _CONST char *name - encoding name.
* int direction - conversion direction.
*
* DESCRIPTION:
* Loads conversion table of appropriate endianess from external file
* and initializes 'iconv_ccs_desc_t' table description structure.
* If 'direction' is 0 - load "To UCS" table, else load "From UCS"
* table.
*
* RETURN:
* iconv_ccs_desc_t * pointer is success, NULL if failure.
*/
static _CONST iconv_ccs_desc_t *
_DEFUN(load_file, (rptr, name, direction),
struct _reent *rptr _AND
_CONST char *name _AND
int direction)
{
int fd;
_CONST unsigned char *buf;
int tbllen, hdrlen;
off_t off;
_CONST char *fname;
iconv_ccs_desc_t *ccsp = NULL;
int nmlen = strlen(name);
/* Since CCS table name length can vary - it is aligned (by adding extra
* bytes to it's end) to 4-byte boundary. */
int alignment = nmlen & 3 ? 4 - (nmlen & 3) : 0;
nmlen = strlen(name);
hdrlen = nmlen + EXTTABLE_HEADER_LEN + alignment;
if ((fname = _iconv_nls_construct_filename (rptr, name, ICONV_SUBDIR,
ICONV_DATA_EXT)) == NULL)
return NULL;
if ((fd = _open_r (rptr, fname, O_RDONLY, S_IRUSR)) == -1)
goto error1;
if ((buf = (_CONST unsigned char *)_malloc_r (rptr, hdrlen)) == NULL)
goto error2;
if (_read_r (rptr, fd, (_VOID_PTR)buf, hdrlen) != hdrlen)
goto error3;
if (_16BIT_ELT (EXTTABLE_VERSION_OFF) != TABLE_VERSION_1
|| _32BIT_ELT (EXTTABLE_CCSNAME_LEN_OFF) != nmlen
|| strncmp (buf + EXTTABLE_CCSNAME_OFF, name, nmlen) != 0)
goto error3; /* Bad file */
if ((ccsp = (iconv_ccs_desc_t *)
_calloc_r (rptr, 1, sizeof (iconv_ccs_desc_t))) == NULL)
goto error3;
ccsp->bits = _16BIT_ELT (EXTTABLE_BITS_OFF);
ccsp->type = TABLE_EXTERNAL;
/* Add 4-byte alignment to name length */
nmlen += alignment;
if (ccsp->bits == TABLE_8BIT)
{
if (direction == 0) /* Load "To UCS" table */
{
off = (off_t)_32BIT_ELT (nmlen + EXTTABLE_TO_SPEED_OFF);
tbllen = _32BIT_ELT (nmlen + EXTTABLE_TO_SPEED_LEN_OFF);
}
else /* Load "From UCS" table */
{
off = (off_t)_32BIT_ELT (nmlen + EXTTABLE_FROM_SPEED_OFF);
tbllen = _32BIT_ELT (nmlen + EXTTABLE_FROM_SPEED_LEN_OFF);
}
}
else if (ccsp->bits == TABLE_16BIT)
{
if (direction == 0) /* Load "To UCS" table */
{
#ifdef TABLE_USE_SIZE_OPTIMIZATION
off = (off_t)_32BIT_ELT (nmlen + EXTTABLE_TO_SIZE_OFF);
tbllen = _32BIT_ELT (nmlen + EXTTABLE_TO_SIZE_LEN_OFF);
#else
off = (off_t)_32BIT_ELT (nmlen + EXTTABLE_TO_SPEED_OFF);
tbllen = _32BIT_ELT (nmlen + EXTTABLE_TO_SPEED_LEN_OFF);
#endif
}
else /* Load "From UCS" table */
{
#ifdef TABLE_USE_SIZE_OPTIMIZATION
off = (off_t)_32BIT_ELT (nmlen + EXTTABLE_FROM_SIZE_OFF);
tbllen = _32BIT_ELT (nmlen + EXTTABLE_FROM_SIZE_LEN_OFF);
#else
off = (off_t)_32BIT_ELT (nmlen + EXTTABLE_FROM_SPEED_OFF);
tbllen = _32BIT_ELT (nmlen + EXTTABLE_FROM_SPEED_LEN_OFF);
#endif
}
#ifdef TABLE_USE_SIZE_OPTIMIZATION
ccsp->optimization = TABLE_SIZE_OPTIMIZED;
#else
ccsp->optimization = TABLE_SPEED_OPTIMIZED;
#endif
}
else
goto error4; /* Bad file */
if (off == EXTTABLE_NO_TABLE)
goto error4; /* No correspondent table in file */
if ((ccsp->tbl = (ucs2_t *)_malloc_r (rptr, tbllen)) == NULL)
goto error4;
if (_lseek_r (rptr, fd, off, SEEK_SET) == (off_t)-1
|| _read_r (rptr, fd, (_VOID_PTR)ccsp->tbl, tbllen) != tbllen)
goto error5;
goto normal_exit;
error5:
_free_r (rptr, (_VOID_PTR)ccsp->tbl);
ccsp->tbl = NULL;
error4:
_free_r (rptr, (_VOID_PTR)ccsp);
ccsp = NULL;
error3:
normal_exit:
_free_r (rptr, (_VOID_PTR)buf);
error2:
if (_close_r (rptr, fd) == -1)
{
if (ccsp != NULL)
{
if (ccsp->tbl != NULL)
_free_r (rptr, (_VOID_PTR)ccsp->tbl);
_free_r (rptr, (_VOID_PTR)ccsp);
}
ccsp = NULL;
}
error1:
_free_r (rptr, (_VOID_PTR)fname);
return ccsp;
}
#endif
#endif /* ICONV_TO_UCS_CES_TABLE || ICONV_FROM_UCS_CES_TABLE */
| {
"language": "C"
} |
#ifndef PA_LINUX_ALSA_H
#define PA_LINUX_ALSA_H
/*
* $Id: pa_linux_alsa.h 1597 2011-02-11 00:15:51Z dmitrykos $
* PortAudio Portable Real-Time Audio Library
* ALSA-specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
* @ingroup public_header
* @brief ALSA-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct PaAlsaStreamInfo
{
unsigned long size;
PaHostApiTypeId hostApiType;
unsigned long version;
const char *deviceString;
}
PaAlsaStreamInfo;
/** Initialize host API specific structure, call this before setting relevant attributes. */
void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info );
/** Instruct whether to enable real-time priority when starting the audio thread.
*
* If this is turned on by the stream is started, the audio callback thread will be created
* with the FIFO scheduling policy, which is suitable for realtime operation.
**/
void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable );
#if 0
void PaAlsa_EnableWatchdog( PaStream *s, int enable );
#endif
/** Get the ALSA-lib card index of this stream's input device. */
PaError PaAlsa_GetStreamInputCard( PaStream *s, int *card );
/** Get the ALSA-lib card index of this stream's output device. */
PaError PaAlsa_GetStreamOutputCard( PaStream *s, int *card );
/** Set the number of periods (buffer fragments) to configure devices with.
*
* By default the number of periods is 4, this is the lowest number of periods that works well on
* the author's soundcard.
* @param numPeriods The number of periods.
*/
PaError PaAlsa_SetNumPeriods( int numPeriods );
/** Set the maximum number of times to retry opening busy device (sleeping for a
* short interval inbetween).
*/
PaError PaAlsa_SetRetriesBusy( int retries );
/** Set the path and name of ALSA library file if PortAudio is configured to load it dynamically (see
* PA_ALSA_DYNAMIC). This setting will overwrite the default name set by PA_ALSA_PATHNAME define.
* @param pathName Full path with filename. Only filename can be used, but dlopen() will lookup default
* searchable directories (/usr/lib;/usr/local/lib) then.
*/
void PaAlsa_SetLibraryPathName( const char *pathName );
PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ); // ppgb
#ifdef __cplusplus
}
#endif
#endif
| {
"language": "C"
} |
/* complex/gsl_complex.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_COMPLEX_H__
#define __GSL_COMPLEX_H__
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* two consecutive built-in types as a complex number */
typedef double * gsl_complex_packed ;
typedef float * gsl_complex_packed_float ;
typedef long double * gsl_complex_packed_long_double ;
typedef const double * gsl_const_complex_packed ;
typedef const float * gsl_const_complex_packed_float ;
typedef const long double * gsl_const_complex_packed_long_double ;
/* 2N consecutive built-in types as N complex numbers */
typedef double * gsl_complex_packed_array ;
typedef float * gsl_complex_packed_array_float ;
typedef long double * gsl_complex_packed_array_long_double ;
typedef const double * gsl_const_complex_packed_array ;
typedef const float * gsl_const_complex_packed_array_float ;
typedef const long double * gsl_const_complex_packed_array_long_double ;
/* Yes... this seems weird. Trust us. The point is just that
sometimes you want to make it obvious that something is
an output value. The fact that it lacks a 'const' may not
be enough of a clue for people in some contexts.
*/
typedef double * gsl_complex_packed_ptr ;
typedef float * gsl_complex_packed_float_ptr ;
typedef long double * gsl_complex_packed_long_double_ptr ;
typedef const double * gsl_const_complex_packed_ptr ;
typedef const float * gsl_const_complex_packed_float_ptr ;
typedef const long double * gsl_const_complex_packed_long_double_ptr ;
typedef struct
{
long double dat[2];
}
gsl_complex_long_double;
typedef struct
{
double dat[2];
}
gsl_complex;
typedef struct
{
float dat[2];
}
gsl_complex_float;
#define GSL_REAL(z) ((z).dat[0])
#define GSL_IMAG(z) ((z).dat[1])
#define GSL_COMPLEX_P(zp) ((zp)->dat)
#define GSL_COMPLEX_P_REAL(zp) ((zp)->dat[0])
#define GSL_COMPLEX_P_IMAG(zp) ((zp)->dat[1])
#define GSL_COMPLEX_EQ(z1,z2) (((z1).dat[0] == (z2).dat[0]) && ((z1).dat[1] == (z2).dat[1]))
#define GSL_SET_COMPLEX(zp,x,y) do {(zp)->dat[0]=(x); (zp)->dat[1]=(y);} while(0)
#define GSL_SET_REAL(zp,x) do {(zp)->dat[0]=(x);} while(0)
#define GSL_SET_IMAG(zp,y) do {(zp)->dat[1]=(y);} while(0)
#define GSL_SET_COMPLEX_PACKED(zp,n,x,y) do {*((zp)+2*(n))=(x); *((zp)+(2*(n)+1))=(y);} while(0)
__END_DECLS
#endif /* __GSL_COMPLEX_H__ */
| {
"language": "C"
} |
/* grabbag - Convenience lib for various routines common to several tools
* Copyright (C) 2002-2009 Josh Coalson
* Copyright (C) 2011-2016 Xiph.Org Foundation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* This .h cannot be included by itself; #include "share/grabbag.h" instead. */
#ifndef GRABBAG__CUESHEET_H
#define GRABBAG__CUESHEET_H
#include <stdio.h>
#include "FLAC/metadata.h"
#ifdef __cplusplus
extern "C" {
#endif
uint32_t grabbag__cuesheet_msf_to_frame(uint32_t minutes, uint32_t seconds, uint32_t frames);
void grabbag__cuesheet_frame_to_msf(uint32_t frame, uint32_t *minutes, uint32_t *seconds, uint32_t *frames);
FLAC__StreamMetadata *grabbag__cuesheet_parse(FILE *file, const char **error_message, uint32_t *last_line_read, uint32_t sample_rate, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset);
void grabbag__cuesheet_emit(FILE *file, const FLAC__StreamMetadata *cuesheet, const char *file_reference);
#ifdef __cplusplus
}
#endif
#endif
| {
"language": "C"
} |
/**
* Copyright (C) 2008 Happy Fish / YuQing
*
* FastDHT may be copied only under the terms of the GNU General
* Public License V3. Please visit the FastDHT Home Page
* http://www.csource.org/ for more detail.
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/time.h>
#include "shared_func.h"
#include "logger.h"
#include "hash.h"
#include "fdht_global.h"
#include "ini_file_reader.h"
#include "sockopt.h"
#include "sync.h"
#include "base64.h"
#define BINLOG_COMPRESSED_INDEX_FILENAME SYNC_BINLOG_FILE_PREFIX".compressed.index"
typedef struct
{
int binlog_index;
int binlog_fd;
int64_t binlog_offset;
} CompressReader;
typedef struct
{
time_t timestamp;
char op_type;
int key_hash_code; //key hash code
FDHTKeyInfo key_info;
int value_len;
time_t expires; //key expires, 0 for never expired
int64_t offset;
int record_length;
} CompressRecord;
typedef struct
{
char key[(FDHT_MAX_FULL_KEY_LEN / 3) * 4];
char op_type;
int64_t offset;
int record_length;
time_t expires; //key expires, 0 for never expired
} CompressRawRow;
typedef struct
{
CompressReader *pReader;
int dest_fd;
int row_count;
char *buff;
int buff_size;
} CompressWalkArg;
static int gn_binlog_index;
static time_t gt_current_time;
static struct base64_context gc_base64_context;
static int get_current_binlog_index();
static int get_binlog_compressed_index();
static int write_to_binlog_compressed_index(const int compressed_index);
static int compress_open_readable_binlog(CompressReader *pReader);
static int compress_binlog_read(CompressReader *pReader, CompressRecord *pRecord);
static int compress_binlog_file(CompressReader *pReader);
int main(int argc, char *argv[])
{
CompressReader reader;
char binlog_filepath[MAX_PATH_SIZE];
int result;
int start_index;
int end_index;
int index;
if (argc < 3)
{
printf("Usage: %s <base_path> <binglog file index>\n" \
"\t file index based 0, \n" \
"\t \"all\" means compressing all binlog files\n" \
"\t \"auto\" means compressing binglog " \
"files automaticlly\n" \
"\t index number means single binlog file\n", argv[0]);
return EINVAL;
}
base64_init(&gc_base64_context, 0);
memset(&reader, 0, sizeof(reader));
reader.binlog_fd = -1;
snprintf(g_fdht_base_path, sizeof(g_fdht_base_path), "%s", argv[1]);
chopPath(g_fdht_base_path);
if (!fileExists(g_fdht_base_path))
{
printf("path %s not exist!\n", g_fdht_base_path);
return ENOENT;
}
log_init();
log_set_prefix(g_fdht_base_path, "fdht_compress");
snprintf(binlog_filepath, sizeof(binlog_filepath), \
"%s/data/sync", g_fdht_base_path);
if (!fileExists(binlog_filepath))
{
logError("binlog path %s not exist!", binlog_filepath);
return ENOENT;
}
if ((result=get_current_binlog_index()) != 0)
{
return result;
}
if (strcmp(argv[2], "all") == 0)
{
if (gn_binlog_index == 0)
{
logError("Current binlog index: %d == 0, " \
"can't compress!", gn_binlog_index);
return EINVAL;
}
start_index = 0;
end_index = gn_binlog_index - 1;
}
else if (strcmp(argv[2], "auto") == 0)
{
if ((result=get_binlog_compressed_index(&start_index)) != 0)
{
return result;
}
end_index = gn_binlog_index - 2; //make sure syncing is done
if (start_index > end_index)
{
return 0;
}
}
else
{
char *pEnd;
pEnd = NULL;
start_index = end_index = (int)strtol(argv[2], &pEnd, 10);
if ((pEnd != NULL && *pEnd != '\0') || start_index < 0)
{
logError("Invalid binlog file index: %s", argv[2]);
return EINVAL;
}
if (start_index >= gn_binlog_index)
{
logError("The compress index: %d >= current binlog " \
"index: %d, can't compress!", \
start_index, gn_binlog_index);
return EINVAL;
}
}
result = 0;
for (index=start_index; index<=end_index; index++)
{
reader.binlog_index = index;
if ((result=compress_binlog_file(&reader)) != 0)
{
break;
}
if (strcmp(argv[2], "auto") == 0)
{
if ((result=write_to_binlog_compressed_index(index + 1)) != 0)
{
break;
}
}
}
log_destroy();
return result;
}
static int get_binlog_compressed_index(int *compressed_index)
{
char full_filename[MAX_PATH_SIZE];
char file_buff[64];
int result;
int bytes;
int fd;
snprintf(full_filename, sizeof(full_filename), \
"%s/data/"SYNC_DIR_NAME"/%s", g_fdht_base_path, \
BINLOG_COMPRESSED_INDEX_FILENAME);
if ((fd=open(full_filename, O_RDONLY)) < 0)
{
*compressed_index = 0;
if ((result=write_to_binlog_compressed_index(\
*compressed_index)) != 0)
{
return result;
}
return 0;
}
bytes = read(fd, file_buff, sizeof(file_buff) - 1);
close(fd);
if (bytes <= 0)
{
logError("file: "__FILE__", line: %d, " \
"read file \"%s\" fail, bytes read: %d", \
__LINE__, full_filename, bytes);
return errno != 0 ? errno : EIO;
}
file_buff[bytes] = '\0';
*compressed_index = atoi(file_buff);
if (*compressed_index < 0)
{
logError("file: "__FILE__", line: %d, " \
"in file \"%s\", compressed binlog index: %d < 0", \
__LINE__, full_filename, *compressed_index);
return EINVAL;
}
return 0;
}
static int write_to_binlog_compressed_index(const int compressed_index)
{
char full_filename[MAX_PATH_SIZE];
char buff[16];
int fd;
int len;
snprintf(full_filename, sizeof(full_filename), \
"%s/data/"SYNC_DIR_NAME"/%s", g_fdht_base_path, \
BINLOG_COMPRESSED_INDEX_FILENAME);
if ((fd=open(full_filename, O_WRONLY | O_CREAT | O_TRUNC, 0644)) < 0)
{
logError("file: "__FILE__", line: %d, " \
"open file \"%s\" fail, " \
"errno: %d, error info: %s", \
__LINE__, full_filename, \
errno, STRERROR(errno));
return errno != 0 ? errno : ENOENT;
}
len = sprintf(buff, "%d", compressed_index);
if (write(fd, buff, len) != len)
{
logError("file: "__FILE__", line: %d, " \
"write to file \"%s\" fail, " \
"errno: %d, error info: %s", \
__LINE__, full_filename, \
errno, STRERROR(errno));
close(fd);
return errno != 0 ? errno : EIO;
}
close(fd);
return 0;
}
static int get_current_binlog_index()
{
char full_filename[MAX_PATH_SIZE];
char file_buff[64];
int bytes;
int fd;
snprintf(full_filename, sizeof(full_filename), \
"%s/data/"SYNC_DIR_NAME"/%s", g_fdht_base_path, \
SYNC_BINLOG_INDEX_FILENAME);
if ((fd=open(full_filename, O_RDONLY)) < 0)
{
logError("file: "__FILE__", line: %d, " \
"open file %s fail, errno: %d, error info: %s", \
__LINE__, full_filename, errno, STRERROR(errno));
return errno != 0 ? errno : EACCES;
}
bytes = read(fd, file_buff, sizeof(file_buff) - 1);
close(fd);
if (bytes <= 0)
{
logError("file: "__FILE__", line: %d, " \
"read file \"%s\" fail, bytes read: %d", \
__LINE__, full_filename, bytes);
return errno != 0 ? errno : EIO;
}
file_buff[bytes] = '\0';
gn_binlog_index = atoi(file_buff);
if (gn_binlog_index < 0)
{
logError("file: "__FILE__", line: %d, " \
"in file \"%s\", binlog_index: %d < 0", \
__LINE__, full_filename, gn_binlog_index);
return EINVAL;
}
return 0;
}
static char *compress_get_binlog_filename(CompressReader *pReader, \
char *full_filename)
{
static char buff[MAX_PATH_SIZE];
if (full_filename == NULL)
{
full_filename = buff;
}
snprintf(full_filename, MAX_PATH_SIZE, \
"%s/data/"SYNC_DIR_NAME"/"SYNC_BINLOG_FILE_PREFIX"" \
SYNC_BINLOG_FILE_EXT_FMT, \
g_fdht_base_path, pReader->binlog_index);
return full_filename;
}
static int compress_open_readable_binlog(CompressReader *pReader)
{
char full_filename[MAX_PATH_SIZE];
if (pReader->binlog_fd >= 0)
{
close(pReader->binlog_fd);
}
compress_get_binlog_filename(pReader, full_filename);
pReader->binlog_fd = open(full_filename, O_RDONLY);
if (pReader->binlog_fd < 0)
{
logError("file: "__FILE__", line: %d, " \
"open binlog file \"%s\" fail, " \
"errno: %d, error info: %s", \
__LINE__, full_filename, \
errno, STRERROR(errno));
return errno != 0 ? errno : ENOENT;
}
pReader->binlog_offset = 0;
return 0;
}
#define CHECK_FIELD_VALUE(pRecord, value, max_length, caption) \
if (value < 0) \
{ \
logError("file: "__FILE__", line: %d, " \
"item \"%s\" in binlog file \"%s\" " \
"is invalid, file offset: %"PRId64", " \
"%s: %d <= 0", __LINE__, caption, \
compress_get_binlog_filename(pReader, NULL), \
pReader->binlog_offset, caption, value); \
return EINVAL; \
} \
if (value > max_length) \
{ \
logError("file: "__FILE__", line: %d, " \
"item \"%s\" in binlog file \"%s\" " \
"is invalid, file offset: %"PRId64", " \
"%s: %d > %d", __LINE__, caption, \
compress_get_binlog_filename(pReader, NULL), \
pReader->binlog_offset, caption, value, max_length); \
return EINVAL; \
} \
static int compress_binlog_read(CompressReader *pReader, CompressRecord *pRecord)
{
char buff[BINLOG_FIX_FIELDS_LENGTH + FDHT_MAX_FULL_KEY_LEN + 2];
char *p;
int read_bytes;
int full_key_len;
int nItem;
time_t *ptTimestamp;
time_t *ptExpires;
int *piTimestamp;
int *piExpires;
read_bytes = read(pReader->binlog_fd, buff, BINLOG_FIX_FIELDS_LENGTH);
if (read_bytes == 0) //end of file
{
return ENOENT;
}
if (read_bytes < 0)
{
logError("file: "__FILE__", line: %d, " \
"read from binlog file \"%s\" fail, " \
"file offset: %"PRId64", " \
"errno: %d, error info: %s", __LINE__, \
compress_get_binlog_filename(pReader, NULL), \
pReader->binlog_offset, errno, STRERROR(errno));
return errno != 0 ? errno : EIO;
}
if (read_bytes != BINLOG_FIX_FIELDS_LENGTH)
{
logError("file: "__FILE__", line: %d, " \
"read from binlog file \"%s\" fail, " \
"file offset: %"PRId64", " \
"read bytes: %d != %d", \
__LINE__, compress_get_binlog_filename(pReader, NULL),\
pReader->binlog_offset, read_bytes, \
BINLOG_FIX_FIELDS_LENGTH);
return EINVAL;
}
*(buff + read_bytes) = '\0';
ptTimestamp = &(pRecord->timestamp);
ptExpires = &(pRecord->expires);
piTimestamp = (int *)ptTimestamp;
piExpires = (int *)ptExpires;
if ((nItem=sscanf(buff, "%10d %c %10d %10d %4d %4d %4d %10d ", \
piTimestamp, &(pRecord->op_type), \
&(pRecord->key_hash_code), piExpires, \
&(pRecord->key_info.namespace_len), \
&(pRecord->key_info.obj_id_len), \
&(pRecord->key_info.key_len), \
&(pRecord->value_len))) != 8)
{
logError("file: "__FILE__", line: %d, " \
"data format invalid, binlog file: %s, " \
"file offset: %"PRId64", " \
"read item: %d != 6", \
__LINE__, compress_get_binlog_filename(pReader, NULL),\
pReader->binlog_offset, nItem);
return EINVAL;
}
CHECK_FIELD_VALUE(pRecord, pRecord->key_info.namespace_len, \
FDHT_MAX_NAMESPACE_LEN, "namespace length")
CHECK_FIELD_VALUE(pRecord, pRecord->key_info.obj_id_len, \
FDHT_MAX_OBJECT_ID_LEN, "object ID length")
CHECK_FIELD_VALUE(pRecord, pRecord->key_info.key_len, \
FDHT_MAX_SUB_KEY_LEN, "key length")
if (pRecord->value_len < 0)
{
logError("file: "__FILE__", line: %d, " \
"item \"value length\" in binlog file \"%s\" " \
"is invalid, file offset: %"PRId64", " \
"value length: %d < 0", \
__LINE__, compress_get_binlog_filename(pReader, NULL), \
pReader->binlog_offset, pRecord->value_len);
return EINVAL;
}
full_key_len = pRecord->key_info.namespace_len + 1 + \
pRecord->key_info.obj_id_len + 1 + \
pRecord->key_info.key_len + 1;
read_bytes = read(pReader->binlog_fd, buff, full_key_len);
if (read_bytes < 0)
{
logError("file: "__FILE__", line: %d, " \
"read from binlog file \"%s\" fail, " \
"file offset: %"PRId64", " \
"errno: %d, error info: %s", __LINE__, \
compress_get_binlog_filename(pReader, NULL), \
pReader->binlog_offset, errno, STRERROR(errno));
return errno != 0 ? errno : EIO;
}
if (read_bytes != full_key_len)
{
logError("file: "__FILE__", line: %d, " \
"read from binlog file \"%s\" fail, " \
"file offset: %"PRId64", " \
"read bytes: %d != %d", \
__LINE__, compress_get_binlog_filename(pReader, NULL),\
pReader->binlog_offset, read_bytes, full_key_len);
return EINVAL;
}
p = buff;
if (pRecord->key_info.namespace_len > 0)
{
memcpy(pRecord->key_info.szNameSpace, p, \
pRecord->key_info.namespace_len);
p += pRecord->key_info.namespace_len;
}
p++;
if (pRecord->key_info.obj_id_len > 0)
{
memcpy(pRecord->key_info.szObjectId, p, \
pRecord->key_info.obj_id_len);
p += pRecord->key_info.obj_id_len;
}
p++;
memcpy(pRecord->key_info.szKey, p, \
pRecord->key_info.key_len);
if (lseek(pReader->binlog_fd, pRecord->value_len + 1, SEEK_CUR) < 0)
{
logError("file: "__FILE__", line: %d, " \
"lseek from binlog file \"%s\" fail, " \
"file offset: %"PRId64", " \
"errno: %d, error info: %s", __LINE__, \
compress_get_binlog_filename(pReader, NULL), \
pReader->binlog_offset, errno, STRERROR(errno));
return errno != 0 ? errno : EIO;
}
pRecord->offset = pReader->binlog_offset;
pRecord->record_length = CALC_RECORD_LENGTH((&(pRecord->key_info)), \
pRecord->value_len);
pReader->binlog_offset += pRecord->record_length;
/*
printf("timestamp=%d, op_type=%c, key len=%d, value len=%d, " \
"record length=%d, offset=%d\n", \
(int)pRecord->timestamp, pRecord->op_type, \
pRecord->key_info.key_len, pRecord->value_len, \
pRecord->record_length, (int)pReader->binlog_offset);
*/
return 0;
}
static int compress_write_to_binlog(CompressWalkArg *pWalkArg, CompressRawRow *pRow)
{
if ((pRow->expires != FDHT_EXPIRES_NEVER && \
pRow->expires < gt_current_time) || \
(pRow->op_type == FDHT_OP_TYPE_SOURCE_DEL || \
pRow->op_type == FDHT_OP_TYPE_REPLICA_DEL))
{
return 0;
}
pWalkArg->row_count++;
if (pRow->record_length > pWalkArg->buff_size)
{
char *pTmp;
int new_size;
new_size = pRow->record_length + 4 * 1024;
pTmp = (char *)malloc(new_size);
if (pTmp == NULL)
{
logError("file: "__FILE__", line: %d, " \
"malloc %d bytes fail, " \
"errno: %d, error info: %s", __LINE__, \
new_size, errno, STRERROR(errno));
return errno != 0 ? errno : ENOMEM;
}
free(pWalkArg->buff);
pWalkArg->buff = pTmp;
pWalkArg->buff_size = new_size;
}
if (pWalkArg->pReader->binlog_offset != pRow->offset)
{
if (lseek(pWalkArg->pReader->binlog_fd, pRow->offset, SEEK_SET) < 0)
{
logError("file: "__FILE__", line: %d, " \
"lseek from binlog file \"%s\" fail, " \
"file offset: %"PRId64", " \
"errno: %d, error info: %s", __LINE__, \
compress_get_binlog_filename(pWalkArg->pReader, NULL), \
pRow->offset, errno, STRERROR(errno));
return errno != 0 ? errno : EIO;
}
}
if (read(pWalkArg->pReader->binlog_fd, pWalkArg->buff,
pRow->record_length) != pRow->record_length)
{
logError("file: "__FILE__", line: %d, " \
"read from binlog file \"%s\" fail, " \
"file offset: %"PRId64", " \
"errno: %d, error info: %s", __LINE__, \
compress_get_binlog_filename(pWalkArg->pReader, NULL), \
pRow->offset, errno, STRERROR(errno));
return errno != 0 ? errno : EIO;
}
if (write(pWalkArg->dest_fd, pWalkArg->buff,
pRow->record_length) != pRow->record_length)
{
logError("file: "__FILE__", line: %d, " \
"write to new binlog file \"%s.new\" fail, " \
"file offset: %"PRId64", " \
"errno: %d, error info: %s", __LINE__, \
compress_get_binlog_filename(pWalkArg->pReader, NULL), \
pRow->offset, errno, STRERROR(errno));
return errno != 0 ? errno : EIO;
}
pWalkArg->pReader->binlog_offset = pRow->offset + pRow->record_length;
return 0;
}
static int compress_binlog_file(CompressReader *pReader)
{
int result;
int row_count;
int item_count;
int bytes;
CompressRecord record;
CompressRawRow current_row;
CompressRawRow previous_row;
CompressWalkArg walk_arg;
int tmp_fd;
int sorted_fd;
char full_filename[MAX_PATH_SIZE];
char tmp_filename[MAX_PATH_SIZE];
char tmp_filepath[MAX_PATH_SIZE];
char sorted_filename[MAX_PATH_SIZE];
char new_filename[MAX_PATH_SIZE];
char full_key[FDHT_MAX_FULL_KEY_LEN];
char base64_key[(FDHT_MAX_FULL_KEY_LEN / 3) * 4];
char buff[(FDHT_MAX_FULL_KEY_LEN / 3) * 4 + 256];
char sort_progam[32];
int full_key_len;
int base64_key_len;
int buff_len;
char *p;
memset(&record, 0, sizeof(record));
if ((result=compress_open_readable_binlog(pReader)) != 0)
{
return result;
}
snprintf(tmp_filepath, sizeof(tmp_filepath), "%s/tmp", g_fdht_base_path);
compress_get_binlog_filename(pReader, full_filename);
snprintf(tmp_filename, sizeof(tmp_filename), "%s.tmp", full_filename);
snprintf(sorted_filename, sizeof(sorted_filename), \
"%s.sorted", full_filename);
if ((tmp_fd=open(tmp_filename, O_WRONLY | O_CREAT |
O_TRUNC, 0666)) < 0)
{
logError("file: "__FILE__", line: %d, " \
"open file %s fail, errno: %d, error info: %s", \
__LINE__, tmp_filename, errno, STRERROR(errno));
return errno != 0 ? errno : EACCES;
}
row_count = 0;
while (1)
{
result = compress_binlog_read(pReader, &record);
if (result != 0)
{
break;
}
FDHT_PACK_FULL_KEY(record.key_info, full_key, full_key_len, p)
base64_encode_ex(&gc_base64_context, full_key, full_key_len, \
base64_key, &base64_key_len, false);
buff_len = sprintf(buff, "%s %d %c %"PRId64" %d\n", \
base64_key, (int)record.expires, record.op_type, \
record.offset, record.record_length);
if (write(tmp_fd, buff, buff_len) != buff_len)
{
logError("file: "__FILE__", line: %d, " \
"write to file %s fail, " \
"errno: %d, error info: %s",\
__LINE__, tmp_filename, errno, STRERROR(errno));
return errno != 0 ? errno : EACCES;
}
row_count++;
}
close(tmp_fd);
if (result != 0 && result != ENOENT)
{
return result;
}
if (row_count == 0)
{
return result;
}
if (fileExists("/bin/sort"))
{
strcpy(sort_progam, "/bin/sort");
}
else
{
strcpy(sort_progam, "/usr/bin/sort");
}
sprintf(buff, "%s --stable --key=1,1 --temporary-directory=%s " \
"--output=%s %s", sort_progam, \
tmp_filepath, sorted_filename, tmp_filename);
result = system(buff);
unlink(tmp_filename);
if (result != 0)
{
logError("file: "__FILE__", line: %d, " \
"sort file %s fail, status: %d", \
__LINE__, tmp_filename, result);
return errno != 0 ? errno : ENOENT;
}
if ((sorted_fd=open(sorted_filename, O_RDONLY, 0666)) < 0)
{
logError("file: "__FILE__", line: %d, " \
"open file %s fail, errno: %d, error info: %s", \
__LINE__, sorted_filename, errno, STRERROR(errno));
return errno != 0 ? errno : EACCES;
}
if (lseek(pReader->binlog_fd, 0, SEEK_SET) < 0)
{
logError("file: "__FILE__", line: %d, " \
"lseek from binlog file \"%s\" fail, " \
"file offset: 0, " \
"errno: %d, error info: %s", __LINE__, \
compress_get_binlog_filename(pReader, NULL), \
errno, STRERROR(errno));
return errno != 0 ? errno : EIO;
}
memset(&walk_arg, 0, sizeof(walk_arg));
compress_get_binlog_filename(pReader, full_filename);
snprintf(new_filename, sizeof(new_filename), "%s.new", full_filename);
if (( walk_arg.dest_fd=open(new_filename, O_WRONLY | O_CREAT |
O_TRUNC, 0666)) < 0)
{
logError("file: "__FILE__", line: %d, " \
"open file %s fail, errno: %d, error info: %s", \
__LINE__, new_filename, errno, STRERROR(errno));
return errno != 0 ? errno : EACCES;
}
gt_current_time = time(NULL);
walk_arg.pReader = pReader;
walk_arg.buff_size = 64 * 1024;
walk_arg.buff = (char *)malloc(walk_arg.buff_size);
if (walk_arg.buff == NULL)
{
logError("file: "__FILE__", line: %d, " \
"malloc %d bytes fail, " \
"errno: %d, error info: %s", __LINE__, \
walk_arg.buff_size, errno, STRERROR(errno));
return errno != 0 ? errno : ENOMEM;
}
walk_arg.pReader->binlog_offset = 0;
memset(&previous_row, 0, sizeof(CompressRawRow));
memset(¤t_row, 0, sizeof(CompressRawRow));
while (1)
{
memcpy(&previous_row, ¤t_row, sizeof(CompressRawRow));
if ((bytes=fd_gets(sorted_fd, buff, sizeof(buff), 32)) < 0)
{
result = errno != 0 ? errno : EIO;
break;
}
if (bytes == 0)
{
break;
}
item_count=sscanf(buff, "%s %d %c %"PRId64" %d", \
current_row.key, (int *)¤t_row.expires, \
¤t_row.op_type, ¤t_row.offset, \
¤t_row.record_length);
if (item_count != 5)
{
logError("file: "__FILE__", line: %d, " \
"sscanf file %s fail, scan items: %d != 5", \
__LINE__, sorted_filename, item_count);
return errno != 0 ? errno : EACCES;
}
if (*previous_row.key == '\0' || strcmp(previous_row.key,
current_row.key) == 0)
{
continue;
}
if ((result=compress_write_to_binlog(&walk_arg, \
&previous_row)) != 0)
{
return result;
}
}
if (*previous_row.key != '\0')
{
if ((result=compress_write_to_binlog(&walk_arg, \
&previous_row)) != 0)
{
return result;
}
}
close(sorted_fd);
close(walk_arg.dest_fd);
close(pReader->binlog_fd);
pReader->binlog_fd = -1;
unlink(sorted_filename);
if (result != 0)
{
return result;
}
if (rename(new_filename, full_filename) != 0)
{
logError("file: "__FILE__", line: %d, " \
"rename file from %s to %s fail, " \
"errno: %d, error info: %s", \
__LINE__, new_filename, full_filename,
errno, STRERROR(errno));
return errno != 0 ? errno : EACCES;
}
logInfo("binlog: %s, row count before compress=%d, after compress=%d" \
, full_filename, row_count, walk_arg.row_count);
return result;
}
| {
"language": "C"
} |
// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause)
//
// This file is provided under a dual BSD/GPLv2 license. When using or
// redistributing this file, you may do so under either license.
//
// Copyright(c) 2018 Intel Corporation. All rights reserved.
//
// Author: Liam Girdwood <liam.r.girdwood@linux.intel.com>
//
#include "ops.h"
#include "sof-priv.h"
#include "sof-audio.h"
/*
* Helper function to determine the target DSP state during
* system suspend. This function only cares about the device
* D-states. Platform-specific substates, if any, should be
* handled by the platform-specific parts.
*/
static u32 snd_sof_dsp_power_target(struct snd_sof_dev *sdev)
{
u32 target_dsp_state;
switch (sdev->system_suspend_target) {
case SOF_SUSPEND_S3:
/* DSP should be in D3 if the system is suspending to S3 */
target_dsp_state = SOF_DSP_PM_D3;
break;
case SOF_SUSPEND_S0IX:
/*
* Currently, the only criterion for retaining the DSP in D0
* is that there are streams that ignored the suspend trigger.
* Additional criteria such Soundwire clock-stop mode and
* device suspend latency considerations will be added later.
*/
if (snd_sof_stream_suspend_ignored(sdev))
target_dsp_state = SOF_DSP_PM_D0;
else
target_dsp_state = SOF_DSP_PM_D3;
break;
default:
/* This case would be during runtime suspend */
target_dsp_state = SOF_DSP_PM_D3;
break;
}
return target_dsp_state;
}
static int sof_send_pm_ctx_ipc(struct snd_sof_dev *sdev, int cmd)
{
struct sof_ipc_pm_ctx pm_ctx;
struct sof_ipc_reply reply;
memset(&pm_ctx, 0, sizeof(pm_ctx));
/* configure ctx save ipc message */
pm_ctx.hdr.size = sizeof(pm_ctx);
pm_ctx.hdr.cmd = SOF_IPC_GLB_PM_MSG | cmd;
/* send ctx save ipc to dsp */
return sof_ipc_tx_message(sdev->ipc, pm_ctx.hdr.cmd, &pm_ctx,
sizeof(pm_ctx), &reply, sizeof(reply));
}
#if IS_ENABLED(CONFIG_SND_SOC_SOF_DEBUG_ENABLE_DEBUGFS_CACHE)
static void sof_cache_debugfs(struct snd_sof_dev *sdev)
{
struct snd_sof_dfsentry *dfse;
list_for_each_entry(dfse, &sdev->dfsentry_list, list) {
/* nothing to do if debugfs buffer is not IO mem */
if (dfse->type == SOF_DFSENTRY_TYPE_BUF)
continue;
/* cache memory that is only accessible in D0 */
if (dfse->access_type == SOF_DEBUGFS_ACCESS_D0_ONLY)
memcpy_fromio(dfse->cache_buf, dfse->io_mem,
dfse->size);
}
}
#endif
static int sof_resume(struct device *dev, bool runtime_resume)
{
struct snd_sof_dev *sdev = dev_get_drvdata(dev);
u32 old_state = sdev->dsp_power_state.state;
int ret;
/* do nothing if dsp resume callbacks are not set */
if (!runtime_resume && !sof_ops(sdev)->resume)
return 0;
if (runtime_resume && !sof_ops(sdev)->runtime_resume)
return 0;
/* DSP was never successfully started, nothing to resume */
if (sdev->first_boot)
return 0;
/*
* if the runtime_resume flag is set, call the runtime_resume routine
* or else call the system resume routine
*/
if (runtime_resume)
ret = snd_sof_dsp_runtime_resume(sdev);
else
ret = snd_sof_dsp_resume(sdev);
if (ret < 0) {
dev_err(sdev->dev,
"error: failed to power up DSP after resume\n");
return ret;
}
/*
* Nothing further to be done for platforms that support the low power
* D0 substate.
*/
if (!runtime_resume && sof_ops(sdev)->set_power_state &&
old_state == SOF_DSP_PM_D0)
return 0;
sdev->fw_state = SOF_FW_BOOT_PREPARE;
/* load the firmware */
ret = snd_sof_load_firmware(sdev);
if (ret < 0) {
dev_err(sdev->dev,
"error: failed to load DSP firmware after resume %d\n",
ret);
return ret;
}
sdev->fw_state = SOF_FW_BOOT_IN_PROGRESS;
/*
* Boot the firmware. The FW boot status will be modified
* in snd_sof_run_firmware() depending on the outcome.
*/
ret = snd_sof_run_firmware(sdev);
if (ret < 0) {
dev_err(sdev->dev,
"error: failed to boot DSP firmware after resume %d\n",
ret);
return ret;
}
/* resume DMA trace, only need send ipc */
ret = snd_sof_init_trace_ipc(sdev);
if (ret < 0) {
/* non fatal */
dev_warn(sdev->dev,
"warning: failed to init trace after resume %d\n",
ret);
}
/* restore pipelines */
ret = sof_restore_pipelines(sdev->dev);
if (ret < 0) {
dev_err(sdev->dev,
"error: failed to restore pipeline after resume %d\n",
ret);
return ret;
}
/* notify DSP of system resume */
ret = sof_send_pm_ctx_ipc(sdev, SOF_IPC_PM_CTX_RESTORE);
if (ret < 0)
dev_err(sdev->dev,
"error: ctx_restore ipc error during resume %d\n",
ret);
return ret;
}
static int sof_suspend(struct device *dev, bool runtime_suspend)
{
struct snd_sof_dev *sdev = dev_get_drvdata(dev);
u32 target_state = 0;
int ret;
/* do nothing if dsp suspend callback is not set */
if (!runtime_suspend && !sof_ops(sdev)->suspend)
return 0;
if (runtime_suspend && !sof_ops(sdev)->runtime_suspend)
return 0;
if (sdev->fw_state != SOF_FW_BOOT_COMPLETE)
goto suspend;
/* set restore_stream for all streams during system suspend */
if (!runtime_suspend) {
ret = sof_set_hw_params_upon_resume(sdev->dev);
if (ret < 0) {
dev_err(sdev->dev,
"error: setting hw_params flag during suspend %d\n",
ret);
return ret;
}
}
target_state = snd_sof_dsp_power_target(sdev);
/* Skip to platform-specific suspend if DSP is entering D0 */
if (target_state == SOF_DSP_PM_D0)
goto suspend;
/* release trace */
snd_sof_release_trace(sdev);
#if IS_ENABLED(CONFIG_SND_SOC_SOF_DEBUG_ENABLE_DEBUGFS_CACHE)
/* cache debugfs contents during runtime suspend */
if (runtime_suspend)
sof_cache_debugfs(sdev);
#endif
/* notify DSP of upcoming power down */
ret = sof_send_pm_ctx_ipc(sdev, SOF_IPC_PM_CTX_SAVE);
if (ret == -EBUSY || ret == -EAGAIN) {
/*
* runtime PM has logic to handle -EBUSY/-EAGAIN so
* pass these errors up
*/
dev_err(sdev->dev,
"error: ctx_save ipc error during suspend %d\n",
ret);
return ret;
} else if (ret < 0) {
/* FW in unexpected state, continue to power down */
dev_warn(sdev->dev,
"ctx_save ipc error %d, proceeding with suspend\n",
ret);
}
suspend:
/* return if the DSP was not probed successfully */
if (sdev->fw_state == SOF_FW_BOOT_NOT_STARTED)
return 0;
/* platform-specific suspend */
if (runtime_suspend)
ret = snd_sof_dsp_runtime_suspend(sdev);
else
ret = snd_sof_dsp_suspend(sdev, target_state);
if (ret < 0)
dev_err(sdev->dev,
"error: failed to power down DSP during suspend %d\n",
ret);
/* Do not reset FW state if DSP is in D0 */
if (target_state == SOF_DSP_PM_D0)
return ret;
/* reset FW state */
sdev->fw_state = SOF_FW_BOOT_NOT_STARTED;
return ret;
}
int snd_sof_dsp_power_down_notify(struct snd_sof_dev *sdev)
{
/* Notify DSP of upcoming power down */
if (sof_ops(sdev)->remove)
return sof_send_pm_ctx_ipc(sdev, SOF_IPC_PM_CTX_SAVE);
return 0;
}
int snd_sof_runtime_suspend(struct device *dev)
{
return sof_suspend(dev, true);
}
EXPORT_SYMBOL(snd_sof_runtime_suspend);
int snd_sof_runtime_idle(struct device *dev)
{
struct snd_sof_dev *sdev = dev_get_drvdata(dev);
return snd_sof_dsp_runtime_idle(sdev);
}
EXPORT_SYMBOL(snd_sof_runtime_idle);
int snd_sof_runtime_resume(struct device *dev)
{
return sof_resume(dev, true);
}
EXPORT_SYMBOL(snd_sof_runtime_resume);
int snd_sof_resume(struct device *dev)
{
return sof_resume(dev, false);
}
EXPORT_SYMBOL(snd_sof_resume);
int snd_sof_suspend(struct device *dev)
{
return sof_suspend(dev, false);
}
EXPORT_SYMBOL(snd_sof_suspend);
int snd_sof_prepare(struct device *dev)
{
struct snd_sof_dev *sdev = dev_get_drvdata(dev);
#if defined(CONFIG_ACPI)
if (acpi_target_system_state() == ACPI_STATE_S0)
sdev->system_suspend_target = SOF_SUSPEND_S0IX;
else
sdev->system_suspend_target = SOF_SUSPEND_S3;
#else
/* will suspend to S3 by default */
sdev->system_suspend_target = SOF_SUSPEND_S3;
#endif
return 0;
}
EXPORT_SYMBOL(snd_sof_prepare);
void snd_sof_complete(struct device *dev)
{
struct snd_sof_dev *sdev = dev_get_drvdata(dev);
sdev->system_suspend_target = SOF_SUSPEND_NONE;
}
EXPORT_SYMBOL(snd_sof_complete);
| {
"language": "C"
} |
/*
* Copyright 2018 Scott Vokes
*
* See LICENCE for the full copyright terms.
*/
#ifndef RE_AST_COMPILE_H
#define RE_AST_COMPILE_H
/*
* Compilation to FSM
*/
struct fsm;
struct re_err;
struct fsm *
ast_compile(const struct ast *ast,
enum re_flags re_flags,
const struct fsm_options *opt,
struct re_err *err);
#endif
| {
"language": "C"
} |
/*
* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* *********************************************************************
*
* The Original Code is the MPI Arbitrary Precision Integer Arithmetic library.
*
* The Initial Developer of the Original Code is
* Michael J. Fromberger.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*********************************************************************** */
/* Bitwise logical operations on MPI values */
#ifndef _MPLOGIC_H
#define _MPLOGIC_H
/* $Id: mplogic.h,v 1.7 2004/04/27 23:04:36 gerv%gerv.net Exp $ */
#include "mpi.h"
/*
The logical operations treat an mp_int as if it were a bit vector,
without regard to its sign (an mp_int is represented in a signed
magnitude format). Values are treated as if they had an infinite
string of zeros left of the most-significant bit.
*/
/* Parity results */
#define MP_EVEN MP_YES
#define MP_ODD MP_NO
/* Bitwise functions */
mp_err mpl_not(mp_int *a, mp_int *b); /* one's complement */
mp_err mpl_and(mp_int *a, mp_int *b, mp_int *c); /* bitwise AND */
mp_err mpl_or(mp_int *a, mp_int *b, mp_int *c); /* bitwise OR */
mp_err mpl_xor(mp_int *a, mp_int *b, mp_int *c); /* bitwise XOR */
/* Shift functions */
mp_err mpl_rsh(const mp_int *a, mp_int *b, mp_digit d); /* right shift */
mp_err mpl_lsh(const mp_int *a, mp_int *b, mp_digit d); /* left shift */
/* Bit count and parity */
mp_err mpl_num_set(mp_int *a, int *num); /* count set bits */
mp_err mpl_num_clear(mp_int *a, int *num); /* count clear bits */
mp_err mpl_parity(mp_int *a); /* determine parity */
/* Get & Set the value of a bit */
mp_err mpl_set_bit(mp_int *a, mp_size bitNum, mp_size value);
mp_err mpl_get_bit(const mp_int *a, mp_size bitNum);
mp_err mpl_get_bits(const mp_int *a, mp_size lsbNum, mp_size numBits);
mp_err mpl_significant_bits(const mp_int *a);
#endif /* _MPLOGIC_H */
| {
"language": "C"
} |
/*
* module.c - module sysfs fun for drivers
*
* This file is released under the GPLv2
*
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/string.h>
#include "base.h"
static char *make_driver_name(struct device_driver *drv)
{
char *driver_name;
driver_name = kasprintf(GFP_KERNEL, "%s:%s", drv->bus->name, drv->name);
if (!driver_name)
return NULL;
return driver_name;
}
static void module_create_drivers_dir(struct module_kobject *mk)
{
static DEFINE_MUTEX(drivers_dir_mutex);
mutex_lock(&drivers_dir_mutex);
if (mk && !mk->drivers_dir)
mk->drivers_dir = kobject_create_and_add("drivers", &mk->kobj);
mutex_unlock(&drivers_dir_mutex);
}
void module_add_driver(struct module *mod, struct device_driver *drv)
{
char *driver_name;
int no_warn;
struct module_kobject *mk = NULL;
if (!drv)
return;
if (mod)
mk = &mod->mkobj;
else if (drv->mod_name) {
struct kobject *mkobj;
/* Lookup built-in module entry in /sys/modules */
mkobj = kset_find_obj(module_kset, drv->mod_name);
if (mkobj) {
mk = container_of(mkobj, struct module_kobject, kobj);
/* remember our module structure */
drv->p->mkobj = mk;
/* kset_find_obj took a reference */
kobject_put(mkobj);
}
}
if (!mk)
return;
/* Don't check return codes; these calls are idempotent */
no_warn = sysfs_create_link(&drv->p->kobj, &mk->kobj, "module");
driver_name = make_driver_name(drv);
if (driver_name) {
module_create_drivers_dir(mk);
no_warn = sysfs_create_link(mk->drivers_dir, &drv->p->kobj,
driver_name);
kfree(driver_name);
}
}
void module_remove_driver(struct device_driver *drv)
{
struct module_kobject *mk = NULL;
char *driver_name;
if (!drv)
return;
sysfs_remove_link(&drv->p->kobj, "module");
if (drv->owner)
mk = &drv->owner->mkobj;
else if (drv->p->mkobj)
mk = drv->p->mkobj;
if (mk && mk->drivers_dir) {
driver_name = make_driver_name(drv);
if (driver_name) {
sysfs_remove_link(mk->drivers_dir, driver_name);
kfree(driver_name);
}
}
}
| {
"language": "C"
} |
/*
* Copyright 2014 Martin Peres
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Martin Peres
*/
#include "priv.h"
static int
gm107_fan_pwm_ctrl(struct nvkm_therm *therm, int line, bool enable)
{
/* nothing to do, it seems hardwired */
return 0;
}
static int
gm107_fan_pwm_get(struct nvkm_therm *therm, int line, u32 *divs, u32 *duty)
{
struct nvkm_device *device = therm->subdev.device;
*divs = nvkm_rd32(device, 0x10eb20) & 0x1fff;
*duty = nvkm_rd32(device, 0x10eb24) & 0x1fff;
return 0;
}
static int
gm107_fan_pwm_set(struct nvkm_therm *therm, int line, u32 divs, u32 duty)
{
struct nvkm_device *device = therm->subdev.device;
nvkm_mask(device, 0x10eb10, 0x1fff, divs); /* keep the high bits */
nvkm_wr32(device, 0x10eb14, duty | 0x80000000);
return 0;
}
static int
gm107_fan_pwm_clock(struct nvkm_therm *therm, int line)
{
return therm->subdev.device->crystal * 1000;
}
static const struct nvkm_therm_func
gm107_therm = {
.init = gf119_therm_init,
.fini = g84_therm_fini,
.pwm_ctrl = gm107_fan_pwm_ctrl,
.pwm_get = gm107_fan_pwm_get,
.pwm_set = gm107_fan_pwm_set,
.pwm_clock = gm107_fan_pwm_clock,
.temp_get = g84_temp_get,
.fan_sense = gt215_therm_fan_sense,
.program_alarms = nvkm_therm_program_alarms_polling,
};
int
gm107_therm_new(struct nvkm_device *device, int index,
struct nvkm_therm **ptherm)
{
return nvkm_therm_new_(&gm107_therm, device, index, ptherm);
}
| {
"language": "C"
} |
/*
* sched_setschedparam.c
*
* Description:
* POSIX thread functions that deal with thread scheduling.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "pthread.h"
#include "implement.h"
#include "sched.h"
int
pthread_setschedparam (pthread_t thread, int policy,
const struct sched_param *param)
{
int result;
/* Validate the thread id. */
result = pthread_kill (thread, 0);
if (0 != result)
{
return result;
}
/* Validate the scheduling policy. */
if (policy < SCHED_MIN || policy > SCHED_MAX)
{
return EINVAL;
}
/* Ensure the policy is SCHED_OTHER. */
if (policy != SCHED_OTHER)
{
return ENOTSUP;
}
return (ptw32_setthreadpriority (thread, policy, param->sched_priority));
}
int
ptw32_setthreadpriority (pthread_t thread, int policy, int priority)
{
int prio;
int result;
ptw32_thread_t * tp = (ptw32_thread_t *) thread.p;
prio = priority;
/* Validate priority level. */
if (prio < sched_get_priority_min (policy) ||
prio > sched_get_priority_max (policy))
{
return EINVAL;
}
#if (THREAD_PRIORITY_LOWEST > THREAD_PRIORITY_NORMAL)
/* WinCE */
#else
/* Everything else */
if (THREAD_PRIORITY_IDLE < prio && THREAD_PRIORITY_LOWEST > prio)
{
prio = THREAD_PRIORITY_LOWEST;
}
else if (THREAD_PRIORITY_TIME_CRITICAL > prio
&& THREAD_PRIORITY_HIGHEST < prio)
{
prio = THREAD_PRIORITY_HIGHEST;
}
#endif
result = pthread_mutex_lock (&tp->threadLock);
if (0 == result)
{
/* If this fails, the current priority is unchanged. */
if (0 == SetThreadPriority (tp->threadH, prio))
{
result = EINVAL;
}
else
{
/*
* Must record the thread's sched_priority as given,
* not as finally adjusted.
*/
tp->sched_priority = priority;
}
(void) pthread_mutex_unlock (&tp->threadLock);
}
return result;
}
| {
"language": "C"
} |
/* SPDX-License-Identifier: GPL-2.0 */
/*
* Copyright (C) 2016-2018 Texas Instruments Incorporated - http://www.ti.com/
* Author: Jyri Sarha <jsarha@ti.com>
*/
#ifndef __TIDSS_DISPC_REGS_H
#define __TIDSS_DISPC_REGS_H
enum dispc_common_regs {
NOT_APPLICABLE_OFF = 0,
DSS_REVISION_OFF,
DSS_SYSCONFIG_OFF,
DSS_SYSSTATUS_OFF,
DISPC_IRQ_EOI_OFF,
DISPC_IRQSTATUS_RAW_OFF,
DISPC_IRQSTATUS_OFF,
DISPC_IRQENABLE_SET_OFF,
DISPC_IRQENABLE_CLR_OFF,
DISPC_VID_IRQENABLE_OFF,
DISPC_VID_IRQSTATUS_OFF,
DISPC_VP_IRQENABLE_OFF,
DISPC_VP_IRQSTATUS_OFF,
WB_IRQENABLE_OFF,
WB_IRQSTATUS_OFF,
DISPC_GLOBAL_MFLAG_ATTRIBUTE_OFF,
DISPC_GLOBAL_OUTPUT_ENABLE_OFF,
DISPC_GLOBAL_BUFFER_OFF,
DSS_CBA_CFG_OFF,
DISPC_DBG_CONTROL_OFF,
DISPC_DBG_STATUS_OFF,
DISPC_CLKGATING_DISABLE_OFF,
DISPC_SECURE_DISABLE_OFF,
FBDC_REVISION_1_OFF,
FBDC_REVISION_2_OFF,
FBDC_REVISION_3_OFF,
FBDC_REVISION_4_OFF,
FBDC_REVISION_5_OFF,
FBDC_REVISION_6_OFF,
FBDC_COMMON_CONTROL_OFF,
FBDC_CONSTANT_COLOR_0_OFF,
FBDC_CONSTANT_COLOR_1_OFF,
DISPC_CONNECTIONS_OFF,
DISPC_MSS_VP1_OFF,
DISPC_MSS_VP3_OFF,
DISPC_COMMON_REG_TABLE_LEN,
};
/*
* dispc_common_regmap should be defined as const u16 * and pointing
* to a valid dss common register map for the platform, before the
* macros bellow can be used.
*/
#define REG(r) (dispc_common_regmap[r ## _OFF])
#define DSS_REVISION REG(DSS_REVISION)
#define DSS_SYSCONFIG REG(DSS_SYSCONFIG)
#define DSS_SYSSTATUS REG(DSS_SYSSTATUS)
#define DISPC_IRQ_EOI REG(DISPC_IRQ_EOI)
#define DISPC_IRQSTATUS_RAW REG(DISPC_IRQSTATUS_RAW)
#define DISPC_IRQSTATUS REG(DISPC_IRQSTATUS)
#define DISPC_IRQENABLE_SET REG(DISPC_IRQENABLE_SET)
#define DISPC_IRQENABLE_CLR REG(DISPC_IRQENABLE_CLR)
#define DISPC_VID_IRQENABLE(n) (REG(DISPC_VID_IRQENABLE) + (n) * 4)
#define DISPC_VID_IRQSTATUS(n) (REG(DISPC_VID_IRQSTATUS) + (n) * 4)
#define DISPC_VP_IRQENABLE(n) (REG(DISPC_VP_IRQENABLE) + (n) * 4)
#define DISPC_VP_IRQSTATUS(n) (REG(DISPC_VP_IRQSTATUS) + (n) * 4)
#define WB_IRQENABLE REG(WB_IRQENABLE)
#define WB_IRQSTATUS REG(WB_IRQSTATUS)
#define DISPC_GLOBAL_MFLAG_ATTRIBUTE REG(DISPC_GLOBAL_MFLAG_ATTRIBUTE)
#define DISPC_GLOBAL_OUTPUT_ENABLE REG(DISPC_GLOBAL_OUTPUT_ENABLE)
#define DISPC_GLOBAL_BUFFER REG(DISPC_GLOBAL_BUFFER)
#define DSS_CBA_CFG REG(DSS_CBA_CFG)
#define DISPC_DBG_CONTROL REG(DISPC_DBG_CONTROL)
#define DISPC_DBG_STATUS REG(DISPC_DBG_STATUS)
#define DISPC_CLKGATING_DISABLE REG(DISPC_CLKGATING_DISABLE)
#define DISPC_SECURE_DISABLE REG(DISPC_SECURE_DISABLE)
#define FBDC_REVISION_1 REG(FBDC_REVISION_1)
#define FBDC_REVISION_2 REG(FBDC_REVISION_2)
#define FBDC_REVISION_3 REG(FBDC_REVISION_3)
#define FBDC_REVISION_4 REG(FBDC_REVISION_4)
#define FBDC_REVISION_5 REG(FBDC_REVISION_5)
#define FBDC_REVISION_6 REG(FBDC_REVISION_6)
#define FBDC_COMMON_CONTROL REG(FBDC_COMMON_CONTROL)
#define FBDC_CONSTANT_COLOR_0 REG(FBDC_CONSTANT_COLOR_0)
#define FBDC_CONSTANT_COLOR_1 REG(FBDC_CONSTANT_COLOR_1)
#define DISPC_CONNECTIONS REG(DISPC_CONNECTIONS)
#define DISPC_MSS_VP1 REG(DISPC_MSS_VP1)
#define DISPC_MSS_VP3 REG(DISPC_MSS_VP3)
/* VID */
#define DISPC_VID_ACCUH_0 0x0
#define DISPC_VID_ACCUH_1 0x4
#define DISPC_VID_ACCUH2_0 0x8
#define DISPC_VID_ACCUH2_1 0xc
#define DISPC_VID_ACCUV_0 0x10
#define DISPC_VID_ACCUV_1 0x14
#define DISPC_VID_ACCUV2_0 0x18
#define DISPC_VID_ACCUV2_1 0x1c
#define DISPC_VID_ATTRIBUTES 0x20
#define DISPC_VID_ATTRIBUTES2 0x24
#define DISPC_VID_BA_0 0x28
#define DISPC_VID_BA_1 0x2c
#define DISPC_VID_BA_UV_0 0x30
#define DISPC_VID_BA_UV_1 0x34
#define DISPC_VID_BUF_SIZE_STATUS 0x38
#define DISPC_VID_BUF_THRESHOLD 0x3c
#define DISPC_VID_CSC_COEF(n) (0x40 + (n) * 4)
#define DISPC_VID_FIRH 0x5c
#define DISPC_VID_FIRH2 0x60
#define DISPC_VID_FIRV 0x64
#define DISPC_VID_FIRV2 0x68
#define DISPC_VID_FIR_COEFS_H0 0x6c
#define DISPC_VID_FIR_COEF_H0(phase) (0x6c + (phase) * 4)
#define DISPC_VID_FIR_COEFS_H0_C 0x90
#define DISPC_VID_FIR_COEF_H0_C(phase) (0x90 + (phase) * 4)
#define DISPC_VID_FIR_COEFS_H12 0xb4
#define DISPC_VID_FIR_COEF_H12(phase) (0xb4 + (phase) * 4)
#define DISPC_VID_FIR_COEFS_H12_C 0xf4
#define DISPC_VID_FIR_COEF_H12_C(phase) (0xf4 + (phase) * 4)
#define DISPC_VID_FIR_COEFS_V0 0x134
#define DISPC_VID_FIR_COEF_V0(phase) (0x134 + (phase) * 4)
#define DISPC_VID_FIR_COEFS_V0_C 0x158
#define DISPC_VID_FIR_COEF_V0_C(phase) (0x158 + (phase) * 4)
#define DISPC_VID_FIR_COEFS_V12 0x17c
#define DISPC_VID_FIR_COEF_V12(phase) (0x17c + (phase) * 4)
#define DISPC_VID_FIR_COEFS_V12_C 0x1bc
#define DISPC_VID_FIR_COEF_V12_C(phase) (0x1bc + (phase) * 4)
#define DISPC_VID_GLOBAL_ALPHA 0x1fc
#define DISPC_VID_K2G_IRQENABLE 0x200 /* K2G */
#define DISPC_VID_K2G_IRQSTATUS 0x204 /* K2G */
#define DISPC_VID_MFLAG_THRESHOLD 0x208
#define DISPC_VID_PICTURE_SIZE 0x20c
#define DISPC_VID_PIXEL_INC 0x210
#define DISPC_VID_K2G_POSITION 0x214 /* K2G */
#define DISPC_VID_PRELOAD 0x218
#define DISPC_VID_ROW_INC 0x21c
#define DISPC_VID_SIZE 0x220
#define DISPC_VID_BA_EXT_0 0x22c
#define DISPC_VID_BA_EXT_1 0x230
#define DISPC_VID_BA_UV_EXT_0 0x234
#define DISPC_VID_BA_UV_EXT_1 0x238
#define DISPC_VID_CSC_COEF7 0x23c
#define DISPC_VID_ROW_INC_UV 0x248
#define DISPC_VID_CLUT 0x260
#define DISPC_VID_SAFETY_ATTRIBUTES 0x2a0
#define DISPC_VID_SAFETY_CAPT_SIGNATURE 0x2a4
#define DISPC_VID_SAFETY_POSITION 0x2a8
#define DISPC_VID_SAFETY_REF_SIGNATURE 0x2ac
#define DISPC_VID_SAFETY_SIZE 0x2b0
#define DISPC_VID_SAFETY_LFSR_SEED 0x2b4
#define DISPC_VID_LUMAKEY 0x2b8
#define DISPC_VID_DMA_BUFSIZE 0x2bc /* J721E */
/* OVR */
#define DISPC_OVR_CONFIG 0x0
#define DISPC_OVR_VIRTVP 0x4 /* J721E */
#define DISPC_OVR_DEFAULT_COLOR 0x8
#define DISPC_OVR_DEFAULT_COLOR2 0xc
#define DISPC_OVR_TRANS_COLOR_MAX 0x10
#define DISPC_OVR_TRANS_COLOR_MAX2 0x14
#define DISPC_OVR_TRANS_COLOR_MIN 0x18
#define DISPC_OVR_TRANS_COLOR_MIN2 0x1c
#define DISPC_OVR_ATTRIBUTES(n) (0x20 + (n) * 4)
#define DISPC_OVR_ATTRIBUTES2(n) (0x34 + (n) * 4) /* J721E */
/* VP */
#define DISPC_VP_CONFIG 0x0
#define DISPC_VP_CONTROL 0x4
#define DISPC_VP_CSC_COEF0 0x8
#define DISPC_VP_CSC_COEF1 0xc
#define DISPC_VP_CSC_COEF2 0x10
#define DISPC_VP_DATA_CYCLE_0 0x14
#define DISPC_VP_DATA_CYCLE_1 0x18
#define DISPC_VP_K2G_GAMMA_TABLE 0x20 /* K2G */
#define DISPC_VP_K2G_IRQENABLE 0x3c /* K2G */
#define DISPC_VP_K2G_IRQSTATUS 0x40 /* K2G */
#define DISPC_VP_DATA_CYCLE_2 0x1c
#define DISPC_VP_LINE_NUMBER 0x44
#define DISPC_VP_POL_FREQ 0x4c
#define DISPC_VP_SIZE_SCREEN 0x50
#define DISPC_VP_TIMING_H 0x54
#define DISPC_VP_TIMING_V 0x58
#define DISPC_VP_CSC_COEF3 0x5c
#define DISPC_VP_CSC_COEF4 0x60
#define DISPC_VP_CSC_COEF5 0x64
#define DISPC_VP_CSC_COEF6 0x68
#define DISPC_VP_CSC_COEF7 0x6c
#define DISPC_VP_SAFETY_ATTRIBUTES_0 0x70
#define DISPC_VP_SAFETY_ATTRIBUTES_1 0x74
#define DISPC_VP_SAFETY_ATTRIBUTES_2 0x78
#define DISPC_VP_SAFETY_ATTRIBUTES_3 0x7c
#define DISPC_VP_SAFETY_CAPT_SIGNATURE_0 0x90
#define DISPC_VP_SAFETY_CAPT_SIGNATURE_1 0x94
#define DISPC_VP_SAFETY_CAPT_SIGNATURE_2 0x98
#define DISPC_VP_SAFETY_CAPT_SIGNATURE_3 0x9c
#define DISPC_VP_SAFETY_POSITION_0 0xb0
#define DISPC_VP_SAFETY_POSITION_1 0xb4
#define DISPC_VP_SAFETY_POSITION_2 0xb8
#define DISPC_VP_SAFETY_POSITION_3 0xbc
#define DISPC_VP_SAFETY_REF_SIGNATURE_0 0xd0
#define DISPC_VP_SAFETY_REF_SIGNATURE_1 0xd4
#define DISPC_VP_SAFETY_REF_SIGNATURE_2 0xd8
#define DISPC_VP_SAFETY_REF_SIGNATURE_3 0xdc
#define DISPC_VP_SAFETY_SIZE_0 0xf0
#define DISPC_VP_SAFETY_SIZE_1 0xf4
#define DISPC_VP_SAFETY_SIZE_2 0xf8
#define DISPC_VP_SAFETY_SIZE_3 0xfc
#define DISPC_VP_SAFETY_LFSR_SEED 0x110
#define DISPC_VP_GAMMA_TABLE 0x120
#define DISPC_VP_DSS_OLDI_CFG 0x160
#define DISPC_VP_DSS_OLDI_STATUS 0x164
#define DISPC_VP_DSS_OLDI_LB 0x168
#define DISPC_VP_DSS_MERGE_SPLIT 0x16c /* J721E */
#define DISPC_VP_DSS_DMA_THREADSIZE 0x170 /* J721E */
#define DISPC_VP_DSS_DMA_THREADSIZE_STATUS 0x174 /* J721E */
/*
* OLDI IO_CTRL register offsets. On AM654 the registers are found
* from CTRL_MMR0, there the syscon regmap should map 0x14 bytes from
* CTRLMMR0P1_OLDI_DAT0_IO_CTRL to CTRLMMR0P1_OLDI_CLK_IO_CTRL
* register range.
*/
#define OLDI_DAT0_IO_CTRL 0x00
#define OLDI_DAT1_IO_CTRL 0x04
#define OLDI_DAT2_IO_CTRL 0x08
#define OLDI_DAT3_IO_CTRL 0x0C
#define OLDI_CLK_IO_CTRL 0x10
#define OLDI_PWRDN_TX BIT(8)
#endif /* __TIDSS_DISPC_REGS_H */
| {
"language": "C"
} |
/* Common definition for ifunc selections optimized with SSSE3 and
SSE4_2.
All versions must be listed in ifunc-impl-list.c.
Copyright (C) 2017-2018 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <init-arch.h>
extern __typeof (REDIRECT_NAME) OPTIMIZE (ia32) attribute_hidden;
extern __typeof (REDIRECT_NAME) OPTIMIZE (ssse3) attribute_hidden;
extern __typeof (REDIRECT_NAME) OPTIMIZE (sse4_2) attribute_hidden;
static inline void *
IFUNC_SELECTOR (void)
{
const struct cpu_features* cpu_features = __get_cpu_features ();
if (CPU_FEATURES_CPU_P (cpu_features, SSE4_2))
return OPTIMIZE (sse4_2);
if (CPU_FEATURES_CPU_P (cpu_features, SSSE3))
return OPTIMIZE (ssse3);
return OPTIMIZE (ia32);
}
| {
"language": "C"
} |
/*
* sc520_freq.c: cpufreq driver for the AMD Elan sc520
*
* Copyright (C) 2005 Sean Young <sean@mess.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Based on elanfreq.c
*
* 2005-03-30: - initial revision
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/cpufreq.h>
#include <linux/timex.h>
#include <linux/io.h>
#include <asm/cpu_device_id.h>
#include <asm/msr.h>
#define MMCR_BASE 0xfffef000 /* The default base address */
#define OFFS_CPUCTL 0x2 /* CPU Control Register */
static __u8 __iomem *cpuctl;
#define PFX "sc520_freq: "
static struct cpufreq_frequency_table sc520_freq_table[] = {
{0x01, 100000},
{0x02, 133000},
{0, CPUFREQ_TABLE_END},
};
static unsigned int sc520_freq_get_cpu_frequency(unsigned int cpu)
{
u8 clockspeed_reg = *cpuctl;
switch (clockspeed_reg & 0x03) {
default:
printk(KERN_ERR PFX "error: cpuctl register has unexpected "
"value %02x\n", clockspeed_reg);
case 0x01:
return 100000;
case 0x02:
return 133000;
}
}
static void sc520_freq_set_cpu_state(unsigned int state)
{
struct cpufreq_freqs freqs;
u8 clockspeed_reg;
freqs.old = sc520_freq_get_cpu_frequency(0);
freqs.new = sc520_freq_table[state].frequency;
freqs.cpu = 0; /* AMD Elan is UP */
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
pr_debug("attempting to set frequency to %i kHz\n",
sc520_freq_table[state].frequency);
local_irq_disable();
clockspeed_reg = *cpuctl & ~0x03;
*cpuctl = clockspeed_reg | sc520_freq_table[state].index;
local_irq_enable();
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
};
static int sc520_freq_verify(struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy, &sc520_freq_table[0]);
}
static int sc520_freq_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
unsigned int newstate = 0;
if (cpufreq_frequency_table_target(policy, sc520_freq_table,
target_freq, relation, &newstate))
return -EINVAL;
sc520_freq_set_cpu_state(newstate);
return 0;
}
/*
* Module init and exit code
*/
static int sc520_freq_cpu_init(struct cpufreq_policy *policy)
{
struct cpuinfo_x86 *c = &cpu_data(0);
int result;
/* capability check */
if (c->x86_vendor != X86_VENDOR_AMD ||
c->x86 != 4 || c->x86_model != 9)
return -ENODEV;
/* cpuinfo and default policy values */
policy->cpuinfo.transition_latency = 1000000; /* 1ms */
policy->cur = sc520_freq_get_cpu_frequency(0);
result = cpufreq_frequency_table_cpuinfo(policy, sc520_freq_table);
if (result)
return result;
cpufreq_frequency_table_get_attr(sc520_freq_table, policy->cpu);
return 0;
}
static int sc520_freq_cpu_exit(struct cpufreq_policy *policy)
{
cpufreq_frequency_table_put_attr(policy->cpu);
return 0;
}
static struct freq_attr *sc520_freq_attr[] = {
&cpufreq_freq_attr_scaling_available_freqs,
NULL,
};
static struct cpufreq_driver sc520_freq_driver = {
.get = sc520_freq_get_cpu_frequency,
.verify = sc520_freq_verify,
.target = sc520_freq_target,
.init = sc520_freq_cpu_init,
.exit = sc520_freq_cpu_exit,
.name = "sc520_freq",
.owner = THIS_MODULE,
.attr = sc520_freq_attr,
};
static const struct x86_cpu_id sc520_ids[] = {
{ X86_VENDOR_AMD, 4, 9 },
{}
};
MODULE_DEVICE_TABLE(x86cpu, sc520_ids);
static int __init sc520_freq_init(void)
{
int err;
if (!x86_match_cpu(sc520_ids))
return -ENODEV;
cpuctl = ioremap((unsigned long)(MMCR_BASE + OFFS_CPUCTL), 1);
if (!cpuctl) {
printk(KERN_ERR "sc520_freq: error: failed to remap memory\n");
return -ENOMEM;
}
err = cpufreq_register_driver(&sc520_freq_driver);
if (err)
iounmap(cpuctl);
return err;
}
static void __exit sc520_freq_exit(void)
{
cpufreq_unregister_driver(&sc520_freq_driver);
iounmap(cpuctl);
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Sean Young <sean@mess.org>");
MODULE_DESCRIPTION("cpufreq driver for AMD's Elan sc520 CPU");
module_init(sc520_freq_init);
module_exit(sc520_freq_exit);
| {
"language": "C"
} |
/* Copyright (C) 2015-2020, Wazuh Inc.
* Copyright (C) 2009 Trend Micro Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the GNU General Public
* License (version 2) as published by the FSF - Free Software
* Foundation.
*/
#ifndef CSYSLOGD_H
#define CSYSLOGD_H
#include "config/csyslogd-config.h"
#include "cJSON.h"
#define OS_CSYSLOGD_MAX_TRIES 10
/** Prototypes **/
/* Read syslog config */
SyslogConfig **OS_ReadSyslogConf(int test_config, const char *cfgfile);
cJSON *getCsyslogConfig(void);
// Com request thread dispatcher
size_t csyscom_dispatch(const char * command, char ** output);
size_t csyscom_getconfig(const char * section, char ** output);
void * csyscom_main(__attribute__((unused)) void * arg);
/* Send alerts via syslog
* Returns 1 on success or 0 on error
*/
int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config);
/* Send alerts via syslog from JSON alert
* Returns 1 on success or 0 on error
*/
int OS_Alert_SendSyslog_JSON(cJSON *json_data, const SyslogConfig *syslog_config);
/* Database inserting main function */
void OS_CSyslogD(SyslogConfig **syslog_config) __attribute__((noreturn));
/* Conditional Field Formatting */
int field_add_int(char *dest, size_t size, const char *format, const int value );
int field_add_string(char *dest, size_t size, const char *format, const char *value );
int field_add_truncated(char *dest, size_t size, const char *format, const char *value, int fmt_size );
/** Global variables **/
/* System hostname */
extern char __shost[512];
/* System hostname (full length) */
extern char __shost_long[512];
extern SyslogConfig **syslog_config;
#endif /* CSYSLOGD_H */
| {
"language": "C"
} |
/* This header file is part of the ATMEL AVR-UC3-SoftwareFramework-1.7.0 Release */
/*This file is prepared for Doxygen automatic documentation generation.*/
/*! \file *********************************************************************
*
* \brief Preprocessor token pasting utils.
*
* - Compiler: IAR EWAVR32 and GNU GCC for AVR32
* - Supported devices: All AVR32 devices can be used.
*
* \author Atmel Corporation: http://www.atmel.com \n
* Support and FAQ: http://support.atmel.no/
*
******************************************************************************/
/* Copyright (c) 2009 Atmel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an Atmel
* AVR product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
*
*/
#ifndef _TPASTE_H_
#define _TPASTE_H_
/*! \name Token Paste
*
* Paste N preprocessing tokens together, these tokens being allowed to be \#defined.
*
* May be used only within macros with the tokens passed as arguments if the tokens are \#defined.
*
* For example, writing TPASTE2(U, WIDTH) within a macro \#defined by
* UTYPE(WIDTH) and invoked as UTYPE(UL_WIDTH) with UL_WIDTH \#defined as 32 is
* equivalent to writing U32.
*/
//! @{
#define TPASTE2( a, b) a##b
#define TPASTE3( a, b, c) a##b##c
#define TPASTE4( a, b, c, d) a##b##c##d
#define TPASTE5( a, b, c, d, e) a##b##c##d##e
#define TPASTE6( a, b, c, d, e, f) a##b##c##d##e##f
#define TPASTE7( a, b, c, d, e, f, g) a##b##c##d##e##f##g
#define TPASTE8( a, b, c, d, e, f, g, h) a##b##c##d##e##f##g##h
#define TPASTE9( a, b, c, d, e, f, g, h, i) a##b##c##d##e##f##g##h##i
#define TPASTE10(a, b, c, d, e, f, g, h, i, j) a##b##c##d##e##f##g##h##i##j
//! @}
/*! \name Absolute Token Paste
*
* Paste N preprocessing tokens together, these tokens being allowed to be \#defined.
*
* No restriction of use if the tokens are \#defined.
*
* For example, writing ATPASTE2(U, UL_WIDTH) anywhere with UL_WIDTH \#defined
* as 32 is equivalent to writing U32.
*/
//! @{
#define ATPASTE2( a, b) TPASTE2( a, b)
#define ATPASTE3( a, b, c) TPASTE3( a, b, c)
#define ATPASTE4( a, b, c, d) TPASTE4( a, b, c, d)
#define ATPASTE5( a, b, c, d, e) TPASTE5( a, b, c, d, e)
#define ATPASTE6( a, b, c, d, e, f) TPASTE6( a, b, c, d, e, f)
#define ATPASTE7( a, b, c, d, e, f, g) TPASTE7( a, b, c, d, e, f, g)
#define ATPASTE8( a, b, c, d, e, f, g, h) TPASTE8( a, b, c, d, e, f, g, h)
#define ATPASTE9( a, b, c, d, e, f, g, h, i) TPASTE9( a, b, c, d, e, f, g, h, i)
#define ATPASTE10(a, b, c, d, e, f, g, h, i, j) TPASTE10(a, b, c, d, e, f, g, h, i, j)
//! @}
#endif // _TPASTE_H_
| {
"language": "C"
} |
/* ocsp_vfy.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2000.
*/
/* ====================================================================
* Copyright (c) 2000-2004 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <openssl/ocsp.h>
#include <openssl/err.h>
#include <string.h>
static int ocsp_find_signer(X509 **psigner, OCSP_BASICRESP *bs,
STACK_OF(X509) *certs, X509_STORE *st,
unsigned long flags);
static X509 *ocsp_find_signer_sk(STACK_OF(X509) *certs, OCSP_RESPID *id);
static int ocsp_check_issuer(OCSP_BASICRESP *bs, STACK_OF(X509) *chain,
unsigned long flags);
static int ocsp_check_ids(STACK_OF(OCSP_SINGLERESP) *sresp,
OCSP_CERTID **ret);
static int ocsp_match_issuerid(X509 *cert, OCSP_CERTID *cid,
STACK_OF(OCSP_SINGLERESP) *sresp);
static int ocsp_check_delegated(X509 *x, int flags);
static int ocsp_req_find_signer(X509 **psigner, OCSP_REQUEST *req,
X509_NAME *nm, STACK_OF(X509) *certs,
X509_STORE *st, unsigned long flags);
/* Verify a basic response message */
int OCSP_basic_verify(OCSP_BASICRESP *bs, STACK_OF(X509) *certs,
X509_STORE *st, unsigned long flags)
{
X509 *signer, *x;
STACK_OF(X509) *chain = NULL;
STACK_OF(X509) *untrusted = NULL;
X509_STORE_CTX ctx;
int i, ret = 0;
ret = ocsp_find_signer(&signer, bs, certs, st, flags);
if (!ret) {
OCSPerr(OCSP_F_OCSP_BASIC_VERIFY,
OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND);
goto end;
}
if ((ret == 2) && (flags & OCSP_TRUSTOTHER))
flags |= OCSP_NOVERIFY;
if (!(flags & OCSP_NOSIGS)) {
EVP_PKEY *skey;
skey = X509_get_pubkey(signer);
if (skey) {
ret = OCSP_BASICRESP_verify(bs, skey, 0);
EVP_PKEY_free(skey);
}
if (!skey || ret <= 0) {
OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, OCSP_R_SIGNATURE_FAILURE);
goto end;
}
}
if (!(flags & OCSP_NOVERIFY)) {
int init_res;
if (flags & OCSP_NOCHAIN) {
untrusted = NULL;
} else if (bs->certs && certs) {
untrusted = sk_X509_dup(bs->certs);
for (i = 0; i < sk_X509_num(certs); i++) {
if (!sk_X509_push(untrusted, sk_X509_value(certs, i))) {
OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, ERR_R_MALLOC_FAILURE);
goto end;
}
}
} else {
untrusted = bs->certs;
}
init_res = X509_STORE_CTX_init(&ctx, st, signer, untrusted);
if (!init_res) {
ret = -1;
OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, ERR_R_X509_LIB);
goto end;
}
X509_STORE_CTX_set_purpose(&ctx, X509_PURPOSE_OCSP_HELPER);
ret = X509_verify_cert(&ctx);
chain = X509_STORE_CTX_get1_chain(&ctx);
X509_STORE_CTX_cleanup(&ctx);
if (ret <= 0) {
i = X509_STORE_CTX_get_error(&ctx);
OCSPerr(OCSP_F_OCSP_BASIC_VERIFY,
OCSP_R_CERTIFICATE_VERIFY_ERROR);
ERR_add_error_data(2, "Verify error:",
X509_verify_cert_error_string(i));
goto end;
}
if (flags & OCSP_NOCHECKS) {
ret = 1;
goto end;
}
/*
* At this point we have a valid certificate chain need to verify it
* against the OCSP issuer criteria.
*/
ret = ocsp_check_issuer(bs, chain, flags);
/* If fatal error or valid match then finish */
if (ret != 0)
goto end;
/*
* Easy case: explicitly trusted. Get root CA and check for explicit
* trust
*/
if (flags & OCSP_NOEXPLICIT)
goto end;
x = sk_X509_value(chain, sk_X509_num(chain) - 1);
if (X509_check_trust(x, NID_OCSP_sign, 0) != X509_TRUST_TRUSTED) {
OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, OCSP_R_ROOT_CA_NOT_TRUSTED);
goto end;
}
ret = 1;
}
end:
if (chain)
sk_X509_pop_free(chain, X509_free);
if (bs->certs && certs)
sk_X509_free(untrusted);
return ret;
}
static int ocsp_find_signer(X509 **psigner, OCSP_BASICRESP *bs,
STACK_OF(X509) *certs, X509_STORE *st,
unsigned long flags)
{
X509 *signer;
OCSP_RESPID *rid = bs->tbsResponseData->responderId;
if ((signer = ocsp_find_signer_sk(certs, rid))) {
*psigner = signer;
return 2;
}
if (!(flags & OCSP_NOINTERN) &&
(signer = ocsp_find_signer_sk(bs->certs, rid))) {
*psigner = signer;
return 1;
}
/* Maybe lookup from store if by subject name */
*psigner = NULL;
return 0;
}
static X509 *ocsp_find_signer_sk(STACK_OF(X509) *certs, OCSP_RESPID *id)
{
int i;
unsigned char tmphash[SHA_DIGEST_LENGTH], *keyhash;
X509 *x;
/* Easy if lookup by name */
if (id->type == V_OCSP_RESPID_NAME)
return X509_find_by_subject(certs, id->value.byName);
/* Lookup by key hash */
/* If key hash isn't SHA1 length then forget it */
if (id->value.byKey->length != SHA_DIGEST_LENGTH)
return NULL;
keyhash = id->value.byKey->data;
/* Calculate hash of each key and compare */
for (i = 0; i < sk_X509_num(certs); i++) {
x = sk_X509_value(certs, i);
X509_pubkey_digest(x, EVP_sha1(), tmphash, NULL);
if (!memcmp(keyhash, tmphash, SHA_DIGEST_LENGTH))
return x;
}
return NULL;
}
static int ocsp_check_issuer(OCSP_BASICRESP *bs, STACK_OF(X509) *chain,
unsigned long flags)
{
STACK_OF(OCSP_SINGLERESP) *sresp;
X509 *signer, *sca;
OCSP_CERTID *caid = NULL;
int i;
sresp = bs->tbsResponseData->responses;
if (sk_X509_num(chain) <= 0) {
OCSPerr(OCSP_F_OCSP_CHECK_ISSUER, OCSP_R_NO_CERTIFICATES_IN_CHAIN);
return -1;
}
/* See if the issuer IDs match. */
i = ocsp_check_ids(sresp, &caid);
/* If ID mismatch or other error then return */
if (i <= 0)
return i;
signer = sk_X509_value(chain, 0);
/* Check to see if OCSP responder CA matches request CA */
if (sk_X509_num(chain) > 1) {
sca = sk_X509_value(chain, 1);
i = ocsp_match_issuerid(sca, caid, sresp);
if (i < 0)
return i;
if (i) {
/* We have a match, if extensions OK then success */
if (ocsp_check_delegated(signer, flags))
return 1;
return 0;
}
}
/* Otherwise check if OCSP request signed directly by request CA */
return ocsp_match_issuerid(signer, caid, sresp);
}
/*
* Check the issuer certificate IDs for equality. If there is a mismatch with
* the same algorithm then there's no point trying to match any certificates
* against the issuer. If the issuer IDs all match then we just need to check
* equality against one of them.
*/
static int ocsp_check_ids(STACK_OF(OCSP_SINGLERESP) *sresp, OCSP_CERTID **ret)
{
OCSP_CERTID *tmpid, *cid;
int i, idcount;
idcount = sk_OCSP_SINGLERESP_num(sresp);
if (idcount <= 0) {
OCSPerr(OCSP_F_OCSP_CHECK_IDS,
OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA);
return -1;
}
cid = sk_OCSP_SINGLERESP_value(sresp, 0)->certId;
*ret = NULL;
for (i = 1; i < idcount; i++) {
tmpid = sk_OCSP_SINGLERESP_value(sresp, i)->certId;
/* Check to see if IDs match */
if (OCSP_id_issuer_cmp(cid, tmpid)) {
/* If algoritm mismatch let caller deal with it */
if (OBJ_cmp(tmpid->hashAlgorithm->algorithm,
cid->hashAlgorithm->algorithm))
return 2;
/* Else mismatch */
return 0;
}
}
/* All IDs match: only need to check one ID */
*ret = cid;
return 1;
}
static int ocsp_match_issuerid(X509 *cert, OCSP_CERTID *cid,
STACK_OF(OCSP_SINGLERESP) *sresp)
{
/* If only one ID to match then do it */
if (cid) {
const EVP_MD *dgst;
X509_NAME *iname;
int mdlen;
unsigned char md[EVP_MAX_MD_SIZE];
if (!(dgst = EVP_get_digestbyobj(cid->hashAlgorithm->algorithm))) {
OCSPerr(OCSP_F_OCSP_MATCH_ISSUERID,
OCSP_R_UNKNOWN_MESSAGE_DIGEST);
return -1;
}
mdlen = EVP_MD_size(dgst);
if (mdlen < 0)
return -1;
if ((cid->issuerNameHash->length != mdlen) ||
(cid->issuerKeyHash->length != mdlen))
return 0;
iname = X509_get_subject_name(cert);
if (!X509_NAME_digest(iname, dgst, md, NULL))
return -1;
if (memcmp(md, cid->issuerNameHash->data, mdlen))
return 0;
X509_pubkey_digest(cert, dgst, md, NULL);
if (memcmp(md, cid->issuerKeyHash->data, mdlen))
return 0;
return 1;
} else {
/* We have to match the whole lot */
int i, ret;
OCSP_CERTID *tmpid;
for (i = 0; i < sk_OCSP_SINGLERESP_num(sresp); i++) {
tmpid = sk_OCSP_SINGLERESP_value(sresp, i)->certId;
ret = ocsp_match_issuerid(cert, tmpid, NULL);
if (ret <= 0)
return ret;
}
return 1;
}
}
static int ocsp_check_delegated(X509 *x, int flags)
{
X509_check_purpose(x, -1, 0);
if ((x->ex_flags & EXFLAG_XKUSAGE) && (x->ex_xkusage & XKU_OCSP_SIGN))
return 1;
OCSPerr(OCSP_F_OCSP_CHECK_DELEGATED, OCSP_R_MISSING_OCSPSIGNING_USAGE);
return 0;
}
/*
* Verify an OCSP request. This is fortunately much easier than OCSP response
* verify. Just find the signers certificate and verify it against a given
* trust value.
*/
int OCSP_request_verify(OCSP_REQUEST *req, STACK_OF(X509) *certs,
X509_STORE *store, unsigned long flags)
{
X509 *signer;
X509_NAME *nm;
GENERAL_NAME *gen;
int ret;
X509_STORE_CTX ctx;
if (!req->optionalSignature) {
OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, OCSP_R_REQUEST_NOT_SIGNED);
return 0;
}
gen = req->tbsRequest->requestorName;
if (!gen || gen->type != GEN_DIRNAME) {
OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY,
OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE);
return 0;
}
nm = gen->d.directoryName;
ret = ocsp_req_find_signer(&signer, req, nm, certs, store, flags);
if (ret <= 0) {
OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY,
OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND);
return 0;
}
if ((ret == 2) && (flags & OCSP_TRUSTOTHER))
flags |= OCSP_NOVERIFY;
if (!(flags & OCSP_NOSIGS)) {
EVP_PKEY *skey;
skey = X509_get_pubkey(signer);
ret = OCSP_REQUEST_verify(req, skey);
EVP_PKEY_free(skey);
if (ret <= 0) {
OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, OCSP_R_SIGNATURE_FAILURE);
return 0;
}
}
if (!(flags & OCSP_NOVERIFY)) {
int init_res;
if (flags & OCSP_NOCHAIN)
init_res = X509_STORE_CTX_init(&ctx, store, signer, NULL);
else
init_res = X509_STORE_CTX_init(&ctx, store, signer,
req->optionalSignature->certs);
if (!init_res) {
OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, ERR_R_X509_LIB);
return 0;
}
X509_STORE_CTX_set_purpose(&ctx, X509_PURPOSE_OCSP_HELPER);
X509_STORE_CTX_set_trust(&ctx, X509_TRUST_OCSP_REQUEST);
ret = X509_verify_cert(&ctx);
X509_STORE_CTX_cleanup(&ctx);
if (ret <= 0) {
ret = X509_STORE_CTX_get_error(&ctx);
OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY,
OCSP_R_CERTIFICATE_VERIFY_ERROR);
ERR_add_error_data(2, "Verify error:",
X509_verify_cert_error_string(ret));
return 0;
}
}
return 1;
}
static int ocsp_req_find_signer(X509 **psigner, OCSP_REQUEST *req,
X509_NAME *nm, STACK_OF(X509) *certs,
X509_STORE *st, unsigned long flags)
{
X509 *signer;
if (!(flags & OCSP_NOINTERN)) {
signer = X509_find_by_subject(req->optionalSignature->certs, nm);
if (signer) {
*psigner = signer;
return 1;
}
}
signer = X509_find_by_subject(certs, nm);
if (signer) {
*psigner = signer;
return 2;
}
return 0;
}
| {
"language": "C"
} |
/*******************************************************************************/
/* Copyright (C) 2008 Jonathan Moore Liles */
/* */
/* This program is free software; you can redistribute it and/or modify it */
/* under the terms of the GNU General Public License as published by the */
/* Free Software Foundation; either version 2 of the License, or (at your */
/* option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT */
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for */
/* more details. */
/* */
/* You should have received a copy of the GNU General Public License along */
/* with This program; see the file COPYING. If not,write to the Free Software */
/* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
/*******************************************************************************/
#pragma once
#include "Sequence.H"
#include "Sequence_Widget.H"
/* Base class representing a /region/ of time on a /sequence/, with
controls for the offset and length points. */
class Sequence_Region : public Sequence_Widget
{
protected:
virtual void get ( Log_Entry &e ) const;
virtual void set ( Log_Entry &e );
Sequence_Region ( );
Sequence_Region ( const Sequence_Region &rhs );
virtual ~Sequence_Region ( );
virtual Fl_Align align ( void ) const { return FL_ALIGN_INSIDE | FL_ALIGN_CENTER | FL_ALIGN_WRAP; }
virtual int handle ( int m );
virtual void draw_box( void );
virtual void draw ( void );
virtual void draw_label ( void ) { Sequence_Widget::draw_label(); }
virtual void draw_label ( const char *label, Fl_Align align, Fl_Color color=(Fl_Color)0, int xo=0, int yo=0 );
public:
LOG_NAME_FUNC( Region );
void trim_right ( nframes_t where );
void trim_left ( nframes_t where );
enum trim_e { NO, LEFT, RIGHT };
void trim ( enum trim_e t, int X );
void split ( Sequence_Region *copy, nframes_t where );
};
| {
"language": "C"
} |
/*******************************************************************************
Intel 10 Gigabit PCI Express Linux driver
Copyright(c) 1999 - 2016 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
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.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#ifndef _IXGBE_H_
#define _IXGBE_H_
#include <linux/bitops.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/cpumask.h>
#include <linux/aer.h>
#include <linux/if_vlan.h>
#include <linux/jiffies.h>
#include <linux/timecounter.h>
#include <linux/net_tstamp.h>
#include <linux/ptp_clock_kernel.h>
#include "ixgbe_type.h"
#include "ixgbe_common.h"
#include "ixgbe_dcb.h"
#if IS_ENABLED(CONFIG_FCOE)
#define IXGBE_FCOE
#include "ixgbe_fcoe.h"
#endif /* IS_ENABLED(CONFIG_FCOE) */
#ifdef CONFIG_IXGBE_DCA
#include <linux/dca.h>
#endif
#include <net/busy_poll.h>
/* common prefix used by pr_<> macros */
#undef pr_fmt
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
/* TX/RX descriptor defines */
#define IXGBE_DEFAULT_TXD 512
#define IXGBE_DEFAULT_TX_WORK 256
#define IXGBE_MAX_TXD 4096
#define IXGBE_MIN_TXD 64
#if (PAGE_SIZE < 8192)
#define IXGBE_DEFAULT_RXD 512
#else
#define IXGBE_DEFAULT_RXD 128
#endif
#define IXGBE_MAX_RXD 4096
#define IXGBE_MIN_RXD 64
#define IXGBE_ETH_P_LLDP 0x88CC
/* flow control */
#define IXGBE_MIN_FCRTL 0x40
#define IXGBE_MAX_FCRTL 0x7FF80
#define IXGBE_MIN_FCRTH 0x600
#define IXGBE_MAX_FCRTH 0x7FFF0
#define IXGBE_DEFAULT_FCPAUSE 0xFFFF
#define IXGBE_MIN_FCPAUSE 0
#define IXGBE_MAX_FCPAUSE 0xFFFF
/* Supported Rx Buffer Sizes */
#define IXGBE_RXBUFFER_256 256 /* Used for skb receive header */
#define IXGBE_RXBUFFER_2K 2048
#define IXGBE_RXBUFFER_3K 3072
#define IXGBE_RXBUFFER_4K 4096
#define IXGBE_MAX_RXBUFFER 16384 /* largest size for a single descriptor */
#define IXGBE_SKB_PAD (NET_SKB_PAD + NET_IP_ALIGN)
#if (PAGE_SIZE < 8192)
#define IXGBE_MAX_FRAME_BUILD_SKB \
(SKB_WITH_OVERHEAD(IXGBE_RXBUFFER_2K) - IXGBE_SKB_PAD)
#else
#define IXGBE_MAX_FRAME_BUILD_SKB IXGBE_RXBUFFER_2K
#endif
/*
* NOTE: netdev_alloc_skb reserves up to 64 bytes, NET_IP_ALIGN means we
* reserve 64 more, and skb_shared_info adds an additional 320 bytes more,
* this adds up to 448 bytes of extra data.
*
* Since netdev_alloc_skb now allocates a page fragment we can use a value
* of 256 and the resultant skb will have a truesize of 960 or less.
*/
#define IXGBE_RX_HDR_SIZE IXGBE_RXBUFFER_256
/* How many Rx Buffers do we bundle into one write to the hardware ? */
#define IXGBE_RX_BUFFER_WRITE 16 /* Must be power of 2 */
#define IXGBE_RX_DMA_ATTR \
(DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING)
enum ixgbe_tx_flags {
/* cmd_type flags */
IXGBE_TX_FLAGS_HW_VLAN = 0x01,
IXGBE_TX_FLAGS_TSO = 0x02,
IXGBE_TX_FLAGS_TSTAMP = 0x04,
/* olinfo flags */
IXGBE_TX_FLAGS_CC = 0x08,
IXGBE_TX_FLAGS_IPV4 = 0x10,
IXGBE_TX_FLAGS_CSUM = 0x20,
/* software defined flags */
IXGBE_TX_FLAGS_SW_VLAN = 0x40,
IXGBE_TX_FLAGS_FCOE = 0x80,
};
/* VLAN info */
#define IXGBE_TX_FLAGS_VLAN_MASK 0xffff0000
#define IXGBE_TX_FLAGS_VLAN_PRIO_MASK 0xe0000000
#define IXGBE_TX_FLAGS_VLAN_PRIO_SHIFT 29
#define IXGBE_TX_FLAGS_VLAN_SHIFT 16
#define IXGBE_MAX_VF_MC_ENTRIES 30
#define IXGBE_MAX_VF_FUNCTIONS 64
#define IXGBE_MAX_VFTA_ENTRIES 128
#define MAX_EMULATION_MAC_ADDRS 16
#define IXGBE_MAX_PF_MACVLANS 15
#define VMDQ_P(p) ((p) + adapter->ring_feature[RING_F_VMDQ].offset)
#define IXGBE_82599_VF_DEVICE_ID 0x10ED
#define IXGBE_X540_VF_DEVICE_ID 0x1515
struct vf_data_storage {
struct pci_dev *vfdev;
unsigned char vf_mac_addresses[ETH_ALEN];
u16 vf_mc_hashes[IXGBE_MAX_VF_MC_ENTRIES];
u16 num_vf_mc_hashes;
bool clear_to_send;
bool pf_set_mac;
u16 pf_vlan; /* When set, guest VLAN config not allowed. */
u16 pf_qos;
u16 tx_rate;
u8 spoofchk_enabled;
bool rss_query_enabled;
u8 trusted;
int xcast_mode;
unsigned int vf_api;
};
enum ixgbevf_xcast_modes {
IXGBEVF_XCAST_MODE_NONE = 0,
IXGBEVF_XCAST_MODE_MULTI,
IXGBEVF_XCAST_MODE_ALLMULTI,
IXGBEVF_XCAST_MODE_PROMISC,
};
struct vf_macvlans {
struct list_head l;
int vf;
bool free;
bool is_macvlan;
u8 vf_macvlan[ETH_ALEN];
};
#define IXGBE_MAX_TXD_PWR 14
#define IXGBE_MAX_DATA_PER_TXD (1u << IXGBE_MAX_TXD_PWR)
/* Tx Descriptors needed, worst case */
#define TXD_USE_COUNT(S) DIV_ROUND_UP((S), IXGBE_MAX_DATA_PER_TXD)
#define DESC_NEEDED (MAX_SKB_FRAGS + 4)
/* wrapper around a pointer to a socket buffer,
* so a DMA handle can be stored along with the buffer */
struct ixgbe_tx_buffer {
union ixgbe_adv_tx_desc *next_to_watch;
unsigned long time_stamp;
struct sk_buff *skb;
unsigned int bytecount;
unsigned short gso_segs;
__be16 protocol;
DEFINE_DMA_UNMAP_ADDR(dma);
DEFINE_DMA_UNMAP_LEN(len);
u32 tx_flags;
};
struct ixgbe_rx_buffer {
struct sk_buff *skb;
dma_addr_t dma;
struct page *page;
#if (BITS_PER_LONG > 32) || (PAGE_SIZE >= 65536)
__u32 page_offset;
#else
__u16 page_offset;
#endif
__u16 pagecnt_bias;
};
struct ixgbe_queue_stats {
u64 packets;
u64 bytes;
};
struct ixgbe_tx_queue_stats {
u64 restart_queue;
u64 tx_busy;
u64 tx_done_old;
};
struct ixgbe_rx_queue_stats {
u64 rsc_count;
u64 rsc_flush;
u64 non_eop_descs;
u64 alloc_rx_page_failed;
u64 alloc_rx_buff_failed;
u64 csum_err;
};
#define IXGBE_TS_HDR_LEN 8
enum ixgbe_ring_state_t {
__IXGBE_RX_3K_BUFFER,
__IXGBE_RX_BUILD_SKB_ENABLED,
__IXGBE_RX_RSC_ENABLED,
__IXGBE_RX_CSUM_UDP_ZERO_ERR,
__IXGBE_RX_FCOE,
__IXGBE_TX_FDIR_INIT_DONE,
__IXGBE_TX_XPS_INIT_DONE,
__IXGBE_TX_DETECT_HANG,
__IXGBE_HANG_CHECK_ARMED,
};
#define ring_uses_build_skb(ring) \
test_bit(__IXGBE_RX_BUILD_SKB_ENABLED, &(ring)->state)
struct ixgbe_fwd_adapter {
unsigned long active_vlans[BITS_TO_LONGS(VLAN_N_VID)];
struct net_device *netdev;
struct ixgbe_adapter *real_adapter;
unsigned int tx_base_queue;
unsigned int rx_base_queue;
int pool;
};
#define check_for_tx_hang(ring) \
test_bit(__IXGBE_TX_DETECT_HANG, &(ring)->state)
#define set_check_for_tx_hang(ring) \
set_bit(__IXGBE_TX_DETECT_HANG, &(ring)->state)
#define clear_check_for_tx_hang(ring) \
clear_bit(__IXGBE_TX_DETECT_HANG, &(ring)->state)
#define ring_is_rsc_enabled(ring) \
test_bit(__IXGBE_RX_RSC_ENABLED, &(ring)->state)
#define set_ring_rsc_enabled(ring) \
set_bit(__IXGBE_RX_RSC_ENABLED, &(ring)->state)
#define clear_ring_rsc_enabled(ring) \
clear_bit(__IXGBE_RX_RSC_ENABLED, &(ring)->state)
struct ixgbe_ring {
struct ixgbe_ring *next; /* pointer to next ring in q_vector */
struct ixgbe_q_vector *q_vector; /* backpointer to host q_vector */
struct net_device *netdev; /* netdev ring belongs to */
struct device *dev; /* device for DMA mapping */
struct ixgbe_fwd_adapter *l2_accel_priv;
void *desc; /* descriptor ring memory */
union {
struct ixgbe_tx_buffer *tx_buffer_info;
struct ixgbe_rx_buffer *rx_buffer_info;
};
unsigned long state;
u8 __iomem *tail;
dma_addr_t dma; /* phys. address of descriptor ring */
unsigned int size; /* length in bytes */
u16 count; /* amount of descriptors */
u8 queue_index; /* needed for multiqueue queue management */
u8 reg_idx; /* holds the special value that gets
* the hardware register offset
* associated with this ring, which is
* different for DCB and RSS modes
*/
u16 next_to_use;
u16 next_to_clean;
unsigned long last_rx_timestamp;
union {
u16 next_to_alloc;
struct {
u8 atr_sample_rate;
u8 atr_count;
};
};
u8 dcb_tc;
struct ixgbe_queue_stats stats;
struct u64_stats_sync syncp;
union {
struct ixgbe_tx_queue_stats tx_stats;
struct ixgbe_rx_queue_stats rx_stats;
};
} ____cacheline_internodealigned_in_smp;
enum ixgbe_ring_f_enum {
RING_F_NONE = 0,
RING_F_VMDQ, /* SR-IOV uses the same ring feature */
RING_F_RSS,
RING_F_FDIR,
#ifdef IXGBE_FCOE
RING_F_FCOE,
#endif /* IXGBE_FCOE */
RING_F_ARRAY_SIZE /* must be last in enum set */
};
#define IXGBE_MAX_RSS_INDICES 16
#define IXGBE_MAX_RSS_INDICES_X550 63
#define IXGBE_MAX_VMDQ_INDICES 64
#define IXGBE_MAX_FDIR_INDICES 63 /* based on q_vector limit */
#define IXGBE_MAX_FCOE_INDICES 8
#define MAX_RX_QUEUES (IXGBE_MAX_FDIR_INDICES + 1)
#define MAX_TX_QUEUES (IXGBE_MAX_FDIR_INDICES + 1)
#define IXGBE_MAX_L2A_QUEUES 4
#define IXGBE_BAD_L2A_QUEUE 3
#define IXGBE_MAX_MACVLANS 31
#define IXGBE_MAX_DCBMACVLANS 8
struct ixgbe_ring_feature {
u16 limit; /* upper limit on feature indices */
u16 indices; /* current value of indices */
u16 mask; /* Mask used for feature to ring mapping */
u16 offset; /* offset to start of feature */
} ____cacheline_internodealigned_in_smp;
#define IXGBE_82599_VMDQ_8Q_MASK 0x78
#define IXGBE_82599_VMDQ_4Q_MASK 0x7C
#define IXGBE_82599_VMDQ_2Q_MASK 0x7E
/*
* FCoE requires that all Rx buffers be over 2200 bytes in length. Since
* this is twice the size of a half page we need to double the page order
* for FCoE enabled Rx queues.
*/
static inline unsigned int ixgbe_rx_bufsz(struct ixgbe_ring *ring)
{
if (test_bit(__IXGBE_RX_3K_BUFFER, &ring->state))
return IXGBE_RXBUFFER_3K;
#if (PAGE_SIZE < 8192)
if (ring_uses_build_skb(ring))
return IXGBE_MAX_FRAME_BUILD_SKB;
#endif
return IXGBE_RXBUFFER_2K;
}
static inline unsigned int ixgbe_rx_pg_order(struct ixgbe_ring *ring)
{
#if (PAGE_SIZE < 8192)
if (test_bit(__IXGBE_RX_3K_BUFFER, &ring->state))
return 1;
#endif
return 0;
}
#define ixgbe_rx_pg_size(_ring) (PAGE_SIZE << ixgbe_rx_pg_order(_ring))
struct ixgbe_ring_container {
struct ixgbe_ring *ring; /* pointer to linked list of rings */
unsigned int total_bytes; /* total bytes processed this int */
unsigned int total_packets; /* total packets processed this int */
u16 work_limit; /* total work allowed per interrupt */
u8 count; /* total number of rings in vector */
u8 itr; /* current ITR setting for ring */
};
/* iterator for handling rings in ring container */
#define ixgbe_for_each_ring(pos, head) \
for (pos = (head).ring; pos != NULL; pos = pos->next)
#define MAX_RX_PACKET_BUFFERS ((adapter->flags & IXGBE_FLAG_DCB_ENABLED) \
? 8 : 1)
#define MAX_TX_PACKET_BUFFERS MAX_RX_PACKET_BUFFERS
/* MAX_Q_VECTORS of these are allocated,
* but we only use one per queue-specific vector.
*/
struct ixgbe_q_vector {
struct ixgbe_adapter *adapter;
#ifdef CONFIG_IXGBE_DCA
int cpu; /* CPU for DCA */
#endif
u16 v_idx; /* index of q_vector within array, also used for
* finding the bit in EICR and friends that
* represents the vector for this ring */
u16 itr; /* Interrupt throttle rate written to EITR */
struct ixgbe_ring_container rx, tx;
struct napi_struct napi;
cpumask_t affinity_mask;
int numa_node;
struct rcu_head rcu; /* to avoid race with update stats on free */
char name[IFNAMSIZ + 9];
/* for dynamic allocation of rings associated with this q_vector */
struct ixgbe_ring ring[0] ____cacheline_internodealigned_in_smp;
};
#ifdef CONFIG_IXGBE_HWMON
#define IXGBE_HWMON_TYPE_LOC 0
#define IXGBE_HWMON_TYPE_TEMP 1
#define IXGBE_HWMON_TYPE_CAUTION 2
#define IXGBE_HWMON_TYPE_MAX 3
struct hwmon_attr {
struct device_attribute dev_attr;
struct ixgbe_hw *hw;
struct ixgbe_thermal_diode_data *sensor;
char name[12];
};
struct hwmon_buff {
struct attribute_group group;
const struct attribute_group *groups[2];
struct attribute *attrs[IXGBE_MAX_SENSORS * 4 + 1];
struct hwmon_attr hwmon_list[IXGBE_MAX_SENSORS * 4];
unsigned int n_hwmon;
};
#endif /* CONFIG_IXGBE_HWMON */
/*
* microsecond values for various ITR rates shifted by 2 to fit itr register
* with the first 3 bits reserved 0
*/
#define IXGBE_MIN_RSC_ITR 24
#define IXGBE_100K_ITR 40
#define IXGBE_20K_ITR 200
#define IXGBE_12K_ITR 336
/* ixgbe_test_staterr - tests bits in Rx descriptor status and error fields */
static inline __le32 ixgbe_test_staterr(union ixgbe_adv_rx_desc *rx_desc,
const u32 stat_err_bits)
{
return rx_desc->wb.upper.status_error & cpu_to_le32(stat_err_bits);
}
static inline u16 ixgbe_desc_unused(struct ixgbe_ring *ring)
{
u16 ntc = ring->next_to_clean;
u16 ntu = ring->next_to_use;
return ((ntc > ntu) ? 0 : ring->count) + ntc - ntu - 1;
}
#define IXGBE_RX_DESC(R, i) \
(&(((union ixgbe_adv_rx_desc *)((R)->desc))[i]))
#define IXGBE_TX_DESC(R, i) \
(&(((union ixgbe_adv_tx_desc *)((R)->desc))[i]))
#define IXGBE_TX_CTXTDESC(R, i) \
(&(((struct ixgbe_adv_tx_context_desc *)((R)->desc))[i]))
#define IXGBE_MAX_JUMBO_FRAME_SIZE 9728 /* Maximum Supported Size 9.5KB */
#ifdef IXGBE_FCOE
/* Use 3K as the baby jumbo frame size for FCoE */
#define IXGBE_FCOE_JUMBO_FRAME_SIZE 3072
#endif /* IXGBE_FCOE */
#define OTHER_VECTOR 1
#define NON_Q_VECTORS (OTHER_VECTOR)
#define MAX_MSIX_VECTORS_82599 64
#define MAX_Q_VECTORS_82599 64
#define MAX_MSIX_VECTORS_82598 18
#define MAX_Q_VECTORS_82598 16
struct ixgbe_mac_addr {
u8 addr[ETH_ALEN];
u16 pool;
u16 state; /* bitmask */
};
#define IXGBE_MAC_STATE_DEFAULT 0x1
#define IXGBE_MAC_STATE_MODIFIED 0x2
#define IXGBE_MAC_STATE_IN_USE 0x4
#define MAX_Q_VECTORS MAX_Q_VECTORS_82599
#define MAX_MSIX_COUNT MAX_MSIX_VECTORS_82599
#define MIN_MSIX_Q_VECTORS 1
#define MIN_MSIX_COUNT (MIN_MSIX_Q_VECTORS + NON_Q_VECTORS)
/* default to trying for four seconds */
#define IXGBE_TRY_LINK_TIMEOUT (4 * HZ)
#define IXGBE_SFP_POLL_JIFFIES (2 * HZ) /* SFP poll every 2 seconds */
/* board specific private data structure */
struct ixgbe_adapter {
unsigned long active_vlans[BITS_TO_LONGS(VLAN_N_VID)];
/* OS defined structs */
struct net_device *netdev;
struct pci_dev *pdev;
unsigned long state;
/* Some features need tri-state capability,
* thus the additional *_CAPABLE flags.
*/
u32 flags;
#define IXGBE_FLAG_MSI_ENABLED BIT(1)
#define IXGBE_FLAG_MSIX_ENABLED BIT(3)
#define IXGBE_FLAG_RX_1BUF_CAPABLE BIT(4)
#define IXGBE_FLAG_RX_PS_CAPABLE BIT(5)
#define IXGBE_FLAG_RX_PS_ENABLED BIT(6)
#define IXGBE_FLAG_DCA_ENABLED BIT(8)
#define IXGBE_FLAG_DCA_CAPABLE BIT(9)
#define IXGBE_FLAG_IMIR_ENABLED BIT(10)
#define IXGBE_FLAG_MQ_CAPABLE BIT(11)
#define IXGBE_FLAG_DCB_ENABLED BIT(12)
#define IXGBE_FLAG_VMDQ_CAPABLE BIT(13)
#define IXGBE_FLAG_VMDQ_ENABLED BIT(14)
#define IXGBE_FLAG_FAN_FAIL_CAPABLE BIT(15)
#define IXGBE_FLAG_NEED_LINK_UPDATE BIT(16)
#define IXGBE_FLAG_NEED_LINK_CONFIG BIT(17)
#define IXGBE_FLAG_FDIR_HASH_CAPABLE BIT(18)
#define IXGBE_FLAG_FDIR_PERFECT_CAPABLE BIT(19)
#define IXGBE_FLAG_FCOE_CAPABLE BIT(20)
#define IXGBE_FLAG_FCOE_ENABLED BIT(21)
#define IXGBE_FLAG_SRIOV_CAPABLE BIT(22)
#define IXGBE_FLAG_SRIOV_ENABLED BIT(23)
#define IXGBE_FLAG_VXLAN_OFFLOAD_CAPABLE BIT(24)
#define IXGBE_FLAG_RX_HWTSTAMP_ENABLED BIT(25)
#define IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER BIT(26)
#define IXGBE_FLAG_DCB_CAPABLE BIT(27)
#define IXGBE_FLAG_GENEVE_OFFLOAD_CAPABLE BIT(28)
u32 flags2;
#define IXGBE_FLAG2_RSC_CAPABLE BIT(0)
#define IXGBE_FLAG2_RSC_ENABLED BIT(1)
#define IXGBE_FLAG2_TEMP_SENSOR_CAPABLE BIT(2)
#define IXGBE_FLAG2_TEMP_SENSOR_EVENT BIT(3)
#define IXGBE_FLAG2_SEARCH_FOR_SFP BIT(4)
#define IXGBE_FLAG2_SFP_NEEDS_RESET BIT(5)
#define IXGBE_FLAG2_FDIR_REQUIRES_REINIT BIT(7)
#define IXGBE_FLAG2_RSS_FIELD_IPV4_UDP BIT(8)
#define IXGBE_FLAG2_RSS_FIELD_IPV6_UDP BIT(9)
#define IXGBE_FLAG2_PTP_PPS_ENABLED BIT(10)
#define IXGBE_FLAG2_PHY_INTERRUPT BIT(11)
#define IXGBE_FLAG2_UDP_TUN_REREG_NEEDED BIT(12)
#define IXGBE_FLAG2_VLAN_PROMISC BIT(13)
#define IXGBE_FLAG2_EEE_CAPABLE BIT(14)
#define IXGBE_FLAG2_EEE_ENABLED BIT(15)
#define IXGBE_FLAG2_RX_LEGACY BIT(16)
/* Tx fast path data */
int num_tx_queues;
u16 tx_itr_setting;
u16 tx_work_limit;
/* Rx fast path data */
int num_rx_queues;
u16 rx_itr_setting;
/* Port number used to identify VXLAN traffic */
__be16 vxlan_port;
__be16 geneve_port;
/* TX */
struct ixgbe_ring *tx_ring[MAX_TX_QUEUES] ____cacheline_aligned_in_smp;
u64 restart_queue;
u64 lsc_int;
u32 tx_timeout_count;
/* RX */
struct ixgbe_ring *rx_ring[MAX_RX_QUEUES];
int num_rx_pools; /* == num_rx_queues in 82598 */
int num_rx_queues_per_pool; /* 1 if 82598, can be many if 82599 */
u64 hw_csum_rx_error;
u64 hw_rx_no_dma_resources;
u64 rsc_total_count;
u64 rsc_total_flush;
u64 non_eop_descs;
u32 alloc_rx_page_failed;
u32 alloc_rx_buff_failed;
struct ixgbe_q_vector *q_vector[MAX_Q_VECTORS];
/* DCB parameters */
struct ieee_pfc *ixgbe_ieee_pfc;
struct ieee_ets *ixgbe_ieee_ets;
struct ixgbe_dcb_config dcb_cfg;
struct ixgbe_dcb_config temp_dcb_cfg;
u8 dcb_set_bitmap;
u8 dcbx_cap;
enum ixgbe_fc_mode last_lfc_mode;
int num_q_vectors; /* current number of q_vectors for device */
int max_q_vectors; /* true count of q_vectors for device */
struct ixgbe_ring_feature ring_feature[RING_F_ARRAY_SIZE];
struct msix_entry *msix_entries;
u32 test_icr;
struct ixgbe_ring test_tx_ring;
struct ixgbe_ring test_rx_ring;
/* structs defined in ixgbe_hw.h */
struct ixgbe_hw hw;
u16 msg_enable;
struct ixgbe_hw_stats stats;
u64 tx_busy;
unsigned int tx_ring_count;
unsigned int rx_ring_count;
u32 link_speed;
bool link_up;
unsigned long sfp_poll_time;
unsigned long link_check_timeout;
struct timer_list service_timer;
struct work_struct service_task;
struct hlist_head fdir_filter_list;
unsigned long fdir_overflow; /* number of times ATR was backed off */
union ixgbe_atr_input fdir_mask;
int fdir_filter_count;
u32 fdir_pballoc;
u32 atr_sample_rate;
spinlock_t fdir_perfect_lock;
#ifdef IXGBE_FCOE
struct ixgbe_fcoe fcoe;
#endif /* IXGBE_FCOE */
u8 __iomem *io_addr; /* Mainly for iounmap use */
u32 wol;
u16 bridge_mode;
u16 eeprom_verh;
u16 eeprom_verl;
u16 eeprom_cap;
u32 interrupt_event;
u32 led_reg;
struct ptp_clock *ptp_clock;
struct ptp_clock_info ptp_caps;
struct work_struct ptp_tx_work;
struct sk_buff *ptp_tx_skb;
struct hwtstamp_config tstamp_config;
unsigned long ptp_tx_start;
unsigned long last_overflow_check;
unsigned long last_rx_ptp_check;
unsigned long last_rx_timestamp;
spinlock_t tmreg_lock;
struct cyclecounter hw_cc;
struct timecounter hw_tc;
u32 base_incval;
u32 tx_hwtstamp_timeouts;
u32 rx_hwtstamp_cleared;
void (*ptp_setup_sdp)(struct ixgbe_adapter *);
/* SR-IOV */
DECLARE_BITMAP(active_vfs, IXGBE_MAX_VF_FUNCTIONS);
unsigned int num_vfs;
struct vf_data_storage *vfinfo;
int vf_rate_link_speed;
struct vf_macvlans vf_mvs;
struct vf_macvlans *mv_list;
u32 timer_event_accumulator;
u32 vferr_refcount;
struct ixgbe_mac_addr *mac_table;
struct kobject *info_kobj;
#ifdef CONFIG_IXGBE_HWMON
struct hwmon_buff *ixgbe_hwmon_buff;
#endif /* CONFIG_IXGBE_HWMON */
#ifdef CONFIG_DEBUG_FS
struct dentry *ixgbe_dbg_adapter;
#endif /*CONFIG_DEBUG_FS*/
u8 default_up;
unsigned long fwd_bitmask; /* Bitmask indicating in use pools */
#define IXGBE_MAX_LINK_HANDLE 10
struct ixgbe_jump_table *jump_tables[IXGBE_MAX_LINK_HANDLE];
unsigned long tables;
/* maximum number of RETA entries among all devices supported by ixgbe
* driver: currently it's x550 device in non-SRIOV mode
*/
#define IXGBE_MAX_RETA_ENTRIES 512
u8 rss_indir_tbl[IXGBE_MAX_RETA_ENTRIES];
#define IXGBE_RSS_KEY_SIZE 40 /* size of RSS Hash Key in bytes */
u32 rss_key[IXGBE_RSS_KEY_SIZE / sizeof(u32)];
};
static inline u8 ixgbe_max_rss_indices(struct ixgbe_adapter *adapter)
{
switch (adapter->hw.mac.type) {
case ixgbe_mac_82598EB:
case ixgbe_mac_82599EB:
case ixgbe_mac_X540:
return IXGBE_MAX_RSS_INDICES;
case ixgbe_mac_X550:
case ixgbe_mac_X550EM_x:
case ixgbe_mac_x550em_a:
return IXGBE_MAX_RSS_INDICES_X550;
default:
return 0;
}
}
struct ixgbe_fdir_filter {
struct hlist_node fdir_node;
union ixgbe_atr_input filter;
u16 sw_idx;
u64 action;
};
enum ixgbe_state_t {
__IXGBE_TESTING,
__IXGBE_RESETTING,
__IXGBE_DOWN,
__IXGBE_DISABLED,
__IXGBE_REMOVING,
__IXGBE_SERVICE_SCHED,
__IXGBE_SERVICE_INITED,
__IXGBE_IN_SFP_INIT,
__IXGBE_PTP_RUNNING,
__IXGBE_PTP_TX_IN_PROGRESS,
__IXGBE_RESET_REQUESTED,
};
struct ixgbe_cb {
union { /* Union defining head/tail partner */
struct sk_buff *head;
struct sk_buff *tail;
};
dma_addr_t dma;
u16 append_cnt;
bool page_released;
};
#define IXGBE_CB(skb) ((struct ixgbe_cb *)(skb)->cb)
enum ixgbe_boards {
board_82598,
board_82599,
board_X540,
board_X550,
board_X550EM_x,
board_x550em_a,
board_x550em_a_fw,
};
extern const struct ixgbe_info ixgbe_82598_info;
extern const struct ixgbe_info ixgbe_82599_info;
extern const struct ixgbe_info ixgbe_X540_info;
extern const struct ixgbe_info ixgbe_X550_info;
extern const struct ixgbe_info ixgbe_X550EM_x_info;
extern const struct ixgbe_info ixgbe_x550em_a_info;
extern const struct ixgbe_info ixgbe_x550em_a_fw_info;
#ifdef CONFIG_IXGBE_DCB
extern const struct dcbnl_rtnl_ops ixgbe_dcbnl_ops;
#endif
extern char ixgbe_driver_name[];
extern const char ixgbe_driver_version[];
#ifdef IXGBE_FCOE
extern char ixgbe_default_device_descr[];
#endif /* IXGBE_FCOE */
int ixgbe_open(struct net_device *netdev);
int ixgbe_close(struct net_device *netdev);
void ixgbe_up(struct ixgbe_adapter *adapter);
void ixgbe_down(struct ixgbe_adapter *adapter);
void ixgbe_reinit_locked(struct ixgbe_adapter *adapter);
void ixgbe_reset(struct ixgbe_adapter *adapter);
void ixgbe_set_ethtool_ops(struct net_device *netdev);
int ixgbe_setup_rx_resources(struct ixgbe_ring *);
int ixgbe_setup_tx_resources(struct ixgbe_ring *);
void ixgbe_free_rx_resources(struct ixgbe_ring *);
void ixgbe_free_tx_resources(struct ixgbe_ring *);
void ixgbe_configure_rx_ring(struct ixgbe_adapter *, struct ixgbe_ring *);
void ixgbe_configure_tx_ring(struct ixgbe_adapter *, struct ixgbe_ring *);
void ixgbe_disable_rx_queue(struct ixgbe_adapter *adapter, struct ixgbe_ring *);
void ixgbe_update_stats(struct ixgbe_adapter *adapter);
int ixgbe_init_interrupt_scheme(struct ixgbe_adapter *adapter);
bool ixgbe_wol_supported(struct ixgbe_adapter *adapter, u16 device_id,
u16 subdevice_id);
#ifdef CONFIG_PCI_IOV
void ixgbe_full_sync_mac_table(struct ixgbe_adapter *adapter);
#endif
int ixgbe_add_mac_filter(struct ixgbe_adapter *adapter,
const u8 *addr, u16 queue);
int ixgbe_del_mac_filter(struct ixgbe_adapter *adapter,
const u8 *addr, u16 queue);
void ixgbe_update_pf_promisc_vlvf(struct ixgbe_adapter *adapter, u32 vid);
void ixgbe_clear_interrupt_scheme(struct ixgbe_adapter *adapter);
netdev_tx_t ixgbe_xmit_frame_ring(struct sk_buff *, struct ixgbe_adapter *,
struct ixgbe_ring *);
void ixgbe_unmap_and_free_tx_resource(struct ixgbe_ring *,
struct ixgbe_tx_buffer *);
void ixgbe_alloc_rx_buffers(struct ixgbe_ring *, u16);
void ixgbe_write_eitr(struct ixgbe_q_vector *);
int ixgbe_poll(struct napi_struct *napi, int budget);
int ethtool_ioctl(struct ifreq *ifr);
s32 ixgbe_reinit_fdir_tables_82599(struct ixgbe_hw *hw);
s32 ixgbe_init_fdir_signature_82599(struct ixgbe_hw *hw, u32 fdirctrl);
s32 ixgbe_init_fdir_perfect_82599(struct ixgbe_hw *hw, u32 fdirctrl);
s32 ixgbe_fdir_add_signature_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_hash_dword input,
union ixgbe_atr_hash_dword common,
u8 queue);
s32 ixgbe_fdir_set_input_mask_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input_mask);
s32 ixgbe_fdir_write_perfect_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input,
u16 soft_id, u8 queue);
s32 ixgbe_fdir_erase_perfect_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input,
u16 soft_id);
void ixgbe_atr_compute_perfect_hash_82599(union ixgbe_atr_input *input,
union ixgbe_atr_input *mask);
int ixgbe_update_ethtool_fdir_entry(struct ixgbe_adapter *adapter,
struct ixgbe_fdir_filter *input,
u16 sw_idx);
void ixgbe_set_rx_mode(struct net_device *netdev);
#ifdef CONFIG_IXGBE_DCB
void ixgbe_set_rx_drop_en(struct ixgbe_adapter *adapter);
#endif
int ixgbe_setup_tc(struct net_device *dev, u8 tc);
void ixgbe_tx_ctxtdesc(struct ixgbe_ring *, u32, u32, u32, u32);
void ixgbe_do_reset(struct net_device *netdev);
#ifdef CONFIG_IXGBE_HWMON
void ixgbe_sysfs_exit(struct ixgbe_adapter *adapter);
int ixgbe_sysfs_init(struct ixgbe_adapter *adapter);
#endif /* CONFIG_IXGBE_HWMON */
#ifdef IXGBE_FCOE
void ixgbe_configure_fcoe(struct ixgbe_adapter *adapter);
int ixgbe_fso(struct ixgbe_ring *tx_ring, struct ixgbe_tx_buffer *first,
u8 *hdr_len);
int ixgbe_fcoe_ddp(struct ixgbe_adapter *adapter,
union ixgbe_adv_rx_desc *rx_desc, struct sk_buff *skb);
int ixgbe_fcoe_ddp_get(struct net_device *netdev, u16 xid,
struct scatterlist *sgl, unsigned int sgc);
int ixgbe_fcoe_ddp_target(struct net_device *netdev, u16 xid,
struct scatterlist *sgl, unsigned int sgc);
int ixgbe_fcoe_ddp_put(struct net_device *netdev, u16 xid);
int ixgbe_setup_fcoe_ddp_resources(struct ixgbe_adapter *adapter);
void ixgbe_free_fcoe_ddp_resources(struct ixgbe_adapter *adapter);
int ixgbe_fcoe_enable(struct net_device *netdev);
int ixgbe_fcoe_disable(struct net_device *netdev);
#ifdef CONFIG_IXGBE_DCB
u8 ixgbe_fcoe_getapp(struct ixgbe_adapter *adapter);
u8 ixgbe_fcoe_setapp(struct ixgbe_adapter *adapter, u8 up);
#endif /* CONFIG_IXGBE_DCB */
int ixgbe_fcoe_get_wwn(struct net_device *netdev, u64 *wwn, int type);
int ixgbe_fcoe_get_hbainfo(struct net_device *netdev,
struct netdev_fcoe_hbainfo *info);
u8 ixgbe_fcoe_get_tc(struct ixgbe_adapter *adapter);
#endif /* IXGBE_FCOE */
#ifdef CONFIG_DEBUG_FS
void ixgbe_dbg_adapter_init(struct ixgbe_adapter *adapter);
void ixgbe_dbg_adapter_exit(struct ixgbe_adapter *adapter);
void ixgbe_dbg_init(void);
void ixgbe_dbg_exit(void);
#else
static inline void ixgbe_dbg_adapter_init(struct ixgbe_adapter *adapter) {}
static inline void ixgbe_dbg_adapter_exit(struct ixgbe_adapter *adapter) {}
static inline void ixgbe_dbg_init(void) {}
static inline void ixgbe_dbg_exit(void) {}
#endif /* CONFIG_DEBUG_FS */
static inline struct netdev_queue *txring_txq(const struct ixgbe_ring *ring)
{
return netdev_get_tx_queue(ring->netdev, ring->queue_index);
}
void ixgbe_ptp_init(struct ixgbe_adapter *adapter);
void ixgbe_ptp_suspend(struct ixgbe_adapter *adapter);
void ixgbe_ptp_stop(struct ixgbe_adapter *adapter);
void ixgbe_ptp_overflow_check(struct ixgbe_adapter *adapter);
void ixgbe_ptp_rx_hang(struct ixgbe_adapter *adapter);
void ixgbe_ptp_rx_pktstamp(struct ixgbe_q_vector *, struct sk_buff *);
void ixgbe_ptp_rx_rgtstamp(struct ixgbe_q_vector *, struct sk_buff *skb);
static inline void ixgbe_ptp_rx_hwtstamp(struct ixgbe_ring *rx_ring,
union ixgbe_adv_rx_desc *rx_desc,
struct sk_buff *skb)
{
if (unlikely(ixgbe_test_staterr(rx_desc, IXGBE_RXD_STAT_TSIP))) {
ixgbe_ptp_rx_pktstamp(rx_ring->q_vector, skb);
return;
}
if (unlikely(!ixgbe_test_staterr(rx_desc, IXGBE_RXDADV_STAT_TS)))
return;
ixgbe_ptp_rx_rgtstamp(rx_ring->q_vector, skb);
/* Update the last_rx_timestamp timer in order to enable watchdog check
* for error case of latched timestamp on a dropped packet.
*/
rx_ring->last_rx_timestamp = jiffies;
}
int ixgbe_ptp_set_ts_config(struct ixgbe_adapter *adapter, struct ifreq *ifr);
int ixgbe_ptp_get_ts_config(struct ixgbe_adapter *adapter, struct ifreq *ifr);
void ixgbe_ptp_start_cyclecounter(struct ixgbe_adapter *adapter);
void ixgbe_ptp_reset(struct ixgbe_adapter *adapter);
void ixgbe_ptp_check_pps_event(struct ixgbe_adapter *adapter);
#ifdef CONFIG_PCI_IOV
void ixgbe_sriov_reinit(struct ixgbe_adapter *adapter);
#endif
netdev_tx_t ixgbe_xmit_frame_ring(struct sk_buff *skb,
struct ixgbe_adapter *adapter,
struct ixgbe_ring *tx_ring);
u32 ixgbe_rss_indir_tbl_entries(struct ixgbe_adapter *adapter);
void ixgbe_store_key(struct ixgbe_adapter *adapter);
void ixgbe_store_reta(struct ixgbe_adapter *adapter);
s32 ixgbe_negotiate_fc(struct ixgbe_hw *hw, u32 adv_reg, u32 lp_reg,
u32 adv_sym, u32 adv_asm, u32 lp_sym, u32 lp_asm);
#endif /* _IXGBE_H_ */
| {
"language": "C"
} |
/*
* Copyright (C) 2015 The Qt Company Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef QWebUndoCommand_h
#define QWebUndoCommand_h
#include <qsharedpointer.h>
#include <qundostack.h>
class UndoStepQt;
#ifndef QT_NO_UNDOCOMMAND
class QWebUndoCommand final : public QUndoCommand {
public:
QWebUndoCommand(QSharedPointer<UndoStepQt>, QUndoCommand *parent = 0);
void undo() final;
void redo() final;
private:
QSharedPointer<UndoStepQt> m_step;
};
#endif // QT_NO_UNDOCOMMAND
#endif // QWebUndoCommand_h
| {
"language": "C"
} |
/**
******************************************************************************
* @file stm32f4xx_hal_dma_ex.c
* @author MCD Application Team
* @brief DMA Extension HAL module driver
* This file provides firmware functions to manage the following
* functionalities of the DMA Extension peripheral:
* + Extended features functions
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The DMA Extension HAL driver can be used as follows:
(#) Start a multi buffer transfer using the HAL_DMA_MultiBufferStart() function
for polling mode or HAL_DMA_MultiBufferStart_IT() for interrupt mode.
-@- In Memory-to-Memory transfer mode, Multi (Double) Buffer mode is not allowed.
-@- When Multi (Double) Buffer mode is enabled the, transfer is circular by default.
-@- In Multi (Double) buffer mode, it is possible to update the base address for
the AHB memory port on the fly (DMA_SxM0AR or DMA_SxM1AR) when the stream is enabled.
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @defgroup DMAEx DMAEx
* @brief DMA Extended HAL module driver
* @{
*/
#ifdef HAL_DMA_MODULE_ENABLED
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private Constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @addtogroup DMAEx_Private_Functions
* @{
*/
static void DMA_MultiBufferSetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength);
/**
* @}
*/
/* Exported functions ---------------------------------------------------------*/
/** @addtogroup DMAEx_Exported_Functions
* @{
*/
/** @addtogroup DMAEx_Exported_Functions_Group1
*
@verbatim
===============================================================================
##### Extended features functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure the source, destination address and data length and
Start MultiBuffer DMA transfer
(+) Configure the source, destination address and data length and
Start MultiBuffer DMA transfer with interrupt
(+) Change on the fly the memory0 or memory1 address.
@endverbatim
* @{
*/
/**
* @brief Starts the multi_buffer DMA Transfer.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param SrcAddress The source memory Buffer address
* @param DstAddress The destination memory Buffer address
* @param SecondMemAddress The second memory Buffer address in case of multi buffer Transfer
* @param DataLength The length of data to be transferred from source to destination
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMAEx_MultiBufferStart(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
assert_param(IS_DMA_BUFFER_SIZE(DataLength));
/* Memory-to-memory transfer not supported in double buffering mode */
if (hdma->Init.Direction == DMA_MEMORY_TO_MEMORY)
{
hdma->ErrorCode = HAL_DMA_ERROR_NOT_SUPPORTED;
status = HAL_ERROR;
}
else
{
/* Process Locked */
__HAL_LOCK(hdma);
if(HAL_DMA_STATE_READY == hdma->State)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_BUSY;
/* Enable the double buffer mode */
hdma->Instance->CR |= (uint32_t)DMA_SxCR_DBM;
/* Configure DMA Stream destination address */
hdma->Instance->M1AR = SecondMemAddress;
/* Configure the source, destination address and the data length */
DMA_MultiBufferSetConfig(hdma, SrcAddress, DstAddress, DataLength);
/* Enable the peripheral */
__HAL_DMA_ENABLE(hdma);
}
else
{
/* Return error status */
status = HAL_BUSY;
}
}
return status;
}
/**
* @brief Starts the multi_buffer DMA Transfer with interrupt enabled.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param SrcAddress The source memory Buffer address
* @param DstAddress The destination memory Buffer address
* @param SecondMemAddress The second memory Buffer address in case of multi buffer Transfer
* @param DataLength The length of data to be transferred from source to destination
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMAEx_MultiBufferStart_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength)
{
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
assert_param(IS_DMA_BUFFER_SIZE(DataLength));
/* Memory-to-memory transfer not supported in double buffering mode */
if (hdma->Init.Direction == DMA_MEMORY_TO_MEMORY)
{
hdma->ErrorCode = HAL_DMA_ERROR_NOT_SUPPORTED;
return HAL_ERROR;
}
/* Check callback functions */
if ((NULL == hdma->XferCpltCallback) || (NULL == hdma->XferM1CpltCallback) || (NULL == hdma->XferErrorCallback))
{
hdma->ErrorCode = HAL_DMA_ERROR_PARAM;
return HAL_ERROR;
}
/* Process locked */
__HAL_LOCK(hdma);
if(HAL_DMA_STATE_READY == hdma->State)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_BUSY;
/* Initialize the error code */
hdma->ErrorCode = HAL_DMA_ERROR_NONE;
/* Enable the Double buffer mode */
hdma->Instance->CR |= (uint32_t)DMA_SxCR_DBM;
/* Configure DMA Stream destination address */
hdma->Instance->M1AR = SecondMemAddress;
/* Configure the source, destination address and the data length */
DMA_MultiBufferSetConfig(hdma, SrcAddress, DstAddress, DataLength);
/* Clear all flags */
__HAL_DMA_CLEAR_FLAG (hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
__HAL_DMA_CLEAR_FLAG (hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
__HAL_DMA_CLEAR_FLAG (hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma));
__HAL_DMA_CLEAR_FLAG (hdma, __HAL_DMA_GET_DME_FLAG_INDEX(hdma));
__HAL_DMA_CLEAR_FLAG (hdma, __HAL_DMA_GET_FE_FLAG_INDEX(hdma));
/* Enable Common interrupts*/
hdma->Instance->CR |= DMA_IT_TC | DMA_IT_TE | DMA_IT_DME;
hdma->Instance->FCR |= DMA_IT_FE;
if((hdma->XferHalfCpltCallback != NULL) || (hdma->XferM1HalfCpltCallback != NULL))
{
hdma->Instance->CR |= DMA_IT_HT;
}
/* Enable the peripheral */
__HAL_DMA_ENABLE(hdma);
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hdma);
/* Return error status */
status = HAL_BUSY;
}
return status;
}
/**
* @brief Change the memory0 or memory1 address on the fly.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param Address The new address
* @param memory the memory to be changed, This parameter can be one of
* the following values:
* MEMORY0 /
* MEMORY1
* @note The MEMORY0 address can be changed only when the current transfer use
* MEMORY1 and the MEMORY1 address can be changed only when the current
* transfer use MEMORY0.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMAEx_ChangeMemory(DMA_HandleTypeDef *hdma, uint32_t Address, HAL_DMA_MemoryTypeDef memory)
{
if(memory == MEMORY0)
{
/* change the memory0 address */
hdma->Instance->M0AR = Address;
}
else
{
/* change the memory1 address */
hdma->Instance->M1AR = Address;
}
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup DMAEx_Private_Functions
* @{
*/
/**
* @brief Set the DMA Transfer parameter.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param SrcAddress The source memory Buffer address
* @param DstAddress The destination memory Buffer address
* @param DataLength The length of data to be transferred from source to destination
* @retval HAL status
*/
static void DMA_MultiBufferSetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
{
/* Configure DMA Stream data length */
hdma->Instance->NDTR = DataLength;
/* Peripheral to Memory */
if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH)
{
/* Configure DMA Stream destination address */
hdma->Instance->PAR = DstAddress;
/* Configure DMA Stream source address */
hdma->Instance->M0AR = SrcAddress;
}
/* Memory to Peripheral */
else
{
/* Configure DMA Stream source address */
hdma->Instance->PAR = SrcAddress;
/* Configure DMA Stream destination address */
hdma->Instance->M0AR = DstAddress;
}
}
/**
* @}
*/
#endif /* HAL_DMA_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"language": "C"
} |
/*
*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
function onhyperlinkclick(element) {
function _postMessage(msg) {
if (window.parent && window.JSON) {
window.parent.postMessage(window.JSON.stringify(msg), "*");
}
}
_postMessage({
command: 'internalCommand',
data: {
type: 'help:hyperlink',
data: element.href
}
});
}
| {
"language": "C"
} |
/*
* Copyright 2012 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "rootnv50.h"
#include "dmacnv50.h"
#include <core/client.h>
#include <core/ramht.h>
#include <subdev/timer.h>
#include <nvif/class.h>
#include <nvif/cl5070.h>
#include <nvif/unpack.h>
int
gf119_disp_root_scanoutpos(NV50_DISP_MTHD_V0)
{
struct nvkm_device *device = disp->base.engine.subdev.device;
const u32 total = nvkm_rd32(device, 0x640414 + (head * 0x300));
const u32 blanke = nvkm_rd32(device, 0x64041c + (head * 0x300));
const u32 blanks = nvkm_rd32(device, 0x640420 + (head * 0x300));
union {
struct nv50_disp_scanoutpos_v0 v0;
} *args = data;
int ret = -ENOSYS;
nvif_ioctl(object, "disp scanoutpos size %d\n", size);
if (!(ret = nvif_unpack(ret, &data, &size, args->v0, 0, 0, false))) {
nvif_ioctl(object, "disp scanoutpos vers %d\n",
args->v0.version);
args->v0.vblanke = (blanke & 0xffff0000) >> 16;
args->v0.hblanke = (blanke & 0x0000ffff);
args->v0.vblanks = (blanks & 0xffff0000) >> 16;
args->v0.hblanks = (blanks & 0x0000ffff);
args->v0.vtotal = ( total & 0xffff0000) >> 16;
args->v0.htotal = ( total & 0x0000ffff);
args->v0.time[0] = ktime_to_ns(ktime_get());
args->v0.vline = /* vline read locks hline */
nvkm_rd32(device, 0x616340 + (head * 0x800)) & 0xffff;
args->v0.time[1] = ktime_to_ns(ktime_get());
args->v0.hline =
nvkm_rd32(device, 0x616344 + (head * 0x800)) & 0xffff;
} else
return ret;
return 0;
}
void
gf119_disp_root_fini(struct nv50_disp_root *root)
{
struct nvkm_device *device = root->disp->base.engine.subdev.device;
/* disable all interrupts */
nvkm_wr32(device, 0x6100b0, 0x00000000);
}
int
gf119_disp_root_init(struct nv50_disp_root *root)
{
struct nv50_disp *disp = root->disp;
struct nvkm_device *device = disp->base.engine.subdev.device;
u32 tmp;
int i;
/* The below segments of code copying values from one register to
* another appear to inform EVO of the display capabilities or
* something similar.
*/
/* ... CRTC caps */
for (i = 0; i < disp->base.head.nr; i++) {
tmp = nvkm_rd32(device, 0x616104 + (i * 0x800));
nvkm_wr32(device, 0x6101b4 + (i * 0x800), tmp);
tmp = nvkm_rd32(device, 0x616108 + (i * 0x800));
nvkm_wr32(device, 0x6101b8 + (i * 0x800), tmp);
tmp = nvkm_rd32(device, 0x61610c + (i * 0x800));
nvkm_wr32(device, 0x6101bc + (i * 0x800), tmp);
}
/* ... DAC caps */
for (i = 0; i < disp->func->dac.nr; i++) {
tmp = nvkm_rd32(device, 0x61a000 + (i * 0x800));
nvkm_wr32(device, 0x6101c0 + (i * 0x800), tmp);
}
/* ... SOR caps */
for (i = 0; i < disp->func->sor.nr; i++) {
tmp = nvkm_rd32(device, 0x61c000 + (i * 0x800));
nvkm_wr32(device, 0x6301c4 + (i * 0x800), tmp);
}
/* steal display away from vbios, or something like that */
if (nvkm_rd32(device, 0x6100ac) & 0x00000100) {
nvkm_wr32(device, 0x6100ac, 0x00000100);
nvkm_mask(device, 0x6194e8, 0x00000001, 0x00000000);
if (nvkm_msec(device, 2000,
if (!(nvkm_rd32(device, 0x6194e8) & 0x00000002))
break;
) < 0)
return -EBUSY;
}
/* point at display engine memory area (hash table, objects) */
nvkm_wr32(device, 0x610010, (root->instmem->addr >> 8) | 9);
/* enable supervisor interrupts, disable everything else */
nvkm_wr32(device, 0x610090, 0x00000000);
nvkm_wr32(device, 0x6100a0, 0x00000000);
nvkm_wr32(device, 0x6100b0, 0x00000307);
/* disable underflow reporting, preventing an intermittent issue
* on some gk104 boards where the production vbios left this
* setting enabled by default.
*
* ftp://download.nvidia.com/open-gpu-doc/gk104-disable-underflow-reporting/1/gk104-disable-underflow-reporting.txt
*/
for (i = 0; i < disp->base.head.nr; i++)
nvkm_mask(device, 0x616308 + (i * 0x800), 0x00000111, 0x00000010);
return 0;
}
static const struct nv50_disp_root_func
gf119_disp_root = {
.init = gf119_disp_root_init,
.fini = gf119_disp_root_fini,
.dmac = {
&gf119_disp_core_oclass,
&gf119_disp_base_oclass,
&gf119_disp_ovly_oclass,
},
.pioc = {
&gf119_disp_oimm_oclass,
&gf119_disp_curs_oclass,
},
};
static int
gf119_disp_root_new(struct nvkm_disp *disp, const struct nvkm_oclass *oclass,
void *data, u32 size, struct nvkm_object **pobject)
{
return nv50_disp_root_new_(&gf119_disp_root, disp, oclass,
data, size, pobject);
}
const struct nvkm_disp_oclass
gf119_disp_root_oclass = {
.base.oclass = GF110_DISP,
.base.minver = -1,
.base.maxver = -1,
.ctor = gf119_disp_root_new,
};
| {
"language": "C"
} |
#include <stdio.h>
#include <sys/time.h>
#include "relic_interface.h"
/* prime curves */
#define DEBUG 1
#define TRIALS 1
#define HEX 16
//void printf_as_hex(unsigned char *buf, size_t len)
//{
// size_t i;
// for(i = 0; i < len; i += 4)
// printf("%02X%02X%02X%02X ", buf[i], buf[i+1], buf[i+2], buf[i+3]);
// printf("\n");
//}
//double calc_usecs(bench_t *start, bench_t *stop) {
// double usec_per_second = 1000000; // 1 000 000
// double result = usec_per_second * (stop->tv_sec - start->tv_sec);
//
// if(stop->tv_usec >= stop->tv_usec) {
// result += (stop->tv_usec - start->tv_usec);
// }
// else {
// result -= (start->tv_usec - stop->tv_usec);
// }
//
// return result / usec_per_second;
//}
/*
double calc_msecs(bench_t *start, bench_t *stop) {
double msec_per_second = 1000; // 1 000 000
double usec_per_second = 1000000; // 1 000 000
double result1 = start->tv_sec + (start->tv_usec / usec_per_second);
double result2 = stop->tv_sec + (stop->tv_usec / usec_per_second);
return (result2 - result1) * msec_per_second;
}
*/
int main(int argc, char *argv[])
{
status_t result;
result = pairing_init();
if(result == ELEMENT_OK)
printf("pairing init: SUCCESS.\n");
else
printf("pairing init: FAILED!\n");
element_ptr e0 = (element_ptr) malloc(sizeof(element_t));
element_t e; // , e1, e2, e3;
/* Start ZR init & operations */
element_init_Zr(e, 0);
element_init_Zr(e0, 1234567890);
element_random(e);
element_printf("e -> ZR :=> ", e);
element_printf("e0 -> ZR :=> ", e0);
element_add(e, e, e0);
element_printf("Add ZR :=> ", e);
element_sub(e0, e, e0);
element_printf("Sub ZR :=> ", e);
element_clear(e);
element_clear(e0);
/* End of ZR operations */
element_t g1_0, g1_1, g1_2, g2_1, g2_2, g2_nil, gt_1, gt_2;
/* Start G1 init & operations */
element_init_G1(g1_0);
element_printf("Identity G1 :=> \n", g1_0);
element_init_G1(g1_1);
element_init_G1(g1_2);
element_init_G2(g2_1);
element_init_G2(g2_2);
element_init_G2(g2_nil);
element_init_GT(gt_1);
element_init_GT(gt_2);
element_init_Zr(e0, 0);
// element_random(g1_0);
// element_random(g1_1);
//
// element_add(g1_2, g1_0, g1_1);
// element_printf("Add G1 :=> \n", g1_2);
//
// element_sub(g1_2, g1_2, g1_0);
// element_printf("Sub G1 :=> \n", g1_2);
//
//
unsigned char *msg = "hello world!";
element_from_hash(e0, msg, strlen((char *) msg));
element_from_hash(g1_2, msg, strlen((char *) msg));
element_from_hash(g2_2, msg, strlen((char *) msg));
element_printf("Hash into e0 :=> \n", e0);
element_printf("Hash into g1 :=> \n", g1_2);
element_printf("Hash into g2 :=> \n", g2_2);
printf("cmp elements ok! :=> '%d'\n", element_cmp(g1_2, g1_2));
printf("cmp elements fail:=> '%d'\n", element_cmp(g1_1, g1_2));
int d_len = element_length(g1_1);
if(d_len > 0) {
printf("%s: g1 d_len :=> '%d'\n", __FUNCTION__, d_len);
uint8_t data[d_len + 1];
element_to_bytes(data, d_len, g1_1);
element_from_bytes(g1_2, data, d_len);
element_printf("rec g1 :=> \n", g1_2);
printf("cmp elements after deserialize :=> '%d'\n", element_cmp(g1_1, g1_2));
}
d_len = element_length(g2_2);
if(d_len > 0) {
element_printf("g2 write bin :=> \n", g2_2);
printf("%s: g2 d_len :=> '%d'\n", __FUNCTION__, d_len);
uint8_t data[d_len + 1];
element_to_bytes(data, d_len, g2_2);
element_from_bytes(g2_1, data, d_len);
element_printf("Rec g2 :=> \n", g2_1);
printf("cmp elements after deserialize :=> '%d'\n", element_cmp(g2_1, g2_2));
}
element_random(gt_1);
d_len = element_length(gt_1);
if(d_len > 0) {
element_printf("gt print :=> \n", gt_1);
printf("%s: g2 d_len :=> '%d'\n", __FUNCTION__, d_len);
uint8_t data[d_len + 1];
element_to_bytes(data, d_len, gt_1);
element_from_bytes(gt_2, data, d_len);
element_printf("Rec gt :=> \n", gt_2);
printf("cmp elements after deserialize :=> '%d'\n", element_cmp(gt_1, gt_2));
}
element_pairing(gt_1, g1_1, g2_1);
element_printf("Pairing result :=> \n", gt_1);
element_printf("g2 :=> \n", g2_nil);
element_pairing(gt_2, g1_1, g2_nil);
element_printf("Pairing result :=> \n", gt_2);
element_clear(e0);
element_clear(g1_0);
element_clear(g1_1);
element_clear(g1_2);
element_clear(g2_1);
element_clear(g2_2);
element_clear(g2_nil);
element_clear(gt_1);
element_clear(gt_2);
/* End of G1 operations */
pairing_clear();
return 0;
}
| {
"language": "C"
} |
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "uv.h"
#include "task.h"
#include <errno.h>
#include <string.h> /* memset */
#define NUM_WRITE_REQS 32
static uv_tcp_t tcp_handle;
static uv_connect_t connect_req;
static int write_cb_called;
static int close_cb_called;
static void connect_cb(uv_connect_t* req, int status);
static void write_cb(uv_write_t* req, int status);
static void close_cb(uv_handle_t* handle);
static void connect_cb(uv_connect_t* conn_req, int status) {
uv_write_t* req;
uv_buf_t buf;
int i, r;
buf = uv_buf_init("PING", 4);
for (i = 0; i < NUM_WRITE_REQS; i++) {
req = malloc(sizeof *req);
ASSERT(req != NULL);
r = uv_write(req, (uv_stream_t*)&tcp_handle, &buf, 1, write_cb);
ASSERT(r == 0);
}
uv_close((uv_handle_t*)&tcp_handle, close_cb);
}
static void write_cb(uv_write_t* req, int status) {
/* write callbacks should run before the close callback */
ASSERT(close_cb_called == 0);
ASSERT(req->handle == (uv_stream_t*)&tcp_handle);
write_cb_called++;
free(req);
}
static void close_cb(uv_handle_t* handle) {
ASSERT(handle == (uv_handle_t*)&tcp_handle);
close_cb_called++;
}
static void connection_cb(uv_stream_t* server, int status) {
ASSERT(status == 0);
}
static void start_server(uv_loop_t* loop, uv_tcp_t* handle) {
struct sockaddr_in addr;
int r;
ASSERT(0 == uv_ip4_addr("127.0.0.1", TEST_PORT, &addr));
r = uv_tcp_init(loop, handle);
ASSERT(r == 0);
r = uv_tcp_bind(handle, (const struct sockaddr*) &addr, 0);
ASSERT(r == 0);
r = uv_listen((uv_stream_t*)handle, 128, connection_cb);
ASSERT(r == 0);
uv_unref((uv_handle_t*)handle);
}
/* Check that pending write requests have their callbacks
* invoked when the handle is closed.
*/
TEST_IMPL(tcp_close) {
struct sockaddr_in addr;
uv_tcp_t tcp_server;
uv_loop_t* loop;
int r;
ASSERT(0 == uv_ip4_addr("127.0.0.1", TEST_PORT, &addr));
loop = uv_default_loop();
/* We can't use the echo server, it doesn't handle ECONNRESET. */
start_server(loop, &tcp_server);
r = uv_tcp_init(loop, &tcp_handle);
ASSERT(r == 0);
r = uv_tcp_connect(&connect_req,
&tcp_handle,
(const struct sockaddr*) &addr,
connect_cb);
ASSERT(r == 0);
ASSERT(write_cb_called == 0);
ASSERT(close_cb_called == 0);
r = uv_run(loop, UV_RUN_DEFAULT);
ASSERT(r == 0);
printf("%d of %d write reqs seen\n", write_cb_called, NUM_WRITE_REQS);
ASSERT(write_cb_called == NUM_WRITE_REQS);
ASSERT(close_cb_called == 1);
MAKE_VALGRIND_HAPPY();
return 0;
}
| {
"language": "C"
} |
/* crypto/bn/bn_exp2.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include "bn_lcl.h"
#define TABLE_SIZE 32
int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1,
const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *in_mont)
{
int i,j,bits,b,bits1,bits2,ret=0,wpos1,wpos2,window1,window2,wvalue1,wvalue2;
int r_is_one=1;
BIGNUM *d,*r;
const BIGNUM *a_mod_m;
/* Tables of variables obtained from 'ctx' */
BIGNUM *val1[TABLE_SIZE], *val2[TABLE_SIZE];
BN_MONT_CTX *mont=NULL;
bn_check_top(a1);
bn_check_top(p1);
bn_check_top(a2);
bn_check_top(p2);
bn_check_top(m);
if (!(m->d[0] & 1))
{
BNerr(BN_F_BN_MOD_EXP2_MONT,BN_R_CALLED_WITH_EVEN_MODULUS);
return(0);
}
bits1=BN_num_bits(p1);
bits2=BN_num_bits(p2);
if ((bits1 == 0) && (bits2 == 0))
{
ret = BN_one(rr);
return ret;
}
bits=(bits1 > bits2)?bits1:bits2;
BN_CTX_start(ctx);
d = BN_CTX_get(ctx);
r = BN_CTX_get(ctx);
val1[0] = BN_CTX_get(ctx);
val2[0] = BN_CTX_get(ctx);
if(!d || !r || !val1[0] || !val2[0]) goto err;
if (in_mont != NULL)
mont=in_mont;
else
{
if ((mont=BN_MONT_CTX_new()) == NULL) goto err;
if (!BN_MONT_CTX_set(mont,m,ctx)) goto err;
}
window1 = BN_window_bits_for_exponent_size(bits1);
window2 = BN_window_bits_for_exponent_size(bits2);
/*
* Build table for a1: val1[i] := a1^(2*i + 1) mod m for i = 0 .. 2^(window1-1)
*/
if (a1->neg || BN_ucmp(a1,m) >= 0)
{
if (!BN_mod(val1[0],a1,m,ctx))
goto err;
a_mod_m = val1[0];
}
else
a_mod_m = a1;
if (BN_is_zero(a_mod_m))
{
BN_zero(rr);
ret = 1;
goto err;
}
if (!BN_to_montgomery(val1[0],a_mod_m,mont,ctx)) goto err;
if (window1 > 1)
{
if (!BN_mod_mul_montgomery(d,val1[0],val1[0],mont,ctx)) goto err;
j=1<<(window1-1);
for (i=1; i<j; i++)
{
if(((val1[i] = BN_CTX_get(ctx)) == NULL) ||
!BN_mod_mul_montgomery(val1[i],val1[i-1],
d,mont,ctx))
goto err;
}
}
/*
* Build table for a2: val2[i] := a2^(2*i + 1) mod m for i = 0 .. 2^(window2-1)
*/
if (a2->neg || BN_ucmp(a2,m) >= 0)
{
if (!BN_mod(val2[0],a2,m,ctx))
goto err;
a_mod_m = val2[0];
}
else
a_mod_m = a2;
if (BN_is_zero(a_mod_m))
{
BN_zero(rr);
ret = 1;
goto err;
}
if (!BN_to_montgomery(val2[0],a_mod_m,mont,ctx)) goto err;
if (window2 > 1)
{
if (!BN_mod_mul_montgomery(d,val2[0],val2[0],mont,ctx)) goto err;
j=1<<(window2-1);
for (i=1; i<j; i++)
{
if(((val2[i] = BN_CTX_get(ctx)) == NULL) ||
!BN_mod_mul_montgomery(val2[i],val2[i-1],
d,mont,ctx))
goto err;
}
}
/* Now compute the power product, using independent windows. */
r_is_one=1;
wvalue1=0; /* The 'value' of the first window */
wvalue2=0; /* The 'value' of the second window */
wpos1=0; /* If wvalue1 > 0, the bottom bit of the first window */
wpos2=0; /* If wvalue2 > 0, the bottom bit of the second window */
if (!BN_to_montgomery(r,BN_value_one(),mont,ctx)) goto err;
for (b=bits-1; b>=0; b--)
{
if (!r_is_one)
{
if (!BN_mod_mul_montgomery(r,r,r,mont,ctx))
goto err;
}
if (!wvalue1)
if (BN_is_bit_set(p1, b))
{
/* consider bits b-window1+1 .. b for this window */
i = b-window1+1;
while (!BN_is_bit_set(p1, i)) /* works for i<0 */
i++;
wpos1 = i;
wvalue1 = 1;
for (i = b-1; i >= wpos1; i--)
{
wvalue1 <<= 1;
if (BN_is_bit_set(p1, i))
wvalue1++;
}
}
if (!wvalue2)
if (BN_is_bit_set(p2, b))
{
/* consider bits b-window2+1 .. b for this window */
i = b-window2+1;
while (!BN_is_bit_set(p2, i))
i++;
wpos2 = i;
wvalue2 = 1;
for (i = b-1; i >= wpos2; i--)
{
wvalue2 <<= 1;
if (BN_is_bit_set(p2, i))
wvalue2++;
}
}
if (wvalue1 && b == wpos1)
{
/* wvalue1 is odd and < 2^window1 */
if (!BN_mod_mul_montgomery(r,r,val1[wvalue1>>1],mont,ctx))
goto err;
wvalue1 = 0;
r_is_one = 0;
}
if (wvalue2 && b == wpos2)
{
/* wvalue2 is odd and < 2^window2 */
if (!BN_mod_mul_montgomery(r,r,val2[wvalue2>>1],mont,ctx))
goto err;
wvalue2 = 0;
r_is_one = 0;
}
}
if (!BN_from_montgomery(rr,r,mont,ctx))
goto err;
ret=1;
err:
if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont);
BN_CTX_end(ctx);
bn_check_top(rr);
return(ret);
}
| {
"language": "C"
} |
/*
* bpf-script-test-kbuild.c
* Test include from kernel header
*/
#ifndef LINUX_VERSION_CODE
# error Need LINUX_VERSION_CODE
# error Example: for 4.2 kernel, put 'clang-opt="-DLINUX_VERSION_CODE=0x40200" into llvm section of ~/.perfconfig'
#endif
#define SEC(NAME) __attribute__((section(NAME), used))
#include <uapi/linux/fs.h>
SEC("func=vfs_llseek")
int bpf_func__vfs_llseek(void *ctx)
{
return 0;
}
char _license[] SEC("license") = "GPL";
int _version SEC("version") = LINUX_VERSION_CODE;
| {
"language": "C"
} |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Spreadtrum mailbox driver
*
* Copyright (c) 2020 Spreadtrum Communications Inc.
*/
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/mailbox_controller.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#define SPRD_MBOX_ID 0x0
#define SPRD_MBOX_MSG_LOW 0x4
#define SPRD_MBOX_MSG_HIGH 0x8
#define SPRD_MBOX_TRIGGER 0xc
#define SPRD_MBOX_FIFO_RST 0x10
#define SPRD_MBOX_FIFO_STS 0x14
#define SPRD_MBOX_IRQ_STS 0x18
#define SPRD_MBOX_IRQ_MSK 0x1c
#define SPRD_MBOX_LOCK 0x20
#define SPRD_MBOX_FIFO_DEPTH 0x24
/* Bit and mask definiation for inbox's SPRD_MBOX_FIFO_STS register */
#define SPRD_INBOX_FIFO_DELIVER_MASK GENMASK(23, 16)
#define SPRD_INBOX_FIFO_OVERLOW_MASK GENMASK(15, 8)
#define SPRD_INBOX_FIFO_DELIVER_SHIFT 16
#define SPRD_INBOX_FIFO_BUSY_MASK GENMASK(7, 0)
/* Bit and mask definiation for SPRD_MBOX_IRQ_STS register */
#define SPRD_MBOX_IRQ_CLR BIT(0)
/* Bit and mask definiation for outbox's SPRD_MBOX_FIFO_STS register */
#define SPRD_OUTBOX_FIFO_FULL BIT(0)
#define SPRD_OUTBOX_FIFO_WR_SHIFT 16
#define SPRD_OUTBOX_FIFO_RD_SHIFT 24
#define SPRD_OUTBOX_FIFO_POS_MASK GENMASK(7, 0)
/* Bit and mask definiation for inbox's SPRD_MBOX_IRQ_MSK register */
#define SPRD_INBOX_FIFO_BLOCK_IRQ BIT(0)
#define SPRD_INBOX_FIFO_OVERFLOW_IRQ BIT(1)
#define SPRD_INBOX_FIFO_DELIVER_IRQ BIT(2)
#define SPRD_INBOX_FIFO_IRQ_MASK GENMASK(2, 0)
/* Bit and mask definiation for outbox's SPRD_MBOX_IRQ_MSK register */
#define SPRD_OUTBOX_FIFO_NOT_EMPTY_IRQ BIT(0)
#define SPRD_OUTBOX_FIFO_IRQ_MASK GENMASK(4, 0)
#define SPRD_MBOX_CHAN_MAX 8
struct sprd_mbox_priv {
struct mbox_controller mbox;
struct device *dev;
void __iomem *inbox_base;
void __iomem *outbox_base;
struct clk *clk;
u32 outbox_fifo_depth;
struct mbox_chan chan[SPRD_MBOX_CHAN_MAX];
};
static struct sprd_mbox_priv *to_sprd_mbox_priv(struct mbox_controller *mbox)
{
return container_of(mbox, struct sprd_mbox_priv, mbox);
}
static u32 sprd_mbox_get_fifo_len(struct sprd_mbox_priv *priv, u32 fifo_sts)
{
u32 wr_pos = (fifo_sts >> SPRD_OUTBOX_FIFO_WR_SHIFT) &
SPRD_OUTBOX_FIFO_POS_MASK;
u32 rd_pos = (fifo_sts >> SPRD_OUTBOX_FIFO_RD_SHIFT) &
SPRD_OUTBOX_FIFO_POS_MASK;
u32 fifo_len;
/*
* If the read pointer is equal with write pointer, which means the fifo
* is full or empty.
*/
if (wr_pos == rd_pos) {
if (fifo_sts & SPRD_OUTBOX_FIFO_FULL)
fifo_len = priv->outbox_fifo_depth;
else
fifo_len = 0;
} else if (wr_pos > rd_pos) {
fifo_len = wr_pos - rd_pos;
} else {
fifo_len = priv->outbox_fifo_depth - rd_pos + wr_pos;
}
return fifo_len;
}
static irqreturn_t sprd_mbox_outbox_isr(int irq, void *data)
{
struct sprd_mbox_priv *priv = data;
struct mbox_chan *chan;
u32 fifo_sts, fifo_len, msg[2];
int i, id;
fifo_sts = readl(priv->outbox_base + SPRD_MBOX_FIFO_STS);
fifo_len = sprd_mbox_get_fifo_len(priv, fifo_sts);
if (!fifo_len) {
dev_warn_ratelimited(priv->dev, "spurious outbox interrupt\n");
return IRQ_NONE;
}
for (i = 0; i < fifo_len; i++) {
msg[0] = readl(priv->outbox_base + SPRD_MBOX_MSG_LOW);
msg[1] = readl(priv->outbox_base + SPRD_MBOX_MSG_HIGH);
id = readl(priv->outbox_base + SPRD_MBOX_ID);
chan = &priv->chan[id];
mbox_chan_received_data(chan, (void *)msg);
/* Trigger to update outbox FIFO pointer */
writel(0x1, priv->outbox_base + SPRD_MBOX_TRIGGER);
}
/* Clear irq status after reading all message. */
writel(SPRD_MBOX_IRQ_CLR, priv->outbox_base + SPRD_MBOX_IRQ_STS);
return IRQ_HANDLED;
}
static irqreturn_t sprd_mbox_inbox_isr(int irq, void *data)
{
struct sprd_mbox_priv *priv = data;
struct mbox_chan *chan;
u32 fifo_sts, send_sts, busy, id;
fifo_sts = readl(priv->inbox_base + SPRD_MBOX_FIFO_STS);
/* Get the inbox data delivery status */
send_sts = (fifo_sts & SPRD_INBOX_FIFO_DELIVER_MASK) >>
SPRD_INBOX_FIFO_DELIVER_SHIFT;
if (!send_sts) {
dev_warn_ratelimited(priv->dev, "spurious inbox interrupt\n");
return IRQ_NONE;
}
while (send_sts) {
id = __ffs(send_sts);
send_sts &= (send_sts - 1);
chan = &priv->chan[id];
/*
* Check if the message was fetched by remote traget, if yes,
* that means the transmission has been completed.
*/
busy = fifo_sts & SPRD_INBOX_FIFO_BUSY_MASK;
if (!(busy & BIT(id)))
mbox_chan_txdone(chan, 0);
}
/* Clear FIFO delivery and overflow status */
writel(fifo_sts &
(SPRD_INBOX_FIFO_DELIVER_MASK | SPRD_INBOX_FIFO_OVERLOW_MASK),
priv->inbox_base + SPRD_MBOX_FIFO_RST);
/* Clear irq status */
writel(SPRD_MBOX_IRQ_CLR, priv->inbox_base + SPRD_MBOX_IRQ_STS);
return IRQ_HANDLED;
}
static int sprd_mbox_send_data(struct mbox_chan *chan, void *msg)
{
struct sprd_mbox_priv *priv = to_sprd_mbox_priv(chan->mbox);
unsigned long id = (unsigned long)chan->con_priv;
u32 *data = msg;
/* Write data into inbox FIFO, and only support 8 bytes every time */
writel(data[0], priv->inbox_base + SPRD_MBOX_MSG_LOW);
writel(data[1], priv->inbox_base + SPRD_MBOX_MSG_HIGH);
/* Set target core id */
writel(id, priv->inbox_base + SPRD_MBOX_ID);
/* Trigger remote request */
writel(0x1, priv->inbox_base + SPRD_MBOX_TRIGGER);
return 0;
}
static int sprd_mbox_flush(struct mbox_chan *chan, unsigned long timeout)
{
struct sprd_mbox_priv *priv = to_sprd_mbox_priv(chan->mbox);
unsigned long id = (unsigned long)chan->con_priv;
u32 busy;
timeout = jiffies + msecs_to_jiffies(timeout);
while (time_before(jiffies, timeout)) {
busy = readl(priv->inbox_base + SPRD_MBOX_FIFO_STS) &
SPRD_INBOX_FIFO_BUSY_MASK;
if (!(busy & BIT(id))) {
mbox_chan_txdone(chan, 0);
return 0;
}
udelay(1);
}
return -ETIME;
}
static int sprd_mbox_startup(struct mbox_chan *chan)
{
struct sprd_mbox_priv *priv = to_sprd_mbox_priv(chan->mbox);
u32 val;
/* Select outbox FIFO mode and reset the outbox FIFO status */
writel(0x0, priv->outbox_base + SPRD_MBOX_FIFO_RST);
/* Enable inbox FIFO overflow and delivery interrupt */
val = readl(priv->inbox_base + SPRD_MBOX_IRQ_MSK);
val &= ~(SPRD_INBOX_FIFO_OVERFLOW_IRQ | SPRD_INBOX_FIFO_DELIVER_IRQ);
writel(val, priv->inbox_base + SPRD_MBOX_IRQ_MSK);
/* Enable outbox FIFO not empty interrupt */
val = readl(priv->outbox_base + SPRD_MBOX_IRQ_MSK);
val &= ~SPRD_OUTBOX_FIFO_NOT_EMPTY_IRQ;
writel(val, priv->outbox_base + SPRD_MBOX_IRQ_MSK);
return 0;
}
static void sprd_mbox_shutdown(struct mbox_chan *chan)
{
struct sprd_mbox_priv *priv = to_sprd_mbox_priv(chan->mbox);
/* Disable inbox & outbox interrupt */
writel(SPRD_INBOX_FIFO_IRQ_MASK, priv->inbox_base + SPRD_MBOX_IRQ_MSK);
writel(SPRD_OUTBOX_FIFO_IRQ_MASK, priv->outbox_base + SPRD_MBOX_IRQ_MSK);
}
static const struct mbox_chan_ops sprd_mbox_ops = {
.send_data = sprd_mbox_send_data,
.flush = sprd_mbox_flush,
.startup = sprd_mbox_startup,
.shutdown = sprd_mbox_shutdown,
};
static void sprd_mbox_disable(void *data)
{
struct sprd_mbox_priv *priv = data;
clk_disable_unprepare(priv->clk);
}
static int sprd_mbox_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct sprd_mbox_priv *priv;
int ret, inbox_irq, outbox_irq;
unsigned long id;
priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->dev = dev;
/*
* The Spreadtrum mailbox uses an inbox to send messages to the target
* core, and uses an outbox to receive messages from other cores.
*
* Thus the mailbox controller supplies 2 different register addresses
* and IRQ numbers for inbox and outbox.
*/
priv->inbox_base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(priv->inbox_base))
return PTR_ERR(priv->inbox_base);
priv->outbox_base = devm_platform_ioremap_resource(pdev, 1);
if (IS_ERR(priv->outbox_base))
return PTR_ERR(priv->outbox_base);
priv->clk = devm_clk_get(dev, "enable");
if (IS_ERR(priv->clk)) {
dev_err(dev, "failed to get mailbox clock\n");
return PTR_ERR(priv->clk);
}
ret = clk_prepare_enable(priv->clk);
if (ret)
return ret;
ret = devm_add_action_or_reset(dev, sprd_mbox_disable, priv);
if (ret) {
dev_err(dev, "failed to add mailbox disable action\n");
return ret;
}
inbox_irq = platform_get_irq(pdev, 0);
if (inbox_irq < 0)
return inbox_irq;
ret = devm_request_irq(dev, inbox_irq, sprd_mbox_inbox_isr,
IRQF_NO_SUSPEND, dev_name(dev), priv);
if (ret) {
dev_err(dev, "failed to request inbox IRQ: %d\n", ret);
return ret;
}
outbox_irq = platform_get_irq(pdev, 1);
if (outbox_irq < 0)
return outbox_irq;
ret = devm_request_irq(dev, outbox_irq, sprd_mbox_outbox_isr,
IRQF_NO_SUSPEND, dev_name(dev), priv);
if (ret) {
dev_err(dev, "failed to request outbox IRQ: %d\n", ret);
return ret;
}
/* Get the default outbox FIFO depth */
priv->outbox_fifo_depth =
readl(priv->outbox_base + SPRD_MBOX_FIFO_DEPTH) + 1;
priv->mbox.dev = dev;
priv->mbox.chans = &priv->chan[0];
priv->mbox.num_chans = SPRD_MBOX_CHAN_MAX;
priv->mbox.ops = &sprd_mbox_ops;
priv->mbox.txdone_irq = true;
for (id = 0; id < SPRD_MBOX_CHAN_MAX; id++)
priv->chan[id].con_priv = (void *)id;
ret = devm_mbox_controller_register(dev, &priv->mbox);
if (ret) {
dev_err(dev, "failed to register mailbox: %d\n", ret);
return ret;
}
return 0;
}
static const struct of_device_id sprd_mbox_of_match[] = {
{ .compatible = "sprd,sc9860-mailbox", },
{ },
};
MODULE_DEVICE_TABLE(of, sprd_mbox_of_match);
static struct platform_driver sprd_mbox_driver = {
.driver = {
.name = "sprd-mailbox",
.of_match_table = sprd_mbox_of_match,
},
.probe = sprd_mbox_probe,
};
module_platform_driver(sprd_mbox_driver);
MODULE_AUTHOR("Baolin Wang <baolin.wang@unisoc.com>");
MODULE_DESCRIPTION("Spreadtrum mailbox driver");
MODULE_LICENSE("GPL v2");
| {
"language": "C"
} |
/*
########################################################################
# #
# Program Name: MINDSENSORS_PSP.c #
# =========================== #
# #
# Copyright (c) 2013 by dexterindustries.com #
# #
# This program is free software. You can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; version 3 of the License. #
# Read the license at: http://www.gnu.org/licenses/gpl.txt #
# #
########################################################################
# History
# ------------------------------------------------
# Author Date Comments
# Karan 04/11/13 Initial Authoring
#
# Ported from the C Library Provided by mindsensors.com:
# Email: info (<at>) mindsensors (<dot>) com
# History
# ------------------------------------------------
# Author Date Comments
# Deepak 04/08/09 Initial Authoring.
#
#--------------------------------------
Controller button layout:
----------------------------------------
L1 R1
L2 R2
d triang
a c square circle
b cross
l_j_b r_j_b
l_j_x r_j_x
l_j_y r_j_y
-------------------------------------- #
#
bits as follows:
b1: a b c d x r_j_b l_j_b x
b2: square cross circle triang R1 L1 R2 L2
*/
#include <stdio.h>
#include "tick.h"
#include <wiringPi.h>
#include "BrickPi.h"
#include <linux/i2c-dev.h>
#include <fcntl.h>
// Compile Using:
// sudo gcc -o program "MINDSENSORS_PSP.c" -lrt -lm
// Run the compiled program using:
// sudo ./program
#define I2C_PORT PORT_1 // I2C port for the dCompass
#define I2C_SPEED 6 // delay for as little time as possible. Usually about 100k baud
int main() {
int result;
ClearTick();
printf("This program is free software. You can redistribute it and/or modify it under the terms of \nthe GNU General Public License as published by the Free Software Foundation; version 3 of the License. \nRead the license at: http://www.gnu.org/licenses/gpl.txt\n\n");
BrickPi.Address[0] = 1;
BrickPi.Address[1] = 2;
result = BrickPiSetup();
printf("BrickPiSetup: %d\n", result);
BrickPi.SensorType [I2C_PORT] = TYPE_SENSOR_I2C;
BrickPi.SensorI2CSpeed [I2C_PORT] = I2C_SPEED;
BrickPi.SensorI2CDevices [I2C_PORT] = 1;
BrickPi.SensorSettings [I2C_PORT][0] = 0;
BrickPi.SensorI2CAddr [I2C_PORT][0] = 0x02; //address for writing
BrickPiSetupSensors();
struct button b1;
b1=init_psp(b1);
while(1)
{
//Send 0x42 to get a response back
BrickPi.SensorI2CWrite [I2C_PORT][0] = 1; //number of bytes to write
BrickPi.SensorI2CRead [I2C_PORT][0] = 6; //number of bytes to read
BrickPi.SensorI2COut [I2C_PORT][0][0] = 0x42; //byte to write
BrickPiUpdateValues();
printf("%d %d %d\n",BrickPi.SensorI2CIn[I2C_PORT][0][0],BrickPi.SensorI2CIn[I2C_PORT][0][1],BrickPi.SensorI2CIn[I2C_PORT][0][2]);
b1=upd(b1,I2C_PORT); //Update the button values
show_val(b1); //#Show the values
//To use the button values in you own program just call it,
//eg x=b.ljx will fetch and store the value of the Left Joystick position in the X-axis in the variable x
b1=init_psp(b1); //Initialize all buttons to 0
usleep(100000); //Give a delay of 100ms
}
return 0;
}
| {
"language": "C"
} |
/*
* OpenKore C++ Standard Library
* Copyright (C) 2006 VCL
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#ifndef _OSL_INPUT_STREAM_H_
#define _OSL_INPUT_STREAM_H_
#include "../Object.h"
#include "IOException.h"
namespace OSL {
/**
* An abstract class for all input stream classes.
*
* An input stream is a stream from which data can be read. Where
* the data originally came from depends on the concrete subclass.
*
* @note
* This abstract class does not guarantee thread-safety. Thread-safety
* depends on the concrete subclass. Though you can use
* createThreadSafe() to create a thread-safe wrapper around this class.
*
* @class InputStream OSL/IO/InputStream.h
* @ingroup IO
*/
class InputStream: public Object {
public:
/**
* Flush and close this stream. If the stream is already
* closed, then this function does nothing.
*/
virtual void close() = 0;
/**
* Check whether the end of the stream has been reached.
*
* @throws IOException
*/
virtual bool eof() const throw(IOException) = 0;
/**
* Read up to size bytes of data from this stream.
*
* @param buffer The buffer to receive the read data.
* @param size The maximum size of buffer.
* @return The number of bytes read, which may be smaller than size, and may even be 0.
* Returns -1 if the end of the stream has been reached.
* @pre buffer != NULL
* @pre size > 0
* @post if eof(): result == -1
* @throws IOException
*/
virtual int read(char *buffer, unsigned int size) throw(IOException) = 0;
/**
* Create a thread-safe wrapper around this InputStream.
*
* @post
* The current InputStream's reference will be increased by 1,
* and the return value will have a reference count of 1.
* @post
* result != NULL
*
* @note
* The return value holds a reference to the current InputStream.
* When the return value is deleted, the current InputStream will be
* dereferenced. So make sure the current InputStream is not deleted
* manually before the return value is deleted. It's recommended that
* you use Object::ref() and Object::unref() instead of @c new and
* @c delete.
*/
virtual InputStream *createThreadSafe() throw();
};
}
#endif /* _OSL_INPUT_STREAM_H_ */
| {
"language": "C"
} |
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
ngx_chain_t *
ngx_writev_chain(ngx_connection_t *c, ngx_chain_t *in, off_t limit)
{
u_char *prev;
ssize_t n, size, sent;
off_t send, prev_send;
ngx_uint_t eintr;
ngx_err_t err;
ngx_array_t vec;
ngx_chain_t *cl;
ngx_event_t *wev;
struct iovec *iov, iovs[NGX_IOVS_PREALLOCATE];
wev = c->write;
if (!wev->ready) {
return in;
}
#if (NGX_HAVE_KQUEUE)
if ((ngx_event_flags & NGX_USE_KQUEUE_EVENT) && wev->pending_eof) {
(void) ngx_connection_error(c, wev->kq_errno,
"kevent() reported about an closed connection");
wev->error = 1;
return NGX_CHAIN_ERROR;
}
#endif
/* the maximum limit size is the maximum size_t value - the page size */
if (limit == 0 || limit > (off_t) (NGX_MAX_SIZE_T_VALUE - ngx_pagesize)) {
limit = NGX_MAX_SIZE_T_VALUE - ngx_pagesize;
}
send = 0;
vec.elts = iovs;
vec.size = sizeof(struct iovec);
vec.nalloc = NGX_IOVS_PREALLOCATE;
vec.pool = c->pool;
for ( ;; ) {
prev = NULL;
iov = NULL;
eintr = 0;
prev_send = send;
vec.nelts = 0;
/* create the iovec and coalesce the neighbouring bufs */
for (cl = in; cl && send < limit; cl = cl->next) {
if (ngx_buf_special(cl->buf)) {
continue;
}
#if 1
if (!ngx_buf_in_memory(cl->buf)) {
ngx_debug_point();
}
#endif
size = cl->buf->last - cl->buf->pos;
if (send + size > limit) {
size = (ssize_t) (limit - send);
}
if (prev == cl->buf->pos) {
iov->iov_len += size;
} else {
if (vec.nelts >= IOV_MAX) {
break;
}
iov = ngx_array_push(&vec);
if (iov == NULL) {
return NGX_CHAIN_ERROR;
}
iov->iov_base = (void *) cl->buf->pos;
iov->iov_len = size;
}
prev = cl->buf->pos + size;
send += size;
}
n = writev(c->fd, vec.elts, vec.nelts);
if (n == -1) {
err = ngx_errno;
switch (err) {
case NGX_EAGAIN:
break;
case NGX_EINTR:
eintr = 1;
break;
default:
wev->error = 1;
(void) ngx_connection_error(c, err, "writev() failed");
return NGX_CHAIN_ERROR;
}
ngx_log_debug0(NGX_LOG_DEBUG_EVENT, c->log, err,
"writev() not ready");
}
sent = n > 0 ? n : 0;
ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0, "writev: %z", sent);
c->sent += sent;
in = ngx_handle_sent_chain(in, sent);
if (eintr) {
send = prev_send;
continue;
}
if (send - prev_send != sent) {
wev->ready = 0;
return in;
}
if (send >= limit || in == NULL) {
return in;
}
}
}
| {
"language": "C"
} |
#ifndef MUSICTKPLCONFIGMANAGER_H
#define MUSICTKPLCONFIGMANAGER_H
/* =================================================
* This file is part of the TTK Music Player project
* Copyright (C) 2015 - 2020 Greedysky Studio
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; If not, see <http://www.gnu.org/licenses/>.
================================================= */
#include "musicabstractxml.h"
#include "musicplaylistinterface.h"
/*! @brief The class of the tkpl config manager.
* @author Greedysky <greedysky@163.com>
*/
class MUSIC_CORE_EXPORT MusicTKPLConfigManager : public MusicAbstractXml, public MusicPlaylistInterface
{
Q_OBJECT
TTK_DECLARE_MODULE(MusicTKPLConfigManager)
public:
/*!
* Object contsructor.
*/
explicit MusicTKPLConfigManager(QObject *parent = nullptr);
/*!
* Read config datas from xml file by given name.
*/
inline bool readConfig(const QString &name = MUSICPATH_FULL) { return MusicAbstractXml::readConfig(name); }
/*!
* Read datas from config file.
*/
virtual bool readPlaylistData(MusicSongItems &items) override;
/*!
* Write music datas into xml file.
*/
bool writePlaylistData(const MusicSongItems &items);
/*!
* Write datas into config file.
*/
virtual bool writePlaylistData(const MusicSongItems &items, const QString &path) override;
protected:
/*!
* Read Music File Path.
*/
MusicSongs readMusicFilePath(const QDomNode &node) const;
};
#endif // MUSICTKPLCONFIGMANAGER_H
| {
"language": "C"
} |