code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#ifndef _HAL_OTG_H_
#define _HAL_OTG_H_
#include "ameba_otg.h"
#include "dwc_otg_regs.h"
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usb_otg/include/hal_otg.h
|
C
|
apache-2.0
| 351
|
#ifndef _HCD_H_
#define _HCD_H_
struct hc_driver {
const char *description; /* "ehci-hcd" etc */
const char *product_desc; /* product/vendor string */
size_t hcd_priv_size; /* size of private data */
/* irq handler */
//irqreturn_t (*irq) (struct usb_hcd *hcd);
int flags;
#define HCD_MEMORY 0x0001 /* HC regs use memory (else I/O) */
#define HCD_LOCAL_MEM 0x0002 /* HC needs local memory */
#define HCD_SHARED 0x0004 /* Two (or more) usb_hcds share HW */
#define HCD_USB11 0x0010 /* USB 1.1 */
#define HCD_USB2 0x0020 /* USB 2.0 */
#define HCD_USB3 0x0040 /* USB 3.0 */
#define HCD_MASK 0x0070
/* called to init HCD and root hub */
int (*reset) (struct usb_hcd *hcd);
int (*start) (struct usb_hcd *hcd);
/* NOTE: these suspend/resume calls relate to the HC as
* a whole, not just the root hub; they're for PCI bus glue.
*/
/* called after suspending the hub, before entering D3 etc */
// int (*pci_suspend)(struct usb_hcd *hcd, bool do_wakeup);
/* called after entering D0 (etc), before resuming the hub */
// int (*pci_resume)(struct usb_hcd *hcd, bool hibernated);
/* cleanly make HCD stop writing memory and doing I/O */
void (*stop) (struct usb_hcd *hcd);
/* shutdown HCD */
// void (*shutdown) (struct usb_hcd *hcd);
/* return current frame number */
int (*get_frame_number) (struct usb_hcd *hcd);
/* manage i/o requests, device state */
int (*urb_enqueue)(struct usb_hcd *hcd,
struct urb *urb);//, gfp_t mem_flags);
int (*urb_dequeue)(struct usb_hcd *hcd,
struct urb *urb, int status);
/*
* (optional) these hooks allow an HCD to override the default DMA
* mapping and unmapping routines. In general, they shouldn't be
* necessary unless the host controller has special DMA requirements,
* such as alignment contraints. If these are not specified, the
* general usb_hcd_(un)?map_urb_for_dma functions will be used instead
* (and it may be a good idea to call these functions in your HCD
* implementation)
*/
#if 0
int (*map_urb_for_dma)(struct usb_hcd *hcd, struct urb *urb,
gfp_t mem_flags);
void (*unmap_urb_for_dma)(struct usb_hcd *hcd, struct urb *urb);
#endif
/* hw synch, freeing endpoint resources that urb_dequeue can't */
void (*endpoint_disable)(struct usb_hcd *hcd,
struct usb_host_endpoint *ep);
/* (optional) reset any endpoint state such as sequence number
and current window */
void (*endpoint_reset)(struct usb_hcd *hcd,
struct usb_host_endpoint *ep);
/* root hub support */
int (*hub_status_data) (struct usb_hcd *hcd, char *buf);
int (*hub_control) (struct usb_hcd *hcd,
u16 typeReq, u16 wValue, u16 wIndex,
char *buf, u16 wLength);
#if 0
int (*bus_suspend)(struct usb_hcd *);
int (*bus_resume)(struct usb_hcd *);
int (*start_port_reset)(struct usb_hcd *, unsigned port_num);
/* force handover of high-speed port to full-speed companion */
void (*relinquish_port)(struct usb_hcd *, int);
/* has a port been handed over to a companion? */
int (*port_handed_over)(struct usb_hcd *, int);
/* CLEAR_TT_BUFFER completion callback */
void (*clear_tt_buffer_complete)(struct usb_hcd *,
struct usb_host_endpoint *);
/* xHCI specific functions */
/* Called by usb_alloc_dev to alloc HC device structures */
int (*alloc_dev)(struct usb_hcd *, struct usb_device *);
/* Called by usb_disconnect to free HC device structures */
void (*free_dev)(struct usb_hcd *, struct usb_device *);
/* Change a group of bulk endpoints to support multiple stream IDs */
int (*alloc_streams)(struct usb_hcd *hcd, struct usb_device *udev,
struct usb_host_endpoint **eps, unsigned int num_eps,
unsigned int num_streams, gfp_t mem_flags);
/* Reverts a group of bulk endpoints back to not using stream IDs.
* Can fail if we run out of memory.
*/
int (*free_streams)(struct usb_hcd *hcd, struct usb_device *udev,
struct usb_host_endpoint **eps, unsigned int num_eps,
gfp_t mem_flags);
/* Bandwidth computation functions */
/* Note that add_endpoint() can only be called once per endpoint before
* check_bandwidth() or reset_bandwidth() must be called.
* drop_endpoint() can only be called once per endpoint also.
* A call to xhci_drop_endpoint() followed by a call to
* xhci_add_endpoint() will add the endpoint to the schedule with
* possibly new parameters denoted by a different endpoint descriptor
* in usb_host_endpoint. A call to xhci_add_endpoint() followed by a
* call to xhci_drop_endpoint() is not allowed.
*/
/* Allocate endpoint resources and add them to a new schedule */
int (*add_endpoint)(struct usb_hcd *, struct usb_device *,
struct usb_host_endpoint *);
/* Drop an endpoint from a new schedule */
int (*drop_endpoint)(struct usb_hcd *, struct usb_device *,
struct usb_host_endpoint *);
/* Check that a new hardware configuration, set using
* endpoint_enable and endpoint_disable, does not exceed bus
* bandwidth. This must be called before any set configuration
* or set interface requests are sent to the device.
*/
int (*check_bandwidth)(struct usb_hcd *, struct usb_device *);
/* Reset the device schedule to the last known good schedule,
* which was set from a previous successful call to
* check_bandwidth(). This reverts any add_endpoint() and
* drop_endpoint() calls since that last successful call.
* Used for when a check_bandwidth() call fails due to resource
* or bandwidth constraints.
*/
void (*reset_bandwidth)(struct usb_hcd *, struct usb_device *);
/* Returns the hardware-chosen device address */
int (*address_device)(struct usb_hcd *, struct usb_device *udev);
/* Notifies the HCD after a hub descriptor is fetched.
* Will block.
*/
int (*update_hub_device)(struct usb_hcd *, struct usb_device *hdev,
struct usb_tt *tt, gfp_t mem_flags);
int (*reset_device)(struct usb_hcd *, struct usb_device *);
/* Notifies the HCD after a device is connected and its
* address is set
*/
int (*update_device)(struct usb_hcd *, struct usb_device *);
int (*set_usb2_hw_lpm)(struct usb_hcd *, struct usb_device *, int);
/* USB 3.0 Link Power Management */
/* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
int (*enable_usb3_lpm_timeout)(struct usb_hcd *,
struct usb_device *, enum usb3_link_state state);
/* The xHCI host controller can still fail the command to
* disable the LPM timeouts, so this can return an error code.
*/
int (*disable_usb3_lpm_timeout)(struct usb_hcd *,
struct usb_device *, enum usb3_link_state state);
int (*find_raw_port_number)(struct usb_hcd *, int);
#endif
};
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usb_otg/include/hcd.h
|
C
|
apache-2.0
| 8,244
|
/*
* Copyright (c) 1998 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Lennart Augustsson (lennart@augustsson.net) at
* Carlstedt Research & Technology.
*
* 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 NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
/* Modified by Synopsys, Inc, 12/12/2007 */
#ifndef _USB_H_
#define _USB_H_
#include "basic_types.h"
#include "dwc_os.h"
#if defined(DWC_WITH_WLAN_OSDEP)
#include "osdep_service.h"
#else
#endif
#include "usb_errno.h"
#include "diag.h"
#include "usb_ch9.h"
#include "usb_defs.h"
//#define DWC_HOST_ONLY 1
//#define DWC_DEVICE_ONLY 1
#define USB_FAST_HUB_ENUM 1
#define prvStrLen _strlen
/*
* The USB records contain some unaligned little-endian word
* components. The U[SG]ETW macros take care of both the alignment
* and endian problem and should always be used to access non-byte
* values.
*/
typedef u8 uByte;
typedef u8 uWord[2];
typedef u8 uDWord[4];
struct LIST_HEADER {
struct LIST_HEADER *Next, *Prev;
};
typedef struct LIST_HEADER _LIST;
typedef xSemaphoreHandle _Sema;
typedef xSemaphoreHandle _Mutex;
typedef u32 _Lock;
#define USETW2(w,h,l) ((w)[0] = (u_int8_t)(l), (w)[1] = (u_int8_t)(h))
#define UCONSTW(x) { (x) & 0xff, ((x) >> 8) & 0xff }
#define UCONSTDW(x) { (x) & 0xff, ((x) >> 8) & 0xff, \
((x) >> 16) & 0xff, ((x) >> 24) & 0xff }
#if 1
#define UGETW(w) ((w)[0] | ((w)[1] << 8))
#define USETW(w,v) ((w)[0] = (u_int8_t)(v), (w)[1] = (u_int8_t)((v) >> 8))
#define UGETDW(w) ((w)[0] | ((w)[1] << 8) | ((w)[2] << 16) | ((w)[3] << 24))
#define USETDW(w,v) ((w)[0] = (u_int8_t)(v), \
(w)[1] = (u_int8_t)((v) >> 8), \
(w)[2] = (u_int8_t)((v) >> 16), \
(w)[3] = (u_int8_t)((v) >> 24))
#else
/*
* On little-endian machines that can handle unanliged accesses
* (e.g. i386) these macros can be replaced by the following.
*/
#define UGETW(w) (*(u_int16_t *)(w))
#define USETW(w,v) (*(u_int16_t *)(w) = (v))
#define UGETDW(w) (*(u_int32_t *)(w))
#define USETDW(w,v) (*(u_int32_t *)(w) = (v))
#endif
/*
* Macros for accessing UAS IU fields, which are big-endian
*/
#define IUSETW2(w,h,l) ((w)[0] = (u_int8_t)(h), (w)[1] = (u_int8_t)(l))
#define IUCONSTW(x) { ((x) >> 8) & 0xff, (x) & 0xff }
#define IUCONSTDW(x) { ((x) >> 24) & 0xff, ((x) >> 16) & 0xff, \
((x) >> 8) & 0xff, (x) & 0xff }
#define IUGETW(w) (((w)[0] << 8) | (w)[1])
#define IUSETW(w,v) ((w)[0] = (u_int8_t)((v) >> 8), (w)[1] = (u_int8_t)(v))
#define IUGETDW(w) (((w)[0] << 24) | ((w)[1] << 16) | ((w)[2] << 8) | (w)[3])
#define IUSETDW(w,v) ((w)[0] = (u_int8_t)((v) >> 24), \
(w)[1] = (u_int8_t)((v) >> 16), \
(w)[2] = (u_int8_t)((v) >> 8), \
(w)[3] = (u_int8_t)(v))
//#define UPACKED __attribute__((__packed__))
#define UPACKED
typedef struct {
uByte bmRequestType;
uByte bRequest;
uWord wValue;
uWord wIndex;
uWord wLength;
} UPACKED usb_device_request_t;
#define UT_GET_DIR(a) ((a) & 0x80)
#define UT_WRITE 0x00
#define UT_READ 0x80
#define UT_GET_TYPE(a) ((a) & 0x60)
#define UT_STANDARD 0x00
#define UT_CLASS 0x20
#define UT_VENDOR 0x40
#define UT_GET_RECIPIENT(a) ((a) & 0x1f)
#define UT_DEVICE 0x00
#define UT_INTERFACE 0x01
#define UT_ENDPOINT 0x02
#define UT_OTHER 0x03
#define UT_READ_DEVICE (UT_READ | UT_STANDARD | UT_DEVICE)
#define UT_READ_INTERFACE (UT_READ | UT_STANDARD | UT_INTERFACE)
#define UT_READ_ENDPOINT (UT_READ | UT_STANDARD | UT_ENDPOINT)
#define UT_WRITE_DEVICE (UT_WRITE | UT_STANDARD | UT_DEVICE)
#define UT_WRITE_INTERFACE (UT_WRITE | UT_STANDARD | UT_INTERFACE)
#define UT_WRITE_ENDPOINT (UT_WRITE | UT_STANDARD | UT_ENDPOINT)
#define UT_READ_CLASS_DEVICE (UT_READ | UT_CLASS | UT_DEVICE)
#define UT_READ_CLASS_INTERFACE (UT_READ | UT_CLASS | UT_INTERFACE)
#define UT_READ_CLASS_OTHER (UT_READ | UT_CLASS | UT_OTHER)
#define UT_READ_CLASS_ENDPOINT (UT_READ | UT_CLASS | UT_ENDPOINT)
#define UT_WRITE_CLASS_DEVICE (UT_WRITE | UT_CLASS | UT_DEVICE)
#define UT_WRITE_CLASS_INTERFACE (UT_WRITE | UT_CLASS | UT_INTERFACE)
#define UT_WRITE_CLASS_OTHER (UT_WRITE | UT_CLASS | UT_OTHER)
#define UT_WRITE_CLASS_ENDPOINT (UT_WRITE | UT_CLASS | UT_ENDPOINT)
#define UT_READ_VENDOR_DEVICE (UT_READ | UT_VENDOR | UT_DEVICE)
#define UT_READ_VENDOR_INTERFACE (UT_READ | UT_VENDOR | UT_INTERFACE)
#define UT_READ_VENDOR_OTHER (UT_READ | UT_VENDOR | UT_OTHER)
#define UT_READ_VENDOR_ENDPOINT (UT_READ | UT_VENDOR | UT_ENDPOINT)
#define UT_WRITE_VENDOR_DEVICE (UT_WRITE | UT_VENDOR | UT_DEVICE)
#define UT_WRITE_VENDOR_INTERFACE (UT_WRITE | UT_VENDOR | UT_INTERFACE)
#define UT_WRITE_VENDOR_OTHER (UT_WRITE | UT_VENDOR | UT_OTHER)
#define UT_WRITE_VENDOR_ENDPOINT (UT_WRITE | UT_VENDOR | UT_ENDPOINT)
/* Requests */
#define UR_GET_STATUS 0x00
#define USTAT_STANDARD_STATUS 0x00
#define WUSTAT_WUSB_FEATURE 0x01
#define WUSTAT_CHANNEL_INFO 0x02
#define WUSTAT_RECEIVED_DATA 0x03
#define WUSTAT_MAS_AVAILABILITY 0x04
#define WUSTAT_CURRENT_TRANSMIT_POWER 0x05
#define UR_CLEAR_FEATURE 0x01
#define UR_SET_FEATURE 0x03
#define UR_SET_AND_TEST_FEATURE 0x0c
#define UR_SET_ADDRESS 0x05
#define UR_GET_DESCRIPTOR 0x06
#define UDESC_DEVICE 0x01
#define UDESC_CONFIG 0x02
#define UDESC_STRING 0x03
#define UDESC_INTERFACE 0x04
#define UDESC_ENDPOINT 0x05
#define UDESC_SS_USB_COMPANION 0x30
#define UDESC_DEVICE_QUALIFIER 0x06
#define UDESC_OTHER_SPEED_CONFIGURATION 0x07
#define UDESC_INTERFACE_POWER 0x08
#define UDESC_OTG 0x09
#define WUDESC_SECURITY 0x0c
#define WUDESC_KEY 0x0d
#define WUD_GET_KEY_INDEX(_wValue_) ((_wValue_) & 0xf)
#define WUD_GET_KEY_TYPE(_wValue_) (((_wValue_) & 0x30) >> 4)
#define WUD_KEY_TYPE_ASSOC 0x01
#define WUD_KEY_TYPE_GTK 0x02
#define WUD_GET_KEY_ORIGIN(_wValue_) (((_wValue_) & 0x40) >> 6)
#define WUD_KEY_ORIGIN_HOST 0x00
#define WUD_KEY_ORIGIN_DEVICE 0x01
#define WUDESC_ENCRYPTION_TYPE 0x0e
#define WUDESC_BOS 0x0f
#define WUDESC_DEVICE_CAPABILITY 0x10
#define WUDESC_WIRELESS_ENDPOINT_COMPANION 0x11
#define UDESC_BOS 0x0f
#define UDESC_DEVICE_CAPABILITY 0x10
#define UDESC_CS_DEVICE 0x21 /* class specific */
#define UDESC_CS_CONFIG 0x22
#define UDESC_CS_STRING 0x23
#define UDESC_CS_INTERFACE 0x24
#define UDESC_CS_ENDPOINT 0x25
#define UDESC_HUB 0x29
#define UR_SET_DESCRIPTOR 0x07
#define UR_GET_CONFIG 0x08
#define UR_SET_CONFIG 0x09
#define UR_GET_INTERFACE 0x0a
#define UR_SET_INTERFACE 0x0b
#define UR_SYNCH_FRAME 0x0c
#define WUR_SET_ENCRYPTION 0x0d
#define WUR_GET_ENCRYPTION 0x0e
#define WUR_SET_HANDSHAKE 0x0f
#define WUR_GET_HANDSHAKE 0x10
#define WUR_SET_CONNECTION 0x11
#define WUR_SET_SECURITY_DATA 0x12
#define WUR_GET_SECURITY_DATA 0x13
#define WUR_SET_WUSB_DATA 0x14
#define WUDATA_DRPIE_INFO 0x01
#define WUDATA_TRANSMIT_DATA 0x02
#define WUDATA_TRANSMIT_PARAMS 0x03
#define WUDATA_RECEIVE_PARAMS 0x04
#define WUDATA_TRANSMIT_POWER 0x05
#define WUR_LOOPBACK_DATA_WRITE 0x15
#define WUR_LOOPBACK_DATA_READ 0x16
#define WUR_SET_INTERFACE_DS 0x17
/* Feature numbers */
#define UF_ENDPOINT_HALT 0
#define UF_DEVICE_REMOTE_WAKEUP 1
#define UF_TEST_MODE 2
#define UF_DEVICE_B_HNP_ENABLE 3
#define UF_DEVICE_A_HNP_SUPPORT 4
#define UF_DEVICE_A_ALT_HNP_SUPPORT 5
#define WUF_WUSB 3
#define WUF_TX_DRPIE 0x0
#define WUF_DEV_XMIT_PACKET 0x1
#define WUF_COUNT_PACKETS 0x2
#define WUF_CAPTURE_PACKETS 0x3
#define UF_FUNCTION_SUSPEND 0
#define UF_U1_ENABLE 48
#define UF_U2_ENABLE 49
#define UF_LTM_ENABLE 50
/* Class requests from the USB 2.0 hub spec, table 11-15 */
#define UCR_CLEAR_HUB_FEATURE (0x2000 | UR_CLEAR_FEATURE)
#define UCR_CLEAR_PORT_FEATURE (0x2300 | UR_CLEAR_FEATURE)
#define UCR_GET_HUB_DESCRIPTOR (0xa000 | UR_GET_DESCRIPTOR)
#define UCR_GET_HUB_STATUS (0xa000 | UR_GET_STATUS)
#define UCR_GET_PORT_STATUS (0xa300 | UR_GET_STATUS)
#define UCR_SET_HUB_FEATURE (0x2000 | UR_SET_FEATURE)
#define UCR_SET_PORT_FEATURE (0x2300 | UR_SET_FEATURE)
#define UCR_SET_AND_TEST_PORT_FEATURE (0xa300 | UR_SET_AND_TEST_FEATURE)
#define USB_MAX_STRING_LEN 128
#define USB_LANGUAGE_TABLE 0 /* # of the string language id table */
/* Hub specific request */
#define UR_GET_BUS_STATE 0x02
#define UR_CLEAR_TT_BUFFER 0x08
#define UR_RESET_TT 0x09
#define UR_GET_TT_STATE 0x0a
#define UR_STOP_TT 0x0b
/* Hub features */
#define UHF_C_HUB_LOCAL_POWER 0
#define UHF_C_HUB_OVER_CURRENT 1
#define UHF_PORT_CONNECTION 0
#define UHF_PORT_ENABLE 1
#define UHF_PORT_SUSPEND 2
#define UHF_PORT_OVER_CURRENT 3
#define UHF_PORT_RESET 4
#define UHF_PORT_L1 5
#define UHF_PORT_POWER 8
#define UHF_PORT_LOW_SPEED 9
#define UHF_PORT_HIGH_SPEED 10
#define UHF_C_PORT_CONNECTION 16
#define UHF_C_PORT_ENABLE 17
#define UHF_C_PORT_SUSPEND 18
#define UHF_C_PORT_OVER_CURRENT 19
#define UHF_C_PORT_RESET 20
#define UHF_C_PORT_L1 23
#define UHF_PORT_TEST 21
#define UHF_PORT_INDICATOR 22
typedef struct {
uByte bLength;
uByte bDescriptorType;
uWord bcdUSB;
uByte bDeviceClass;
uByte bDeviceSubClass;
uByte bDeviceProtocol;
uByte bMaxPacketSize0;
uByte bNumConfigurations;
uByte bReserved;
} UPACKED usb_device_qualifier_t;
#define USB_DEVICE_QUALIFIER_SIZE 10
typedef struct {
uByte bLength;
uByte bDescriptorType;
uByte bmAttributes;
#define UOTG_SRP 0x01
#define UOTG_HNP 0x02
} UPACKED usb_otg_descriptor_t;
/* OTG feature selectors */
#define UOTG_B_HNP_ENABLE 3
#define UOTG_A_HNP_SUPPORT 4
#define UOTG_A_ALT_HNP_SUPPORT 5
typedef struct {
uWord wStatus;
/* Device status flags */
#define UDS_SELF_POWERED 0x0001
#define UDS_REMOTE_WAKEUP 0x0002
/* Endpoint status flags */
#define UES_HALT 0x0001
} UPACKED usb_status_t;
typedef struct {
uWord wHubStatus;
#define UHS_LOCAL_POWER 0x0001
#define UHS_OVER_CURRENT 0x0002
uWord wHubChange;
} UPACKED usb_hub_status_t;
typedef struct {
uWord wPortStatus;
#define UPS_CURRENT_CONNECT_STATUS 0x0001
#define UPS_PORT_ENABLED 0x0002
#define UPS_SUSPEND 0x0004
#define UPS_OVERCURRENT_INDICATOR 0x0008
#define UPS_RESET 0x0010
#define UPS_PORT_POWER 0x0100
#define UPS_LOW_SPEED 0x0200
#define UPS_HIGH_SPEED 0x0400
#define UPS_PORT_TEST 0x0800
#define UPS_PORT_INDICATOR 0x1000
uWord wPortChange;
#define UPS_C_CONNECT_STATUS 0x0001
#define UPS_C_PORT_ENABLED 0x0002
#define UPS_C_SUSPEND 0x0004
#define UPS_C_OVERCURRENT_INDICATOR 0x0008
#define UPS_C_PORT_RESET 0x0010
} UPACKED usb_port_status_t;
/* Device class codes */
#define UDCLASS_IN_INTERFACE 0x00
#define UDCLASS_COMM 0x02
#define UDCLASS_HUB 0x09
#define UDSUBCLASS_HUB 0x00
#define UDPROTO_FSHUB 0x00
#define UDPROTO_HSHUBSTT 0x01
#define UDPROTO_HSHUBMTT 0x02
#define UDCLASS_DIAGNOSTIC 0xdc
#define UDCLASS_WIRELESS 0xe0
#define UDSUBCLASS_RF 0x01
#define UDPROTO_BLUETOOTH 0x01
#define UDCLASS_VENDOR 0xff
/* Interface class codes */
#define UICLASS_UNSPEC 0x00
#define UICLASS_AUDIO 0x01
#define UISUBCLASS_AUDIOCONTROL 1
#define UISUBCLASS_AUDIOSTREAM 2
#define UISUBCLASS_MIDISTREAM 3
#define UICLASS_CDC 0x02 /* communication */
#define UISUBCLASS_DIRECT_LINE_CONTROL_MODEL 1
#define UISUBCLASS_ABSTRACT_CONTROL_MODEL 2
#define UISUBCLASS_TELEPHONE_CONTROL_MODEL 3
#define UISUBCLASS_MULTICHANNEL_CONTROL_MODEL 4
#define UISUBCLASS_CAPI_CONTROLMODEL 5
#define UISUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL 6
#define UISUBCLASS_ATM_NETWORKING_CONTROL_MODEL 7
#define UIPROTO_CDC_AT 1
#define UICLASS_HID 0x03
#define UISUBCLASS_BOOT 1
#define UIPROTO_BOOT_KEYBOARD 1
#define UICLASS_PHYSICAL 0x05
#define UICLASS_IMAGE 0x06
#define UICLASS_PRINTER 0x07
#define UISUBCLASS_PRINTER 1
#define UIPROTO_PRINTER_UNI 1
#define UIPROTO_PRINTER_BI 2
#define UIPROTO_PRINTER_1284 3
#define UICLASS_MASS 0x08
#define UISUBCLASS_RBC 1
#define UISUBCLASS_SFF8020I 2
#define UISUBCLASS_QIC157 3
#define UISUBCLASS_UFI 4
#define UISUBCLASS_SFF8070I 5
#define UISUBCLASS_SCSI 6
#define UIPROTO_MASS_CBI_I 0
#define UIPROTO_MASS_CBI 1
#define UIPROTO_MASS_BBB_OLD 2 /* Not in the spec anymore */
#define UIPROTO_MASS_BBB 80 /* 'P' for the Iomega Zip drive */
#define UICLASS_HUB 0x09
#define UISUBCLASS_HUB 0
#define UIPROTO_FSHUB 0
#define UIPROTO_HSHUBSTT 0 /* Yes, same as previous */
#define UIPROTO_HSHUBMTT 1
#define UICLASS_CDC_DATA 0x0a
#define UISUBCLASS_DATA 0
#define UIPROTO_DATA_ISDNBRI 0x30 /* Physical iface */
#define UIPROTO_DATA_HDLC 0x31 /* HDLC */
#define UIPROTO_DATA_TRANSPARENT 0x32 /* Transparent */
#define UIPROTO_DATA_Q921M 0x50 /* Management for Q921 */
#define UIPROTO_DATA_Q921 0x51 /* Data for Q921 */
#define UIPROTO_DATA_Q921TM 0x52 /* TEI multiplexer for Q921 */
#define UIPROTO_DATA_V42BIS 0x90 /* Data compression */
#define UIPROTO_DATA_Q931 0x91 /* Euro-ISDN */
#define UIPROTO_DATA_V120 0x92 /* V.24 rate adaption */
#define UIPROTO_DATA_CAPI 0x93 /* CAPI 2.0 commands */
#define UIPROTO_DATA_HOST_BASED 0xfd /* Host based driver */
#define UIPROTO_DATA_PUF 0xfe /* see Prot. Unit Func. Desc.*/
#define UIPROTO_DATA_VENDOR 0xff /* Vendor specific */
#define UICLASS_SMARTCARD 0x0b
/*#define UICLASS_FIRM_UPD 0x0c*/
#define UICLASS_SECURITY 0x0d
#define UICLASS_DIAGNOSTIC 0xdc
#define UICLASS_WIRELESS 0xe0
#define UISUBCLASS_RF 0x01
#define UIPROTO_BLUETOOTH 0x01
#define UICLASS_APPL_SPEC 0xfe
#define UISUBCLASS_FIRMWARE_DOWNLOAD 1
#define UISUBCLASS_IRDA 2
#define UIPROTO_IRDA 0
#define UICLASS_VENDOR 0xff
#define USB_HUB_MAX_DEPTH 5
/*
* Minimum time a device needs to be powered down to go through
* a power cycle. XXX Are these time in the spec?
*/
#define USB_POWER_DOWN_TIME 200 /* ms */
#define USB_PORT_POWER_DOWN_TIME 100 /* ms */
#if 0
/* These are the values from the spec. */
#define USB_PORT_RESET_DELAY 10 /* ms */
#define USB_PORT_ROOT_RESET_DELAY 50 /* ms */
#define USB_PORT_RESET_RECOVERY 10 /* ms */
#define USB_PORT_POWERUP_DELAY 100 /* ms */
#define USB_SET_ADDRESS_SETTLE 2 /* ms */
#define USB_RESUME_DELAY (20*5) /* ms */
#define USB_RESUME_WAIT 10 /* ms */
#define USB_RESUME_RECOVERY 10 /* ms */
#define USB_EXTRA_POWER_UP_TIME 0 /* ms */
#else
/* Allow for marginal (i.e. non-conforming) devices. */
#define USB_PORT_RESET_DELAY 50 /* ms */
#define USB_PORT_ROOT_RESET_DELAY 250 /* ms */
#define USB_PORT_RESET_RECOVERY 250 /* ms */
#define USB_PORT_POWERUP_DELAY 300 /* ms */
#define USB_SET_ADDRESS_SETTLE 10 /* ms */
#define USB_RESUME_DELAY (50*5) /* ms */
#define USB_RESUME_WAIT 50 /* ms */
#define USB_RESUME_RECOVERY 50 /* ms */
#define USB_EXTRA_POWER_UP_TIME 20 /* ms */
#endif
#define USB_MIN_POWER 100 /* mA */
#define USB_MAX_POWER 500 /* mA */
#define USB_BUS_RESET_DELAY 100 /* ms XXX?*/
#define USB_UNCONFIG_NO 0
#define USB_UNCONFIG_INDEX (-1)
/*** ioctl() related stuff ***/
struct usb_ctl_request {
int ucr_addr;
usb_device_request_t ucr_request;
void *ucr_data;
int ucr_flags;
#define USBD_SHORT_XFER_OK 0x04 /* allow short reads */
int ucr_actlen; /* actual length transferred */
};
struct usb_alt_interface {
int uai_config_index;
int uai_interface_index;
int uai_alt_no;
};
#define USB_CURRENT_CONFIG_INDEX (-1)
#define USB_CURRENT_ALT_INDEX (-1)
struct usb_full_desc {
int ufd_config_index;
u16 ufd_size;
u8 *ufd_data;
};
struct usb_ctl_report_desc {
int ucrd_size;
u8 ucrd_data[1024]; /* filled data size will vary */
};
typedef struct { u32 cookie; } usb_event_cookie_t;
#define USB_MAX_DEVNAMES 4
#define USB_MAX_DEVNAMELEN 16
struct usb_device_info {
u8 udi_bus;
u8 udi_addr; /* device address */
usb_event_cookie_t udi_cookie;
char udi_product[USB_MAX_STRING_LEN];
char udi_vendor[USB_MAX_STRING_LEN];
char udi_release[8];
u16 udi_productNo;
u16 udi_vendorNo;
u16 udi_releaseNo;
u8 udi_class;
u8 udi_subclass;
u8 udi_protocol;
u8 udi_config;
u8 udi_speed;
#if 0
#define USB_SPEED_UNKNOWN 0
#define USB_SPEED_LOW 1
#define USB_SPEED_FULL 2
#define USB_SPEED_HIGH 3
#define USB_SPEED_VARIABLE 4
#define USB_SPEED_SUPER 5
#endif
int udi_power; /* power consumption in mA, 0 if selfpowered */
int udi_nports;
char udi_devnames[USB_MAX_DEVNAMES][USB_MAX_DEVNAMELEN];
u8 udi_ports[16];/* hub only: addresses of devices on ports */
#define USB_PORT_ENABLED 0xff
#define USB_PORT_SUSPENDED 0xfe
#define USB_PORT_POWERED 0xfd
#define USB_PORT_DISABLED 0xfc
};
struct usb_ctl_report {
int ucr_report;
u8 ucr_data[1024]; /* filled data size will vary */
};
struct usb_device_stats {
u32 uds_requests[4]; /* indexed by transfer type UE_* */
};
#define WUSB_MIN_IE 0x80
#define WUSB_WCTA_IE 0x80
#define WUSB_WCONNECTACK_IE 0x81
#define WUSB_WHOSTINFO_IE 0x82
#define WUHI_GET_CA(_bmAttributes_) ((_bmAttributes_) & 0x3)
#define WUHI_CA_RECONN 0x00
#define WUHI_CA_LIMITED 0x01
#define WUHI_CA_ALL 0x03
#define WUHI_GET_MLSI(_bmAttributes_) (((_bmAttributes_) & 0x38) >> 3)
#define WUSB_WCHCHANGEANNOUNCE_IE 0x83
#define WUSB_WDEV_DISCONNECT_IE 0x84
#define WUSB_WHOST_DISCONNECT_IE 0x85
#define WUSB_WRELEASE_CHANNEL_IE 0x86
#define WUSB_WWORK_IE 0x87
#define WUSB_WCHANNEL_STOP_IE 0x88
#define WUSB_WDEV_KEEPALIVE_IE 0x89
#define WUSB_WISOCH_DISCARD_IE 0x8A
#define WUSB_WRESETDEVICE_IE 0x8B
#define WUSB_WXMIT_PACKET_ADJUST_IE 0x8C
#define WUSB_MAX_IE 0x8C
/* Device Notification Types */
#define WUSB_DN_MIN 0x01
#define WUSB_DN_CONNECT 0x01
# define WUSB_DA_OLDCONN 0x00
# define WUSB_DA_NEWCONN 0x01
# define WUSB_DA_SELF_BEACON 0x02
# define WUSB_DA_DIR_BEACON 0x04
# define WUSB_DA_NO_BEACON 0x06
#define WUSB_DN_DISCONNECT 0x02
#define WUSB_DN_EPRDY 0x03
#define WUSB_DN_MASAVAILCHANGED 0x04
#define WUSB_DN_REMOTEWAKEUP 0x05
#define WUSB_DN_SLEEP 0x06
#define WUSB_DN_ALIVE 0x07
#define WUSB_DN_MAX 0x07
/* WUSB Handshake Data. Used during the SET/GET HANDSHAKE requests */
typedef struct wusb_hndshk_data {
uByte bMessageNumber;
uByte bStatus;
uByte tTKID[3];
uByte bReserved;
uByte CDID[16];
uByte Nonce[16];
uByte MIC[8];
} UPACKED wusb_hndshk_data_t;
#define WUSB_HANDSHAKE_LEN_FOR_MIC 38
/* WUSB Connection Context */
typedef struct wusb_conn_context {
uByte CHID [16];
uByte CDID [16];
uByte CK [16];
} UPACKED wusb_conn_context_t;
/* WUSB Security Descriptor */
typedef struct wusb_security_desc {
uByte bLength;
uByte bDescriptorType;
uWord wTotalLength;
uByte bNumEncryptionTypes;
} UPACKED wusb_security_desc_t;
/* WUSB Encryption Type Descriptor */
typedef struct wusb_encrypt_type_desc {
uByte bLength;
uByte bDescriptorType;
uByte bEncryptionType;
#define WUETD_UNSECURE 0
#define WUETD_WIRED 1
#define WUETD_CCM_1 2
#define WUETD_RSA_1 3
uByte bEncryptionValue;
uByte bAuthKeyIndex;
} UPACKED wusb_encrypt_type_desc_t;
/* WUSB Key Descriptor */
typedef struct wusb_key_desc {
uByte bLength;
uByte bDescriptorType;
uByte tTKID[3];
uByte bReserved;
uByte KeyData[1]; /* variable length */
} UPACKED wusb_key_desc_t;
/* WUSB BOS Descriptor (Binary device Object Store) */
typedef struct wusb_bos_desc {
uByte bLength;
uByte bDescriptorType;
uWord wTotalLength;
uByte bNumDeviceCaps;
} UPACKED wusb_bos_desc_t;
#define USB_DEVICE_CAPABILITY_20_EXTENSION 0x02
typedef struct usb_dev_cap_20_ext_desc {
uByte bLength;
uByte bDescriptorType;
uByte bDevCapabilityType;
#define USB_20_EXT_LPM 0x02
uDWord bmAttributes;
} UPACKED usb_dev_cap_20_ext_desc_t;
#define USB_DEVICE_CAPABILITY_SS_USB 0x03
typedef struct usb_dev_cap_ss_usb {
uByte bLength;
uByte bDescriptorType;
uByte bDevCapabilityType;
#define USB_DC_SS_USB_LTM_CAPABLE 0x02
uByte bmAttributes;
#define USB_DC_SS_USB_SPEED_SUPPORT_LOW 0x01
#define USB_DC_SS_USB_SPEED_SUPPORT_FULL 0x02
#define USB_DC_SS_USB_SPEED_SUPPORT_HIGH 0x04
#define USB_DC_SS_USB_SPEED_SUPPORT_SS 0x08
uWord wSpeedsSupported;
uByte bFunctionalitySupport;
uByte bU1DevExitLat;
uWord wU2DevExitLat;
} UPACKED usb_dev_cap_ss_usb_t;
#define USB_DEVICE_CAPABILITY_CONTAINER_ID 0x04
typedef struct usb_dev_cap_container_id {
uByte bLength;
uByte bDescriptorType;
uByte bDevCapabilityType;
uByte bReserved;
uByte containerID[16];
} UPACKED usb_dev_cap_container_id_t;
/* Device Capability Type Codes */
#define WUSB_DEVICE_CAPABILITY_WIRELESS_USB 0x01
/* Device Capability Descriptor */
typedef struct wusb_dev_cap_desc {
uByte bLength;
uByte bDescriptorType;
uByte bDevCapabilityType;
uByte caps[1]; /* Variable length */
} UPACKED wusb_dev_cap_desc_t;
/* Device Capability Descriptor */
typedef struct wusb_dev_cap_uwb_desc {
uByte bLength;
uByte bDescriptorType;
uByte bDevCapabilityType;
uByte bmAttributes;
uWord wPHYRates; /* Bitmap */
uByte bmTFITXPowerInfo;
uByte bmFFITXPowerInfo;
uWord bmBandGroup;
uByte bReserved;
} UPACKED wusb_dev_cap_uwb_desc_t;
/* Wireless USB Endpoint Companion Descriptor */
typedef struct wusb_endpoint_companion_desc {
uByte bLength;
uByte bDescriptorType;
uByte bMaxBurst;
uByte bMaxSequence;
uWord wMaxStreamDelay;
uWord wOverTheAirPacketSize;
uByte bOverTheAirInterval;
uByte bmCompAttributes;
} UPACKED wusb_endpoint_companion_desc_t;
/* Wireless USB Numeric Association M1 Data Structure */
typedef struct wusb_m1_data {
uByte version;
uWord langId;
uByte deviceFriendlyNameLength;
uByte sha_256_m3[32];
uByte deviceFriendlyName[256];
} UPACKED wusb_m1_data_t;
typedef struct wusb_m2_data {
uByte version;
uWord langId;
uByte hostFriendlyNameLength;
uByte pkh[384];
uByte hostFriendlyName[256];
} UPACKED wusb_m2_data_t;
typedef struct wusb_m3_data {
uByte pkd[384];
uByte nd;
} UPACKED wusb_m3_data_t;
typedef struct wusb_m4_data {
uDWord _attributeTypeIdAndLength_1;
uWord associationTypeId;
uDWord _attributeTypeIdAndLength_2;
uWord associationSubTypeId;
uDWord _attributeTypeIdAndLength_3;
uDWord length;
uDWord _attributeTypeIdAndLength_4;
uDWord associationStatus;
uDWord _attributeTypeIdAndLength_5;
uByte chid[16];
uDWord _attributeTypeIdAndLength_6;
uByte cdid[16];
uDWord _attributeTypeIdAndLength_7;
uByte bandGroups[2];
} UPACKED wusb_m4_data_t;
/* Original Host */
/* USB directions */
#define USB_DIR_OUT 0
#define USB_DIR_IN 0x80
/* Endpoints */
#define USB_ENDPOINT_NUMBER_MASK 0x0f /* in bEndpointAddress */
#define USB_ENDPOINT_DIR_MASK 0x80
#define USB_ENDPOINT_XFERTYPE_MASK 0x03 /* in bmAttributes */
#define USB_ENDPOINT_XFER_CONTROL 0
#define USB_ENDPOINT_XFER_ISOC 1
#define USB_ENDPOINT_XFER_BULK 2
#define USB_ENDPOINT_XFER_INT 3
#define USB_ENDPOINT_HALT 0 /* IN/OUT will STALL */
#if 1
#define UGETW(w) ((w)[0] | ((w)[1] << 8))
#define USETW(w,v) ((w)[0] = (u_int8_t)(v), (w)[1] = (u_int8_t)((v) >> 8))
#define UGETDW(w) ((w)[0] | ((w)[1] << 8) | ((w)[2] << 16) | ((w)[3] << 24))
#define USETDW(w,v) ((w)[0] = (u_int8_t)(v), \
(w)[1] = (u_int8_t)((v) >> 8), \
(w)[2] = (u_int8_t)((v) >> 16), \
(w)[3] = (u_int8_t)((v) >> 24))
#else
/*
* On little-endian machines that can handle unanliged accesses
* (e.g. i386) these macros can be replaced by the following.
*/
#define UGETW(w) (*(u_int16_t *)(w))
#define USETW(w,v) (*(u_int16_t *)(w) = (v))
#define UGETDW(w) (*(u_int32_t *)(w))
#define USETDW(w,v) (*(u_int32_t *)(w) = (v))
#endif
//#define UPACKED __attribute__((__packed__))
/* Everything is aribtrary */
#define USB_ALTSETTINGALLOC 4
#define USB_MAXALTSETTING 128 /* Hard limit */
#define USB_MAX_DEVICE 2 // at least 2: 1 for the root hub device, 1 for usb device
#define USB_MAXCONFIG 8
#define USB_MAXINTERFACES 8
#define USB_MAXENDPOINTS 16
#define USB_MAXCHILDREN 8 /* This is arbitrary */
#define USB_MAX_HUB 2
#define USB_MAXIADS (USB_MAXINTERFACES/2)
#define USB_CNTL_TIMEOUT 5000 /* 100ms timeout */
/* Requests */
#define UR_GET_STATUS 0x00
#define USTAT_STANDARD_STATUS 0x00
#define WUSTAT_WUSB_FEATURE 0x01
#define WUSTAT_CHANNEL_INFO 0x02
#define WUSTAT_RECEIVED_DATA 0x03
#define WUSTAT_MAS_AVAILABILITY 0x04
#define WUSTAT_CURRENT_TRANSMIT_POWER 0x05
#define UR_CLEAR_FEATURE 0x01
#define UR_SET_FEATURE 0x03
#define UR_SET_AND_TEST_FEATURE 0x0c
#define UR_SET_ADDRESS 0x05
#define UR_GET_DESCRIPTOR 0x06
#define UDESC_DEVICE 0x01
#define UDESC_CONFIG 0x02
#define UDESC_STRING 0x03
#define UDESC_INTERFACE 0x04
#define UDESC_ENDPOINT 0x05
#define UDESC_SS_USB_COMPANION 0x30
#define UDESC_DEVICE_QUALIFIER 0x06
#define UDESC_OTHER_SPEED_CONFIGURATION 0x07
#define UDESC_INTERFACE_POWER 0x08
#define UDESC_OTG 0x09
#define WUDESC_SECURITY 0x0c
#define WUDESC_KEY 0x0d
#define WUD_GET_KEY_INDEX(_wValue_) ((_wValue_) & 0xf)
#define WUD_GET_KEY_TYPE(_wValue_) (((_wValue_) & 0x30) >> 4)
#define WUD_KEY_TYPE_ASSOC 0x01
#define WUD_KEY_TYPE_GTK 0x02
#define WUD_GET_KEY_ORIGIN(_wValue_) (((_wValue_) & 0x40) >> 6)
#define WUD_KEY_ORIGIN_HOST 0x00
#define WUD_KEY_ORIGIN_DEVICE 0x01
#define WUDESC_ENCRYPTION_TYPE 0x0e
#define WUDESC_BOS 0x0f
#define WUDESC_DEVICE_CAPABILITY 0x10
#define WUDESC_WIRELESS_ENDPOINT_COMPANION 0x11
#define UDESC_BOS 0x0f
#define UDESC_DEVICE_CAPABILITY 0x10
#define UDESC_CS_DEVICE 0x21 /* class specific */
#define UDESC_CS_CONFIG 0x22
#define UDESC_CS_STRING 0x23
#define UDESC_CS_INTERFACE 0x24
#define UDESC_CS_ENDPOINT 0x25
#define UDESC_HUB 0x29
#define UR_SET_DESCRIPTOR 0x07
#define UR_GET_CONFIG 0x08
#define UR_SET_CONFIG 0x09
#define UR_GET_INTERFACE 0x0a
#define UR_SET_INTERFACE 0x0b
#define UR_SYNCH_FRAME 0x0c
#define WUR_SET_ENCRYPTION 0x0d
#define WUR_GET_ENCRYPTION 0x0e
#define WUR_SET_HANDSHAKE 0x0f
#define WUR_GET_HANDSHAKE 0x10
#define WUR_SET_CONNECTION 0x11
#define WUR_SET_SECURITY_DATA 0x12
#define WUR_GET_SECURITY_DATA 0x13
#define WUR_SET_WUSB_DATA 0x14
#define WUDATA_DRPIE_INFO 0x01
#define WUDATA_TRANSMIT_DATA 0x02
#define WUDATA_TRANSMIT_PARAMS 0x03
#define WUDATA_RECEIVE_PARAMS 0x04
#define WUDATA_TRANSMIT_POWER 0x05
#define WUR_LOOPBACK_DATA_WRITE 0x15
#define WUR_LOOPBACK_DATA_READ 0x16
#define WUR_SET_INTERFACE_DS 0x17
/* Hub features */
#define UHF_C_HUB_LOCAL_POWER 0
#define UHF_C_HUB_OVER_CURRENT 1
#define UHF_PORT_CONNECTION 0
#define UHF_PORT_ENABLE 1
#define UHF_PORT_SUSPEND 2
#define UHF_PORT_OVER_CURRENT 3
#define UHF_PORT_RESET 4
#define UHF_PORT_L1 5
#define UHF_PORT_POWER 8
#define UHF_PORT_LOW_SPEED 9
#define UHF_PORT_HIGH_SPEED 10
#define UHF_C_PORT_CONNECTION 16
#define UHF_C_PORT_ENABLE 17
#define UHF_C_PORT_SUSPEND 18
#define UHF_C_PORT_OVER_CURRENT 19
#define UHF_C_PORT_RESET 20
#define UHF_C_PORT_L1 23
#define UHF_PORT_TEST 21
#define UHF_PORT_INDICATOR 22
typedef struct {
uByte bLength;
uByte bDescriptorType;
uByte bDescriptorSubtype;
} UPACKED usb_descriptor_t;
typedef struct {
uByte bLength;
uByte bDescriptorType;
} UPACKED usb_descriptor_header_t;
typedef struct {
uByte bLength;
uByte bDescriptorType;
uWord bcdUSB;
#define UD_USB_2_0 0x0200
#define UD_IS_USB2(d) (UGETW((d)->bcdUSB) >= UD_USB_2_0)
uByte bDeviceClass;
uByte bDeviceSubClass;
uByte bDeviceProtocol;
uByte bMaxPacketSize;
/* The fields below are not part of the initial descriptor. */
uWord idVendor;
uWord idProduct;
uWord bcdDevice;
uByte iManufacturer;
uByte iProduct;
uByte iSerialNumber;
uByte bNumConfigurations;
} UPACKED usb_device_descriptor_t;
typedef struct {
uByte bLength;
uByte bDescriptorType;
uWord wTotalLength;
uByte bNumInterface;
uByte bConfigurationValue;
uByte iConfiguration;
#define UC_ATT_ONE (1 << 7) /* must be set */
#define UC_ATT_SELFPOWER (1 << 6) /* self powered */
#define UC_ATT_WAKEUP (1 << 5) /* can wakeup */
#define UC_ATT_BATTERY (1 << 4) /* battery powered */
uByte bmAttributes;
#define UC_BUS_POWERED 0x80
#define UC_SELF_POWERED 0x40
#define UC_REMOTE_WAKEUP 0x20
uByte bMaxPower; /* max current in 2 mA units */
#define UC_POWER_FACTOR 2
} UPACKED usb_config_descriptor_t;
#define USB_CONFIG_DESCRIPTOR_SIZE 9
typedef struct {
uByte bLength;
uByte bDescriptorType;
uByte bInterfaceNumber;
uByte bAlternateSetting;
uByte bNumEndpoints;
uByte bInterfaceClass;
uByte bInterfaceSubClass;
uByte bInterfaceProtocol;
uByte iInterface;
} UPACKED usb_interface_descriptor_t;
#define USB_INTERFACE_DESCRIPTOR_SIZE 9
/* String descriptor */
/* device request (setup) */
struct devrequest {
unsigned char requesttype;
unsigned char request;
unsigned short value;
unsigned short index;
unsigned short length;
} UPACKED;
/* All standard descriptors have these 2 fields in common */
/* Device descriptor */
/* Endpoint descriptor */
/* Interface descriptor */
/* Configuration descriptor information.. */
/* USB_DT_INTERFACE_ASSOCIATION: groups interfaces */
enum {
/* Maximum packet size; encoded as 0,1,2,3 = 8,16,32,64 */
PACKET_SIZE_8 = 0,
PACKET_SIZE_16 = 1,
PACKET_SIZE_32 = 2,
PACKET_SIZE_64 = 3,
};
struct usb_host_endpoint {
struct usb_endpoint_descriptor desc;
#if defined(DWC_WITH_WLAN_OSDEP)
_list urb_list;
#else
_LIST urb_list;
#endif
void *hcpriv;
unsigned char *extra; /* Extra descriptors */
int extralen;
int enabled;
};
/* host-side wrapper for one interface setting's parsed descriptors */
struct usb_host_interface {
struct usb_interface_descriptor desc;
int extralen;
unsigned char *extra; /* Extra descriptors */
/* array of desc.bNumEndpoint endpoints associated with this
* interface setting. these will be in no particular order.
*/
struct usb_host_endpoint *endpoint;
char *string; /* iInterface string, if present */
};
struct usb_interface {
/* array of alternate settings for this interface,
* stored in no particular order */
struct usb_host_interface *altsetting;
struct usb_host_interface *cur_altsetting; /* the currently
* active alternate setting */
unsigned num_altsetting; /* number of alternate settings */
/* If there is an interface association descriptor then it will list
* the associated interfaces */
struct usb_interface_assoc_descriptor *intf_assoc;
// int minor; /* minor number this interface is
// * bound to */
unsigned ep_devs_created:1; /* endpoint "devices" exist */
unsigned unregistering:1; /* unregistration is in progress */
unsigned needs_altsetting0:1; /* switch to altsetting 0 is pending */
unsigned reset_running:1;
unsigned resetting_device:1; /* true: bandwidth alloc after reset */
void *dev_prive_data;/* interface specific device info i.e struct v4l2_device pointer */
void *driver;
void *drv_priv; // functional driver priv data
void *usb_dev;
};
#define to_usb_interface(d) container_of(d, struct usb_interface, usb_dev)
struct usb_interface_cache {
unsigned num_altsetting; /* number of alternate settings */
/* variable-length array of alternate settings for this interface,
* stored in no particular order */
struct usb_host_interface altsetting[0];
};
struct usb_host_config {
struct usb_config_descriptor desc;
char *string; /* iConfiguration string, if present */
/* List of any Interface Association Descriptors in this
* configuration. */
struct usb_interface_assoc_descriptor *intf_assoc[USB_MAXIADS];
/* the interfaces associated with this configuration,
* stored in no particular order */
struct usb_interface *interface[USB_MAXINTERFACES];
/* Interface information available even when this is not the
* active configuration */
struct usb_interface_cache *intf_cache[USB_MAXINTERFACES];
unsigned char *extra; /* Extra descriptors */
int extralen;
};
struct usb_device {
int devnum;
u32 route;
enum usb_device_state state;
enum usb_device_speed speed;
unsigned int toggle[2];
struct usb_device *parent;
struct usb_device *children[USB_MAXCHILDREN];
void *hcd;
struct usb_host_endpoint ep0;
struct usb_device_descriptor descriptor;
struct usb_host_config *config;
struct usb_host_config *actconfig;
struct usb_host_endpoint *ep_in[16];
struct usb_host_endpoint *ep_out[16];
int configno; /* selected config number */
char **rawdescriptors;
unsigned int rawdeslen[USB_MAXCONFIG];
// unsigned short bus_mA;
u8 portnum;
u8 level;
unsigned can_submit:1;
unsigned persist_enabled:1;
unsigned have_langid:1;
unsigned authorized:1;
unsigned authenticated:1;
int string_langid;
/* static strings from the device */
// char *product;
// char *manufacturer;
// char *serial;
int maxchild;
u32 quirks;
atomic_t urbnum;
// unsigned long active_duration;
char mf[32]; /* manufacturer */
char prod[32]; /* product */
char serial[32]; /* serial number */
#if defined(DWC_WITH_WLAN_OSDEP)
_mutex Mutex;
#else
_Mutex Mutex;
#endif
};
/*
* urb->transfer_flags:
*
* Note: URB_DIR_IN/OUT is automatically set in usb_submit_urb().
*/
#define URB_SHORT_NOT_OK 0x0001 /* report short reads as errors */
#define URB_ISO_ASAP 0x0002 /* iso-only, urb->start_frame
* ignored */
#define URB_NO_TRANSFER_DMA_MAP 0x0004 /* urb->transfer_dma valid on submit */
#define URB_NO_FSBR 0x0020 /* UHCI-specific */
#define URB_ZERO_PACKET 0x0040 /* Finish bulk OUT with short packet */
#define URB_NO_INTERRUPT 0x0080 /* HINT: no non-error interrupt
* needed */
#define URB_FREE_BUFFER 0x0100 /* Free transfer buffer with the URB */
/* The following flags are used internally by usbcore and HCDs */
#define URB_DIR_IN 0x0200 /* Transfer from device to host */
#define URB_DIR_OUT 0
#define URB_DIR_MASK URB_DIR_IN
#define URB_DMA_MAP_SINGLE 0x00010000 /* Non-scatter-gather mapping */
#define URB_DMA_MAP_PAGE 0x00020000 /* HCD-unsupported S-G */
#define URB_DMA_MAP_SG 0x00040000 /* HCD-supported S-G */
#define URB_MAP_LOCAL 0x00080000 /* HCD-local-memory mapping */
#define URB_SETUP_MAP_SINGLE 0x00100000 /* Setup packet DMA mapped */
#define URB_SETUP_MAP_LOCAL 0x00200000 /* HCD-local setup packet */
#define URB_DMA_SG_COMBINED 0x00400000 /* S-G entries were combined */
#define URB_ALIGNED_TEMP_BUFFER 0x00800000 /* Temp buffer was alloc'd */
struct usb_iso_packet_descriptor {
unsigned int offset;
unsigned int length; /* expected length */
unsigned int actual_length;
int status;
};
struct urb;
typedef void (*usb_complete_t)(struct urb *);
struct urb {
/* private: usb core and host controller only fields in the urb */
void *hcpriv; /* private data for host controller */
atomic_t use_count; /* concurrent submissions counter */
atomic_t reject; /* submissions will fail */
int unlinked; /* unlink error code */
/* public: documented fields in the urb that can be used by drivers */
#if defined(DWC_WITH_WLAN_OSDEP)
_list urb_list; /* list head for use by the urb's
* current owner */
// _list anchor_list; /* the URB may be anchored */
#else
_LIST urb_list; /* list head for use by the urb's
* current owner */
// _LIST anchor_list; /* the URB may be anchored */
#endif
// struct usb_anchor *anchor;
struct usb_device *dev; /* (in) pointer to associated device */
struct usb_host_endpoint *ep; /* (internal) pointer to endpoint */
unsigned int pipe; /* (in) pipe information */
unsigned int stream_id; /* (in) stream ID */
int status; /* (return) non-ISO status */
unsigned int transfer_flags; /* (in) URB_SHORT_NOT_OK | ...*/
void *transfer_buffer; /* (in) associated data buffer */
dma_addr_t transfer_dma; /* (in) dma addr for transfer_buffer */
u32 transfer_buffer_length; /* (in) data buffer length */
u32 actual_length; /* (return) actual transfer length */
unsigned char *setup_packet; /* (in) setup packet (control only) */
int start_frame; /* (modify) start frame (ISO) */
int number_of_packets; /* (in) number of ISO packets */
int interval; /* (modify) transfer interval
* (INT/ISO) */
int error_count; /* (return) number of ISO errors */
void *context; /* (in) context for completion */
#if defined(DWC_WITH_WLAN_OSDEP)
_mutex Mutex; // mutext for atomic or link-list operation
#else
_Mutex Mutex; // mutext for atomic or link-list operation
#endif
usb_complete_t complete; /* (in) completion routine */
unsigned int iso_packets;
struct usb_iso_packet_descriptor iso_frame_desc[0];
/* (in) ISO ONLY */
};
struct usb_hcd {
/*
* housekeeping
*/
void *rhdev; /* self usb_dev */
const char *product_desc; /* product/vendor string */
int speed; /* Speed for this roothub.
* May be different from
* hcd->driver->flags & HCD_MASK
*/
struct urb *status_urb; /* the current status urb */
/*
* hardware info/state
*/
/* Flags that need to be manipulated atomically because they can
* change while the host controller is running. Always use
* set_bit() or clear_bit() to change their values.
*/
unsigned long flags;
/* Flags that get set only during HCD registration or removal. */
unsigned rh_registered:1;/* is root hub registered? */
unsigned rh_pollable:1; /* may we poll the root hub? */
unsigned msix_enabled:1; /* driver has MSI-X enabled? */
/* The next flag is a stopgap, to be removed when all the HCDs
* support the new root-hub polling mechanism. */
unsigned uses_new_polling:1;
unsigned authorized_default:1;
unsigned has_tt:1; /* Integrated TT in root hub */
/* bandwidth_mutex should be taken before adding or removing
* any new bus bandwidth constraints:
* 1. Before adding a configuration for a new device.
* 2. Before removing the configuration to put the device into
* the addressed state.
* 3. Before selecting a different configuration.
* 4. Before selecting an alternate interface setting.
*
* bandwidth_mutex should be dropped after a successful control message
* to the device, or resetting the bandwidth after a failed attempt.
*/
#if defined(DWC_WITH_WLAN_OSDEP)
_mutex bandwidth_mutex;
#else
_Mutex bandwidth_mutex;
#endif
int state;
int devnum_next; /* Next open device number in
* round-robin allocation */
#if defined(DWC_WITH_WLAN_OSDEP)
_mutex hcd_urb_list_lock;
_mutex hcd_urb_unlink_lock;
_mutex hcd_root_hub_lock; // mutext for atomic or link-list operation
#else
_Mutex hcd_urb_list_lock;
_Mutex hcd_urb_unlink_lock;
_Mutex hcd_root_hub_lock; // mutext for atomic or link-list operation
#endif
/* The HC driver's private data is stored at the end of
* this structure.
*/
#ifdef __ICCARM__
#pragma pack(64)
unsigned long hcd_priv[0];
#elif defined (__GNUC__)
unsigned long hcd_priv[0]
__attribute__ ((aligned(sizeof(s64))));
#endif
};
#define le16_to_cpu rtk_le16_to_cpu
#define cpu_to_le16 rtk_cpu_to_le16
#if 0
/*
* Calling this entity a "pipe" is glorifying it. A USB pipe
* is something embarrassingly simple: it basically consists
* of the following information:
* - device number (7 bits)
* - endpoint number (4 bits)
* - current Data0/1 state (1 bit)
* - direction (1 bit)
* - speed (2 bits)
* - max packet size (2 bits: 8, 16, 32 or 64)
* - pipe type (2 bits: control, interrupt, bulk, isochronous)
*
* That's 18 bits. Really. Nothing more. And the USB people have
* documented these eighteen bits as some kind of glorious
* virtual data structure.
*
* Let's not fall in that trap. We'll just encode it as a simple
* unsigned int. The encoding is:
*
* - max size: bits 0-1 (00 = 8, 01 = 16, 10 = 32, 11 = 64)
* - direction: bit 7 (0 = Host-to-Device [Out],
* (1 = Device-to-Host [In])
* - device: bits 8-14
* - endpoint: bits 15-18
* - Data0/1: bit 19
* - speed: bit 26 (0 = Full, 1 = Low Speed, 2 = High)
* - pipe type: bits 30-31 (00 = isochronous, 01 = interrupt,
* 10 = control, 11 = bulk)
*
* Why? Because it's arbitrary, and whatever encoding we select is really
* up to us. This one happens to share a lot of bit positions with the UHCI
* specification, so that much of the uhci driver can just mask the bits
* appropriately.
*/
/* Create various pipes... */
#define create_pipe(dev,endpoint) \
(((dev)->devnum << 8) | (endpoint << 15) | \
((dev)->speed << 26) | (dev)->maxpacketsize)
#define default_pipe(dev) ((dev)->speed << 26)
#define usb_sndctrlpipe(dev, endpoint) ((PIPE_CONTROL << 30) | \
create_pipe(dev, endpoint))
#define usb_rcvctrlpipe(dev, endpoint) ((PIPE_CONTROL << 30) | \
create_pipe(dev, endpoint) | \
USB_DIR_IN)
#define usb_sndisocpipe(dev, endpoint) ((PIPE_ISOCHRONOUS << 30) | \
create_pipe(dev, endpoint))
#define usb_rcvisocpipe(dev, endpoint) ((PIPE_ISOCHRONOUS << 30) | \
create_pipe(dev, endpoint) | \
USB_DIR_IN)
#define usb_sndbulkpipe(dev, endpoint) ((PIPE_BULK << 30) | \
create_pipe(dev, endpoint))
#define usb_rcvbulkpipe(dev, endpoint) ((PIPE_BULK << 30) | \
create_pipe(dev, endpoint) | \
USB_DIR_IN)
#define usb_sndintpipe(dev, endpoint) ((PIPE_INTERRUPT << 30) | \
create_pipe(dev, endpoint))
#define usb_rcvintpipe(dev, endpoint) ((PIPE_INTERRUPT << 30) | \
create_pipe(dev, endpoint) | \
USB_DIR_IN)
#define usb_snddefctrl(dev) ((PIPE_CONTROL << 30) | \
default_pipe(dev))
#define usb_rcvdefctrl(dev) ((PIPE_CONTROL << 30) | \
default_pipe(dev) | \
USB_DIR_IN)
/* The D0/D1 toggle bits */
#define usb_gettoggle(dev, ep, out) (((dev)->toggle[out] >> ep) & 1)
#define usb_dotoggle(dev, ep, out) ((dev)->toggle[out] ^= (1 << ep))
#define usb_settoggle(dev, ep, out, bit) ((dev)->toggle[out] = \
((dev)->toggle[out] & \
~(1 << ep)) | ((bit) << ep))
/* Endpoint halt control/status */
#define usb_endpoint_out(ep_dir) (((ep_dir >> 7) & 1) ^ 1)
#define usb_endpoint_halt(dev, ep, out) ((dev)->halted[out] |= (1 << (ep)))
#define usb_endpoint_running(dev, ep, out) ((dev)->halted[out] &= ~(1 << (ep)))
#define usb_endpoint_halted(dev, ep, out) ((dev)->halted[out] & (1 << (ep)))
#define usb_packetid(pipe) (((pipe) & USB_DIR_IN) ? USB_PID_IN : \
USB_PID_OUT)
#define usb_pipeout(pipe) ((((pipe) >> 7) & 1) ^ 1)
#define usb_pipein(pipe) (((pipe) >> 7) & 1)
#define usb_pipedevice(pipe) (((pipe) >> 8) & 0x7f)
#define usb_pipe_endpdev(pipe) (((pipe) >> 8) & 0x7ff)
#define usb_pipeendpoint(pipe) (((pipe) >> 15) & 0xf)
#define usb_pipedata(pipe) (((pipe) >> 19) & 1)
#define usb_pipespeed(pipe) (((pipe) >> 26) & 3)
#define usb_pipeslow(pipe) (usb_pipespeed(pipe) == USB_SPEED_LOW)
#define usb_pipetype(pipe) (((pipe) >> 30) & 3)
#define usb_pipeisoc(pipe) (usb_pipetype((pipe)) == PIPE_ISOCHRONOUS)
#define usb_pipeint(pipe) (usb_pipetype((pipe)) == PIPE_INTERRUPT)
#define usb_pipecontrol(pipe) (usb_pipetype((pipe)) == PIPE_CONTROL)
#define usb_pipebulk(pipe) (usb_pipetype((pipe)) == PIPE_BULK)
#else
/* ----------------------------------------------------------------------- */
/*
* For various legacy reasons, Linux has a small cookie that's paired with
* a struct usb_device to identify an endpoint queue. Queue characteristics
* are defined by the endpoint's descriptor. This cookie is called a "pipe",
* an unsigned int encoded as:
*
* - direction: bit 7 (0 = Host-to-Device [Out],
* 1 = Device-to-Host [In] ...
* like endpoint bEndpointAddress)
* - device address: bits 8-14 ... bit positions known to uhci-hcd
* - endpoint: bits 15-18 ... bit positions known to uhci-hcd
* - pipe type: bits 30-31 (00 = isochronous, 01 = interrupt,
* 10 = control, 11 = bulk)
*
* Given the device address and endpoint descriptor, pipes are redundant.
*/
/* NOTE: these are not the standard USB_ENDPOINT_XFER_* values!! */
/* (yet ... they're the values used by usbfs) */
#define usb_pipein(pipe) (((pipe) & USB_DIR_IN) >> 7)
#define usb_pipeout(pipe) (!usb_pipein(pipe))
#define usb_pipedevice(pipe) (((pipe) >> 8) & 0x7f)
#define usb_pipeendpoint(pipe) (((pipe) >> 15) & 0xf)
#define usb_pipetype(pipe) (((pipe) >> 30) & 3)
#define usb_pipeisoc(pipe) (usb_pipetype((pipe)) == PIPE_ISOCHRONOUS)
#define usb_pipeint(pipe) (usb_pipetype((pipe)) == PIPE_INTERRUPT)
#define usb_pipecontrol(pipe) (usb_pipetype((pipe)) == PIPE_CONTROL)
#define usb_pipebulk(pipe) (usb_pipetype((pipe)) == PIPE_BULK)
static inline unsigned int __create_pipe(struct usb_device *dev,
unsigned int endpoint)
{
return (dev->devnum << 8) | (endpoint << 15);
}
#define usb_sndaddr0pipe() (PIPE_CONTROL << 30)
#define usb_rcvaddr0pipe() ((PIPE_CONTROL << 30) | USB_DIR_IN)
/* Create various pipes... */
#define usb_sndctrlpipe(dev, endpoint) \
((PIPE_CONTROL << 30) | __create_pipe(dev, endpoint))
#define usb_rcvctrlpipe(dev, endpoint) \
((PIPE_CONTROL << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN)
#define usb_sndisocpipe(dev, endpoint) \
((PIPE_ISOCHRONOUS << 30) | __create_pipe(dev, endpoint))
#define usb_rcvisocpipe(dev, endpoint) \
((PIPE_ISOCHRONOUS << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN)
#define usb_sndbulkpipe(dev, endpoint) \
((PIPE_BULK << 30) | __create_pipe(dev, endpoint))
#define usb_rcvbulkpipe(dev, endpoint) \
((PIPE_BULK << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN)
#define usb_sndintpipe(dev, endpoint) \
((PIPE_INTERRUPT << 30) | __create_pipe(dev, endpoint))
#define usb_rcvintpipe(dev, endpoint) \
((PIPE_INTERRUPT << 30) | __create_pipe(dev, endpoint) | USB_DIR_IN)
static inline struct usb_host_endpoint *
usb_pipe_endpoint(struct usb_device *dev, unsigned int pipe)
{
struct usb_host_endpoint **eps;
eps = usb_pipein(pipe) ? dev->ep_in : dev->ep_out;
return eps[usb_pipeendpoint(pipe)];
}
/* The D0/D1 toggle bits ... USE WITH CAUTION (they're almost hcd-internal) */
#define usb_gettoggle(dev, ep, out) (((dev)->toggle[out] >> (ep)) & 1)
#define usb_dotoggle(dev, ep, out) ((dev)->toggle[out] ^= (1 << (ep)))
#define usb_settoggle(dev, ep, out, bit) \
((dev)->toggle[out] = ((dev)->toggle[out] & ~(1 << (ep))) | \
((bit) << (ep)))
#endif
/*************************************************************************
* Hub Stuff
*/
struct usb_port_status {
unsigned short wPortStatus;
unsigned short wPortChange;
} UPACKED;
struct usb_hub_status {
unsigned short wHubStatus;
unsigned short wHubChange;
}UPACKED;
/* Hub descriptor */
struct usb_hub_descriptor {
unsigned char bLength;
unsigned char bDescriptorType;
unsigned char bNbrPorts;
unsigned short wHubCharacteristics;
unsigned char bPwrOn2PwrGood;
unsigned char bHubContrCurrent;
unsigned char DeviceRemovable[(USB_MAXCHILDREN+1+7)/8];
unsigned char PortPowerCtrlMask[(USB_MAXCHILDREN+1+7)/8];
/* DeviceRemovable and PortPwrCtrlMask want to be variable-length
bitmaps that hold max 255 entries. (bit0 is ignored) */
}UPACKED;
struct usb_hub_device {
struct usb_device *pusb_dev;
struct usb_hub_descriptor desc;
};
/*-------------------------------------------------------------------------*/
/**
* usb_endpoint_num - get the endpoint's number
* @epd: endpoint to be checked
*
* Returns @epd's number: 0 to 15.
*/
static inline int usb_endpoint_num(const struct usb_endpoint_descriptor *epd)
{
return epd->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
}
/**
* usb_endpoint_type - get the endpoint's transfer type
* @epd: endpoint to be checked
*
* Returns one of USB_ENDPOINT_XFER_{CONTROL, ISOC, BULK, INT} according
* to @epd's transfer type.
*/
static inline int usb_endpoint_type(const struct usb_endpoint_descriptor *epd)
{
return epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
}
/**
* usb_endpoint_dir_in - check if the endpoint has IN direction
* @epd: endpoint to be checked
*
* Returns true if the endpoint is of type IN, otherwise it returns false.
*/
static inline int usb_endpoint_dir_in(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN);
}
/**
* usb_endpoint_dir_out - check if the endpoint has OUT direction
* @epd: endpoint to be checked
*
* Returns true if the endpoint is of type OUT, otherwise it returns false.
*/
static inline int usb_endpoint_dir_out(
const struct usb_endpoint_descriptor *epd)
{
return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
}
#define usb_endpoint_out(ep_dir) (!((ep_dir) & USB_DIR_IN))
/**
* usb_endpoint_xfer_bulk - check if the endpoint has bulk transfer type
* @epd: endpoint to be checked
*
* Returns true if the endpoint is of type bulk, otherwise it returns false.
*/
static inline int usb_endpoint_xfer_bulk(
const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_BULK);
}
/**
* usb_endpoint_xfer_control - check if the endpoint has control transfer type
* @epd: endpoint to be checked
*
* Returns true if the endpoint is of type control, otherwise it returns false.
*/
static inline int usb_endpoint_xfer_control(
const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_CONTROL);
}
/**
* usb_endpoint_xfer_int - check if the endpoint has interrupt transfer type
* @epd: endpoint to be checked
*
* Returns true if the endpoint is of type interrupt, otherwise it returns
* false.
*/
static inline int usb_endpoint_xfer_int(
const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_INT);
}
/**
* usb_endpoint_xfer_isoc - check if the endpoint has isochronous transfer type
* @epd: endpoint to be checked
*
* Returns true if the endpoint is of type isochronous, otherwise it returns
* false.
*/
static inline int usb_endpoint_xfer_isoc(
const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_ISOC);
}
/**
* usb_endpoint_is_bulk_in - check if the endpoint is bulk IN
* @epd: endpoint to be checked
*
* Returns true if the endpoint has bulk transfer type and IN direction,
* otherwise it returns false.
*/
static inline int usb_endpoint_is_bulk_in(
const struct usb_endpoint_descriptor *epd)
{
return usb_endpoint_xfer_bulk(epd) && usb_endpoint_dir_in(epd);
}
/**
* usb_endpoint_is_bulk_out - check if the endpoint is bulk OUT
* @epd: endpoint to be checked
*
* Returns true if the endpoint has bulk transfer type and OUT direction,
* otherwise it returns false.
*/
static inline int usb_endpoint_is_bulk_out(
const struct usb_endpoint_descriptor *epd)
{
return usb_endpoint_xfer_bulk(epd) && usb_endpoint_dir_out(epd);
}
/**
* usb_endpoint_is_int_in - check if the endpoint is interrupt IN
* @epd: endpoint to be checked
*
* Returns true if the endpoint has interrupt transfer type and IN direction,
* otherwise it returns false.
*/
static inline int usb_endpoint_is_int_in(
const struct usb_endpoint_descriptor *epd)
{
return usb_endpoint_xfer_int(epd) && usb_endpoint_dir_in(epd);
}
/**
* usb_endpoint_is_int_out - check if the endpoint is interrupt OUT
* @epd: endpoint to be checked
*
* Returns true if the endpoint has interrupt transfer type and OUT direction,
* otherwise it returns false.
*/
static inline int usb_endpoint_is_int_out(
const struct usb_endpoint_descriptor *epd)
{
return usb_endpoint_xfer_int(epd) && usb_endpoint_dir_out(epd);
}
/**
* usb_endpoint_is_isoc_in - check if the endpoint is isochronous IN
* @epd: endpoint to be checked
*
* Returns true if the endpoint has isochronous transfer type and IN direction,
* otherwise it returns false.
*/
static inline int usb_endpoint_is_isoc_in(
const struct usb_endpoint_descriptor *epd)
{
return usb_endpoint_xfer_isoc(epd) && usb_endpoint_dir_in(epd);
}
/**
* usb_endpoint_is_isoc_out - check if the endpoint is isochronous OUT
* @epd: endpoint to be checked
*
* Returns true if the endpoint has isochronous transfer type and OUT direction,
* otherwise it returns false.
*/
static inline int usb_endpoint_is_isoc_out(
const struct usb_endpoint_descriptor *epd)
{
return usb_endpoint_xfer_isoc(epd) && usb_endpoint_dir_out(epd);
}
/**
* usb_endpoint_maxp - get endpoint's max packet size
* @epd: endpoint to be checked
*
* Returns @epd's max packet
*/
static inline int usb_endpoint_maxp(const struct usb_endpoint_descriptor *epd)
{
return rtk_le16_to_cpu(epd->wMaxPacketSize);
}
/**
* usb_urb_dir_in - check if an URB describes an IN transfer
* @urb: URB to be checked
*
* Returns 1 if @urb describes an IN transfer (device-to-host),
* otherwise 0.
*/
static inline int usb_urb_dir_in(struct urb *urb)
{
return (urb->transfer_flags & URB_DIR_MASK) == URB_DIR_IN;
}
/**
* usb_urb_dir_out - check if an URB describes an OUT transfer
* @urb: URB to be checked
*
* Returns 1 if @urb describes an OUT transfer (host-to-device),
* otherwise 0.
*/
static inline int usb_urb_dir_out(struct urb *urb)
{
return (urb->transfer_flags & URB_DIR_MASK) == URB_DIR_OUT;
}
/**
* usb_get_dev - increments the reference count of the usb device structure
* @dev: the device being referenced
*
* Each live reference to a device should be refcounted.
*
* Drivers for USB interfaces should normally record such references in
* their probe() methods, when they bind to an interface, and release
* them by calling usb_put_dev(), in their disconnect() methods.
*
* A pointer to the device with the incremented reference counter is returned.
*/
static inline void *usb_get_dev(struct usb_device *dev)
{
return dev;
}
/**
* usb_put_dev - release a use of the usb device structure
* @dev: device that's been disconnected
*
* Must be called when a user of a device is finished with it. When the last
* user of the device calls this function, the memory of the device is freed.
*/
static inline void usb_put_dev(struct usb_device *dev)
{
/* To avoid gcc warnings */
( void ) dev;
}
/**
* usb_get_intf - increments the reference count of the usb interface structure
* @intf: the interface being referenced
*
* Each live reference to a interface must be refcounted.
*
* Drivers for USB interfaces should normally record such references in
* their probe() methods, when they bind to an interface, and release
* them by calling usb_put_intf(), in their disconnect() methods.
*
* A pointer to the interface with the incremented reference counter is
* returned.
*/
static inline void *usb_get_intf(struct usb_interface *intf)
{
return intf;
}
/**
* usb_put_intf - release a use of the usb interface structure
* @intf: interface that's been decremented
*
* Must be called when a user of an interface is finished with it. When the
* last user of the interface calls this function, the memory of the interface
* is freed.
*/
static inline void usb_put_intf(struct usb_interface *intf)
{
/* To avoid gcc warnings */
( void ) intf;
}
static inline void *usb_get_intfdata(struct usb_interface *intf)
{
return (intf->drv_priv);
}
static inline void usb_set_intfdata(struct usb_interface *intf, void *data)
{
intf->drv_priv = data;
}
static inline struct usb_device *interface_to_usbdev(struct usb_interface *intf)
{
return (struct usb_device *)(intf->usb_dev);
}
static inline struct usb_driver *interface_to_usbdri(struct usb_interface *intf)
{
return (struct usb_driver *)(intf->driver);
}
/*-------------------------------------------------------------------------*/
/*=====================================================*/
#ifdef DWC_HOST_ONLY
typedef struct {
uByte bLength;
uByte bDescriptorType;
uByte bEndpointAddress;
#define UE_GET_DIR(a) ((a) & 0x80)
#define UE_SET_DIR(a,d) ((a) | (((d)&1) << 7))
#define UE_DIR_IN 0x01
#define UE_DIR_OUT 0x00
#define UE_ADDR 0x0f
#define UE_GET_ADDR(a) ((a) & UE_ADDR)
uByte bmAttributes;
#define UE_XFERTYPE 0x03
#define UE_CONTROL 0x00
#define UE_ISOCHRONOUS 0x01
#define UE_BULK 0x02
#define UE_INTERRUPT 0x03
#define UE_GET_XFERTYPE(a) ((a) & UE_XFERTYPE)
#if 0
#define UE_ISO_TYPE 0x0c
#define UE_ISO_ASYNC 0x04
#define UE_ISO_ADAPT 0x08
#define UE_ISO_SYNC 0x0c
#define UE_GET_ISO_TYPE(a) ((a) & UE_ISO_TYPE)
#endif
uWord wMaxPacketSize;
uByte bInterval;
} usb_endpoint_descriptor_t;//UPACKED usb_endpoint_descriptor_t;
#define USB_ENDPOINT_DESCRIPTOR_SIZE 7
#endif
#ifdef DWC_DEVICE_ONLY
typedef struct {
uByte bLength;
uByte bDescriptorType;
uByte bEndpointAddress;
#define UE_GET_DIR(a) ((a) & 0x80)
#define UE_SET_DIR(a,d) ((a) | (((d)&1) << 7))
#define UE_DIR_IN 0x80
#define UE_DIR_OUT 0x00
#define UE_ADDR 0x0f
#define UE_GET_ADDR(a) ((a) & UE_ADDR)
uByte bmAttributes;
#define UE_XFERTYPE 0x03
#define UE_CONTROL 0x00
#define UE_ISOCHRONOUS 0x01
#define UE_BULK 0x02
#define UE_INTERRUPT 0x03
#define UE_GET_XFERTYPE(a) ((a) & UE_XFERTYPE)
#define UE_ISO_TYPE 0x0c
#define UE_ISO_ASYNC 0x04
#define UE_ISO_ADAPT 0x08
#define UE_ISO_SYNC 0x0c
#define UE_GET_ISO_TYPE(a) ((a) & UE_ISO_TYPE)
uWord wMaxPacketSize;
uByte bInterval;
} UPACKED usb_endpoint_descriptor_t;
#endif
typedef struct ss_endpoint_companion_descriptor {
uByte bLength;
uByte bDescriptorType;
uByte bMaxBurst;
#define USSE_GET_MAX_STREAMS(a) ((a) & 0x1f)
#define USSE_SET_MAX_STREAMS(a, b) ((a) | ((b) & 0x1f))
#define USSE_GET_MAX_PACKET_NUM(a) ((a) & 0x03)
#define USSE_SET_MAX_PACKET_NUM(a, b) ((a) | ((b) & 0x03))
uByte bmAttributes;
uWord wBytesPerInterval;
} UPACKED ss_endpoint_companion_descriptor_t;
#define USB_SS_ENDPOINT_COMPANION_DESCRIPTOR_SIZE 6
typedef struct {
uByte bLength;
uByte bDescriptorType;
uWord bString[127];
} UPACKED usb_string_descriptor_t;
#define USB_MAX_STRING_LEN 128
#define USB_LANGUAGE_TABLE 0 /* # of the string language id table */
/* USB_DT_DEVICE_QUALIFIER: Device Qualifier descriptor */
/* USB_DT_OTG (from OTG 1.0a supplement) */
/* from usb_otg_descriptor.bmAttributes */
#define USB_OTG_SRP (1 << 0)
#define USB_OTG_HNP (1 << 1) /* swap host/device roles */
extern void _usb_init(void);
extern void _usb_deinit(void);
extern int wait_usb_ready(void);
extern void usb_disable_asynch(int disable);
extern unsigned short usb_maxpacket(struct usb_device *udev, int pipe, int is_out);
extern int usb_set_interface(struct usb_device *dev, int interface, int alternate);
extern int usb_set_configuration(struct usb_device *dev, int configuration);
extern int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol);
extern int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id);
extern int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type,
unsigned char id, void *buf, int size);
extern int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
unsigned char type, unsigned char id, void *buf, int size);
extern int usb_string(struct usb_device *dev, int index, char *buf, int size);
extern void usb_hcd_giveback_urb(struct usb_hcd *hcd, struct urb *urb, int status);
extern struct usb_hcd *usb_create_hcd(unsigned int priv_size);
extern int usb_add_hcd(struct usb_hcd *hcd);
extern struct urb *usb_alloc_urb(int iso_packets);
extern void usb_free_urb(struct urb *urb);
extern void usb_kill_urb(struct urb *urb);
extern void usb_fill_control_urb(struct urb *urb,
struct usb_device *dev,
unsigned int pipe,
unsigned char *setup_packet,
void *transfer_buffer,
int buffer_length,
usb_complete_t complete_fn,
void *context);
extern void usb_fill_bulk_urb(struct urb *urb,
struct usb_device *dev,
unsigned int pipe,
void *transfer_buffer,
int buffer_length,
usb_complete_t complete_fn,
void *context);
extern void usb_fill_int_urb(struct urb *urb,
struct usb_device *dev,
unsigned int pipe,
void *transfer_buffer,
int buffer_length,
usb_complete_t complete_fn,
void *context,
int interval);
extern int usb_submit_urb(struct urb *urb);
extern void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr);
extern void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
bool reset_hardware);
extern void usb_enable_interface(struct usb_device *dev,
struct usb_interface *intf, bool reset_eps);
extern int usb_control_msg(struct usb_device *dev, unsigned int pipe, u8 request,
u8 requesttype, u16 value, u16 index, void *data,
u16 size, int timeout);
extern int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout);
extern int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout);
extern int usb_get_descriptor(struct usb_device *dev, unsigned char type,
unsigned char index, void *buf, int size);
extern int usb_get_device_descriptor(struct usb_device *dev, unsigned int size);
extern int usb_clear_halt(struct usb_device *dev, int pipe);
#if defined(DWC_WITH_WLAN_OSDEP)
extern _sema CtrlUrbCompSema; /* Semaphore for for Control URB Complete waiting */
extern _sema UrbKillSema; /* Semaphore for for URB Kill waiting */
#else
extern _Sema CtrlUrbCompSema; /* Semaphore for for Control URB Complete waiting */
extern _Sema UrbKillSema; /* Semaphore for for URB Kill waiting */
#endif
typedef unsigned long kernel_ulong_t;
extern int usb_deinit(void);
struct usb_device_id {
/* which fields to match against? */
u16 match_flags;
/* Used for product specific matches; range is inclusive */
u16 idVendor;
u16 idProduct;
u16 bcdDevice_lo;
u16 bcdDevice_hi;
/* Used for device class matches */
u8 bDeviceClass;
u8 bDeviceSubClass;
u8 bDeviceProtocol;
/* Used for interface class matches */
u8 bInterfaceClass;
u8 bInterfaceSubClass;
u8 bInterfaceProtocol;
/* Used for vendor-specific interface matches */
u8 bInterfaceNumber;
/* not matched against */
#ifdef __ICCARM__
#pragma pack(64)
kernel_ulong_t driver_info;
#elif defined (__GNUC__)
kernel_ulong_t driver_info
__attribute__((aligned(sizeof(kernel_ulong_t))));
#endif
};
/* Some useful macros to use to create struct usb_device_id */
#define USB_DEVICE_ID_MATCH_VENDOR 0x0001
#define USB_DEVICE_ID_MATCH_PRODUCT 0x0002
#define USB_DEVICE_ID_MATCH_DEV_LO 0x0004
#define USB_DEVICE_ID_MATCH_DEV_HI 0x0008
#define USB_DEVICE_ID_MATCH_DEV_CLASS 0x0010
#define USB_DEVICE_ID_MATCH_DEV_SUBCLASS 0x0020
#define USB_DEVICE_ID_MATCH_DEV_PROTOCOL 0x0040
#define USB_DEVICE_ID_MATCH_INT_CLASS 0x0080
#define USB_DEVICE_ID_MATCH_INT_SUBCLASS 0x0100
#define USB_DEVICE_ID_MATCH_INT_PROTOCOL 0x0200
#define USB_DEVICE_ID_MATCH_INT_NUMBER 0x0400
#define USB_DEVICE_ID_MATCH_DEVICE \
(USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_PRODUCT)
#define USB_DEVICE_ID_MATCH_DEV_RANGE \
(USB_DEVICE_ID_MATCH_DEV_LO | USB_DEVICE_ID_MATCH_DEV_HI)
#define USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION \
(USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_DEV_RANGE)
#define USB_DEVICE_ID_MATCH_DEV_INFO \
(USB_DEVICE_ID_MATCH_DEV_CLASS | \
USB_DEVICE_ID_MATCH_DEV_SUBCLASS | \
USB_DEVICE_ID_MATCH_DEV_PROTOCOL)
#define USB_DEVICE_ID_MATCH_INT_INFO \
(USB_DEVICE_ID_MATCH_INT_CLASS | \
USB_DEVICE_ID_MATCH_INT_SUBCLASS | \
USB_DEVICE_ID_MATCH_INT_PROTOCOL)
/**
* USB_DEVICE - macro used to describe a specific usb device
* @vend: the 16 bit USB Vendor ID
* @prod: the 16 bit USB Product ID
*
* This macro is used to create a struct usb_device_id that matches a
* specific device.
*/
#define USB_DEVICE(vend, prod) \
.match_flags = USB_DEVICE_ID_MATCH_DEVICE, \
.idVendor = (vend), \
.idProduct = (prod)
/**
* USB_DEVICE_VER - describe a specific usb device with a version range
* @vend: the 16 bit USB Vendor ID
* @prod: the 16 bit USB Product ID
* @lo: the bcdDevice_lo value
* @hi: the bcdDevice_hi value
*
* This macro is used to create a struct usb_device_id that matches a
* specific device, with a version range.
*/
#define USB_DEVICE_VER(vend, prod, lo, hi) \
.match_flags = USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION, \
.idVendor = (vend), \
.idProduct = (prod), \
.bcdDevice_lo = (lo), \
.bcdDevice_hi = (hi)
/**
* USB_INTERFACE_INFO - macro used to describe a class of usb interfaces
* @cl: bInterfaceClass value
* @sc: bInterfaceSubClass value
* @pr: bInterfaceProtocol value
*
* This macro is used to create a struct usb_device_id that matches a
* specific class of interfaces.
*/
#define USB_INTERFACE_INFO(cl, sc, pr) \
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO, \
.bInterfaceClass = (cl), \
.bInterfaceSubClass = (sc), \
.bInterfaceProtocol = (pr)
typedef enum{
USB_INIT_NONE = -1,
USB_INIT_OK = 0,
USB_INIT_FAIL = 1,
USB_NOT_ATTACHED = 2
}_usb_init_s;
struct usb_driver {
const char *name;
int (*probe) (struct usb_interface *intf);
void (*disconnect) (struct usb_interface *intf);
int (*resume) (struct usb_interface *intf);
int (*reset_resume)(struct usb_interface *intf);
int (*pre_reset)(struct usb_interface *intf);
int (*post_reset)(struct usb_interface *intf);
const struct usb_device_id *id_table;
_list list;
};
int usb_register_class_driver(struct usb_driver *driver);
#endif /* _USB_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usb_otg/include/usb.h
|
C
|
apache-2.0
| 66,641
|
/*
* This file holds USB constants and structures that are needed for USB
* device APIs. These are used by the USB device model, which is defined
* in chapter 9 of the USB 2.0 specification. Linux has several APIs in C
* that need these:
*
* - the master/host side Linux-USB kernel driver API;
* - the "usbfs" user space API; and
* - the Linux "gadget" slave/device/peripheral side driver API.
*
* USB 2.0 adds an additional "On The Go" (OTG) mode, which lets systems
* act either as a USB master/host or as a USB slave/device. That means
* the master and slave side APIs benefit from working well together.
*
* There's also "Wireless USB", using low power short range radios for
* peripheral interconnection but otherwise building on the USB framework.
*/
#ifndef _USB_CH9_H_
#define _USB_CH9_H_
#include "basic_types.h"
//#include <linux/types.h> /* __u8 etc */
//#include "../otg/osk/sys-support.h"
/*-------------------------------------------------------------------------*/
/* CONTROL REQUEST SUPPORT */
/*
* USB directions
*
* This bit flag is used in endpoint descriptors' bEndpointAddress field.
* It's also one of three fields in control requests bRequestType.
*/
//#define USB_DIR_OUT 0 /* to device */
//#define USB_DIR_IN 0x80 /* to host */
/*
* USB types, the second of three bRequestType fields
*/
#define USB_TYPE_MASK (0x03 << 5)
#define USB_TYPE_STANDARD (0x00 << 5)
#define USB_TYPE_CLASS (0x01 << 5)
#define USB_TYPE_VENDOR (0x02 << 5)
#define USB_TYPE_RESERVED (0x03 << 5)
/*
* USB recipients, the third of three bRequestType fields
*/
#define USB_RECIP_MASK 0x1f
#define USB_RECIP_DEVICE 0x00
#define USB_RECIP_INTERFACE 0x01
#define USB_RECIP_ENDPOINT 0x02
#define USB_RECIP_OTHER 0x03
/* From Wireless USB 1.0 */
#define USB_RECIP_PORT 0x04
#define USB_RECIP_RPIPE 0x05
/*
* Standard requests, for the bRequest field of a SETUP packet.
*
* These are qualified by the bRequestType field, so that for example
* TYPE_CLASS or TYPE_VENDOR specific feature flags could be retrieved
* by a GET_STATUS request.
*/
#define USB_REQ_GET_STATUS 0x00
#define USB_REQ_CLEAR_FEATURE 0x01
#define USB_REQ_SET_FEATURE 0x03
#define USB_REQ_SET_ADDRESS 0x05
#define USB_REQ_GET_DESCRIPTOR 0x06
#define USB_REQ_SET_DESCRIPTOR 0x07
#define USB_REQ_GET_CONFIGURATION 0x08
#define USB_REQ_SET_CONFIGURATION 0x09
#define USB_REQ_GET_INTERFACE 0x0A
#define USB_REQ_SET_INTERFACE 0x0B
#define USB_REQ_SYNCH_FRAME 0x0C
#define USB_REQ_SET_ENCRYPTION 0x0D /* Wireless USB */
#define USB_REQ_GET_ENCRYPTION 0x0E
#define USB_REQ_RPIPE_ABORT 0x0E
#define USB_REQ_SET_HANDSHAKE 0x0F
#define USB_REQ_RPIPE_RESET 0x0F
#define USB_REQ_GET_HANDSHAKE 0x10
#define USB_REQ_SET_CONNECTION 0x11
#define USB_REQ_SET_SECURITY_DATA 0x12
#define USB_REQ_GET_SECURITY_DATA 0x13
#define USB_REQ_SET_WUSB_DATA 0x14
#define USB_REQ_LOOPBACK_DATA_WRITE 0x15
#define USB_REQ_LOOPBACK_DATA_READ 0x16
#define USB_REQ_SET_INTERFACE_DS 0x17
/*
* USB feature flags are written using USB_REQ_{CLEAR,SET}_FEATURE, and
* are read as a bit array returned by USB_REQ_GET_STATUS. (So there
* are at most sixteen features of each type.)
*/
#define USB_DEVICE_SELF_POWERED 0 /* (read only) */
#define USB_DEVICE_REMOTE_WAKEUP 1 /* dev may initiate wakeup */
#define USB_DEVICE_TEST_MODE 2 /* (wired high speed only) */
#define USB_DEVICE_BATTERY 2 /* (wireless) */
#define USB_DEVICE_B_HNP_ENABLE 3 /* (otg) dev may initiate HNP */
#define USB_DEVICE_WUSB_DEVICE 3 /* (wireless)*/
#define USB_DEVICE_A_HNP_SUPPORT 4 /* (otg) RH port supports HNP */
#define USB_DEVICE_A_ALT_HNP_SUPPORT 5 /* (otg) other RH port does */
#define USB_DEVICE_DEBUG_MODE 6 /* (special devices only) */
#define USB_ENDPOINT_HALT 0 /* IN/OUT will STALL */
/**
* struct usb_ctrlrequest - SETUP data for a USB device control request
* @bRequestType: matches the USB bmRequestType field
* @bRequest: matches the USB bRequest field
* @wValue: matches the USB wValue field (le16 byte order)
* @wIndex: matches the USB wIndex field (le16 byte order)
* @wLength: matches the USB wLength field (le16 byte order)
*
* This structure is used to send control requests to a USB device. It matches
* the different fields of the USB 2.0 Spec section 9.3, table 9-2. See the
* USB spec for a fuller description of the different fields, and what they are
* used for.
*
* Note that the driver for any interface can issue control requests.
* For most devices, interfaces don't coordinate with each other, so
* such requests may be made at any time.
*/
struct usb_ctrlrequest {
u8 bRequestType;
u8 bRequest;
u16 wValue;
u16 wIndex;
u16 wLength;
};
/*-------------------------------------------------------------------------*/
/*
* STANDARD DESCRIPTORS ... as returned by GET_DESCRIPTOR, or
* (rarely) accepted by SET_DESCRIPTOR.
*
* Note that all multi-byte values here are encoded in little endian
* byte order "on the wire". But when exposed through Linux-USB APIs,
* they've been converted to cpu byte order.
*/
/*
* Descriptor types ... USB 2.0 spec table 9.5
*/
#define USB_DT_DEVICE 0x01
#define USB_DT_CONFIG 0x02
#define USB_DT_STRING 0x03
#define USB_DT_INTERFACE 0x04
#define USB_DT_ENDPOINT 0x05
#define USB_DT_DEVICE_QUALIFIER 0x06
#define USB_DT_OTHER_SPEED_CONFIG 0x07
#define USB_DT_INTERFACE_POWER 0x08
/* these are from a minor usb 2.0 revision (ECN) */
#define USB_DT_OTG 0x09
#define USB_DT_DEBUG 0x0a
#define USB_DT_INTERFACE_ASSOCIATION 0x0b
/* these are from the Wireless USB spec */
#define USB_DT_SECURITY 0x0c
#define USB_DT_KEY 0x0d
#define USB_DT_ENCRYPTION_TYPE 0x0e
#define USB_DT_BOS 0x0f
#define USB_DT_DEVICE_CAPABILITY 0x10
#define USB_DT_WIRELESS_ENDPOINT_COMP 0x11
#define USB_DT_WIRE_ADAPTER 0x21
#define USB_DT_RPIPE 0x22
/* conventional codes for class-specific descriptors */
#define USB_DT_CS_DEVICE 0x21
#define USB_DT_CS_CONFIG 0x22
#define USB_DT_CS_STRING 0x23
#define USB_DT_CS_INTERFACE 0x24
#define USB_DT_CS_ENDPOINT 0x25
/* All standard descriptors have these 2 fields at the beginning */
struct usb_descriptor_header {
u8 bLength;
u8 bDescriptorType;
};
/*-------------------------------------------------------------------------*/
/* USB_DT_DEVICE: Device descriptor */
struct usb_device_descriptor {
u8 bLength;
u8 bDescriptorType;
u16 bcdUSB;
u8 bDeviceClass;
u8 bDeviceSubClass;
u8 bDeviceProtocol;
u8 bMaxPacketSize0;
u16 idVendor;
u16 idProduct;
u16 bcdDevice;
u8 iManufacturer;
u8 iProduct;
u8 iSerialNumber;
u8 bNumConfigurations;
};
#define USB_DT_DEVICE_SIZE 18
/*
* Device and/or Interface Class codes
* as found in bDeviceClass or bInterfaceClass
* and defined by www.usb.org documents
*/
#define USB_CLASS_PER_INTERFACE 0 /* for DeviceClass */
#define USB_CLASS_AUDIO 1
#define USB_CLASS_COMM 2
#define USB_CLASS_HID 3
#define USB_CLASS_PHYSICAL 5
#define USB_CLASS_STILL_IMAGE 6
#define USB_CLASS_PRINTER 7
#define USB_CLASS_MASS_STORAGE 8
#define USB_CLASS_HUB 9
#define USB_CLASS_CDC_DATA 0x0a
#define USB_CLASS_CSCID 0x0b /* chip+ smart card */
#define USB_CLASS_CONTENT_SEC 0x0d /* content security */
#define USB_CLASS_VIDEO 0x0e
#define USB_CLASS_WIRELESS_CONTROLLER 0xe0
#define USB_CLASS_APP_SPEC 0xfe
#define USB_CLASS_VENDOR_SPEC 0xff
/*-------------------------------------------------------------------------*/
/* USB_DT_CONFIG: Configuration descriptor information.
*
* USB_DT_OTHER_SPEED_CONFIG is the same descriptor, except that the
* descriptor type is different. Highspeed-capable devices can look
* different depending on what speed they're currently running. Only
* devices with a USB_DT_DEVICE_QUALIFIER have any OTHER_SPEED_CONFIG
* descriptors.
*/
struct usb_config_descriptor {
u8 bLength;
u8 bDescriptorType;
u16 wTotalLength;
u8 bNumInterfaces;
u8 bConfigurationValue;
u8 iConfiguration;
u8 bmAttributes;
u8 bMaxPower;
};
#define USB_DT_CONFIG_SIZE 9
/* from config descriptor bmAttributes */
#define USB_CONFIG_ATT_ONE (1 << 7) /* must be set */
#define USB_CONFIG_ATT_SELFPOWER (1 << 6) /* self powered */
#define USB_CONFIG_ATT_WAKEUP (1 << 5) /* can wakeup */
#define USB_CONFIG_ATT_BATTERY (1 << 4) /* battery powered */
/*-------------------------------------------------------------------------*/
/* USB_DT_STRING: String descriptor */
struct usb_string_descriptor {
u8 bLength;
u8 bDescriptorType;
u16 wData[1]; /* UTF-16LE encoded */
};
/* note that "string" zero is special, it holds language codes that
* the device supports, not Unicode characters.
*/
/*-------------------------------------------------------------------------*/
/* USB_DT_INTERFACE: Interface descriptor */
struct usb_interface_descriptor {
u8 bLength;
u8 bDescriptorType;
u8 bInterfaceNumber;
u8 bAlternateSetting;
u8 bNumEndpoints;
u8 bInterfaceClass;
u8 bInterfaceSubClass;
u8 bInterfaceProtocol;
u8 iInterface;
};
#define USB_DT_INTERFACE_SIZE 9
/*-------------------------------------------------------------------------*/
/* Endpoint descriptor */
struct usb_endpoint_descriptor {
u8 bLength;
u8 bDescriptorType;
u8 bEndpointAddress;
u8 bmAttributes;
u16 wMaxPacketSize;
u8 bInterval;
u8 bRefresh;
u8 bSynchAddress;
unsigned char *extra; /* Extra descriptors */
int extralen;
};
#define USB_DT_ENDPOINT_SIZE 7
#define USB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */
/*
* Endpoints
*/
#if 0
#define USB_ENDPOINT_NUMBER_MASK 0x0f /* in bEndpointAddress */
#define USB_ENDPOINT_DIR_MASK 0x80
#define USB_ENDPOINT_XFERTYPE_MASK 0x03 /* in bmAttributes */
#define USB_ENDPOINT_XFER_CONTROL 0
#define USB_ENDPOINT_XFER_ISOC 1
#define USB_ENDPOINT_XFER_BULK 2
#define USB_ENDPOINT_XFER_INT 3
#define USB_ENDPOINT_MAX_ADJUSTABLE 0x80
#endif
/*-------------------------------------------------------------------------*/
/* USB_DT_DEVICE_QUALIFIER: Device Qualifier descriptor */
struct usb_qualifier_descriptor {
u8 bLength;
u8 bDescriptorType;
u16 bcdUSB;
u8 bDeviceClass;
u8 bDeviceSubClass;
u8 bDeviceProtocol;
u8 bMaxPacketSize0;
u8 bNumConfigurations;
u8 bRESERVED;
};
/*-------------------------------------------------------------------------*/
/* USB_DT_OTG (from OTG 1.0a supplement) */
struct usb_otg_descriptor {
u8 bLength;
u8 bDescriptorType;
u8 bmAttributes; /* support for HNP, SRP, etc */
};
/* from usb_otg_descriptor.bmAttributes */
#define USB_OTG_SRP (1 << 0)
#define USB_OTG_HNP (1 << 1) /* swap host/device roles */
/*-------------------------------------------------------------------------*/
/* USB_DT_DEBUG: for special highspeed devices, replacing serial console */
struct usb_debug_descriptor {
u8 bLength;
u8 bDescriptorType;
/* bulk endpoints with 8 byte maxpacket */
u8 bDebugInEndpoint;
u8 bDebugOutEndpoint;
};
/*-------------------------------------------------------------------------*/
/* USB_DT_INTERFACE_ASSOCIATION: groups interfaces */
struct usb_interface_assoc_descriptor {
u8 bLength;
u8 bDescriptorType;
u8 bFirstInterface;
u8 bInterfaceCount;
u8 bFunctionClass;
u8 bFunctionSubClass;
u8 bFunctionProtocol;
u8 iFunction;
};
/*-------------------------------------------------------------------------*/
/* USB_DT_SECURITY: group of wireless security descriptors, including
* encryption types available for setting up a CC/association.
*/
struct usb_security_descriptor {
u8 bLength;
u8 bDescriptorType;
u16 wTotalLength;
u8 bNumEncryptionTypes;
};
/*-------------------------------------------------------------------------*/
/* USB_DT_KEY: used with {GET,SET}_SECURITY_DATA; only public keys
* may be retrieved.
*/
struct usb_key_descriptor {
u8 bLength;
u8 bDescriptorType;
u8 tTKID[3];
u8 bReserved;
u8 bKeyData[0];
};
/*-------------------------------------------------------------------------*/
/* USB_DT_ENCRYPTION_TYPE: bundled in DT_SECURITY groups */
struct usb_encryption_descriptor {
u8 bLength;
u8 bDescriptorType;
u8 bEncryptionType;
#define USB_ENC_TYPE_UNSECURE 0
#define USB_ENC_TYPE_WIRED 1 /* non-wireless mode */
#define USB_ENC_TYPE_CCM_1 2 /* aes128/cbc session */
#define USB_ENC_TYPE_RSA_1 3 /* rsa3072/sha1 auth */
u8 bEncryptionValue; /* use in SET_ENCRYPTION */
u8 bAuthKeyIndex;
};
/*-------------------------------------------------------------------------*/
/* USB_DT_BOS: group of wireless capabilities */
struct usb_bos_descriptor {
u8 bLength;
u8 bDescriptorType;
u16 wTotalLength;
u8 bNumDeviceCaps;
};
/*-------------------------------------------------------------------------*/
/* USB_DT_DEVICE_CAPABILITY: grouped with BOS */
struct usb_dev_cap_header {
u8 bLength;
u8 bDescriptorType;
u8 bDevCapabilityType;
};
#define USB_CAP_TYPE_WIRELESS_USB 1
struct usb_wireless_cap_descriptor { /* Ultra Wide Band */
u8 bLength;
u8 bDescriptorType;
u8 bDevCapabilityType;
u8 bmAttributes;
#define USB_WIRELESS_P2P_DRD (1 << 1)
#define USB_WIRELESS_BEACON_MASK (3 << 2)
#define USB_WIRELESS_BEACON_SELF (1 << 2)
#define USB_WIRELESS_BEACON_DIRECTED (2 << 2)
#define USB_WIRELESS_BEACON_NONE (3 << 2)
u16 wPHYRates; /* bit rates, Mbps */
#define USB_WIRELESS_PHY_53 (1 << 0) /* always set */
#define USB_WIRELESS_PHY_80 (1 << 1)
#define USB_WIRELESS_PHY_107 (1 << 2) /* always set */
#define USB_WIRELESS_PHY_160 (1 << 3)
#define USB_WIRELESS_PHY_200 (1 << 4) /* always set */
#define USB_WIRELESS_PHY_320 (1 << 5)
#define USB_WIRELESS_PHY_400 (1 << 6)
#define USB_WIRELESS_PHY_480 (1 << 7)
u8 bmTFITXPowerInfo; /* TFI power levels */
u8 bmFFITXPowerInfo; /* FFI power levels */
u16 bmBandGroup;
u8 bReserved;
};
/*-------------------------------------------------------------------------*/
/* USB_DT_WIRELESS_ENDPOINT_COMP: companion descriptor associated with
* each endpoint descriptor for a wireless device
*/
struct usb_wireless_ep_comp_descriptor {
u8 bLength;
u8 bDescriptorType;
u8 bMaxBurst;
u8 bMaxSequence;
u16 wMaxStreamDelay;
u16 wOverTheAirPacketSize;
u8 bOverTheAirInterval;
u8 bmCompAttributes;
#define USB_ENDPOINT_SWITCH_MASK 0x03 /* in bmCompAttributes */
#define USB_ENDPOINT_SWITCH_NO 0
#define USB_ENDPOINT_SWITCH_SWITCH 1
#define USB_ENDPOINT_SWITCH_SCALE 2
};
/*-------------------------------------------------------------------------*/
/* USB_REQ_SET_HANDSHAKE is a four-way handshake used between a wireless
* host and a device for connection set up, mutual authentication, and
* exchanging short lived session keys. The handshake depends on a CC.
*/
struct usb_handshake {
u8 bMessageNumber;
u8 bStatus;
u8 tTKID[3];
u8 bReserved;
u8 CDID[16];
u8 nonce[16];
u8 MIC[8];
};
/*-------------------------------------------------------------------------*/
/* USB_REQ_SET_CONNECTION modifies or revokes a connection context (CC).
* A CC may also be set up using non-wireless secure channels (including
* wired USB!), and some devices may support CCs with multiple hosts.
*/
struct usb_connection_context {
u8 CHID[16]; /* persistent host id */
u8 CDID[16]; /* device id (unique w/in host context) */
u8 CK[16]; /* connection key */
};
/*-------------------------------------------------------------------------*/
#if 1
enum usb_device_state {
/* NOTATTACHED isn't in the USB spec, and this state acts
* the same as ATTACHED ... but it's clearer this way.
*/
USB_STATE_NOTATTACHED = 0,
/* chapter 9 and authentication (wireless) device states */
USB_STATE_ATTACHED,
USB_STATE_POWERED, /* wired */
USB_STATE_UNAUTHENTICATED, /* auth */
USB_STATE_RECONNECTING, /* auth */
USB_STATE_DEFAULT, /* limited function */
USB_STATE_ADDRESS,
USB_STATE_CONFIGURED, /* most functions */
USB_STATE_SUSPENDED
/* NOTE: there are actually four different SUSPENDED
* states, returning to POWERED, DEFAULT, ADDRESS, or
* CONFIGURED respectively when SOF tokens flow again.
*/
};
#endif
#endif /* __LINUX_USB_CH9_H */
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usb_otg/include/usb_ch9.h
|
C
|
apache-2.0
| 16,060
|
#ifndef _USB_ERRNO_H
#define _USB_ERRNO_H
#define EPERM 1 /* Operation not permitted */
#define ENOENT 2 /* No such file or directory */
#define ESRCH 3 /* No such process */
#define EINTR 4 /* Interrupted system call */
#define EIO 5 /* I/O error */
#define ENXIO 6 /* No such device or address */
#define E2BIG 7 /* Argument list too long */
#define ENOEXEC 8 /* Exec format error */
#define EBADF 9 /* Bad file number */
#define ECHILD 10 /* No child processes */
#define EAGAIN 11 /* Try again */
#define ENOMEM 12 /* Out of memory */
#define EACCES 13 /* Permission denied */
#define EFAULT 14 /* Bad address */
#define ENOTBLK 15 /* Block device required */
#define EBUSY 16 /* Device or resource busy */
#define EEXIST 17 /* File exists */
#define EXDEV 18 /* Cross-device link */
#define ENODEV 19 /* No such device */
#define ENOTDIR 20 /* Not a directory */
#define EISDIR 21 /* Is a directory */
#define EINVAL 22 /* Invalid argument */
#define ENFILE 23 /* File table overflow */
#define EMFILE 24 /* Too many open files */
#define ENOTTY 25 /* Not a typewriter */
#define ETXTBSY 26 /* Text file busy */
#define EFBIG 27 /* File too large */
#define ENOSPC 28 /* No space left on device */
#define ESPIPE 29 /* Illegal seek */
#define EROFS 30 /* Read-only file system */
#define EMLINK 31 /* Too many links */
#define EPIPE 32 /* Broken pipe */
#define EDOM 33 /* Math argument out of domain of func */
#define ERANGE 34 /* Math result not representable */
#define EDEADLK 35 /* Resource deadlock would occur */
#define ENAMETOOLONG 36 /* File name too long */
#define ENOLCK 37 /* No record locks available */
#define ENOSYS 38 /* Function not implemented */
#define ENOTEMPTY 39 /* Directory not empty */
#define ELOOP 40 /* Too many symbolic links encountered */
#define EWOULDBLOCK EAGAIN /* Operation would block */
#define ENOMSG 42 /* No message of desired type */
#define EIDRM 43 /* Identifier removed */
#define ECHRNG 44 /* Channel number out of range */
#define EL2NSYNC 45 /* Level 2 not synchronized */
#define EL3HLT 46 /* Level 3 halted */
#define EL3RST 47 /* Level 3 reset */
#define ELNRNG 48 /* Link number out of range */
#define EUNATCH 49 /* Protocol driver not attached */
#define ENOCSI 50 /* No CSI structure available */
#define EL2HLT 51 /* Level 2 halted */
#define EBADE 52 /* Invalid exchange */
#define EBADR 53 /* Invalid request descriptor */
#define EXFULL 54 /* Exchange full */
#define ENOANO 55 /* No anode */
#define EBADRQC 56 /* Invalid request code */
#define EBADSLT 57 /* Invalid slot */
#define EDEADLOCK EDEADLK
#define EBFONT 59 /* Bad font file format */
#define ENOSTR 60 /* Device not a stream */
#define ENODATA 61 /* No data available */
#define ETIME 62 /* Timer expired */
#define ENOSR 63 /* Out of streams resources */
#define ENONET 64 /* Machine is not on the network */
#define ENOPKG 65 /* Package not installed */
#define EREMOTE 66 /* Object is remote */
#define ENOLINK 67 /* Link has been severed */
#define EADV 68 /* Advertise error */
#define ESRMNT 69 /* Srmount error */
#define ECOMM 70 /* Communication error on send */
#define EPROTO 71 /* Protocol error */
#define EMULTIHOP 72 /* Multihop attempted */
#define EDOTDOT 73 /* RFS specific error */
#define EBADMSG 74 /* Not a data message */
#define EOVERFLOW 75 /* Value too large for defined data type */
#define ENOTUNIQ 76 /* Name not unique on network */
#define EBADFD 77 /* File descriptor in bad state */
#define EREMCHG 78 /* Remote address changed */
#define ELIBACC 79 /* Can not access a needed shared library */
#define ELIBBAD 80 /* Accessing a corrupted shared library */
#define ELIBSCN 81 /* .lib section in a.out corrupted */
#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
#define ELIBEXEC 83 /* Cannot exec a shared library directly */
#define EILSEQ 84 /* Illegal byte sequence */
#define ERESTART 85 /* Interrupted system call should be restarted */
#define ESTRPIPE 86 /* Streams pipe error */
#define EUSERS 87 /* Too many users */
#define ENOTSOCK 88 /* Socket operation on non-socket */
#define EDESTADDRREQ 89 /* Destination address required */
#define EMSGSIZE 90 /* Message too long */
#define EPROTOTYPE 91 /* Protocol wrong type for socket */
#define ENOPROTOOPT 92 /* Protocol not available */
#define EPROTONOSUPPORT 93 /* Protocol not supported */
#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
#define EPFNOSUPPORT 96 /* Protocol family not supported */
#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
#define EADDRINUSE 98 /* Address already in use */
#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
#define ENETDOWN 100 /* Network is down */
#define ENETUNREACH 101 /* Network is unreachable */
#define ENETRESET 102 /* Network dropped connection because of reset */
#define ECONNABORTED 103 /* Software caused connection abort */
#define ECONNRESET 104 /* Connection reset by peer */
#define ENOBUFS 105 /* No buffer space available */
#define EISCONN 106 /* Transport endpoint is already connected */
#define ENOTCONN 107 /* Transport endpoint is not connected */
#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
#define ETOOMANYREFS 109 /* Too many references: cannot splice */
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */
#define EHOSTUNREACH 113 /* No route to host */
#define EALREADY 114 /* Operation already in progress */
#define EINPROGRESS 115 /* Operation now in progress */
#define ESTALE 116 /* Stale NFS file handle */
#define EUCLEAN 117 /* Structure needs cleaning */
#define ENOTNAM 118 /* Not a XENIX named type file */
#define ENAVAIL 119 /* No XENIX semaphores available */
#define EISNAM 120 /* Is a named type file */
#define EREMOTEIO 121 /* Remote I/O error */
#define EDQUOT 122 /* Quota exceeded */
#define ENOMEDIUM 123 /* No medium found */
#define EMEDIUMTYPE 124 /* Wrong medium type */
#define ECANCELED 125 /* Operation Canceled */
#define ENOKEY 126 /* Required key not available */
#define EKEYEXPIRED 127 /* Key has expired */
#define EKEYREVOKED 128 /* Key has been revoked */
#define EKEYREJECTED 129 /* Key was rejected by service */
/* for robust mutexes */
#define EOWNERDEAD 130 /* Owner died */
#define ENOTRECOVERABLE 131 /* State not recoverable */
#define ERFKILL 132 /* Operation not possible due to RF-kill */
#define EHWPOISON 133 /* Memory page has hardware error */
#define ENOTSUPP 524 /* Operation is not supported */
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usb_otg/include/usb_errno.h
|
C
|
apache-2.0
| 6,737
|
#ifndef __LINUX_USB_ULINKER_H
#define __LINUX_USB_ULINKER_H
//#include "linux/autoconf.h"
//#ifndef CONFIG_RTL_ULINKER_CUSTOMIZATION
#if 1//ModifiedByJD
#define ULINKER_ETHER_VID 0x0BDA
#define ULINKER_ETHER_PID 0x8195
#define ULINKER_MANUFACTURER "Realtek Semicoonductor Corp."
#define ULINKER_WINTOOLS_GUID "1CACC490-055C-4035-A026-1DAB0BDA8196"
#define ULINKER_WINTOOLS_DISPLAY_NAME "Realtek RTL8196EU Universal Linker"
#define ULINKER_WINTOOLS_CONTACT "nicfae@realtek.com.tw"
#define ULINKER_WINTOOLS_DISPLAY_VERSION "v1.0.0.0"
#define ULINKER_WINTOOLS_HELP_LINK "http://www.realtek.com.tw"
#define ULINKER_WINTOOLS_PUBLISHER ULINKER_MANUFACTURER
#define ULINKER_WINTOOLS_TARGET_DIR ULINKER_WINTOOLS_DISPLAY_NAME
#else
#define ULINKER_ETHER_VID CONFIG_RTL_ULINKER_VID
#define ULINKER_ETHER_PID CONFIG_RTL_ULINKER_PID
#define ULINKER_STORAGE_VID CONFIG_RTL_ULINKER_VID_S
#define ULINKER_STORAGE_PID CONFIG_RTL_ULINKER_PID_S
#define ULINKER_MANUFACTURER CONFIG_RTL_ULINKER_MANUFACTURE
#define ULINKER_WINTOOLS_GUID CONFIG_RTL_ULINKER_WINTOOLS_GUID
#define ULINKER_WINTOOLS_DISPLAY_NAME CONFIG_RTL_ULINKER_WINTOOLS_DISPLAY_NAME
#define ULINKER_WINTOOLS_CONTACT CONFIG_RTL_ULINKER_WINTOOLS_CONTACT
#define ULINKER_WINTOOLS_DISPLAY_VERSION CONFIG_RTL_ULINKER_WINTOOLS_DISPLAY_VERSION
#define ULINKER_WINTOOLS_HELP_LINK CONFIG_RTL_ULINKER_WINTOOLS_HELP_LINK
#define ULINKER_WINTOOLS_PUBLISHER ULINKER_MANUFACTURER
#define ULINKER_WINTOOLS_TARGET_DIR ULINKER_WINTOOLS_DISPLAY_NAME
#endif
//------------------------------------------------
// if you don't have a specific PID for storage, don't change following define of storage mode.
//
// begin: don't change
#ifndef ULINKER_STORAGE_VID
#define ULINKER_STORAGE_VID 0x0BDA
#define ULINKER_STORAGE_PID 0x8197
#endif
#define ULINKER_STORAGE_VID_STR "USB Ether "
#define ULINKER_STORAGE_PID_DISK_STR "Driver DISC"
#define ULINKER_STORAGE_PID_CDROM_STR "Driver CDROM"
#define ULINKER_WINTOOLS_DRIVER_PATH "Driver"
// end: don't change
//------------------------------------------------
//----------------------------------------------------------------------
#if defined(CONFIG_RTL_ULINKER)
#define ULINKER_DEVINIT
#define ULINKER_DEVINITDATA
#define ULINKER_DEVINITCONST
#define ULINKER_DEVEXIT
#define ULINKER_DEVEXITDATA
#define ULINKER_DEVEXITCONST
#else
#define ULINKER_DEVINIT __devinit
#define ULINKER_DEVINITDATA __devinitdata
#define ULINKER_DEVINITCONST __devinitconst
#define ULINKER_DEVEXIT __devexit
#define ULINKER_DEVEXITDATA __devexitdata
#define ULINKER_DEVEXITCONST __devexitconst
#endif
#endif /* __LINUX_USB_ULINKER_H */
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usb_otg/include/usb_ulinker.h
|
C
|
apache-2.0
| 2,750
|
/**
******************************************************************************
* @file rtl8721d_bootcfg.c
* @author
* @version V1.0.0
* @date 2018-09-12
* @brief This file provides firmware functions to manage the following
* functionalities:
* - memory layout config
******************************************************************************
* @attention
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*
* Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved.
******************************************************************************
*/
#include "ameba_soc.h"
/*
* @brif MMU Configuration.
* There are 8 MMU entries totally. Entry 0 & Entry 1 are already used by OTA, Entry 2~7 can be used by Users.
*/
BOOT_RAM_DATA_SECTION
MMU_ConfDef Flash_MMU_Config[] = {
/*VAddrStart, VAddrEnd, PAddrStart, PAddrEnd*/
{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, //Entry 2
{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, //Entry 3
{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, //Entry 4
{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, //Entry 5
{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, //Entry 6
{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, //Entry 7
{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF},
};
/*
* @brif OTA start address. Because KM0 & KM4 IMG2 are combined, users only need to set the start address
* of KM0 IMG2.
*/
BOOT_RAM_DATA_SECTION
u32 OTA_Region[2] = {
0x08006000, /* OTA1 region start address */
0x08106000, /* OTA2 region start address */
};
/*
* @brif RSIP Mask Configuration.
* There are 4 RSIP mask entries totally. Entry 0 is already used by System Data, Entry 3 is reserved by Realtek.
* Only Entry 1 & Entry 2 can be used by Users.
* MaskAddr: start address for RSIP Mask, should be 4KB aligned
* MaskSize: size of the mask area, unit is 4KB
*/
BOOT_RAM_DATA_SECTION
RSIP_MaskDef RSIP_Mask_Config[] = {
/*MaskAddr, MaskSize*/
{0x08001000, 3}, //Entry 0: 4K system data & 4K backup & DPK
/* customer can set here */
{0xFFFFFFFF, 0xFFFF}, //Entry 1: can be used by users
{0xFFFFFFFF, 0xFFFF}, //Entry 2: can be used by users
{0xFFFFFFFF, 0xFFFF}, //Entry 3: Reserved by Realtek. If RDP is not used, this entry can be used by users.
/* End */
{0xFFFFFFFF, 0xFFFF},
};
/**
* @brif GPIO force OTA1 as image2. 0xFF means force OTA1 trigger is disabled.
* BIT[7]: active level, 0 is low level active, 1 is high level active,
* BIT[6:5]: port, 0 is PORT_A, 1 is PORT_B
* BIT[4:0]: pin num 0~31
*/
BOOT_RAM_DATA_SECTION
u8 Force_OTA1_GPIO = 0xFF;
/**
* @brif boot log enable or disable.
* FALSE: disable
* TRUE: enable
*/
BOOT_RAM_DATA_SECTION
u8 Boot_Log_En = FALSE;
/**
* @brif Firmware verify callback handler.
* If users need to verify checksum/hash for image2, implement the function and assign the address
* to this function pointer.
* @param None
* @retval 1: Firmware verify successfully, 0: verify failed
*/
BOOT_RAM_DATA_SECTION
FuncPtr FwCheckCallback = NULL;
/**
* @brif Firmware select hook.
* If users need to implement own OTA select method, implement the function and assign the address
* to this function pointer.
* @param None
* @retval 0: both firmwares are invalid, select none, 1: boot from OTA1, 2: boot from OTA2
*/
BOOT_RAM_DATA_SECTION
FuncPtr OTASelectHook = NULL;
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721d_bootcfg.c
|
C
|
apache-2.0
| 3,511
|
/**
******************************************************************************
* @file rtl8721d_ipccfg.c
* @author
* @version V1.0.0
* @date 2016-05-17
* @brief This file provides configurations for KM0 or KM4 IPC init
******************************************************************************
* @attention
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*
* Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved.
******************************************************************************
*/
#include "ameba_soc.h"
#if defined (ARM_CORE_CM4)
const IPC_INIT_TABLE ipc_init_config[] =
{
//USER_MSG_TYPE IRQFUNC IRQDATA
{IPC_USER_DATA, shell_switch_ipc_int, (VOID*) NULL},//channel 0: IPC_INT_CHAN_SHELL_SWITCH
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 1: IPC_INT_CHAN_WIFI_FW
{IPC_USER_DATA, FLASH_Write_IPC_Int, (VOID*) NULL},//channel 2: IPC_INT_CHAN_FLASHPG_REQ
{IPC_USER_POINT, NULL, (VOID*) NULL},//channel 3: IPC_INT_KM4_TICKLESS_INDICATION
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 4: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 5: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 6: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 7: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 8: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 9: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 10: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 11: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 12: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 13: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 14: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 15: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 16: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 17: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 18: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 19: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 20: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 21: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 22: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 23: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 24: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 25: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 26: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 27: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 28: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 29: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 30: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 31: Reserved for Customer use
{0xFFFFFFFF, OFF, OFF}, /* Table end */
};
#else
#if CONFIG_WIFI_FW_EN
extern void driver_fw_flow_ipc_int(VOID *Data, u32 IrqStatus, u32 ChanNum);
#define fw_flow_ipc_int driver_fw_flow_ipc_int
#else
#define fw_flow_ipc_int NULL
#endif
const IPC_INIT_TABLE ipc_init_config[] =
{
//USER_MSG_TYPE IRQFUNC IRQDATA
{IPC_USER_DATA, shell_switch_ipc_int, (VOID*) NULL},//channel 0: IPC_INT_CHAN_SHELL_SWITCH
{IPC_USER_DATA, fw_flow_ipc_int, (VOID*) IPCM4_DEV},//channel 1: IPC_INT_CHAN_WIFI_FW
{IPC_USER_DATA, FLASH_Write_IPC_Int, (VOID*) NULL},//channel 2: IPC_INT_CHAN_FLASHPG_REQ
{IPC_USER_POINT, km4_tickless_ipc_int, (VOID*) NULL},//channel 3: IPC_INT_KM4_TICKLESS_INDICATION
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 4: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 5: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 6: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 7: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 8: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 9: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 10: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 11: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 12: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 13: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 14: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 15: Reserved for Realtek use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 16: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 17: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 18: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 19: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 20: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 21: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 22: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 23: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 24: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 25: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 26: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 27: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 28: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 29: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 30: Reserved for Customer use
{IPC_USER_DATA, NULL, (VOID*) NULL},//channel 31: Reserved for Customer use
{0xFFFFFFFF, OFF, OFF}, /* Table end */
};
#endif
/******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721d_ipccfg.c
|
C
|
apache-2.0
| 6,616
|
/**
******************************************************************************
* @file rtl8721d_wificfg.c
* @author
* @version V1.0.0
* @date 2016-05-17
* @brief This file provides firmware functions to manage the wifi configration
******************************************************************************
* @attention
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*
* Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved.
******************************************************************************
*/
#include "ameba_soc.h"
WIFICFG_TypeDef wifi_config =
{
.wifi_app_ctrl_tdma = FALSE,
.wifi_ultra_low_power = FALSE, /* default is FALSE */
.km4_cache_enable = TRUE, /* default is TRUE */
.km0_dslp_force_reinit = TRUE, /*default is TURE*/
};
/******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721d_wificfg.c
|
C
|
apache-2.0
| 1,009
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "ameba_soc.h"
BOOT_RAM_DATA_SECTION
const TZ_CFG_TypeDef tz_config[]=
{
// Start End NSC
{0x40000000, 0x50000000-1, 0}, /* entry0: Peripherals NS */
{0x1010A000, 0x101D4000-1, 0}, /* entry1: IROM & DROM NS */
{0x00080000, (u32)__ram_image3_start__ -1,0}, /* entry2: KM0 SRAM, Retention SRAM, PSRAM & FLASH & SRAM NS */
{(u32)__ram_image3_end__, 0x1007C000-1, 1}, /* entry3: NSC 4K */
{0x100E0000, 0x10100000-1, 0}, /* entry4: BT/WIFI Extention SRAM */
{0xFFFFFFFF, 0xFFFFFFFF, 0}, /* entry5: TODO */
{0xFFFFFFFF, 0xFFFFFFFF, 0}, /* entry6: TODO */
{0xFFFFFFFF, 0xFFFFFFFF, 0}, /* entry7: TODO */
{0xFFFFFFFF, 0xFFFFFFFF, 0},
};
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721dhp_boot_trustzonecfg.c
|
C
|
apache-2.0
| 941
|
/**
******************************************************************************
* @file rtl8721dlp_intfcfg.c
* @author
* @version V1.0.0
* @date 2016-05-17
* @brief This file provides firmware functions to manage the following
* functionalities:
* - uart mbed function config
******************************************************************************
* @attention
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*
* Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved.
******************************************************************************
*/
#include "ameba_soc.h"
#include "autoconf.h"
PSRAMCFG_TypeDef psram_dev_config = {
#if defined(CONFIG_REPEATER) && CONFIG_REPEATER
.psram_dev_enable = TRUE, //enable psram
.psram_dev_cal_enable = TRUE, //enable psram calibration function
.psram_dev_retention = TRUE, //enable psram retention
#else
.psram_dev_enable = TRUE, //enable psram
.psram_dev_cal_enable = TRUE, //enable psram calibration function
.psram_dev_retention = TRUE, //enable psram retention
#endif
};
SDIOHCFG_TypeDef sdioh_config = {
.sdioh_bus_speed = SD_SPEED_HS, //SD_SPEED_DS or SD_SPEED_HS
.sdioh_bus_width = SDIOH_BUS_WIDTH_4BIT, //SDIOH_BUS_WIDTH_1BIT or SDIOH_BUS_WIDTH_4BIT
.sdioh_cd_pin = _PB_25, //_PB_25/_PA_6/_PNC
.sdioh_wp_pin = _PNC, //_PB_24/_PA_5/_PNC
};
#if defined(CONFIG_FTL_ENABLED)
#define FTL_MEM_CUSTEM 1
#if FTL_MEM_CUSTEM == 0
#error "You should allocate flash sectors to for FTL physical map as following, then set FTL_MEM_CUSTEM to 1. For more information, Please refer to Application Note, FTL chapter. "
#else
#if 0 /* Move ftl configuration to board\xxx\config\partition_conf.c */
const u8 ftl_phy_page_num = 3; /* The number of physical map pages, default is 3*/
const u32 ftl_phy_page_start_addr = 0x00102000; /* The start offset of flash pages which is allocated to FTL physical map.
Users should modify it according to their own memory layout!! */
#endif
#endif
#endif
/******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721dhp_intfcfg.c
|
C
|
apache-2.0
| 2,271
|
/**
******************************************************************************
* @file rtl8721dlp_flashcfg.c
* @author
* @version V1.0.0
* @date 2018-09-12
* @brief This file provides firmware functions to manage the following
* functionalities:
* - flash function config
******************************************************************************
* @attention
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*
* Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved.
******************************************************************************
*/
#include "ameba_soc.h"
void flash_init_userdef(void);
/**
* @brif Indicate the flash baudrate. It can be one of the following value:
* 0xFFFF: 80MHz
* 0x7FFF: 100MHz
* 0x3FFF: 67MHz
* 0x1FFF: 57MHz
* 0x0FFF: 50MHz
*/
const u16 Flash_Speed = 0xFFFF;
/**
* @brif Indicate the flash read I/O mode. It can be one of the following value:
* 0xFFFF: Read quad IO, Address & Data 4 bits mode
* 0x7FFF: Read quad O, Just data 4 bits mode
* 0x3FFF: Read dual IO, Address & Data 2 bits mode
* 0x1FFF: Read dual O, Just data 2 bits mode
* 0x0FFF: 1 bit mode
* @note If the configured read mode is not supported, other modes would be searched until find the appropriate mode.
*/
const u16 Flash_ReadMode = 0xFFFF;
/**
* @brif Flash_AVL maintains the flash IC supported by SDK.
* If users want to adpot new flash, add item in the following AVL.
* Note that, if new flash can be classfied as one of the Realtek-defined categories according to Classification SPEC,
* filling in the defined class index is necessary. Otherwise, FlashClassUser can be used to indicate new class.
*/
const FlashInfo_TypeDef Flash_AVL[] = {
/*flash_id, flash_id_mask, flash_class, status_mask, FlashInitHandler */
/* case1: Realtek defined class, any modification is not allowed */
{0xEF, 0x000000FF, FlashClass1, 0x000043FC, NULL}, /* Winbond: MANUFACTURER_ID_WINBOND */
{0xA1, 0x000000FF, FlashClass1, 0x0000FFFC, NULL}, /* Fudan Micro: MANUFACTURER_ID_FM */
{0x0B, 0x000000FF, FlashClass1, 0x000043FC, NULL}, /* XTX */
{0x0E, 0x000000FF, FlashClass1, 0x000043FC, NULL}, /* XTX(FT) */
{0xC8, 0x000000FF, FlashClass2, 0x000043FC, NULL}, /* GD normal: MANUFACTURER_ID_GD */
{0x28C2, 0x0000FFFF, FlashClass6, 0x000200FC, NULL}, /* MXIC wide-range VCC: MANUFACTURER_ID_MXIC */
{0xC2, 0x000000FF, FlashClass3, 0x000000FC, NULL}, /* MXIC normal: MANUFACTURER_ID_BOHONG */
{0x68, 0x000000FF, FlashClass3, 0x000000FC, NULL}, /* Hua Hong */
{0x51, 0x000000FF, FlashClass3, 0x000000FC, NULL}, /* GD MD serial */
{0x1C, 0x000000FF, FlashClass4, 0x000000FC, NULL}, /* ESMT: MANUFACTURER_ID_EON */
{0x20, 0x000000FF, FlashClass5, 0x000000FC, NULL}, /* Microm: MANUFACTURER_ID_MICRON */
/* case2: new flash, ID is not included in case1 list, but specification is compatible with FlashClass1~FlashClass6 */
//{0xXX, 0x0000XXXX, FlashClassX, 0x0000XXXX, NULL},
/* case3: new flash, ID is not included in case1 list, and specification is not compatible with FlashClass1~FlashClass6 */
{0x00, 0x000000FF, FlashClassUser, 0xFFFFFFFF, &flash_init_userdef},
/* End */
{0xFF, 0xFFFFFFFF, FlashClassNone, 0xFFFFFFFF, NULL},
};
/**
* @brief To adopt user defined class, need to initialize the parameters in the function below
* with its default values according to flash Spec, and add additional config code if need.
* @param none.
* @retval none
* @note The following parameter setting is an example of MXIC flash. For users reference.
*/
void flash_init_userdef(void)
{
FLASH_InitTypeDef* FLASH_InitStruct = &flash_init_para;
/*1. Initialize CMD parameters */
FLASH_InitStruct->FLASH_Id = FLASH_ID_MXIC;
/*1.1 status bit define */
FLASH_InitStruct->FLASH_QuadEn_bit = BIT(6);
FLASH_InitStruct->FLASH_Busy_bit = BIT(0);
FLASH_InitStruct->FLASH_WLE_bit = BIT(1);
FLASH_InitStruct->FLASH_Status2_exist = 0;
/*1.2 dummy cycle */
FLASH_InitStruct->FLASH_rd_dummy_cyle[0] = 0;
FLASH_InitStruct->FLASH_rd_dummy_cyle[1] = 0x04;
FLASH_InitStruct->FLASH_rd_dummy_cyle[2] = 0x06;
/*1.3 set 2bit mode cmd */
FLASH_InitStruct->FLASH_rd_dual_io = 0xBB;
FLASH_InitStruct->FLASH_rd_dual_o = 0x3B;
/*1.4 set 4bit mode cmd */
FLASH_InitStruct->FLASH_rd_quad_io = 0xEB;
FLASH_InitStruct->FLASH_rd_quad_o = 0x6B;
/*1.5 other flash commnad set */
FLASH_InitStruct->FLASH_cmd_wr_en = 0x06;
FLASH_InitStruct->FLASH_cmd_rd_id = 0x9F;
FLASH_InitStruct->FLASH_cmd_rd_status = 0x05;
FLASH_InitStruct->FLASH_cmd_rd_status2 = 0;
FLASH_InitStruct->FLASH_cmd_wr_status = 0x01;
FLASH_InitStruct->FLASH_cmd_wr_status2 = 0;
FLASH_InitStruct->FLASH_cmd_chip_e = 0x60;
FLASH_InitStruct->FLASH_cmd_block_e = 0xD8;
FLASH_InitStruct->FLASH_cmd_sector_e = 0x20;
FLASH_InitStruct->FLASH_cmd_pwdn_release = 0xAB;
FLASH_InitStruct->FLASH_cmd_pwdn = 0xB9;
/*2. Add other configuration code here if needed for flash */
//TODO
}
/******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721dlp_flashcfg.c
|
C
|
apache-2.0
| 5,234
|
/**
******************************************************************************
* @file rtl8721dlp_intfcfg.c
* @author
* @version V1.0.0
* @date 2016-05-17
* @brief This file provides firmware functions to manage the following
* functionalities:
* - uart mbed function config
******************************************************************************
* @attention
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*
* Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved.
******************************************************************************
*/
#include "ameba_soc.h"
UARTCFG_TypeDef uart_config[2]=
{
/* UART0 */
{
.LOW_POWER_RX_ENABLE = DISABLE, /*Enable low power RX*/
},
/* UART1 */
{
.LOW_POWER_RX_ENABLE = DISABLE,
},
};
/******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721dlp_intfcfg.c
|
C
|
apache-2.0
| 1,024
|
/******************************************************************************
*
* Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved.
*
* 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 License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/**
******************************************************************************
* @file rtl8721dlp_pinmapcfg.c
* @author
* @version V1.0.0
* @date 2016-05-17
* @brief This file provides firmware functions to manage the following
* functionalities of pin control:
* - pinmux
* - active pad pull up & pull down
* - sleep pad pull up & pull down
******************************************************************************
*/
#include "ameba_soc.h"
/* KM0 without KM4 ON: 4.30mA */
/* KM0 CG without KM4 ON: 135uA */
/* DSLP(RTC, KEYSCAN OFF, TOUCH OFF): 2uA under power supply, but 7uA under current meter */
/* DSLP(RTC+KEYSCAN, TOUCH OFF): 3uA under power supply */
/* DSLP(RTC+KEYSCAN+TOUCH): 3.9uA under power supply (peak is 3.7mA) */
const PMAP_TypeDef pmap_func[]=
{
// Pin Name Func PU/PD Slp PU/PD DSlp PU/PD LowPowerPin
{_PA_0, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_1, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_2, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_3, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_4, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_5, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_6, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_7, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //UART_LOG_TXD
{_PA_8, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //UART_LOG_RXD
{_PA_9, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_10, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_11, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_12, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_13, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_14, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_15, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_16, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_17, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_18, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_19, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_20, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_21, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_22, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_23, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_24, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_25, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_26, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan
{_PA_27, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SWD_DATA or normal_mode_sel
{_PA_28, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_29, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_30, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_31, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_0, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_1, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_2, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_3, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SWD_CLK
{_PB_4, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //Touch0
{_PB_5, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //Touch1
{_PB_6, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //Touch2
//{_PB_6, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE},
{_PB_7, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //Touch3
{_PB_8, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_9, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_10, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_11, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_12, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SPI_DATA3
{_PB_13, GPIO_PuPd_UP, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, FALSE}, //SPI_CLK
{_PB_14, GPIO_PuPd_UP, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, FALSE}, //SPI_DATA0
{_PB_15, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SPI_DATA2
{_PB_16, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SPI_CS
{_PB_17, GPIO_PuPd_UP, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, FALSE}, //SPI_DATA1
{_PB_18, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_19, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_20, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_21, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_22, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //IR pin should no-pull when you use IR
//{_PB_22, GPIO_PuPd_NOPULL, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE},
{_PB_23, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_24, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_25, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_26, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, // fix antanna diversity can not use issue
{_PB_27, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_28, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_29, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_30, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_31, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PNC, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //table end
};
/******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721dlp_pinmapcfg.c
|
C
|
apache-2.0
| 6,901
|
/******************************************************************************
*
* Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved.
*
* 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 License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/**
******************************************************************************
* @file rtl8721dlp_pinmapcfg.c
* @author
* @version V1.0.0
* @date 2016-05-17
* @brief This file provides firmware functions to manage the following
* functionalities of pin control:
* - pinmux
* - active pad pull up & pull down
* - sleep pad pull up & pull down
******************************************************************************
*/
#include "ameba_soc.h"
/* KM0 without KM4 ON: 4.30mA */
/* KM0 CG without KM4 ON: 135uA */
/* DSLP(RTC, KEYSCAN OFF, TOUCH OFF): 2uA under power supply, but 7uA under current meter */
/* DSLP(RTC+KEYSCAN, TOUCH OFF): 3uA under power supply */
/* DSLP(RTC+KEYSCAN+TOUCH): 3.9uA under power supply (peak is 3.7mA) */
const PMAP_TypeDef pmap_func[]=
{
// Pin Name Func PU/PD Slp PU/PD DSlp PU/PD LowPowerPin
{_PA_0, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_1, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_2, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_3, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_4, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_5, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_6, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_7, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //UART_LOG_TXD
{_PA_8, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //UART_LOG_RXD
{_PA_9, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_10, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_11, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_12, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, row0
{_PA_13, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, row1
{_PA_14, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, row2
{_PA_15, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, row3
{_PA_16, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, row4
{_PA_17, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, col3
{_PA_18, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan,col4
{_PA_19, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, col2
{_PA_20, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, col7
{_PA_21, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, row7
{_PA_22, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_23, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //HS USI UART
{_PA_24, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //HS USI UART
{_PA_25, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, col1
{_PA_26, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, TRUE}, //keyscan, col0
{_PA_27, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SWD_DATA or normal_mode_sel
{_PA_28, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_DOWN, FALSE}, //
{_PA_29, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PA_30, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //sps_sel
{_PA_31, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_0, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_1, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //ADC
{_PB_2, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //ADC
{_PB_3, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SWD_CLK
{_PB_4, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //Touch0
{_PB_5, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //Touch1
{_PB_6, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //Touch2
{_PB_6, GPIO_PuPd_NOPULL, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //dmic power
{_PB_7, GPIO_PuPd_NOPULL, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //Touch3
{_PB_8, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_9, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_10, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_11, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_12, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SPI_DATA3
{_PB_13, GPIO_PuPd_UP, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, FALSE}, //SPI_CLK
{_PB_14, GPIO_PuPd_UP, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, FALSE}, //SPI_DATA0
{_PB_15, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SPI_DATA2
{_PB_16, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //SPI_CS
{_PB_17, GPIO_PuPd_UP, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, FALSE}, //SPI_DATA1
{_PB_18, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_19, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_20, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_21, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
//{_PB_22, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //IR pin should no-pull when you use IR
{_PB_22, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //flash power mos control, ext pull low already
{_PB_23, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_24, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_25, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_26, GPIO_PuPd_NOPULL, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, // vbat_en, ext pul high already
{_PB_27, GPIO_PuPd_UP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_28, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_29, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_30, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PB_31, GPIO_PuPd_DOWN, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //
{_PNC, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, GPIO_PuPd_KEEP, FALSE}, //table end
};
/******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/fwlib/usrcfg/rtl8721dlp_pinmapcfg_qfn88_evb_v1.c
|
C
|
apache-2.0
| 7,078
|
/**
******************************************************************************
* @file rtl8721d_ota.c
* @author
* @version V1.0.0
* @date 2016-12-19
* @brief This file contains the code which is used to update firmware over the air(OTA) in local area network
*
* @verbatim
*
* ===================================================================
* How to use the local OTA upgrade code
* ===================================================================
* 1. Firstly, read the OTA related documents to know about how the code to realize updating firmware
* over the air(OTA), and some protocol included in it.
*
* 2. Read the source code and APIs in this file.
*
* 3. Porting this code in this file to the specified cloud platform according to the upgrade flow and parameters of
* the specified cloud service providers
*
* 4. Test the code after porting on the specified cloud platform.
*
* 5. Generate the release verision that will run.
*
* ===================================================================
* the basic flow of the local ota upgrade code
* ===================================================================
* (1) Connects to server
*
* (2) Receive newer firmware file header from server
*
* (3) Parse firmware file header and get the target OTA image header
*
* (4) Erase flash space for new firmware
*
* (5) Download new firmware from server and write it to flash
*
* (6) Verify checksum and update signature
*
* (7) OTA upgrade successfully, restart device
* @endverbatim
*
******************************************************************************
* @attention
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*
* Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved.
******************************************************************************
*/
#include <stdlib.h>
#include <string.h>
#include <FreeRTOS.h>
//#include <task.h>
#include <lwip/sockets.h>
//#include <sys.h>
#include <device_lock.h>
#include "ameba_soc.h"
#include "lwip/netdb.h"
#include "osdep_service.h"
//sys_thread_t TaskOTA = NULL;
void rtc_backup_timeinfo(void);
#if (SERVER_TYPE == SERVER_LOCAL)
typedef struct
{
uint32_t ip_addr;
uint16_t port;
}update_cfg_local_t;
const u32 IMG_ADDR[MAX_IMG_NUM][2] = {
{LS_IMG2_OTA1_ADDR, LS_IMG2_OTA2_ADDR},
};
/**
* @brief Allocate memory from heap.
* @param size: the number of bytes to be allocated.
* @retval The pointer to the allocated memory.
*/
void* ota_update_malloc(unsigned int size)
{
return rtw_malloc(size);
}
/**
* @brief Deallocate memory from heap.
* @param buf: the pointer to the memory to be deallocated.
* @retval none
*/
void ota_update_free(void *buf)
{
rtw_free(buf);
}
/**
* @brief Reset CPU
* @param none
* @retval none
*/
void ota_platform_reset(void)
{
WDG_InitTypeDef WDG_InitStruct;
u32 CountProcess;
u32 DivFacProcess;
rtw_msleep_os(100);
/* CPU reset: Cortex-M3 SCB->AIRCR*/
//NVIC_SystemReset();
#if defined(CONFIG_MBED_API_EN) && CONFIG_MBED_API_EN
rtc_backup_timeinfo();
#endif
WDG_Scalar(50, &CountProcess, &DivFacProcess);
WDG_InitStruct.CountProcess = CountProcess;
WDG_InitStruct.DivFacProcess = DivFacProcess;
WDG_Init(&WDG_InitStruct);
WDG_Cmd(ENABLE);
}
/**
* @brief Read a stream of data from specified address in user mode
* @param obj: Flash object define in application software.
* @param address: Specifies the starting address to read from.
* @param len: Specifies the length of the data to read.
* @param data: Specified the address to save the readback data.
* @retval status: Success:1 or Failure: Others.
* @note SPIC user mode is used because this mode can bypass RSIP(include OTF and MMU).
* User mode can read original data from physical address without decrypting, which is
* useful when calculate checksum.
*/
IMAGE2_RAM_TEXT_SECTION
int ota_readstream_user(u32 address, u32 len, u8 * data)
{
assert_param(data != NULL);
u32 offset_to_align;
u32 i;
u32 read_word;
u8 *ptr;
u8 *pbuf;
FLASH_Write_Lock();
offset_to_align = address & 0x03;
pbuf = data;
if (offset_to_align != 0) {
/* the start address is not 4-bytes aligned */
FLASH_RxData(0, address - offset_to_align, 4, (u8*)&read_word);
ptr = (u8*)&read_word + offset_to_align;
offset_to_align = 4 - offset_to_align;
for (i=0;i<offset_to_align;i++) {
*pbuf = *(ptr+i);
pbuf++;
len--;
if (len == 0) {
break;
}
}
}
/* address = next 4-bytes aligned */
address = (((address-1) >> 2) + 1) << 2;
ptr = (u8*)&read_word;
if ((u32)pbuf & 0x03) {
while (len >= 4) {
FLASH_RxData(0, address, 4, (u8*)&read_word);
for (i=0;i<4;i++) {
*pbuf = *(ptr+i);
pbuf++;
}
address += 4;
len -= 4;
}
} else {
while (len >= 4) {
FLASH_RxData(0, address, 4, pbuf);
pbuf += 4;
address += 4;
len -= 4;
}
}
if (len > 0) {
FLASH_RxData(0, address, 4, (u8*)&read_word);
for (i=0;i<len;i++) {
*pbuf = *(ptr+i);
pbuf++;
}
}
FLASH_Write_Unlock();
return 1;
}
/**
* @brief Write a stream of data to specified address in user mode
* @param address: Specifies the starting address to write to.
* @param len: Specifies the length of the data to write.
* @param data: Pointer to a byte array that is to be written.
* @retval status: Success:1 or Failure: Others.
* @note SPIC user mode is used because this mode can bypass RSIP(include OTF and MMU).
* User mode can read original data from physical address without decrypting, which is
* useful when address or len is not 4 byte aligned.
*/
IMAGE2_RAM_TEXT_SECTION
int ota_writestream_user(u32 address, u32 len, u8 * data)
{
// Check address: 4byte aligned & page(256bytes) aligned
u32 page_begin = address & (~0xff);
u32 page_end = (address + len) & (~0xff);
u32 page_cnt = ((page_end - page_begin) >> 8) + 1;
u32 addr_begin = address;
u32 addr_end = (page_cnt == 1) ? (address + len) : (page_begin + 0x100);
u32 size = addr_end - addr_begin;
u8 *buffer = data;
u8 write_data[12];
u32 offset_to_align;
u32 read_word;
u32 i;
FLASH_Write_Lock();
while(page_cnt){
offset_to_align = addr_begin & 0x3;
if(offset_to_align != 0){
FLASH_RxData(0, addr_begin - offset_to_align, 4, (u8*)&read_word);
for(i = offset_to_align;i < 4;i++){
read_word = (read_word & (~(0xff << (8*i)))) |( (*buffer) <<(8*i));
size--;
buffer++;
if(size == 0)
break;
}
FLASH_TxData12B(addr_begin - offset_to_align, 4, (u8*)&read_word);
}
addr_begin = (((addr_begin-1) >> 2) + 1) << 2;
for(;size >= 12 ;size -= 12){
_memcpy(write_data, buffer, 12);
FLASH_TxData12B(addr_begin, 12, write_data);
buffer += 12;
addr_begin += 12;
}
for(;size >= 4; size -=4){
_memcpy(write_data, buffer, 4);
FLASH_TxData12B(addr_begin, 4, write_data);
buffer += 4;
addr_begin += 4;
}
if(size > 0){
FLASH_RxData(0, addr_begin, 4, (u8*)&read_word);
for( i = 0;i < size;i++){
read_word = (read_word & (~(0xff << (8*i)))) | ((*buffer) <<(8*i));
buffer++;
}
FLASH_TxData12B(addr_begin, 4, (u8*)&read_word);
}
page_cnt--;
addr_begin = addr_end;
addr_end = (page_cnt == 1) ? (address + len) : (((addr_begin>>8) + 1)<<8);
size = addr_end - addr_begin;
}
DCache_Invalidate(address, len);
FLASH_Write_Unlock();
return 1;
}
/**
* @brief get current image2 location
* @param none
* @retval The retval can be one of the followings:
* OTA_INDEX_1: current images located in OTA1 address space
* OTA_INDEX_2: current images located in OTA2 address space
*/
u32 ota_get_cur_index(void)
{
u32 AddrStart, Offset, IsMinus, PhyAddr;;
RSIP_REG_TypeDef* RSIP = ((RSIP_REG_TypeDef *) RSIP_REG_BASE);
u32 CtrlTemp = RSIP->FLASH_MMU[0].MMU_ENTRYx_CTRL;
if (CtrlTemp & MMU_BIT_ENTRY_VALID) {
AddrStart = RSIP->FLASH_MMU[0].MMU_ENTRYx_STRADDR;
Offset = RSIP->FLASH_MMU[0].MMU_ENTRYx_OFFSET;
IsMinus = CtrlTemp & MMU_BIT_ENTRY_OFFSET_MINUS;
if(IsMinus)
PhyAddr = AddrStart - Offset;
else
PhyAddr = AddrStart + Offset;
if(PhyAddr == LS_IMG2_OTA1_ADDR)
return OTA_INDEX_1;
else if(PhyAddr == LS_IMG2_OTA2_ADDR)
return OTA_INDEX_2;
}
return OTA_INDEX_1;
}
/**
* @brief disable flash run time decrypt in some special FLASH area
* @param Addr: FLASH area address (should 4k alignment)
* @param Len: number of bytes
* @param NewStatus This parameter can be one of the following values
* @arg DISABLE close this area run time decypt mask
* @arg ENABLE enable this area run time decypt mask (this area will not be decrypt when read)
*/
void ota_rsip_mask(u32 addr, u32 len, u8 status)
{
u32 NewImg2BlkSize = ((len - 1)/4096) + 1;
RSIP_OTF_Mask(1, addr, NewImg2BlkSize, status);
DCache_Invalidate(addr, len);
}
/**
* @brief receive file_info from server. This operation is patched for the compatibility with ameba.
* @param Recvbuf: point for receiving buffer
* @param len: length of file info
* @param socket: socket handle
* @retval 0: receive fail, 1: receive ok
*/
u32 recv_file_info_from_server(u8 * Recvbuf, u32 len, int socket)
{
int read_bytes = 0;
u32 TempLen;
u8 * buf;
/*read 4 Dwords from server, get image header number and header length*/
buf = Recvbuf;
TempLen = len;
while(TempLen > 0) {
read_bytes = lwip_read(socket, buf, TempLen);
if(read_bytes < 0){
printf("\n\r[%s] read socket failed\n", __FUNCTION__);
goto error;
}
if(read_bytes == 0) {
break;
}
TempLen -= read_bytes;
buf += read_bytes;
}
return 1;
error:
return 0;
}
/**
* @brief receive OTA firmware file header from server.
* @param Recvbuf: pointer to buffer for receiving OTA header of firmware file
* @param len: data length to be received from server
* @param pOtaTgtHdr: point to target image OTA header
* @param socket: socket handle
* @retval 0: receive fail, 1: receive ok
*/
u32 recv_ota_file_hdr(u8 * Recvbuf, u32 * len, update_ota_target_hdr * pOtaTgtHdr, int socket)
{
int read_bytes = 0;
u32 TempLen;
u8 * buf;
update_file_hdr * pOtaFileHdr;
update_file_img_hdr * pOtaFileImgHdr;
/*read 4 Dwords from server, get image header number and header length*/
buf = Recvbuf;
TempLen = 16;
while(TempLen > 0) {
read_bytes = lwip_read(socket, buf, TempLen);
if(read_bytes < 0){
printf("\n\r[%s] read socket failed\n", __FUNCTION__);
goto error;
}
if(read_bytes == 0) {
break;
}
TempLen -= read_bytes;
buf += read_bytes;
}
pOtaFileHdr = (update_file_hdr *)Recvbuf;
pOtaFileImgHdr = (update_file_img_hdr *)(Recvbuf + 8);
pOtaTgtHdr->FileHdr.FwVer = pOtaFileHdr->FwVer;
pOtaTgtHdr->FileHdr.HdrNum = pOtaFileHdr->HdrNum;
/*read the remaining Header info*/
buf = Recvbuf + 16;
TempLen = (pOtaFileHdr->HdrNum * pOtaFileImgHdr->ImgHdrLen) - 8;
while(TempLen > 0) {
read_bytes = lwip_read(socket, buf, TempLen);
if(read_bytes < 0){
printf("\n\r[%s] read socket failed\n", __FUNCTION__);
goto error;
}
if(read_bytes == 0) {
break;
}
TempLen -= read_bytes;
buf += read_bytes;
}
*len = (pOtaFileHdr->HdrNum * pOtaFileImgHdr->ImgHdrLen) + 8;
return 1;
error:
return 0;
}
/**
* @brief parse firmware file header and get the desired OTA header
* @param buf: point to buffer for receiving OTA header of new firmware
* @param len: data length to be received from server
* @param pOtaTgtHdr:point to target image OTA header
* @param ImgId: point to image identification strings
* @retval 0: receive fail, 1: receive ok
*/
u32 get_ota_tartget_header(u8* buf, u32 len, update_ota_target_hdr * pOtaTgtHdr, u8 target_idx)
{
update_file_img_hdr * ImgHdr;
update_file_hdr * FileHdr;
u8 * pTempAddr;
u32 i = 0, j = 0;
int index = -1;
/*check if buf and len is valid or not*/
if((len < (sizeof(update_file_img_hdr) + 8)) || (!buf)) {
goto error;
}
FileHdr = (update_file_hdr *)buf;
ImgHdr = (update_file_img_hdr *)(buf + 8);
pTempAddr = buf + 8;
if(len < (FileHdr->HdrNum * ImgHdr->ImgHdrLen + 8)) {
goto error;
}
/*get the target OTA header from the new firmware file header*/
for(i = 0; i < FileHdr->HdrNum; i++) {
index = -1;
pTempAddr = buf + 8 + ImgHdr->ImgHdrLen * i;
if(strncmp("OTA", (const char *)pTempAddr, 3) == 0)
index = 0;
else
goto error;
if(index >= 0) {
_memcpy((u8*)(&pOtaTgtHdr->FileImgHdr[j]), pTempAddr, sizeof(update_file_img_hdr));
pOtaTgtHdr->FileImgHdr[j].FlashAddr = IMG_ADDR[index][target_idx];
j++;
}
}
pOtaTgtHdr->ValidImgCnt = j;
if(j == 0) {
printf("\n\r[%s] no valid image\n", __FUNCTION__);
goto error;
}
return 1;
error:
return 0;
}
/**
* @brief erase the flash space for new firmware.
* @param addr: new image address
* @param len: new image length
* @retval none
*/
void erase_ota_target_flash( u32 addr, u32 len)
{
u32 sector_cnt;
u32 i;
sector_cnt = ((len - 1)/4096) + 1;
device_mutex_lock(RT_DEV_LOCK_FLASH);
for( i = 0; i < sector_cnt; i++)
FLASH_EraseXIP(EraseSector, addr -SPI_FLASH_BASE + i * 4096);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
}
/**
* @brief download new firmware from server and write it to flash.
* @param addr: new image address
* @param socket: socket handle
* @param pOtaTgtHdr: point to target image OTA header
* @param signature: point to signature strings
* @retval download size of OTA image
*/
u32 download_new_fw_from_server(int socket, update_ota_target_hdr * pOtaTgtHdr, u8 targetIdx)
{
/* To avoid gcc warnings */
( void ) targetIdx;
u8 * alloc;
u8 * buf;
s32 size = 0;
int read_bytes;
int read_bytes_buf;
u32 TempLen;
u32 ImageCnt;
update_dw_info DownloadInfo[MAX_IMG_NUM];
/*initialize the variables used in downloading procedure*/
u32 OtaFg = 0;
u32 IncFg = 0;
s32 RemainBytes;
u32 SigCnt = 0;
u32 TempCnt = 0;
u32 i;
u8 res = _TRUE;
u8 * signature;
/*acllocate buffer for downloading image from server*/
alloc = ota_update_malloc(BUF_SIZE);
buf = alloc;
/*init download information buffer*/
memset((u8 *)DownloadInfo, 0, MAX_IMG_NUM*sizeof(update_dw_info));
ImageCnt = pOtaTgtHdr->ValidImgCnt;
for(i = 0; i < ImageCnt; i++) {
/* get OTA image and Write New Image to flash, skip the signature,
not write signature first for power down protection*/
DownloadInfo[i].ImgId = OTA_IMAG;
DownloadInfo[i].FlashAddr = pOtaTgtHdr->FileImgHdr[i].FlashAddr - SPI_FLASH_BASE + 8;
DownloadInfo[i].ImageLen = pOtaTgtHdr->FileImgHdr[i].ImgLen - 8; /*skip the signature*/
DownloadInfo[i].ImgOffset = pOtaTgtHdr->FileImgHdr[i].Offset;
}
/*initialize the reveiving counter*/
TempLen = (pOtaTgtHdr->FileHdr.HdrNum * pOtaTgtHdr->FileImgHdr[0].ImgHdrLen) + sizeof(update_file_hdr);
/*downloading parse the OTA and RDP image from the data stream sent by server*/
for(i = 0; i < ImageCnt; i++) {
/*the next image length*/
RemainBytes = DownloadInfo[i].ImageLen;
signature = &pOtaTgtHdr->Sign[i][0];
/*download the new firmware from server*/
while(RemainBytes > 0){
buf = alloc;
if(IncFg == 1) {
IncFg = 0;
read_bytes = read_bytes_buf;
} else {
memset(buf, 0, BUF_SIZE);
read_bytes = lwip_read(socket, buf, BUF_SIZE);
if(read_bytes == 0){
break; // Read end
}
if(read_bytes < 0){
//OtaImgSize = -1;
printf("\n\r[%s] Read socket failed", __FUNCTION__);
res = _FALSE;
goto exit;
}
read_bytes_buf = read_bytes;
TempLen += read_bytes;
}
if(TempLen > DownloadInfo[i].ImgOffset) {
if(!OtaFg) {
/*reach the desired image, the first packet process*/
OtaFg = 1;
TempCnt = TempLen -DownloadInfo[i].ImgOffset;
if(TempCnt < 8) {
SigCnt = TempCnt;
} else {
SigCnt = 8;
}
_memcpy(signature, buf + read_bytes -TempCnt, SigCnt);
if((SigCnt < 8) || (TempCnt -8 == 0)) {
continue;
}
buf = buf + (read_bytes -TempCnt + 8);
read_bytes = TempCnt -8;
} else {
/*normal packet process*/
if(SigCnt < 8) {
if(read_bytes < (int)(8 -SigCnt)) {
_memcpy(signature + SigCnt, buf, read_bytes);
SigCnt += read_bytes;
continue;
} else {
_memcpy(signature + SigCnt, buf, (8 -SigCnt));
buf = buf + (8 - SigCnt);
read_bytes -= (8 - SigCnt) ;
SigCnt = 8;
if(!read_bytes) {
continue;
}
}
}
}
RemainBytes -= read_bytes;
if(RemainBytes < 0) {
read_bytes = read_bytes -(-RemainBytes);
}
device_mutex_lock(RT_DEV_LOCK_FLASH);
if(ota_writestream_user(DownloadInfo[i].FlashAddr + size, read_bytes, buf) < 0){
printf("\n\r[%s] Write sector failed", __FUNCTION__);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
res = _FALSE;
goto exit;
}
device_mutex_unlock(RT_DEV_LOCK_FLASH);
size += read_bytes;
}
}
printf("\n\rUpdate file size: %d bytes, start addr:%08x", size + 8, pOtaTgtHdr->FileImgHdr[i].FlashAddr);
if((u32)size != (pOtaTgtHdr->FileImgHdr[i].ImgLen - 8)) {
printf("\n\rdownload new firmware failed\n");
goto exit;
}
/*update flag status*/
size = 0;
OtaFg = 0;
IncFg = 1;
}
exit:
ota_update_free(alloc);
return res;
}
/**
* @brief verify new firmware checksum.
* @param addr: new image address
* @param len: new image length
* @param signature: point to signature strings
* @param pOtaTgtHdr: point to target image OTA header
* @retval 0: verify fail, 1: verify ok
*/
u32 verify_ota_checksum(update_ota_target_hdr * pOtaTgtHdr)
{
u32 i, index;
u32 flash_checksum=0;
u32 addr, len;
u8 * signature;
u8 * pTempbuf;
int k;
int rlen;
u8 res = _TRUE;
pTempbuf = ota_update_malloc(BUF_SIZE);
for(index = 0; index < pOtaTgtHdr->ValidImgCnt; index++) {
flash_checksum = 0;
addr = pOtaTgtHdr->FileImgHdr[index].FlashAddr;
len = pOtaTgtHdr->FileImgHdr[index].ImgLen - 8;
signature = &pOtaTgtHdr->Sign[index][0];
/* read flash data back and calculate checksum */
for(i=0;i<len;i+=BUF_SIZE){
rlen = (len-i)>BUF_SIZE?BUF_SIZE:(len-i);
ota_readstream_user(addr - SPI_FLASH_BASE+i+8, rlen, pTempbuf);
for(k=0;k<rlen;k++)
flash_checksum+=pTempbuf[k];
}
/*add signature's checksum*/
for(i = 0; i < 8; i++) {
flash_checksum += signature[i];
}
if(flash_checksum != pOtaTgtHdr->FileImgHdr[index].Checksum) {
printf("\n\rOTA image(%08x) checksum error!!!\nCalculated checksum 0x%8x, host checksum 0x%8x\n", addr, \
flash_checksum, pOtaTgtHdr->FileImgHdr[index].Checksum);
res = _FALSE;
goto EXIT;
} else {
printf("\n\rOTA image(%08x) checksum ok!!!\n", addr);
}
}
EXIT:
ota_update_free(pTempbuf);
return res;
}
/**
* @brief update signature.
* @param addr: new image address
* @retval 0: change signature fail, 1: change signature ok
*/
u32 change_ota_signature(update_ota_target_hdr * pOtaTgtHdr, u32 ota_target_index)
{
u32 addr;
u8 * signature;
u8 index;
u8 ota_old_index = ota_target_index ^ 1;
u8 empty_sig = 0x0;
device_mutex_lock(RT_DEV_LOCK_FLASH);
for(index = 0; index < pOtaTgtHdr->ValidImgCnt; index++) {
addr = pOtaTgtHdr->FileImgHdr[index].FlashAddr;
signature = &pOtaTgtHdr->Sign[index][0];
/*write the signature finally*/
if(FLASH_WriteStream(addr - SPI_FLASH_BASE, 8, signature) < 0){
printf("\n\r[%s] Write sector failed", __FUNCTION__);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
goto error;
}
}
for(index = 0; index < pOtaTgtHdr->ValidImgCnt; index++) {
if(strncmp("OTA", (const char *)pOtaTgtHdr->FileImgHdr[index].ImgId, 3) == 0)
addr = IMG_ADDR[0][ota_old_index];
/*clear the old FW signature finally*/
if(FLASH_WriteStream(addr - SPI_FLASH_BASE, 4, &empty_sig) < 0){
printf("\n\r[%s] Write sector failed", __FUNCTION__);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
goto error;
}
}
device_mutex_unlock(RT_DEV_LOCK_FLASH);
printf("\n\r[%s] Update OTA success!", __FUNCTION__);
return 1;
error:
return 0;
}
#if 0
/**
* @brief OTA upgrade task for single image method.
* @param param: pointer to configuration of server
* @retval none
*/
static void ota_update_local_task(void *param)
{
int server_socket;
struct sockaddr_in server_addr;
unsigned char *alloc;
update_cfg_local_t *cfg = (update_cfg_local_t *)param;
uint32_t file_info[3];
int ret = -1 ;
uint32_t ota_target_index = OTA_INDEX_2;
update_ota_target_hdr OtaTargetHdr;
u32 RevHdrLen;
u8 i = 0;
memset((u8 *)&OtaTargetHdr, 0, sizeof(update_ota_target_hdr));
printf("\n\r[%s] Update task start\n", __FUNCTION__);
alloc = ota_update_malloc(BUF_SIZE);
if(!alloc){
printf("\n\r[%s] Alloc buffer failed", __FUNCTION__);
goto update_ota_exit;
}
/*-------------------step1: connect to server-------------------*/
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if(server_socket < 0){
printf("\n\r[%s] Create socket failed", __FUNCTION__);
goto update_ota_exit;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = cfg->ip_addr;
server_addr.sin_port = cfg->port;
if(connect(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1){
printf("\n\r[%s] socket connect failed", __FUNCTION__);
goto update_ota_exit;
}
DBG_INFO_MSG_OFF(MODULE_FLASH);
/* check OTA index we should update */
if (ota_get_cur_index() == OTA_INDEX_1) {
ota_target_index = OTA_INDEX_2;
printf("\n\r[%s] OTA2 address space will be upgraded", __FUNCTION__);
} else {
ota_target_index = OTA_INDEX_1;
printf("\n\r[%s] OTA1 address space will be upgraded", __FUNCTION__);
}
/* Receive file_info[] from server. Add this for compatibility. This file_info includes the
file_size and checksum information of the total firmware file. Even though the file_info
is received from server , it won't be used.*/
memset(file_info, 0, sizeof(file_info));
if(!recv_file_info_from_server((u8 *)file_info, sizeof(file_info), server_socket)) {
printf("\n\r[%s] receive file_info failed", __FUNCTION__);
goto update_ota_exit;
}
/*----------------step2: receive firmware file header---------------------*/
if(!recv_ota_file_hdr(alloc, &RevHdrLen, &OtaTargetHdr, server_socket)) {
printf("\n\r[%s] rev firmware header failed", __FUNCTION__);
goto update_ota_exit;
}
/* -----step3: parse firmware file header and get the target OTA image header-----*/
if(!get_ota_tartget_header(alloc, RevHdrLen, &OtaTargetHdr, ota_target_index)) {
printf("\n\rget OTA header failed\n");
goto update_ota_exit;
}
/* the upgrade space should be masked */
//ota_rsip_mask(NewImg2Addr, OtaTargetHdr.FileImgHdr.ImgLen, ENABLE);
/*-------------------step4: erase flash space for new firmware--------------*/
/*erase flash space new OTA image */
printf("\n\rErase is ongoing...");
for(i = 0; i < OtaTargetHdr.ValidImgCnt; i++) {
erase_ota_target_flash(OtaTargetHdr.FileImgHdr[i].FlashAddr, OtaTargetHdr.FileImgHdr[i].ImgLen);
}
/*---------step5: download new firmware from server and write it to flash--------*/
//size = download_new_fw_from_server(NewImg2Addr, server_socket, &OtaTargetHdr, signature);
if(download_new_fw_from_server(server_socket, &OtaTargetHdr, ota_target_index) == _FALSE){
goto update_ota_exit;
}
/*-------------step6: verify checksum and update signature-----------------*/
if(verify_ota_checksum(&OtaTargetHdr)){
if(!change_ota_signature(&OtaTargetHdr, ota_target_index)) {
printf("\n\rChange signature failed\n");
goto update_ota_exit;
}
ret = 0;
}
/* unmask the upgrade space */
//ota_rsip_mask(NewImg2Addr, OtaTargetHdr.FileImgHdr.ImgLen, DISABLE);
update_ota_exit:
if(alloc)
ota_update_free(alloc);
if(server_socket >= 0)
close(server_socket);
if(param)
ota_update_free(param);
TaskOTA = NULL;
printf("\n\r[%s] Update task exit", __FUNCTION__);
/*-------------step7: OTA upgrade successfully, restart device------------*/
if(!ret){
//printf("\n\r[%s] Ready to reboot", __FUNCTION__);
//ota_platform_reset();
printf("\n\rOTA is finished. Please reset device.", __FUNCTION__);
}
vTaskDelete(NULL);
return;
}
int update_ota_local(char *ip, int port)
{
update_cfg_local_t *pUpdateCfg;
if(TaskOTA){
printf("\n\r[%s] Update task has created.", __FUNCTION__);
return 0;
}
pUpdateCfg = ota_update_malloc(sizeof(update_cfg_local_t));
if(pUpdateCfg == NULL){
printf("\n\r[%s] Alloc update cfg failed", __FUNCTION__);
return -1;
}
pUpdateCfg->ip_addr = inet_addr(ip);
pUpdateCfg->port = ntohs(port);
if(xTaskCreate(ota_update_local_task, "OTA_server", 1024, pUpdateCfg, tskIDLE_PRIORITY + 1, &TaskOTA) != pdPASS){
ota_update_free(pUpdateCfg);
printf("\n\r[%s] Create update task failed", __FUNCTION__);
}
return 0;
}
#endif // #if (SERVER_TYPE == SERVER_LOCAL)
#endif
#if 0
/* choose to boot from ota2 image or not */
void cmd_ota_image(bool cmd)
{
/* To avoid gcc warnings */
( void ) cmd;
#if 0
if (cmd == 1)
OTA_Change(OTA_INDEX_2);
else
OTA_Change(OTA_INDEX_1);
#endif
}
void cmd_update(int argc, char **argv)
{
#if (SERVER_TYPE == SERVER_LOCAL)
int port;
if(argc != 3){
printf("\n\r[%s] Usage: update IP PORT", __FUNCTION__);
return;
}
port = atoi(argv[2]);
update_ota_local(argv[1], port);
#elif (SERVER_TYPE == SERVER_CLOUD)
printf("OTA demo doesn't support update from cloud server. "
"Please customized OTA process according to the standard of different cloud providers\n");
#endif
}
#endif
#if 0
#if (defined HTTP_OTA_UPDATE) || (defined HTTPS_OTA_UPDATE)
static char *redirect = NULL;
static int redirect_len;
static u16 redirect_server_port;
static char *redirect_server_host = NULL;
static char *redirect_resource = NULL;
int parser_url( char *url, char *host, u16 *port, char *resource)
{
if(url){
char *http = NULL, *pos = NULL;
http = strstr(url, "http://");
if(http) // remove http
url += strlen("http://");
memset(host, 0, redirect_len);
pos = strstr(url, ":"); // get port
if(pos){
memcpy(host, url, (pos-url));
pos += 1;
*port = atoi(pos);
}else{
pos = strstr(url, "/");
if(pos){
memcpy(host, url, (pos-url));
url = pos;
}
*port = 80;
}
printf("server: %s\n\r", host);
printf("port: %d\n\r", *port);
memset(resource, 0, redirect_len);
pos = strstr(url, "/");
if(pos){
memcpy(resource, pos + 1, strlen(pos + 1));
}
printf("resource: %s\n\r", resource);
return 0;
}
return -1;
}
/**
* @brief parse http response.
* @param response: the http response got from server
* @param response_len: The length of http response
* @param result: The struct that store the useful info from the http response
* @retval 1:only got status code;3:got status code and content length,but not get the full header;4: got all info;-1:failed
*/
int parse_http_response(unsigned char *response, unsigned int response_len, http_response_result_t *result) {
uint32_t i, p, q, m;
uint32_t header_end = 0;
//Get status code
if(0 == result->parse_status){//didn't get the http response
uint8_t status[4] = {0};
i = p = q = m = 0;
for (; i < response_len; ++i) {
if (' ' == response[i]) {
++m;
if (1 == m) {//after HTTP/1.1
p = i;
}
else if (2 == m) {//after status code
q = i;
break;
}
}
}
if (!p || !q || q-p != 4) {//Didn't get the status code
return -1;
}
memcpy(status, response+p+1, 3);//get the status code
result->status_code = atoi((char const *)status);
if(result->status_code == 200)
result->parse_status = 1;
else if(result->status_code == 302)
{
char *tmp=NULL;
const char *location1 = "LOCATION";
const char *location2 = "Location";
printf("response 302:%s \r\n", response);
if((tmp =strstr((char *)response, location1)) ||(tmp=strstr((char *)response, location2)))
{
redirect_len = strlen(tmp+10);
printf("Location len = %d\r\n", redirect_len);
if(redirect ==NULL)
{
redirect = ota_update_malloc(redirect_len);
if(redirect == NULL)
{
return -1;
}
}
memset(redirect, 0, redirect_len);
memcpy(redirect, tmp+10, strlen(tmp+10));
}
if(redirect_server_host ==NULL)
{
redirect_server_host = ota_update_malloc(redirect_len);
if(redirect_server_host == NULL)
{
return -1;
}
}
if(redirect_resource ==NULL)
{
redirect_resource = ota_update_malloc(redirect_len);
if(redirect_resource == NULL)
{
return -1;
}
}
memset(redirect_server_host, 0, redirect_len);
memset(redirect_resource, 0, redirect_len);
if(parser_url(redirect, redirect_server_host, &redirect_server_port , redirect_resource)<0)
{
return -1;
}
return -1;
}
else{
printf("\n\r[%s] The http response status code is %d", __FUNCTION__, result->status_code);
return -1;
}
}
//if didn't receive the full http header
if(3 == result->parse_status){//didn't get the http response
p = q = 0;
for (i = 0; i < response_len; ++i) {
if (response[i] == '\r' && response[i+1] == '\n' &&
response[i+2] == '\r' && response[i+3] == '\n') {//the end of header
header_end = i+4;
result->parse_status = 4;
result->header_len = header_end;
result->body = response + header_end;
break;
}
}
if (3 == result->parse_status) {//Still didn't receive the full header
result->header_bak = ota_update_malloc(HEADER_BAK_LEN + 1);
memset(result->header_bak, 0, strlen((const char*)result->header_bak));
memcpy(result->header_bak, response + response_len - HEADER_BAK_LEN, HEADER_BAK_LEN);
}
}
//Get Content-Length
if(1 == result->parse_status){//didn't get the content length
const char *content_length_buf1 = "CONTENT-LENGTH";
const char *content_length_buf2 = "Content-Length";
const uint32_t content_length_buf_len = strlen((const char*)content_length_buf1);
p = q = 0;
for (i = 0; i < response_len; ++i) {
if (response[i] == '\r' && response[i+1] == '\n') {
q = i;//the end of the line
if (!memcmp(response+p, content_length_buf1, content_length_buf_len) ||
!memcmp(response+p, content_length_buf2, content_length_buf_len)) {//get the content length
unsigned int j1 = p+content_length_buf_len, j2 = q-1;
while ( j1 < q && (*(response+j1) == ':' || *(response+j1) == ' ') ) ++j1;
while ( j2 > j1 && *(response+j2) == ' ') --j2;
uint8_t len_buf[12] = {0};
memcpy(len_buf, response+j1, j2-j1+1);
result->body_len = atoi((char const *)len_buf);
result->parse_status = 2;
}
p = i+2;
}
if (response[i] == '\r' && response[i+1] == '\n' &&
response[i+2] == '\r' && response[i+3] == '\n') {//Get the end of header
header_end = i+4;//p is the start of the body
if(result->parse_status == 2){//get the full header and the content length
result->parse_status = 4;
result->header_len = header_end;
result->body = response + header_end;
}
else {//there are no content length in header
printf("\n\r[%s] No Content-Length in header", __FUNCTION__);
return -1;
}
break;
}
}
if (1 == result->parse_status) {//didn't get the content length and the full header
result->header_bak = ota_update_malloc(HEADER_BAK_LEN + 1);
memset(result->header_bak, 0, strlen((char *)result->header_bak));
memcpy(result->header_bak, response + response_len - HEADER_BAK_LEN, HEADER_BAK_LEN);
}
else if (2 == result->parse_status) {//didn't get the full header but get the content length
result->parse_status = 3;
result->header_bak = ota_update_malloc(HEADER_BAK_LEN + 1);
memset(result->header_bak, 0, strlen((char *)result->header_bak));
memcpy(result->header_bak, response + response_len - HEADER_BAK_LEN, HEADER_BAK_LEN);
}
}
return result->parse_status;
}
#ifdef HTTP_OTA_UPDATE
/**
* @brief connect to the OTA http server.
* @param server_socket: the socket used
* @param host: host address of the OTA server
* @param port: port of the OTA server
* @retval -1 when connect fail, socket value when connect success
*/
int update_ota_http_connect_server(int server_socket, char *host, int port){
struct sockaddr_in server_addr;
struct hostent *server;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if(server_socket < 0){
printf("\n\r[%s] Create socket failed", __FUNCTION__);
return -1;
}
printf("[%s] Create socket: %d success!\n", __FUNCTION__, server_socket);
server = gethostbyname(host);
if(server == NULL){
printf("[ERROR] Get host ip failed\n");
return -1;
}
memset(&server_addr,0,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
memcpy((void *)&server_addr.sin_addr,(void *)server->h_addr,4);
if (connect(server_socket,(struct sockaddr *)&server_addr, sizeof(server_addr)) < 0){
printf("\n\r[%s] Socket connect failed", __FUNCTION__);
return -1;
}
return server_socket;
}
/**
* @brief receive OTA firmware file header from server
* @param Recvbuf: pointer to buffer for receiving OTA header of firmware file
* @param writelen:the length already read from server
* @param len: data length to be received from server
* @param pOtaTgtHdr: point to target image OTA header
* @param socket: socket handler
* @retval 0:failed;1:success
*/
u32 recv_ota_file_hdr_http(u8 * Recvbuf, u32 writelen, u32 * len, update_ota_target_hdr * pOtaTgtHdr, int socket)
{
int read_bytes = 0;
u32 TempLen;
u8 * buf;
update_file_hdr * pOtaFileHdr;
update_file_img_hdr * pOtaFileImgHdr;
buf = Recvbuf + writelen;
/*receive the remaining OTA firmware file header info if needed*/
if (writelen < 32) {
TempLen = 32 - writelen;
while(TempLen) {
read_bytes = recv(socket, buf, TempLen, 0);
if(read_bytes < 0){
printf("[%s] read socket failed\n", __FUNCTION__);
goto error;
}
if(read_bytes == 0) {
break;
}
TempLen -= read_bytes;
buf += read_bytes;
}
}
pOtaFileHdr = (update_file_hdr *)(Recvbuf);
pOtaFileImgHdr = (update_file_img_hdr *)(Recvbuf + 8);
pOtaTgtHdr->FileHdr.FwVer = pOtaFileHdr->FwVer;
pOtaTgtHdr->FileHdr.HdrNum = pOtaFileHdr->HdrNum;
*len = (pOtaFileHdr->HdrNum * pOtaFileImgHdr->ImgHdrLen) + 8;
return 1;
error:
return 0;
}
/**
* @brief http read socket
* @param Recvbuf: pointer to buffer for receiving
* @param socket: socket handler
* @param buf_len: read data length
* @retval >0:success;<0:error
*/
int http_read_socket( int socket, u8 *recevie_buf, int buf_len )
{
int bytes_rcvd = -1;
if( socket < 0 ) {
printf("[%s], socket is invalid\n", __FUNCTION__);
return bytes_rcvd;
}
memset(recevie_buf, 0, buf_len);
//DBG_8195A("R\n");
bytes_rcvd = recv(socket, recevie_buf, buf_len, 0 );
if(bytes_rcvd <= 0) {
printf("[%s], Close HTTP Socket[%d].\n", socket, __FUNCTION__);
return -2;
}
return bytes_rcvd;
}
/**
* @brief download new firmware from http server and write it to flash.
* @param first_buf: point data already from http server
* @param firstbuf_len: the length of already read data
* @param socket: socket handle
* @param pOtaTgtHdr: point to target image OTA header
* @param targetIdx: target OTA index
* @retval download size of OTA image
*/
u32 download_new_fw_from_server_http(u8* first_buf, unsigned int firstbuf_len, int socket, update_ota_target_hdr * pOtaTgtHdr, u8 targetIdx)
{
/* To avoid gcc warnings */
( void ) targetIdx;
u8 * alloc;
u8 * buf;
s32 size = 0;
int read_bytes;
int read_bytes_buf;
u32 TempLen;
u32 ImageCnt;
update_dw_info DownloadInfo[MAX_IMG_NUM];
/*initialize the variables used in downloading procedure*/
u32 OtaFg = 0;
u32 IncFg = 0;
u32 firstbufFg = 0;
s32 RemainBytes;
u32 SigCnt = 0;
u32 TempCnt = 0;
u32 i;
u8 res = _TRUE;
u8 * signature;
u32 write_sector = 0;
u32 next_erase_sector = 0;
/*acllocate buffer for downloading image from server*/
alloc = ota_update_malloc(BUF_SIZE);
buf = alloc;
/*init download information buffer*/
memset((u8 *)DownloadInfo, 0, MAX_IMG_NUM*sizeof(update_dw_info));
ImageCnt = pOtaTgtHdr->ValidImgCnt;
for(i = 0; i < ImageCnt; i++) {
/* get OTA image and Write New Image to flash, skip the signature,
not write signature first for power down protection*/
DownloadInfo[i].ImgId = OTA_IMAG;
DownloadInfo[i].FlashAddr = pOtaTgtHdr->FileImgHdr[i].FlashAddr - SPI_FLASH_BASE + 8;
DownloadInfo[i].ImageLen = pOtaTgtHdr->FileImgHdr[i].ImgLen - 8; /*skip the signature*/
DownloadInfo[i].ImgOffset = pOtaTgtHdr->FileImgHdr[i].Offset;
}
/*initialize the reveiving counter*/
TempLen = (pOtaTgtHdr->FileHdr.HdrNum * pOtaTgtHdr->FileImgHdr[0].ImgHdrLen) + sizeof(update_file_hdr);
/*downloading parse the OTA and RDP image from the data stream sent by server*/
for(i = 0; i < ImageCnt; i++) {
/*the next image length*/
RemainBytes = DownloadInfo[i].ImageLen;
signature = &pOtaTgtHdr->Sign[i][0];
if (i == 0) {
if (firstbuf_len > DownloadInfo[i].ImgOffset) {
firstbufFg = 1;
TempLen += firstbuf_len -DownloadInfo[i].ImgOffset;
}
}
/*download the new firmware from server*/
while(RemainBytes > 0){
buf = alloc;
if(IncFg == 1) {
IncFg = 0;
read_bytes = read_bytes_buf;
} else if(firstbufFg != 1) {
read_bytes = http_read_socket(socket, buf, BUF_SIZE);
if(read_bytes == 0){
break; // Read end
}
if(read_bytes < 0){
//OtaImgSize = -1;
printf("\n\r[%s] Read socket failed", __FUNCTION__);
res = _FALSE;
goto exit;
}
read_bytes_buf = read_bytes;
TempLen += read_bytes;
}
if(TempLen > DownloadInfo[i].ImgOffset) {
if(!OtaFg) {
/*reach the desired image, the first packet process*/
OtaFg = 1;
TempCnt = TempLen -DownloadInfo[i].ImgOffset;
if(TempCnt < 8) {
SigCnt = TempCnt;
} else {
SigCnt = 8;
}
if (firstbufFg == 1)
_memcpy(signature, first_buf + DownloadInfo[i].ImgOffset, SigCnt);
else
_memcpy(signature, buf + read_bytes -TempCnt, SigCnt);
if((SigCnt < 8) || (TempCnt -8 == 0)) {
if (firstbufFg == 1) {
firstbufFg = 0;
}
continue;
}
if (firstbufFg == 1) {
buf = first_buf + DownloadInfo[i].ImgOffset + 8;
firstbufFg = 0;
} else
buf = buf + (read_bytes -TempCnt + 8);
read_bytes = TempCnt -8;
} else {
/*normal packet process*/
if(SigCnt < 8) {
if(read_bytes < (int)(8 -SigCnt)) {
_memcpy(signature + SigCnt, buf, read_bytes);
SigCnt += read_bytes;
continue;
} else {
_memcpy(signature + SigCnt, buf, (8 -SigCnt));
buf = buf + (8 - SigCnt);
read_bytes -= (8 - SigCnt) ;
SigCnt = 8;
if(!read_bytes) {
continue;
}
}
}
}
RemainBytes -= read_bytes;
if(RemainBytes < 0) {
read_bytes = read_bytes -(-RemainBytes);
}
#if 1
/* erase flash */
write_sector = (DownloadInfo[i].ImageLen - RemainBytes-1+8)/4096;
if (write_sector >= next_erase_sector){
//DBG_8195A("E1\n");
device_mutex_lock(RT_DEV_LOCK_FLASH);
//DelayMs(30);
FLASH_EraseXIP(EraseSector, pOtaTgtHdr->FileImgHdr[i].FlashAddr -SPI_FLASH_BASE + write_sector * 4096);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
next_erase_sector++;
//DBG_8195A("E2\n");
}
//DBG_8195A("E3\n");
device_mutex_lock(RT_DEV_LOCK_FLASH);
if(ota_writestream_user(DownloadInfo[i].FlashAddr + size, read_bytes, buf) < 0){
printf("\n\r[%s] Write sector failed", __FUNCTION__);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
res = _FALSE;
goto exit;
}
//DelayMs(2);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
#endif
//DBG_8195A("E4\n");
size += read_bytes;
}
}
printf("\n\rUpdate file size: %d bytes, start addr:%08x", size + 8, pOtaTgtHdr->FileImgHdr[i].FlashAddr);
if((u32)size != (pOtaTgtHdr->FileImgHdr[i].ImgLen - 8)) {
printf("\n\rdownload new firmware failed\n");
goto exit;
}
/*update flag status*/
size = 0;
OtaFg = 0;
IncFg = 1;
next_erase_sector = 0;
}
exit:
ota_update_free(alloc);
return res;
}
/**
* @brief OTA update through http
* @param host: host addr of http server
* @param port: http server port
* @param resource: resource path
* @retval -1:fail;0:success
*/
int http_update_ota(char *host, int port, char *resource)
{
int server_socket = -1;
unsigned char *alloc=NULL, *request=NULL;
int alloc_buf_size = BUF_SIZE;
int read_bytes = 0;
int ret = -1;
int writelen = 0;
u32 RevHdrLen = 0;
http_response_result_t rsp_result = {0};
uint32_t ota_target_index = OTA_INDEX_2;
update_ota_target_hdr OtaTargetHdr;
restart_http_ota:
redirect_server_port = 0;
alloc = (unsigned char *)ota_update_malloc(alloc_buf_size);
if(!alloc){
printf("[%s] Alloc buffer failed\n", __FUNCTION__);
goto update_ota_exit;
}
/*Connect server */
server_socket = update_ota_http_connect_server(server_socket, host, port);
if(server_socket == -1){
goto update_ota_exit;
}
uint32_t idx = 0;
printf("\n\r");
/*send http request*/
request = (unsigned char *) ota_update_malloc(strlen("GET /") + strlen(resource) + strlen(" HTTP/1.1\r\nHost: ")
+ strlen(host) + strlen("\r\n\r\n") + 1);
sprintf((char*)request, "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", resource, host);
ret = write(server_socket, request, strlen((char*)request));
if(ret < 0){
printf("[%s] Send HTTP request failed\n", __FUNCTION__);
goto update_ota_exit;
}
/* parse http response*/
while (3 >= rsp_result.parse_status){//still read header
if(0 == rsp_result.parse_status){//didn't get the http response
memset(alloc, 0, alloc_buf_size);
read_bytes = read(server_socket, alloc, alloc_buf_size);
if(read_bytes <= 0){
printf("[%s] Read socket failed\n", __FUNCTION__);
goto update_ota_exit;
}
idx = read_bytes;
memset(&rsp_result, 0, sizeof(rsp_result));
if(parse_http_response(alloc, idx, &rsp_result) == -1){
goto update_ota_exit;
}
} else if ((1 == rsp_result.parse_status) || (3 == rsp_result.parse_status)){//just get the status code
memset(alloc, 0, alloc_buf_size);
memcpy(alloc, rsp_result.header_bak, HEADER_BAK_LEN);
ota_update_free(rsp_result.header_bak);
rsp_result.header_bak = NULL;
read_bytes = read(server_socket, alloc + HEADER_BAK_LEN, (alloc_buf_size - HEADER_BAK_LEN));
if(read_bytes <= 0){
printf("[%s] Read socket failed\n", __FUNCTION__);
goto update_ota_exit;
}
idx = read_bytes + HEADER_BAK_LEN;
if (parse_http_response(alloc, read_bytes + HEADER_BAK_LEN, &rsp_result) == -1){
goto update_ota_exit;
}
}
}
if (0 == rsp_result.body_len) {
printf("[%s] New firmware size = 0 !\n", __FUNCTION__);
goto update_ota_exit;
} else {
printf("[%s] Download new firmware begin, total size : %d\n", __FUNCTION__, rsp_result.body_len);
}
writelen = idx - rsp_result.header_len;
/* remove http header_len from alloc*/
memset(alloc, 0, rsp_result.header_len);
_memcpy(alloc, alloc+rsp_result.header_len, writelen);
memset(alloc+writelen, 0, rsp_result.header_len);
/* check OTA index we should update */
if (ota_get_cur_index() == OTA_INDEX_1) {
ota_target_index = OTA_INDEX_2;
printf("\n\r[%s] OTA2 address space will be upgraded\n", __FUNCTION__);
} else {
ota_target_index = OTA_INDEX_1;
printf("\n\r[%s] OTA1 address space will be upgraded\n", __FUNCTION__);
}
/*----------------step2: receive firmware file header---------------------*/
if(!recv_ota_file_hdr_http(alloc, writelen, &RevHdrLen, &OtaTargetHdr, server_socket)) {
printf("\n\r[%s] rev firmware header failed", __FUNCTION__);
goto update_ota_exit;
}
/* -----step3: parse firmware file header and get the target OTA image header-----*/
if(!get_ota_tartget_header(alloc, RevHdrLen, &OtaTargetHdr, ota_target_index)) {
printf("\n\rget OTA header failed\n");
goto update_ota_exit;
}
/* the upgrade space should be masked */
//ota_rsip_mask(NewImg2Addr, OtaTargetHdr.FileImgHdr.ImgLen, ENABLE);
/*-------------------step4: erase flash space for new firmware--------------*/
/*erase flash space new OTA image */
//printf("\n\rErase is ongoing...");
//for(i = 0; i < OtaTargetHdr.ValidImgCnt; i++) {
// erase_ota_target_flash(OtaTargetHdr.FileImgHdr[i].FlashAddr, OtaTargetHdr.FileImgHdr[i].ImgLen);
//}
/*---------step5: download new firmware from server and write it to flash--------*/
if(download_new_fw_from_server_http(alloc, writelen, server_socket, &OtaTargetHdr, ota_target_index) == _FALSE){
goto update_ota_exit;
}
/*-------------step6: verify checksum and update signature-----------------*/
if(verify_ota_checksum(&OtaTargetHdr)){
//if(!change_ota_signature(&OtaTargetHdr, ota_target_index)) {
//printf("\n\rChange signature failed\n");
//goto update_ota_exit;
//}
//ret = 0;
}
update_ota_exit:
if(alloc)
ota_update_free(alloc);
if(request)
ota_update_free(request);
if(server_socket >= 0)
close(server_socket);
/* redirect_server_port != 0 means there is redirect URL can be downloaded*/
if(redirect_server_port != 0){
host = redirect_server_host;
resource = redirect_resource;
port = redirect_server_port;
printf("OTA redirect host: %s, port: %s, resource: %s\n\r", host, port, resource);
goto restart_http_ota;
}
ota_update_free(redirect);
ota_update_free(redirect_server_host);
ota_update_free(redirect_resource);
return ret;
}
#endif
#ifdef HTTPS_OTA_UPDATE
static int my_random(void *p_rng, unsigned char *output, size_t output_len)
{
( void ) p_rng;
rtw_get_random_bytes(output, output_len);
return 0;
}
static void* my_calloc(size_t nelements, size_t elementSize)
{
size_t size;
void *ptr = NULL;
size = nelements * elementSize;
ptr = pvPortMalloc(size);
if(ptr)
memset(ptr, 0, size);
return ptr;
}
static char *https_itoa(int value){
char *val_str;
int tmp = value, len = 1;
while((tmp /= 10) > 0)
len ++;
val_str = (char *) pvPortMalloc(len + 1);
sprintf(val_str, "%d", value);
return val_str;
}
/**
* @brief receive OTA firmware file header from server
* @param Recvbuf: pointer to buffer for receiving OTA header of firmware file
* @param writelen:the length already read from server
* @param len: data length to be received from server
* @param pOtaTgtHdr: point to target image OTA header
* @param ssl: context for mbedtls
* @retval 0:failed;1:success
*/
u32 recv_ota_file_hdr_https(u8 * Recvbuf, u32 writelen, u32 * len, update_ota_target_hdr * pOtaTgtHdr, mbedtls_ssl_context *ssl)
{
int read_bytes = 0;
u32 TempLen;
u8 * buf;
update_file_hdr * pOtaFileHdr;
update_file_img_hdr * pOtaFileImgHdr;
buf = Recvbuf + writelen;
/*receive the remaining OTA firmware file header info if needed*/
if (writelen < 32) {
TempLen = 32 - writelen;
while(TempLen) {
read_bytes = mbedtls_ssl_read(ssl, buf, TempLen);
if(read_bytes < 0){
printf("[%s] read socket failed [%d]\n", __FUNCTION__, read_bytes);
goto error;
}
if(read_bytes == 0) {
break;
}
TempLen -= read_bytes;
buf += read_bytes;
}
}
pOtaFileHdr = (update_file_hdr *)(Recvbuf);
pOtaFileImgHdr = (update_file_img_hdr *)(Recvbuf + 8);
pOtaTgtHdr->FileHdr.FwVer = pOtaFileHdr->FwVer;
pOtaTgtHdr->FileHdr.HdrNum = pOtaFileHdr->HdrNum;
*len = (pOtaFileHdr->HdrNum * pOtaFileImgHdr->ImgHdrLen) + 8;
return 1;
error:
return 0;
}
/**
* @brief https read socket
* @param Recvbuf: pointer to buffer for receiving
* @param ssl: context for mbedtls
* @param buf_len: read data length
* @retval >0:success;<0:error
*/
int https_read_socket( mbedtls_ssl_context *ssl, u8 *recevie_buf, int buf_len )
{
int bytes_rcvd = -1;
memset(recevie_buf, 0, buf_len);
bytes_rcvd = mbedtls_ssl_read(ssl, recevie_buf, buf_len );
if(bytes_rcvd <= 0) {
printf("[%s], ssl read failed [%d]\n", __FUNCTION__, bytes_rcvd);
return -2;
}
return bytes_rcvd;
}
/**
* @brief download new firmware from https server and write it to flash.
* @param first_buf: point data already from https server
* @param firstbuf_len: the length of already read data
* @param ssl: context for mbedtls
* @param pOtaTgtHdr: point to target image OTA header
* @param targetIdx: target OTA index
* @retval download size of OTA image
*/
u32 download_new_fw_from_server_https(u8* first_buf, unsigned int firstbuf_len, mbedtls_ssl_context *ssl, update_ota_target_hdr * pOtaTgtHdr, u8 targetIdx)
{
/* To avoid gcc warnings */
( void ) targetIdx;
u8 * alloc;
u8 * buf;
s32 size = 0;
int read_bytes;
int read_bytes_buf;
u32 TempLen;
u32 ImageCnt;
update_dw_info DownloadInfo[MAX_IMG_NUM];
/*initialize the variables used in downloading procedure*/
u32 OtaFg = 0;
u32 IncFg = 0;
u32 firstbufFg = 0;
s32 RemainBytes;
u32 SigCnt = 0;
u32 TempCnt = 0;
u32 i;
u8 res = _TRUE;
u8 * signature;
u32 write_sector = 0;
u32 next_erase_sector = 0;
/*acllocate buffer for downloading image from server*/
alloc = ota_update_malloc(BUF_SIZE);
buf = alloc;
/*init download information buffer*/
memset((u8 *)DownloadInfo, 0, MAX_IMG_NUM*sizeof(update_dw_info));
ImageCnt = pOtaTgtHdr->ValidImgCnt;
for(i = 0; i < ImageCnt; i++) {
/* get OTA image and Write New Image to flash, skip the signature,
not write signature first for power down protection*/
DownloadInfo[i].ImgId = OTA_IMAG;
DownloadInfo[i].FlashAddr = pOtaTgtHdr->FileImgHdr[i].FlashAddr - SPI_FLASH_BASE + 8;
DownloadInfo[i].ImageLen = pOtaTgtHdr->FileImgHdr[i].ImgLen - 8; /*skip the signature*/
DownloadInfo[i].ImgOffset = pOtaTgtHdr->FileImgHdr[i].Offset;
}
/*initialize the reveiving counter*/
TempLen = (pOtaTgtHdr->FileHdr.HdrNum * pOtaTgtHdr->FileImgHdr[0].ImgHdrLen) + sizeof(update_file_hdr);
/*downloading parse the OTA and RDP image from the data stream sent by server*/
for(i = 0; i < ImageCnt; i++) {
/*the next image length*/
RemainBytes = DownloadInfo[i].ImageLen;
signature = &pOtaTgtHdr->Sign[i][0];
if (i == 0) {
if (firstbuf_len > DownloadInfo[i].ImgOffset) {
firstbufFg = 1;
TempLen += firstbuf_len -DownloadInfo[i].ImgOffset;
}
}
/*download the new firmware from server*/
while(RemainBytes > 0){
buf = alloc;
if(IncFg == 1) {
IncFg = 0;
read_bytes = read_bytes_buf;
} else if(firstbufFg != 1) {
read_bytes = https_read_socket(ssl, buf, BUF_SIZE);
if(read_bytes == 0){
break; // Read end
}
if(read_bytes < 0){
//OtaImgSize = -1;
printf("\n\r[%s] Read socket failed", __FUNCTION__);
res = _FALSE;
goto exit;
}
read_bytes_buf = read_bytes;
TempLen += read_bytes;
}
if(TempLen > DownloadInfo[i].ImgOffset) {
if(!OtaFg) {
/*reach the desired image, the first packet process*/
OtaFg = 1;
TempCnt = TempLen -DownloadInfo[i].ImgOffset;
if(TempCnt < 8) {
SigCnt = TempCnt;
} else {
SigCnt = 8;
}
if (firstbufFg == 1)
_memcpy(signature, first_buf + DownloadInfo[i].ImgOffset, SigCnt);
else
_memcpy(signature, buf + read_bytes -TempCnt, SigCnt);
if((SigCnt < 8) || (TempCnt -8 == 0)) {
if (firstbufFg == 1) {
firstbufFg = 0;
}
continue;
}
if (firstbufFg == 1) {
buf = first_buf + DownloadInfo[i].ImgOffset + 8;
firstbufFg = 0;
} else
buf = buf + (read_bytes -TempCnt + 8);
read_bytes = TempCnt -8;
} else {
/*normal packet process*/
if(SigCnt < 8) {
if(read_bytes < (int)(8 -SigCnt)) {
_memcpy(signature + SigCnt, buf, read_bytes);
SigCnt += read_bytes;
continue;
} else {
_memcpy(signature + SigCnt, buf, (8 -SigCnt));
buf = buf + (8 - SigCnt);
read_bytes -= (8 - SigCnt) ;
SigCnt = 8;
if(!read_bytes) {
continue;
}
}
}
}
RemainBytes -= read_bytes;
if(RemainBytes < 0) {
read_bytes = read_bytes -(-RemainBytes);
}
/* erase flash */
write_sector = (DownloadInfo[i].ImageLen - RemainBytes-1+8)/4096;
if (write_sector >= next_erase_sector){
device_mutex_lock(RT_DEV_LOCK_FLASH);
FLASH_EraseXIP(EraseSector, pOtaTgtHdr->FileImgHdr[i].FlashAddr -SPI_FLASH_BASE + write_sector * 4096);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
next_erase_sector++;
}
device_mutex_lock(RT_DEV_LOCK_FLASH);
if(ota_writestream_user(DownloadInfo[i].FlashAddr + size, read_bytes, buf) < 0){
printf("\n\r[%s] Write sector failed", __FUNCTION__);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
res = _FALSE;
goto exit;
}
device_mutex_unlock(RT_DEV_LOCK_FLASH);
size += read_bytes;
}
}
printf("\n\rUpdate file size: %d bytes, start addr:%08x", size + 8, pOtaTgtHdr->FileImgHdr[i].FlashAddr);
if((u32)size != (pOtaTgtHdr->FileImgHdr[i].ImgLen - 8)) {
printf("\n\rdownload new firmware failed\n");
goto exit;
}
/*update flag status*/
size = 0;
OtaFg = 0;
IncFg = 1;
next_erase_sector = 0;
}
exit:
ota_update_free(alloc);
return res;
}
/**
* @brief OTA update through https
* @param host: host addr of https server
* @param port: https server port
* @param resource: resource path
* @retval -1:fail;0:success
*/
int https_update_ota(char *host, int port, char *resource)
{
unsigned char *alloc=NULL, *request=NULL;
int alloc_buf_size = BUF_SIZE;
int read_bytes = 0;
int ret = -1;
int writelen = 0;
u32 RevHdrLen = 0;
http_response_result_t rsp_result = {0};
uint32_t ota_target_index = OTA_INDEX_2;
update_ota_target_hdr OtaTargetHdr;
mbedtls_net_context server_fd;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
restart_https_ota:
redirect_server_port = 0;
alloc = (unsigned char *)ota_update_malloc(alloc_buf_size);
if(!alloc){
printf("[%s] Alloc buffer failed\n", __FUNCTION__);
goto update_ota_exit;
}
/*connect https server*/
mbedtls_platform_set_calloc_free(my_calloc, vPortFree);
mbedtls_net_init(&server_fd);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
char *port_str = https_itoa (port);
if((ret = mbedtls_net_connect(&server_fd, host, port_str, MBEDTLS_NET_PROTO_TCP)) != 0) {
printf("ERROR: mbedtls_net_connect ret(%d)\n", ret);
goto update_ota_exit;
}
mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
if((ret = mbedtls_ssl_config_defaults(&conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
printf("ERRPR: mbedtls_ssl_config_defaults ret(%d)\n", ret);
goto update_ota_exit;
}
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_NONE);
mbedtls_ssl_conf_rng(&conf, my_random, NULL);
if((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
printf("ERRPR: mbedtls_ssl_setup ret(%d)\n", ret);
goto update_ota_exit;
}
if((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
printf("ERROR: mbedtls_ssl_handshake ret(-0x%x)", -ret);
goto update_ota_exit;
}
printf("SSL ciphersuite %s\n", mbedtls_ssl_get_ciphersuite(&ssl));
/*send https request*/
uint32_t idx = 0;
request = (unsigned char *) ota_update_malloc(strlen("GET /") + strlen(resource) + strlen(" HTTP/1.1\r\nHost: ")
+ strlen(host) + strlen("\r\n\r\n") + 1);
sprintf((char*)request, "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", resource, host);
ret = mbedtls_ssl_write(&ssl, request, strlen((char*)request));
if(ret < 0){
printf("[%s] Send HTTPS request failed\n", __FUNCTION__);
goto update_ota_exit;
}
/* parse https response*/
while (3 >= rsp_result.parse_status){//still read header
if(0 == rsp_result.parse_status){//didn't get the http response
memset(alloc, 0, alloc_buf_size);
read_bytes = mbedtls_ssl_read(&ssl, alloc, alloc_buf_size);
if(read_bytes <= 0){
printf("[%s] Read socket failed\n", __FUNCTION__);
goto update_ota_exit;
}
idx = read_bytes;
memset(&rsp_result, 0, sizeof(rsp_result));
if(parse_http_response(alloc, idx, &rsp_result) == -1){
goto update_ota_exit;
}
} else if ((1 == rsp_result.parse_status) || (3 == rsp_result.parse_status)){//just get the status code
memset(alloc, 0, alloc_buf_size);
memcpy(alloc, rsp_result.header_bak, HEADER_BAK_LEN);
ota_update_free(rsp_result.header_bak);
rsp_result.header_bak = NULL;
read_bytes = mbedtls_ssl_read(&ssl, alloc + HEADER_BAK_LEN, (alloc_buf_size - HEADER_BAK_LEN));
if(read_bytes <= 0){
printf("[%s] Read socket failed\n", __FUNCTION__);
goto update_ota_exit;
}
idx = read_bytes + HEADER_BAK_LEN;
if (parse_http_response(alloc, read_bytes + HEADER_BAK_LEN, &rsp_result) == -1){
goto update_ota_exit;
}
}
}
if (0 == rsp_result.body_len) {
printf("[%s] New firmware size = 0 !\n", __FUNCTION__);
goto update_ota_exit;
} else {
printf("[%s] Download new firmware begin, total size : %d\n", __FUNCTION__, rsp_result.body_len);
}
writelen = idx - rsp_result.header_len;
/* remove https header_len from alloc*/
memset(alloc, 0, rsp_result.header_len);
_memcpy(alloc, alloc+rsp_result.header_len, writelen);
memset(alloc+writelen, 0, rsp_result.header_len);
/* check OTA index we should update */
if (ota_get_cur_index() == OTA_INDEX_1) {
ota_target_index = OTA_INDEX_2;
printf("\n\r[%s] OTA2 address space will be upgraded \n", __FUNCTION__);
} else {
ota_target_index = OTA_INDEX_1;
printf("\n\r[%s] OTA1 address space will be upgraded \n", __FUNCTION__);
}
/*----------------step2: receive firmware file header---------------------*/
if(!recv_ota_file_hdr_https(alloc, writelen, &RevHdrLen, &OtaTargetHdr, &ssl)) {
printf("\n\r[%s] recv firmware header failed", __FUNCTION__);
goto update_ota_exit;
}
/* -----step3: parse firmware file header and get the target OTA image header-----*/
if(!get_ota_tartget_header(alloc, RevHdrLen, &OtaTargetHdr, ota_target_index)) {
printf("\n\rget OTA header failed\n");
goto update_ota_exit;
}
/* the upgrade space should be masked */
//ota_rsip_mask(NewImg2Addr, OtaTargetHdr.FileImgHdr.ImgLen, ENABLE);
/*-------------------step4: erase flash space for new firmware--------------*/
/*erase flash space new OTA image */
//printf("\n\rErase is ongoing...");
//for(i = 0; i < OtaTargetHdr.ValidImgCnt; i++) {
// erase_ota_target_flash(OtaTargetHdr.FileImgHdr[i].FlashAddr, OtaTargetHdr.FileImgHdr[i].ImgLen);
//}
/*---------step5: download new firmware from server and write it to flash--------*/
if(download_new_fw_from_server_https(alloc, writelen, &ssl, &OtaTargetHdr, ota_target_index) == _FALSE){
goto update_ota_exit;
}
/*-------------step6: verify checksum and update signature-----------------*/
if(verify_ota_checksum(&OtaTargetHdr)){
if(!change_ota_signature(&OtaTargetHdr, ota_target_index)) {
printf("\n\rChange signature failed\n");
goto update_ota_exit;
}
ret = 0;
}
update_ota_exit:
if(alloc)
ota_update_free(alloc);
if(request)
ota_update_free(request);
mbedtls_net_free(&server_fd);
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
/* redirect_server_port != 0 means there is redirect URL can be downloaded*/
if(redirect_server_port != 0){
host = redirect_server_host;
resource = redirect_resource;
port = redirect_server_port;
printf("OTA redirect host: %s, port: %d, resource: %s\n\r", host, port, resource);
goto restart_https_ota;
}
ota_update_free(redirect);
ota_update_free(redirect_server_host);
ota_update_free(redirect_resource);
return ret;
}
#endif
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/misc/rtl8721d_ota.c
|
C
|
apache-2.0
| 60,268
|
#ifndef _RTL_LIB_ROM_H_
#define _RTL_LIB_ROM_H_
#include "memproc.h"
#include "strproc.h"
#include "diag.h"
#endif /* _RTL_LIB_ROM_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/include/rt_lib_rom.h
|
C
|
apache-2.0
| 140
|
#ifndef _RTL_LIB_H_
#define _RTL_LIB_H_
#include "memproc.h"
#include "strproc.h"
#include "diag.h"
#endif /* _RTL_LIB_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/include/rtl_lib.h
|
C
|
apache-2.0
| 127
|
include $(MAKE_INCLUDE_GEN)
.PHONY: all clean
MODULE_IFLAGS = -I./include
#*****************************************************************************#
# Object FILE LIST #
#*****************************************************************************#
#OBJS = diag.o memset.o strproc.o rand.o memcpy.o memcmp.o rtl_utility.o
OBJS =
INFRA_ROM_OBJS = diag.o memset.o strproc.o rand.o memcpy.o memcmp.o
OBJS = $(INFRA_ROM_OBJS)
#*****************************************************************************#
# RULES TO GENERATE TARGETS #
#*****************************************************************************#
# Define the Rules to build the core targets
all: CORE_TARGETS RENAME_ROM_OBJS COPY_ROM_OBJS
#*****************************************************************************#
# GENERATE OBJECT FILE
#*****************************************************************************#
CORE_TARGETS: $(OBJS)
#*****************************************************************************#
# RULES TO CLEAN TARGETS #
#*****************************************************************************#
clean:
$(REMOVE) *.o
$(REMOVE) *.i
$(REMOVE) *.s
$(REMOVE) *.d
-include $(DEPS)
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/Makefile
|
Makefile
|
apache-2.0
| 1,380
|
#include <section_config.h>
#include <basic_types.h>
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
u8 _char2num(u8 ch)
{
if((ch>='0')&&(ch<='9'))
return ch - '0';
else if ((ch>='a')&&(ch<='f'))
return ch - 'a' + 10;
else if ((ch>='A')&&(ch<='F'))
return ch - 'A' + 10;
else
return 0xff;
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
u8 _2char2dec(u8 hch, u8 lch)
{
return ((_char2num(hch) * 10 ) + _char2num(lch));
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
u8 _2char2hex(u8 hch, u8 lch)
{
return ((_char2num(hch) << 4) | _char2num(lch));
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/char2num.c
|
C
|
apache-2.0
| 558
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "basic_types.h"
#include <stdarg.h>
#include "ameba_soc.h"
#include "rtl8721d_loguart.h"
#include "section_config.h"
#include <strproc.h>
#include "diag.h"
HAL_ROM_BSS_SECTION DIAG_PRINT_BUF_FUNC ConfigDebugBufferGet;
HAL_ROM_BSS_SECTION u32 ConfigDebugBuffer;
HAL_ROM_BSS_SECTION u32 ConfigDebugClose;
HAL_ROM_BSS_SECTION u32 ConfigDebug[LEVEL_NUMs];
HAL_ROM_TEXT_SECTION
int DiagVSprintf(char *buf, const char *fmt, const int *dp)
{
char *p, *s;
s = buf;
for(; *fmt != '\0'; ++fmt) {
if(*fmt != '%') {
if(buf) {
*s++ = *fmt;
} else {
DiagPutChar(*fmt);
}
continue;
}
if(*++fmt == 's') {
for(p = (char *)*dp++; *p != '\0'; p++) {
if(buf) {
*s++ = *p;
} else {
DiagPutChar(*p);
}
}
}
else { /* Length of item is bounded */
char tmp[20], *q = tmp;
int alt = 0;
int shift = 0;// = 12;
const long *lpforchk = (const long *)dp;
if((*lpforchk) < 0x10) {
shift = 0;
}
else if(((*lpforchk) >= 0x10) && ((*lpforchk) < 0x100)) {
shift = 4;
}
else if(((*lpforchk) >= 0x100) && ((*lpforchk) < 0x1000)) {
shift = 8;
}
else if(((*lpforchk) >= 0x1000) && ((*lpforchk) < 0x10000)) {
shift = 12;
}
else if(((*lpforchk) >= 0x10000) && ((*lpforchk) < 0x100000)) {
shift = 16;
}
else if(((*lpforchk) >= 0x100000) && ((*lpforchk) < 0x1000000)) {
shift = 20;
}
else if(((*lpforchk) >= 0x1000000) && ((*lpforchk) < 0x10000000)) {
shift = 24;
}
else if((*lpforchk) >= 0x10000000) {
shift = 28;
}
else {
shift = 28;
}
#if 1 //wei patch for %02x
if((*fmt >= '0') && (*fmt <= '9'))
{
int width;
unsigned char fch = *fmt;
for(width=0; (fch>='0') && (fch<='9'); fch=*++fmt)
{ width = width * 10 + fch - '0';
}
shift=(width-1)*4;
}
#endif
/*
* Before each format q points to tmp buffer
* After each format q points past end of item
*/
if((*fmt == 'x')||(*fmt == 'X') || (*fmt == 'p') || (*fmt == 'P')) {
/* With x86 gcc, sizeof(long) == sizeof(int) */
const long *lp = (const long *)dp;
unsigned long h = *lp++;
int hex_count = 0;
unsigned long h_back = h;
int ncase = (*fmt & 0x20);
dp = (const int *)lp;
if((*fmt == 'p') || (*fmt == 'P'))
alt=1;
if(alt) {
*q++ = '0';
*q++ = 'X' | ncase;
}
//hback 是实际得到的数据,hex_count是统计数据的HEX字符个数
while(h_back) {
hex_count += 1;
h_back = h_back >> 4;
}
//这里修复 example: 字符有4个,但是用了%02x导致字符被截断的情况
if(shift < (hex_count - 1)*4)
shift = (hex_count - 1)*4;
//printf("(%d,%d)", hex_count, shift);
for(; shift >= 0; shift -= 4) {
*q++ = "0123456789ABCDEF"[(h >> shift) & 0xF] | ncase;
}
}
else if(*fmt == 'd') {
int i = *dp++;
char *r;
int digit_space = 0;
if(i < 0) {
*q++ = '-';
i = -i;
digit_space++;
}
p = q; /* save beginning of digits */
do {
*q++ = '0' + (i % 10);
i /= 10;
digit_space++;
} while(i);
//这里修复 example:用了%08d后,在数字前面没有0的情况
for(; shift >= 0; shift -= 4) {
if(digit_space-- > 0) {
; //do nothing
} else {
*q++ = '0';
}
}
/* reverse digits, stop in middle */
r = q; /* don't alter q */
while(--r > p) {
i = *r;
*r = *p;
*p++ = i;
}
}
else if(*fmt == 'c')
*q++ = *dp++;
else
*q++ = *fmt;
/* now output the saved string */
for(p = tmp; p < q; ++p) {
if(buf) {
*s++ = *p;
} else {
DiagPutChar(*p);
}
if((*p) == '\n') {
DiagPutChar('\r');
}
}
}
}
if(buf)
*s = '\0';
return (s - buf);
}
HAL_ROM_TEXT_SECTION
_LONG_CALL_ u32
DiagPrintf(
IN const char *fmt, ...
)
{
log_buffer_t *buf = NULL;
int ret = 0;
if (ConfigDebugClose == 1)
return 0;
if (ConfigDebugBuffer == 1 && ConfigDebugBufferGet != NULL) {
buf = (log_buffer_t *)ConfigDebugBufferGet(fmt);
}
if (buf != NULL) {
return DiagVSprintf(buf->buffer, fmt, ((const int *)&fmt)+1);
} else {
ret = DiagVSprintf(NULL, fmt, ((const int *)&fmt)+1);
return ret;
}
}
HAL_ROM_TEXT_SECTION
_LONG_CALL_ u32
DiagPrintfD(
IN const char *fmt, ...
)
{
//log_buffer_t *buf = NULL;
if (ConfigDebugClose == 1)
return 0;
return DiagVSprintf(NULL, fmt, ((const int *)&fmt)+1);
}
HAL_ROM_TEXT_SECTION
u32
DiagSPrintf(
IN u8 *buf,
IN const char *fmt, ...
)
{
if (ConfigDebugClose == 1)
return 0;
return DiagVSprintf((char*)buf, fmt, ((const int *)&fmt)+1);
}
HAL_ROM_TEXT_SECTION
int DiagSnPrintf(char *buf, size_t size, const char *fmt, ...)
{
va_list ap;
char *p, *s, *buf_end = NULL;
const int *dp = ((const int *)&fmt)+1;
if(buf == NULL)
return 0;
va_start(ap, fmt);
s = buf;
buf_end = size? (buf + size):(char*)~0;
for(; *fmt != '\0'; ++fmt) {
if(*fmt != '%') {
*s++ = *fmt;
if(s >= buf_end) {
goto Exit;
}
continue;
}
if(*++fmt == 's') {
for(p = (char *)*dp++; *p != '\0'; p++) {
*s++ = *p;
if(s >= buf_end) {
goto Exit;
}
}
}
else { /* Length of item is bounded */
char tmp[20], *q = tmp;
int alt = 0;
int shift = 0;// = 12;
const long *lpforchk = (const long *)dp;
if((*lpforchk) < 0x10) {
shift = 0;
}
else if(((*lpforchk) >= 0x10) && ((*lpforchk) < 0x100)) {
shift = 4;
}
else if(((*lpforchk) >= 0x100) && ((*lpforchk) < 0x1000)) {
shift = 8;
}
else if(((*lpforchk) >= 0x1000) && ((*lpforchk) < 0x10000)) {
shift = 12;
}
else if(((*lpforchk) >= 0x10000) && ((*lpforchk) < 0x100000)) {
shift = 16;
}
else if(((*lpforchk) >= 0x100000) && ((*lpforchk) < 0x1000000)) {
shift = 20;
}
else if(((*lpforchk) >= 0x1000000) && ((*lpforchk) < 0x10000000)) {
shift = 24;
}
else if((*lpforchk) >= 0x10000000) {
shift = 28;
}
else {
shift = 28;
}
if((*fmt >= '0') && (*fmt <= '9'))
{
int width;
unsigned char fch = *fmt;
for(width=0; (fch>='0') && (fch<='9'); fch=*++fmt)
{ width = width * 10 + fch - '0';
}
shift=(width-1)*4;
}
/*
* Before each format q points to tmp buffer
* After each format q points past end of item
*/
if((*fmt == 'x')||(*fmt == 'X') || (*fmt == 'p') || (*fmt == 'P')) {
/* With x86 gcc, sizeof(long) == sizeof(int) */
const long *lp = (const long *)dp;
long h = *lp++;
int hex_count = 0;
unsigned long h_back = h;
int ncase = (*fmt & 0x20);
dp = (const int *)lp;
if((*fmt == 'p') || (*fmt == 'P'))
alt=1;
if(alt) {
*q++ = '0';
*q++ = 'X' | ncase;
}
while(h_back) {
hex_count += (h_back & 0xF) ? 1 : 0;
h_back = h_back >> 4;
}
if(shift < (hex_count - 1)*4)
shift = (hex_count - 1)*4;
for(; shift >= 0; shift -= 4)
*q++ = "0123456789ABCDEF"[(h >> shift) & 0xF] | ncase;
}
else if(*fmt == 'd') {
int i = *dp++;
char *r;
int digit_space = 0;
if(i < 0) {
*q++ = '-';
i = -i;
digit_space++;
}
p = q; /* save beginning of digits */
do {
*q++ = '0' + (i % 10);
i /= 10;
digit_space++;
} while(i);
for(; shift >= 0; shift -= 4) {
if(digit_space-- > 0) {
; //do nothing
} else {
*q++ = '0';
}
}
/* reverse digits, stop in middle */
r = q; /* don't alter q */
while(--r > p) {
i = *r;
*r = *p;
*p++ = i;
}
}
else if(*fmt == 'c')
*q++ = *dp++;
else
*q++ = *fmt;
/* now output the saved string */
for(p = tmp; p < q; ++p) {
*s++ = *p;
if(s >= buf_end) {
goto Exit;
}
}
}
}
Exit:
if(buf)
*s = '\0';
va_end(ap);
return(s-buf);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/diag.c
|
C
|
apache-2.0
| 8,126
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#ifndef _DIAG_H_
#define _DIAG_H_
#include "platform_autoconf.h"
#include "basic_types.h"
#include "rtl_trace.h"
u32 DiagPrintf(const char *fmt, ...);
u32 DiagPrintfD(const char *fmt, ...);
int DiagVSprintf(char *buf, const char *fmt, const int *dp);
/** @addtogroup Ameba_Platform
* @{
*/
/** @defgroup Platform_Debug Debug
* @brief Platform_Debug modules
* @{
*/
/** @defgroup Platform_Debug_Log_Trace_Exported_Types Log Trace Types
* @{
*/
/** @brief Log Module Definition */
typedef enum {
MODULE_OS = 0, /**< FreeRTOS */
MODULE_BOOT = 1, /**< bootloader */
MODULE_GDMA = 2, /**< gdma */
MODULE_GPIO = 3, /**< gpio */
MODULE_TIMER = 4, /**< timer */
MODULE_I2C = 5, /**< i2c */
MODULE_I2S = 6, /**< i2s */
MODULE_PWM = 7, /**< pwm */
MODULE_SDIO = 8, /**< sdio */
MODULE_SPI = 9, /**< spi */
MODULE_FLASH = 10, /**< flash */
MODULE_UART = 11, /**< uart */
MODULE_USB_OTG = 12, /**< usb otg */
MODULE_IPSEC = 13, /**< ipsec */
MODULE_ADC = 14, /**< adc */
MODULE_EFUSE = 15, /**< efuse */
MODULE_MONIT = 16, /**< monitor */
MODULE_MISC = 17, /**< misc */
MODULE_IR = 18,
MODULE_QDECODE = 19,
MODULE_KEYSCAN = 20,
MODULE_SGPIO = 21,
MODULE_AUDIO = 22,
MODULE_LCD = 23,
MODULE_WIFIFW = 24,
MODULE_BT = 25,
MODULE_IPC = 26,
MODULE_KM4 = 27,
MODULE_NUMs = 32 /**< Module Number */
} MODULE_DEFINE;
/** @brief Log Level Definition */
typedef enum {
LEVEL_ERROR = 0, /**< Error */
LEVEL_WARN = 1, /**< Warning */
LEVEL_INFO = 2, /**< Information */
LEVEL_TRACE = 3, /**< Trace Data */
LEVEL_NUMs = 4 /**< Level Number */
} LEVEL_DEFINE;
/** End of Platform_Debug_Log_Trace_Exported_Types
* @}
*/
/** @defgroup Platform_Debug_Log_Trace_Functions_And_Macro Function & Macro
* @{
*/
/** @cond private */
/** @brief Debug Log mask */
extern u32 ConfigDebug[];
/** @endcond */
/**
* @brief Debug Log Mask Set.
* @param config[4] -- Print log if bit MODULE_DEFINE of config[LEVEL_DEFINE] is 1;
* @return void.
* @note Here is a MODULE_BOOT module sample to demostrate the using of LOG_MASK().
* We want to print log under ERROR level and INFO level.
* @code{.c}
* u32 debug[4];
* debug[LEVEL_ERROR] = BIT(MODULE_BOOT);
* debug[LEVEL_WARN] = 0x0;
* debug[LEVEL_INFO] = BIT(MODULE_BOOT);
* debug[LEVEL_TRACE] = 0x0;
*
* LOG_MASK(LEVEL_ERROR, debug[LEVEL_ERROR]);
* LOG_MASK(LEVEL_WARN, debug[LEVEL_WARN]);
* LOG_MASK(LEVEL_INFO, debug[LEVEL_INFO]);
* LOG_MASK(LEVEL_TRACE, debug[LEVEL_TRACE]);
*
* DBG_PRINTF(MODULE_BOOT, LEVEL_INFO, "MODULE_BOOT Info.\n");
* DBG_PRINTF(MODULE_BOOT, LEVEL_ERROR, "MODULE_BOOT Error!\n");
* @endcode
*/
#define LOG_MASK(level, config) do {\
ConfigDebug[level] = config;\
} while (0)
#define LOG_MASK_MODULE(module, level, new_status) do {\
if (new_status == ENABLE) { \
ConfigDebug[level] |= BIT(module); \
} else { \
ConfigDebug[level] &= ~BIT(module); \
} \
} while (0)
/**
* @brief DBG_PRINTF is used to print log
*/
//#define RELEASE_VERSION
#ifdef RELEASE_VERSION
#define DBG_PRINTF(MODULE, LEVEL, pFormat, ...) do {\
if ((LEVEL < LEVEL_NUMs) && (MODULE < MODULE_NUMs) && (ConfigDebug[LEVEL] & BIT(MODULE))) {\
}\
}while(0)
#else
#define DBG_PRINTF(MODULE, LEVEL, pFormat, ...) do {\
if ((LEVEL < LEVEL_NUMs) && (MODULE < MODULE_NUMs) && (ConfigDebug[LEVEL] & BIT(MODULE)))\
DiagPrintf("["#MODULE"-"#LEVEL"]:"pFormat, ##__VA_ARGS__);\
}while(0)
#endif
#define DBG_ERR_MSG_ON(x) (ConfigDebug[LEVEL_ERROR] |= BIT(x))
#define DBG_WARN_MSG_ON(x) (ConfigDebug[LEVEL_WARN] |= BIT(x))
#define DBG_INFO_MSG_ON(x) (ConfigDebug[LEVEL_INFO] |= BIT(x))
#define DBG_ERR_MSG_OFF(x) (ConfigDebug[LEVEL_ERROR] &= ~BIT(x))
#define DBG_WARN_MSG_OFF(x) (ConfigDebug[LEVEL_WARN] &= ~BIT(x))
#define DBG_INFO_MSG_OFF(x) (ConfigDebug[LEVEL_INFO] &= ~BIT(x))
#define DRIVER_PREFIX "RTL8721D[Driver]: "
#ifdef CONFIG_DEBUG_LOG
#define DBG_8195A(...) do {\
if (unlikely(ConfigDebug[LEVEL_ERROR] & BIT(MODULE_MISC))) \
DiagPrintf("\r" __VA_ARGS__);\
}while(0)
#define MONITOR_LOG(...) do {\
if (unlikely(ConfigDebug[LEVEL_ERROR] & BIT(MODULE_MONIT))) \
DiagPrintf( __VA_ARGS__);\
}while(0)
#else // else of "#if CONFIG_DEBUG_LOG"
#define DBG_8195A(...)
#define MONITOR_LOG(...)
#endif
/** End of Platform_Debug_Log_Trace_Functions_And_Macro
* @}
*/
/** End of Platform_Debug
* @}
*/
/** End of AmebaZ_Platform
* @}
*/
extern u32 ConfigDebugBuffer;
extern u32 ConfigDebugClose;
extern u32 ConfigDebug[];
#endif //_DIAG_H_
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/diag.h
|
C
|
apache-2.0
| 4,869
|
#include <_ansi.h>
//#include <../libc/rom/ctype/local.h>
/* internal function to compute width of wide char. */
int _EXFUN (__wcwidth, (wint_t));
/* Defined in locale/locale.c. Returns a value != 0 if the current
language is assumed to use CJK fonts. */
int __locale_cjk_lang (void);
/*
Taken from glibc:
Add the compiler optimization to inhibit loop transformation to library
calls. This is used to avoid recursive calls in memset and memmove
default implementations.
*/
#ifdef _HAVE_CC_INHIBIT_LOOP_TO_LIBCALL
# define __inhibit_loop_to_libcall \
__attribute__ ((__optimize__ ("-fno-tree-loop-distribute-patterns")))
#else
# define __inhibit_loop_to_libcall
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/local.h
|
C
|
apache-2.0
| 692
|
/*
FUNCTION
<<memchr>>---find character in memory
INDEX
memchr
ANSI_SYNOPSIS
#include <string.h>
void *memchr(const void *<[src]>, int <[c]>, size_t <[length]>);
TRAD_SYNOPSIS
#include <string.h>
void *memchr(<[src]>, <[c]>, <[length]>)
void *<[src]>;
void *<[c]>;
size_t <[length]>;
DESCRIPTION
This function searches memory starting at <<*<[src]>>> for the
character <[c]>. The search only ends with the first
occurrence of <[c]>, or after <[length]> characters; in
particular, <<NUL>> does not terminate the search.
RETURNS
If the character <[c]> is found within <[length]> characters
of <<*<[src]>>>, a pointer to the character is returned. If
<[c]> is not found, then <<NULL>> is returned.
PORTABILITY
<<memchr>> is ANSI C.
<<memchr>> requires no supporting OS subroutines.
QUICKREF
memchr ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <_ansi.h>
#include <string.h>
#include <limits.h>
/* Nonzero if either X or Y is not aligned on a "long" boundary. */
#define UNALIGNED(X) ((long)X & (sizeof (long) - 1))
/* How many bytes are loaded each iteration of the word copy loop. */
#define LBLOCKSIZE (sizeof (long))
/* Threshhold for punting to the bytewise iterator. */
#define TOO_SMALL(LEN) ((LEN) < LBLOCKSIZE)
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
/* Nonzero if X (a long int) contains a NULL byte. */
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif
/* DETECTCHAR returns nonzero if (long)X contains the byte used
to fill (long)MASK. */
#define DETECTCHAR(X,MASK) (DETECTNULL(X ^ MASK))
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
void * _memchr(const void * src_void , int c , size_t length)
{
const unsigned char *src = (const unsigned char *) src_void;
unsigned char d = c;
#if !defined(PREFER_SIZE_OVER_SPEED)
unsigned long *asrc;
unsigned long mask;
u32 i;
while (UNALIGNED (src))
{
if (!length--)
return NULL;
if (*src == d)
return (void *) src;
src++;
}
if (!TOO_SMALL (length))
{
/* If we get this far, we know that length is large and src is
word-aligned. */
/* The fast code reads the source one word at a time and only
performs the bytewise search on word-sized segments if they
contain the search character, which is detected by XORing
the word-sized segment with a word-sized block of the search
character and then detecting for the presence of NUL in the
result. */
asrc = (unsigned long *) src;
mask = d << 8 | d;
mask = mask << 16 | mask;
for (i = 32; i < LBLOCKSIZE * 8; i <<= 1)
mask = (mask << i) | mask;
while (length >= LBLOCKSIZE)
{
if (DETECTCHAR (*asrc, mask))
break;
length -= LBLOCKSIZE;
asrc++;
}
/* If there are fewer than LBLOCKSIZE characters left,
then we resort to the bytewise loop. */
src = (unsigned char *) asrc;
}
#endif /* not PREFER_SIZE_OVER_SPEED */
while (length--)
{
if (*src == d)
return (void *) src;
src++;
}
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/memchr.c
|
C
|
apache-2.0
| 3,393
|
/*
FUNCTION
<<memcmp>>---compare two memory areas
INDEX
memcmp
ANSI_SYNOPSIS
#include <string.h>
int memcmp(const void *<[s1]>, const void *<[s2]>, size_t <[n]>);
TRAD_SYNOPSIS
#include <string.h>
int memcmp(<[s1]>, <[s2]>, <[n]>)
void *<[s1]>;
void *<[s2]>;
size_t <[n]>;
DESCRIPTION
This function compares not more than <[n]> characters of the
object pointed to by <[s1]> with the object pointed to by <[s2]>.
RETURNS
The function returns an integer greater than, equal to or
less than zero according to whether the object pointed to by
<[s1]> is greater than, equal to or less than the object
pointed to by <[s2]>.
PORTABILITY
<<memcmp>> is ANSI C.
<<memcmp>> requires no supporting OS subroutines.
QUICKREF
memcmp ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
/* Nonzero if either X or Y is not aligned on a "long" boundary. */
#define UNALIGNED(X, Y) \
(((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
/* How many bytes are copied each iteration of the word copy loop. */
#define LBLOCKSIZE (sizeof (long))
/* Threshhold for punting to the byte copier. */
#define TOO_SMALL(LEN) ((LEN) < LBLOCKSIZE)
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
int _memcmp(const void * m1 , const void * m2 , size_t n)
{
#if defined(PREFER_SIZE_OVER_SPEED)
unsigned char *s1 = (unsigned char *) m1;
unsigned char *s2 = (unsigned char *) m2;
while (n--)
{
if (*s1 != *s2)
{
return *s1 - *s2;
}
s1++;
s2++;
}
return 0;
#else
unsigned char *s1 = (unsigned char *) m1;
unsigned char *s2 = (unsigned char *) m2;
unsigned long *a1;
unsigned long *a2;
/* If the size is too small, or either pointer is unaligned,
then we punt to the byte compare loop. Hopefully this will
not turn up in inner loops. */
if (!TOO_SMALL(n) && !UNALIGNED(s1,s2))
{
/* Otherwise, load and compare the blocks of memory one
word at a time. */
a1 = (unsigned long*) s1;
a2 = (unsigned long*) s2;
while (n >= LBLOCKSIZE)
{
if (*a1 != *a2)
break;
a1++;
a2++;
n -= LBLOCKSIZE;
}
/* check m mod LBLOCKSIZE remaining characters */
s1 = (unsigned char*)a1;
s2 = (unsigned char*)a2;
}
while (n--)
{
if (*s1 != *s2)
return *s1 - *s2;
s1++;
s2++;
}
return 0;
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/memcmp.c
|
C
|
apache-2.0
| 2,465
|
/*
FUNCTION
<<memcpy>>---copy memory regions
ANSI_SYNOPSIS
#include <string.h>
void* memcpy(void *restrict <[out]>, const void *restrict <[in]>,
size_t <[n]>);
TRAD_SYNOPSIS
#include <string.h>
void *memcpy(<[out]>, <[in]>, <[n]>
void *<[out]>;
void *<[in]>;
size_t <[n]>;
DESCRIPTION
This function copies <[n]> bytes from the memory region
pointed to by <[in]> to the memory region pointed to by
<[out]>.
If the regions overlap, the behavior is undefined.
RETURNS
<<memcpy>> returns a pointer to the first byte of the <[out]>
region.
PORTABILITY
<<memcpy>> is ANSI C.
<<memcpy>> requires no supporting OS subroutines.
QUICKREF
memcpy ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <_ansi.h>
#include <string.h>
/* Nonzero if either X or Y is not aligned on a "long" boundary. */
#define UNALIGNED(X, Y) \
(((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
/* How many bytes are copied each iteration of the 4X unrolled loop. */
#define BIGBLOCKSIZE (sizeof (long) << 2)
/* How many bytes are copied each iteration of the word copy loop. */
#define LITTLEBLOCKSIZE (sizeof (long))
/* Threshhold for punting to the byte copier. */
#define TOO_SMALL(LEN) ((LEN) < BIGBLOCKSIZE)
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
void * _memcpy(void * __restrict dst0 , const void * __restrict src0 , size_t len0)
{
#if defined(PREFER_SIZE_OVER_SPEED)
char *dst = (char *) dst0;
char *src = (char *) src0;
void * save = dst0;
while (len0--)
{
*dst++ = *src++;
}
return save;
#else
char *dst = dst0;
const char *src = src0;
long *aligned_dst;
const long *aligned_src;
/* If the size is small, or either SRC or DST is unaligned,
then punt into the byte copy loop. This should be rare. */
if (!TOO_SMALL(len0) && !UNALIGNED (src, dst))
{
aligned_dst = (long*)dst;
aligned_src = (long*)src;
/* Copy 4X long words at a time if possible. */
while (len0 >= BIGBLOCKSIZE)
{
*aligned_dst++ = *aligned_src++;
*aligned_dst++ = *aligned_src++;
*aligned_dst++ = *aligned_src++;
*aligned_dst++ = *aligned_src++;
len0 -= BIGBLOCKSIZE;
}
/* Copy one long word at a time if possible. */
while (len0 >= LITTLEBLOCKSIZE)
{
*aligned_dst++ = *aligned_src++;
len0 -= LITTLEBLOCKSIZE;
}
/* Pick up any residual with a byte copier. */
dst = (char*)aligned_dst;
src = (char*)aligned_src;
}
while (len0--)
*dst++ = *src++;
return dst0;
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/memcpy.c
|
C
|
apache-2.0
| 2,772
|
/*
FUNCTION
<<memmove>>---move possibly overlapping memory
INDEX
memmove
ANSI_SYNOPSIS
#include <string.h>
void *memmove(void *<[dst]>, const void *<[src]>, size_t <[length]>);
TRAD_SYNOPSIS
#include <string.h>
void *memmove(<[dst]>, <[src]>, <[length]>)
void *<[dst]>;
void *<[src]>;
size_t <[length]>;
DESCRIPTION
This function moves <[length]> characters from the block of
memory starting at <<*<[src]>>> to the memory starting at
<<*<[dst]>>>. <<memmove>> reproduces the characters correctly
at <<*<[dst]>>> even if the two areas overlap.
RETURNS
The function returns <[dst]> as passed.
PORTABILITY
<<memmove>> is ANSI C.
<<memmove>> requires no supporting OS subroutines.
QUICKREF
memmove ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <_ansi.h>
#include <stddef.h>
#include <limits.h>
#include "local.h"
/* Nonzero if either X or Y is not aligned on a "long" boundary. */
#define UNALIGNED(X, Y) \
(((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
/* How many bytes are copied each iteration of the 4X unrolled loop. */
#define BIGBLOCKSIZE (sizeof (long) << 2)
/* How many bytes are copied each iteration of the word copy loop. */
#define LITTLEBLOCKSIZE (sizeof (long))
/* Threshhold for punting to the byte copier. */
#define TOO_SMALL(LEN) ((LEN) < BIGBLOCKSIZE)
/*SUPPRESS 20*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
void * __inhibit_loop_to_libcall _memmove( void * dst_void , const void * src_void , size_t length)
{
#if defined(PREFER_SIZE_OVER_SPEED)
char *dst = dst_void;
const char *src = src_void;
if (src < dst && dst < src + length)
{
/* Have to copy backwards */
src += length;
dst += length;
while (length--)
{
*--dst = *--src;
}
}
else
{
while (length--)
{
*dst++ = *src++;
}
}
return dst_void;
#else
char *dst = dst_void;
const char *src = src_void;
long *aligned_dst;
const long *aligned_src;
if (src < dst && dst < src + length)
{
/* Destructive overlap...have to copy backwards */
src += length;
dst += length;
while (length--)
{
*--dst = *--src;
}
}
else
{
/* Use optimizing algorithm for a non-destructive copy to closely
match memcpy. If the size is small or either SRC or DST is unaligned,
then punt into the byte copy loop. This should be rare. */
if (!TOO_SMALL(length) && !UNALIGNED (src, dst))
{
aligned_dst = (long*)dst;
aligned_src = (long*)src;
/* Copy 4X long words at a time if possible. */
while (length >= BIGBLOCKSIZE)
{
*aligned_dst++ = *aligned_src++;
*aligned_dst++ = *aligned_src++;
*aligned_dst++ = *aligned_src++;
*aligned_dst++ = *aligned_src++;
length -= BIGBLOCKSIZE;
}
/* Copy one long word at a time if possible. */
while (length >= LITTLEBLOCKSIZE)
{
*aligned_dst++ = *aligned_src++;
length -= LITTLEBLOCKSIZE;
}
/* Pick up any residual with a byte copier. */
dst = (char*)aligned_dst;
src = (char*)aligned_src;
}
while (length--)
{
*dst++ = *src++;
}
}
return dst_void;
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/memmove.c
|
C
|
apache-2.0
| 3,423
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#ifndef _MEM_PROC_H_
#define _MEM_PROC_H_
#include <basic_types.h>
/* change name from hal_misc.h */
extern _LONG_CALL_ void *_memset( void *s, int c, SIZE_T n );
extern _LONG_CALL_ void *_memcpy( void *s1, const void *s2, SIZE_T n );
extern _LONG_CALL_ int _memcmp( const void *av, const void *bv, SIZE_T len );
extern _LONG_CALL_ void * _memchr(const void * src_void , int c , size_t length);
extern _LONG_CALL_ void * _memmove( void * dst_void , const void * src_void , size_t length);
void memcpy_gdma_init(void);
int memcpy_gdma(void *dest, void *src, u32 size);
#endif //_MEM_PROC_H_
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/memproc.h
|
C
|
apache-2.0
| 843
|
/*
FUNCTION
<<memset>>---set an area of memory
INDEX
memset
ANSI_SYNOPSIS
#include <string.h>
void *memset(void *<[dst]>, int <[c]>, size_t <[length]>);
TRAD_SYNOPSIS
#include <string.h>
void *memset(<[dst]>, <[c]>, <[length]>)
void *<[dst]>;
int <[c]>;
size_t <[length]>;
DESCRIPTION
This function converts the argument <[c]> into an unsigned
char and fills the first <[length]> characters of the array
pointed to by <[dst]> to the value.
RETURNS
<<memset>> returns the value of <[dst]>.
PORTABILITY
<<memset>> is ANSI C.
<<memset>> requires no supporting OS subroutines.
QUICKREF
memset ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include "local.h"
#define LBLOCKSIZE (sizeof(long))
#define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1))
#define TOO_SMALL(LEN) ((LEN) < LBLOCKSIZE)
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
void * __inhibit_loop_to_libcall _memset(void * m , int c , size_t n)
{
char *s = (char *) m;
//#if !defined(PREFER_SIZE_OVER_SPEED)
u32 i;
unsigned long buffer;
unsigned long *aligned_addr;
unsigned int d = c & 0xff; /* To avoid sign extension, copy C to an
unsigned variable. */
while (UNALIGNED (s))
{
if (n--)
*s++ = (char) c;
else
return m;
}
if (!TOO_SMALL (n))
{
/* If we get this far, we know that n is large and s is word-aligned. */
aligned_addr = (unsigned long *) s;
/* Store D into each char sized location in BUFFER so that
we can set large blocks quickly. */
buffer = (d << 8) | d;
buffer |= (buffer << 16);
for (i = 32; i < LBLOCKSIZE * 8; i <<= 1)
buffer = (buffer << i) | buffer;
/* Unroll the loop. */
while (n >= LBLOCKSIZE*4)
{
*aligned_addr++ = buffer;
*aligned_addr++ = buffer;
*aligned_addr++ = buffer;
*aligned_addr++ = buffer;
n -= 4*LBLOCKSIZE;
}
while (n >= LBLOCKSIZE)
{
*aligned_addr++ = buffer;
n -= LBLOCKSIZE;
}
/* Pick up the remainder with a bytewise loop. */
s = (char*)aligned_addr;
}
//#endif /* not PREFER_SIZE_OVER_SPEED */
while (n--)
*s++ = (char) c;
return m;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/memset.c
|
C
|
apache-2.0
| 2,264
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#ifndef _RTL_PRINTF_H_
#define _RTL_PRINTF_H_
#define LONGFLAG 0x00000001
#define LONGLONGFLAG 0x00000002
#define HALFFLAG 0x00000004
#define HALFHALFFLAG 0x00000008
#define SIZETFLAG 0x00000010
#define INTMAXFLAG 0x00000020
#define PTRDIFFFLAG 0x00000040
#define ALTFLAG 0x00000080
#define CAPSFLAG 0x00000100
#define SHOWSIGNFLAG 0x00000200
#define SIGNEDFLAG 0x00000400
#define LEFTFORMATFLAG 0x00000800
#define LEADZEROFLAG 0x00001000
#define BLANKPOSFLAG 0x00002000
unsigned int printf_engine(const char *fmt, va_list args);
int _rtl_printf(const char * fmt,...);
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/printf.h
|
C
|
apache-2.0
| 880
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "ameba_soc.h"
HAL_ROM_BSS_SECTION u32 rand_seed[4]; //z1, z2, z3, z4,
HAL_ROM_BSS_SECTION u32 rand_first;
HAL_ROM_TEXT_SECTION
_LONG_CALL_ u32
Rand (
VOID
)
{
u32 b;
if (!rand_first) {
rand_seed[0] = 12345;
rand_seed[1] = 12345;
rand_seed[2] = 12345;
rand_seed[3] = 12345;
rand_first = 1;
}
b = ((rand_seed[0] << 6) ^ rand_seed[0]) >> 13;
rand_seed[0] = ((rand_seed[0] & 4294967294U) << 18) ^ b;
b = ((rand_seed[1] << 2) ^ rand_seed[1]) >> 27;
rand_seed[1] = ((rand_seed[1] & 4294967288U) << 2) ^ b;
b = ((rand_seed[2]<< 13) ^ rand_seed[2]) >> 21;
rand_seed[2] = ((rand_seed[2] & 4294967280U) << 7) ^ b;
b = ((rand_seed[3] << 3) ^ rand_seed[3]) >> 12;
rand_seed[3] = ((rand_seed[3] & 4294967168U) << 13) ^ b;
return (rand_seed[0] ^ rand_seed[1] ^ rand_seed[2] ^ rand_seed[3]);
}
HAL_ROM_TEXT_SECTION _LONG_CALL_
int Rand_Arc4(void)
{
u32 res = SYSTIMER_TickGet();
HAL_ROM_BSS_SECTION static unsigned long seed = 0xDEADB00B;
seed = ((seed & 0x007F00FF) << 7) ^
((seed & 0x0F80FF00) >> 8) ^ // be sure to stir those low bits
(res << 13) ^ (res >> 9); // using the clock too!
return (int)seed;
}
HAL_ROM_TEXT_SECTION _LONG_CALL_
int RandBytes_Get(void *buf, u32 len)
{
unsigned int ranbuf;
unsigned int *lp;
int i, count;
count = len / sizeof(unsigned int);
lp = (unsigned int *) buf;
for(i = 0; i < count; i ++) {
lp[i] = Rand_Arc4();
len -= sizeof(unsigned int);
}
if(len > 0) {
ranbuf = Rand_Arc4();
_memcpy(&lp[i], &ranbuf, len);
}
return 0;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/rand.c
|
C
|
apache-2.0
| 1,783
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
extern u32 rand_seed[4]; //z1, z2, z3, z4,
extern u32 rand_first;
u32
Rand (
VOID
);
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/rand.h
|
C
|
apache-2.0
| 338
|
#*****************************************************************************#
# ROM Object FILE LIST #
#*****************************************************************************#
SYS_ROM_OBJS = diag.o \
memcmp.o \
memcpy.o \
memset.o \
rand.o \
strproc.o
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/rom_lib.mk
|
Makefile
|
apache-2.0
| 377
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
#define USHRT_MAX ((u16)(~0U))
#define SHRT_MAX ((s16)(USHRT_MAX>>1))
#define ULLONG_MAX (~0ULL)
#define STR_STORE_MAX_LEN 24
#define KSTRTOX_OVERFLOW (1U << 31)
/**
* div_u64_rem - unsigned 64bit divide with 32bit divisor with remainder
*
* This is commonly provided by 32bit archs to provide an optimized 64bit
* divide.
*/
//static inline
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static u64 div_u64_rem(u64 dividend, u32 divisor, u32 *remainder)
{
*remainder = (u32)dividend % divisor;
return (u32)dividend / divisor;
}
/**
* div_s64_rem - signed 64bit divide with 32bit divisor with remainder
*/
//static inline
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static s64 div_s64_rem(s64 dividend, s32 divisor, s32 *remainder)
{
*remainder = (s32)dividend % divisor;
return (s32)dividend / divisor;
}
/**
* div_u64 - unsigned 64bit divide with 32bit divisor
*
* This is the most common 64bit divide and should be used if possible,
* as many 32bit archs can optimize this variant better than a full 64bit
* divide.
*/
#ifndef div_u64
//static inline
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static u64 div_u64(u64 dividend, u32 divisor)
{
u32 remainder;
return div_u64_rem(dividend, divisor, &remainder);
}
#endif
/**
* div_s64 - signed 64bit divide with 32bit divisor
*/
#ifndef div_s64
//static inline
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static s64 div_s64(s64 dividend, s32 divisor)
{
s32 remainder;
return div_s64_rem(dividend, divisor, &remainder);
}
#endif
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static const char *_parse_integer_fixup_radix(const char *s, unsigned int *base)
{
if (*base == 0) {
if (s[0] == '0') {
if (_tolower(s[1]) == 'x' && isxdigit(s[2]))
*base = 16;
else
*base = 8;
} else
*base = 10;
}
if (*base == 16 && s[0] == '0' && _tolower(s[1]) == 'x')
s += 2;
return s;
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static char *skip_spaces(const char *str)
{
while (isspace(*str))
++str;
return (char *)str;
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static int skip_atoi(const char **s)
{
int i = 0;
while (isdigit(**s))
i = i*10 + *((*s)++) - '0';
return i;
}
LIBC_ROM_TEXT_SECTION
static int judge_digit_width(const char *str, unsigned int base)
{
int width = 0;
if ((base == 16 || base == 0) && str[0] == '0' && _tolower(str[1]) == 'x') {
str += 2;
width += 2;
while(isxdigit(*str)) {
width++;
str++;
}
}else if(base == 16){
while(isxdigit(*str)) {
width++;
str++;
}
}else if(base == 8 ||(base == 0 && str[0] == '0' )) {
while(isdigit(*str) && (*str)<'8'){
width++;
str++;
}
}else{
while(isdigit(*str)) {
width++;
str++;
}
}
return width;
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ int _vsscanf(const char *buf, const char *fmt, va_list args)
{
const char *str = buf;
char *next;
char digit;
int num = 0;
int i =0;
u8 qualifier;
unsigned int base;
union {
long long s;
unsigned long long u;
} val;
s16 field_width;
bool is_sign;
char str_store[STR_STORE_MAX_LEN];
for(i = 0; i<STR_STORE_MAX_LEN ; i++)
str_store[i] = 0;
while(*fmt) {
/* skip any white space in format */
/* white space in format matchs any amount of
* white space, including none, in the input.
*/
if(isspace(*fmt)) {
fmt = skip_spaces(++fmt);
str = skip_spaces(str);
}
/* anything that is not a conversion must match exactly */
if(*fmt != '%' && *fmt) {
if(*fmt++ != *str++) {
break;
}
continue;
}
if(!*fmt) {
break;
}
++fmt;
/* skip this conversion.
* advance both strings to next white space
*/
if(*fmt == '*') {
if(!*str) {
break;
}
while(!isspace(*fmt) && *fmt != '%' && *fmt)
fmt++;
while(!isspace(*str) && *str)
str++;
continue;
}
/* get field width */
field_width = -1;
if(isdigit(*fmt)) {
field_width = skip_atoi(&fmt);
if(field_width <= 0) {
break;
}
}
/* get conversion qualifier */
qualifier = -1;
if(*fmt == 'h' || _tolower(*fmt) == 'l' ||
_tolower(*fmt) == 'z') {
qualifier = *fmt++;
if(qualifier == *fmt) {
if(qualifier == 'h') {
qualifier = 'H';
fmt++;
} else if(qualifier == 'l') {
qualifier = 'L';
fmt++;
}
}
}
if(!*fmt) {
break;
}
if(*fmt == 'n') {
/* return number of characters read so far */
*va_arg(args, int *) = str - buf;
++fmt;
continue;
}
if(!*str) {
break;
}
base = 10;
is_sign = 0;
switch(*fmt++) {
case 'c': {
char *s = (char *)va_arg(args, char*);
if(field_width == -1)
field_width = 1;
do {
*s++ = *str++;
} while(--field_width > 0 && *str);
num++;
}
continue;
case 's': {
char *s = (char *)va_arg(args, char *);
if(field_width == -1)
field_width = SHRT_MAX;
/* first, skip leading white space in buffer */
str = skip_spaces(str);
/* now copy until next white space */
while(*str && !isspace(*str) && field_width--) {
*s++ = *str++;
}
*s = '\0';
num++;
}
continue;
case 'o':
base = 8;
break;
case 'x':
case 'X':
base = 16;
break;
case 'i':
base = 0;
case 'd':
is_sign = 1;
case 'u':
break;
case '%':
/* looking for '%' in str */
if(*str++ != '%') {
return num;
}
continue;
default:
/* invalid format; stop here */
return num;
}
/* have some sort of integer conversion.
* first, skip white space in buffer.
*/
str = skip_spaces(str);
digit = *str;
if(is_sign && digit == '-')
{
if(field_width==-1)
{
field_width = judge_digit_width(str+1, base);
field_width++;
}else{
field_width = (judge_digit_width(str+1,base)+1)<field_width ?
(judge_digit_width(str+1,base)+1) :
field_width;
}
digit = *(str + 1);
}else if(field_width==-1){
field_width = judge_digit_width(str, base);
}else{
field_width = judge_digit_width(str,base)<field_width ?
judge_digit_width(str,base) :
field_width;
}
if(!digit
|| (base == 16 && !isxdigit(digit))
|| (base == 10 && !isdigit(digit))
|| (base == 8 && (!isdigit(digit) || digit > '7'))
|| (base == 0 && !isdigit(digit))) {
break;
}
//here problem *******************************************
//troy add ,fix support %2d, but not support %d
#if 0
if(field_width <= 0) {
field_width = judge_digit_width(str);
}
#else
//field_width = judge_digit_width(str, base);
#endif
/////troy add, fix str passed inwidth wrong
assert_param (field_width <= STR_STORE_MAX_LEN);
for(i = 0; i<field_width ; i++)
str_store[i] = str[i];
#if 0//ndef CONFIG_STDLIB_STRING
/* simple strtoul need this */
next = (char*)str + field_width;
#endif
if(is_sign) {
val.s = qualifier != 'L' ?
_strtol(str_store, &next, base) :
_strtoll(str_store, &next, base);
} else {
val.u = qualifier != 'L' ?
_strtoul(str_store, &next, base) :
_strtoull(str_store, &next, base);
}
#if 1//def CONFIG_STDLIB_STRING
/* standard strtoul need this */
next = (char*)str + field_width;
#endif
////troy add
for(i = 0; i<STR_STORE_MAX_LEN ; i++)
str_store[i] = 0;
//判断转换的字符串的宽度是否大于 %2d
if(field_width > 0 && next - str > field_width) {
if(base == 0)
_parse_integer_fixup_radix(str, &base);
while(next - str > field_width) {
if(is_sign) {
val.s = div_s64(val.s, base);
} else {
val.u = div_u64(val.u, base);
}
--next;
}
}
switch(qualifier) {
case 'H': /* that's 'hh' in format */
if(is_sign)
*va_arg(args, signed char *) = val.s;
else
*va_arg(args, unsigned char *) = val.u;
break;
case 'h':
if(is_sign)
*va_arg(args, short *) = val.s;
else
*va_arg(args, unsigned short *) = val.u;
break;
case 'l':
if(is_sign)
*va_arg(args, long *) = val.s;
else
*va_arg(args, unsigned long *) = val.u;
break;
case 'L':
if(is_sign)
*va_arg(args, long long *) = val.s;
else
*va_arg(args, unsigned long long *) = val.u;
break;
case 'Z':
case 'z':
*va_arg(args, size_t *) = val.u;
break;
default:
if(is_sign)
*va_arg(args, int *) = val.s;
else
*va_arg(args, unsigned int *) = val.u;
break;
}
num++;
if(!next) {
break;
}
str = next;
}
return num;
}
/**
* sscanf - Unformat a buffer into a list of arguments
* @buf: input buffer
* @fmt: formatting of buffer
* @...: resulting arguments
*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ int _sscanf(const char *buf, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i = _vsscanf(buf, fmt, args);
va_end(args);
return i;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/sscanf.c
|
C
|
apache-2.0
| 9,480
|
/* Byte-wise substring search, using the Two-Way algorithm.
* Copyright (C) 2008, 2010 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*/
/* Before including this file, you need to include <string.h>, and define:
RESULT_TYPE A macro that expands to the return type.
AVAILABLE(h, h_l, j, n_l) A macro that returns nonzero if there are
at least N_L bytes left starting at
H[J]. H is 'unsigned char *', H_L, J,
and N_L are 'size_t'; H_L is an
lvalue. For NUL-terminated searches,
H_L can be modified each iteration to
avoid having to compute the end of H
up front.
For case-insensitivity, you may optionally define:
CMP_FUNC(p1, p2, l) A macro that returns 0 iff the first L
characters of P1 and P2 are equal.
CANON_ELEMENT(c) A macro that canonicalizes an element
right after it has been fetched from
one of the two strings. The argument
is an 'unsigned char'; the result must
be an 'unsigned char' as well.
This file undefines the macros documented above, and defines
LONG_NEEDLE_THRESHOLD.
*/
#include <limits.h>
#include <stdint.h>
extern void * _memchr(const void * src_void , int c , size_t length);
extern int _memcmp(const void * m1 , const void * m2 , size_t n);
/* We use the Two-Way string matching algorithm, which guarantees
linear complexity with constant space. Additionally, for long
needles, we also use a bad character shift table similar to the
Boyer-Moore algorithm to achieve improved (potentially sub-linear)
performance.
See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260
and http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm
*/
/* Point at which computing a bad-byte shift table is likely to be
worthwhile. Small needles should not compute a table, since it
adds (1 << CHAR_BIT) + NEEDLE_LEN computations of preparation for a
speedup no greater than a factor of NEEDLE_LEN. The larger the
needle, the better the potential performance gain. On the other
hand, on non-POSIX systems with CHAR_BIT larger than eight, the
memory required for the table is prohibitive. */
#if CHAR_BIT < 10
# define LONG_NEEDLE_THRESHOLD 32U
#else
# define LONG_NEEDLE_THRESHOLD SIZE_MAX
#endif
#define MAX(a, b) ((a < b) ? (b) : (a))
#ifndef CANON_ELEMENT
# define CANON_ELEMENT(c) c
#endif
#ifndef CMP_FUNC
# define CMP_FUNC _memcmp
#endif
/* Perform a critical factorization of NEEDLE, of length NEEDLE_LEN.
Return the index of the first byte in the right half, and set
*PERIOD to the global period of the right half.
The global period of a string is the smallest index (possibly its
length) at which all remaining bytes in the string are repetitions
of the prefix (the last repetition may be a subset of the prefix).
When NEEDLE is factored into two halves, a local period is the
length of the smallest word that shares a suffix with the left half
and shares a prefix with the right half. All factorizations of a
non-empty NEEDLE have a local period of at least 1 and no greater
than NEEDLE_LEN.
A critical factorization has the property that the local period
equals the global period. All strings have at least one critical
factorization with the left half smaller than the global period.
Given an ordered alphabet, a critical factorization can be computed
in linear time, with 2 * NEEDLE_LEN comparisons, by computing the
larger of two ordered maximal suffixes. The ordered maximal
suffixes are determined by lexicographic comparison of
periodicity. */
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
static size_t
__rtl_critical_factorization (const unsigned char *needle, size_t needle_len,
size_t *period)
{
/* Index of last byte of left half, or SIZE_MAX. */
size_t max_suffix, max_suffix_rev;
size_t j; /* Index into NEEDLE for current candidate suffix. */
size_t k; /* Offset into current period. */
size_t p; /* Intermediate period. */
unsigned char a, b; /* Current comparison bytes. */
/* Invariants:
0 <= j < NEEDLE_LEN - 1
-1 <= max_suffix{,_rev} < j (treating SIZE_MAX as if it were signed)
min(max_suffix, max_suffix_rev) < global period of NEEDLE
1 <= p <= global period of NEEDLE
p == global period of the substring NEEDLE[max_suffix{,_rev}+1...j]
1 <= k <= p
*/
/* Perform lexicographic search. */
max_suffix = SIZE_MAX;
j = 0;
k = p = 1;
while (j + k < needle_len)
{
a = CANON_ELEMENT (needle[j + k]);
b = CANON_ELEMENT (needle[(size_t)(max_suffix + k)]);
if (a < b)
{
/* Suffix is smaller, period is entire prefix so far. */
j += k;
k = 1;
p = j - max_suffix;
}
else if (a == b)
{
/* Advance through repetition of the current period. */
if (k != p)
++k;
else
{
j += p;
k = 1;
}
}
else /* b < a */
{
/* Suffix is larger, start over from current location. */
max_suffix = j++;
k = p = 1;
}
}
*period = p;
/* Perform reverse lexicographic search. */
max_suffix_rev = SIZE_MAX;
j = 0;
k = p = 1;
while (j + k < needle_len)
{
a = CANON_ELEMENT (needle[j + k]);
b = CANON_ELEMENT (needle[max_suffix_rev + k]);
if (b < a)
{
/* Suffix is smaller, period is entire prefix so far. */
j += k;
k = 1;
p = j - max_suffix_rev;
}
else if (a == b)
{
/* Advance through repetition of the current period. */
if (k != p)
++k;
else
{
j += p;
k = 1;
}
}
else /* a < b */
{
/* Suffix is larger, start over from current location. */
max_suffix_rev = j++;
k = p = 1;
}
}
/* Choose the longer suffix. Return the first byte of the right
half, rather than the last byte of the left half. */
if (max_suffix_rev + 1 < max_suffix + 1)
return max_suffix + 1;
*period = p;
return max_suffix_rev + 1;
}
/* Return the first location of non-empty NEEDLE within HAYSTACK, or
NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
method is optimized for NEEDLE_LEN < LONG_NEEDLE_THRESHOLD.
Performance is guaranteed to be linear, with an initialization cost
of 2 * NEEDLE_LEN comparisons.
If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
static RETURN_TYPE
__rtl_two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
const unsigned char *needle, size_t needle_len)
{
size_t i; /* Index into current byte of NEEDLE. */
size_t j; /* Index into current window of HAYSTACK. */
size_t period; /* The period of the right half of needle. */
size_t suffix; /* The index of the right half of needle. */
/* Factor the needle into two halves, such that the left half is
smaller than the global period, and the right half is
periodic (with a period as large as NEEDLE_LEN - suffix). */
suffix = __rtl_critical_factorization (needle, needle_len, &period);
/* Perform the search. Each iteration compares the right half
first. */
if (CMP_FUNC (needle, needle + period, suffix) == 0)
{
/* Entire needle is periodic; a mismatch can only advance by the
period, so use memory to avoid rescanning known occurrences
of the period. */
size_t memory = 0;
j = 0;
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Scan for matches in right half. */
i = MAX (suffix, memory);
while (i < needle_len && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
if (needle_len <= i)
{
/* Scan for matches in left half. */
i = suffix - 1;
while (memory < i + 1 && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
--i;
if (i + 1 < memory + 1)
return (RETURN_TYPE) (haystack + j);
/* No match, so remember how many repetitions of period
on the right half were scanned. */
j += period;
memory = needle_len - period;
}
else
{
j += i - suffix + 1;
memory = 0;
}
}
}
else
{
/* The two halves of needle are distinct; no extra memory is
required, and any mismatch results in a maximal shift. */
period = MAX (suffix, needle_len - suffix) + 1;
j = 0;
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Scan for matches in right half. */
i = suffix;
while (i < needle_len && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
if (needle_len <= i)
{
/* Scan for matches in left half. */
i = suffix - 1;
while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
--i;
if (i == SIZE_MAX)
return (RETURN_TYPE) (haystack + j);
j += period;
}
else
j += i - suffix + 1;
}
}
return NULL;
}
/* Return the first location of non-empty NEEDLE within HAYSTACK, or
NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
Performance is guaranteed to be linear, with an initialization cost
of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
sublinear performance is not possible. */
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
static RETURN_TYPE
__rtl_two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
const unsigned char *needle, size_t needle_len)
{
size_t i; /* Index into current byte of NEEDLE. */
size_t j; /* Index into current window of HAYSTACK. */
size_t period; /* The period of the right half of needle. */
size_t suffix; /* The index of the right half of needle. */
size_t shift_table[1U << CHAR_BIT]; /* See below. */
/* Factor the needle into two halves, such that the left half is
smaller than the global period, and the right half is
periodic (with a period as large as NEEDLE_LEN - suffix). */
suffix = __rtl_critical_factorization (needle, needle_len, &period);
/* Populate shift_table. For each possible byte value c,
shift_table[c] is the distance from the last occurrence of c to
the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
for (i = 0; i < 1U << CHAR_BIT; i++)
shift_table[i] = needle_len;
for (i = 0; i < needle_len; i++)
shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
/* Perform the search. Each iteration compares the right half
first. */
if (CMP_FUNC (needle, needle + period, suffix) == 0)
{
/* Entire needle is periodic; a mismatch can only advance by the
period, so use memory to avoid rescanning known occurrences
of the period. */
size_t memory = 0;
size_t shift;
j = 0;
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Check the last byte first; if it does not match, then
shift to the next possible match location. */
shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
if (0 < shift)
{
if (memory && shift < period)
{
/* Since needle is periodic, but the last period has
a byte out of place, there can be no match until
after the mismatch. */
shift = needle_len - period;
}
memory = 0;
j += shift;
continue;
}
/* Scan for matches in right half. The last byte has
already been matched, by virtue of the shift table. */
i = MAX (suffix, memory);
while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
if (needle_len - 1 <= i)
{
/* Scan for matches in left half. */
i = suffix - 1;
while (memory < i + 1 && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
--i;
if (i + 1 < memory + 1)
return (RETURN_TYPE) (haystack + j);
/* No match, so remember how many repetitions of period
on the right half were scanned. */
j += period;
memory = needle_len - period;
}
else
{
j += i - suffix + 1;
memory = 0;
}
}
}
else
{
/* The two halves of needle are distinct; no extra memory is
required, and any mismatch results in a maximal shift. */
size_t shift;
period = MAX (suffix, needle_len - suffix) + 1;
j = 0;
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Check the last byte first; if it does not match, then
shift to the next possible match location. */
shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
if (0 < shift)
{
j += shift;
continue;
}
/* Scan for matches in right half. The last byte has
already been matched, by virtue of the shift table. */
i = suffix;
while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
if (needle_len - 1 <= i)
{
/* Scan for matches in left half. */
i = suffix - 1;
while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
--i;
if (i == SIZE_MAX)
return (RETURN_TYPE) (haystack + j);
j += period;
}
else
j += i - suffix + 1;
}
}
return NULL;
}
#undef AVAILABLE
#undef CANON_ELEMENT
#undef CMP_FUNC
#undef MAX
#undef RETURN_TYPE
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/str-two-way.h
|
C
|
apache-2.0
| 14,049
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ int _stratoi(const char * s)
{
int num=0,flag=0;
u32 i;
for(i=0;i<=_strlen(s);i++)
{
if(s[i] >= '0' && s[i] <= '9')
num = num * 10 + s[i] -'0';
else if(s[0] == '-' && i==0)
flag =1;
else
break;
}
if(flag == 1)
num = num * -1;
return(num);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/stratoi.c
|
C
|
apache-2.0
| 778
|
/*
FUNCTION
<<strcat>>---concatenate strings
INDEX
strcat
ANSI_SYNOPSIS
#include <string.h>
char *strcat(char *restrict <[dst]>, const char *restrict <[src]>);
TRAD_SYNOPSIS
#include <string.h>
char *strcat(<[dst]>, <[src]>)
char *<[dst]>;
char *<[src]>;
DESCRIPTION
<<strcat>> appends a copy of the string pointed to by <[src]>
(including the terminating null character) to the end of the
string pointed to by <[dst]>. The initial character of
<[src]> overwrites the null character at the end of <[dst]>.
RETURNS
This function returns the initial value of <[dst]>
PORTABILITY
<<strcat>> is ANSI C.
<<strcat>> requires no supporting OS subroutines.
QUICKREF
strcat ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <limits.h>
extern char* _strcpy(char *dst0 , const char *src0);
/* Nonzero if X is aligned on a "long" boundary. */
#define ALIGNED(X) \
(((long)X & (sizeof (long) - 1)) == 0)
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
/* Nonzero if X (a long int) contains a NULL byte. */
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif
/*SUPPRESS 560*/
/*SUPPRESS 530*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * _strcat(char *__restrict s1 , const char *__restrict s2)
{
#if defined(PREFER_SIZE_OVER_SPEED)
char *s = s1;
while (*s1)
s1++;
while (*s1++ = *s2++)
;
return s;
#else
char *s = s1;
/* Skip over the data in s1 as quickly as possible. */
if (ALIGNED (s1))
{
unsigned long *aligned_s1 = (unsigned long *)s1;
while (!DETECTNULL (*aligned_s1))
aligned_s1++;
s1 = (char *)aligned_s1;
}
while (*s1)
s1++;
/* s1 now points to the its trailing null character, we can
just use strcpy to do the work for us now.
?!? We might want to just include strcpy here.
Also, this will cause many more unaligned string copies because
s1 is much less likely to be aligned. I don't know if its worth
tweaking strcpy to handle this better. */
_strcpy(s1, s2);
return s;
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strcat.c
|
C
|
apache-2.0
| 2,336
|
/*
FUNCTION
<<strchr>>---search for character in string
INDEX
strchr
ANSI_SYNOPSIS
#include <string.h>
char * strchr(const char *<[string]>, int <[c]>);
TRAD_SYNOPSIS
#include <string.h>
char * strchr(<[string]>, <[c]>);
const char *<[string]>;
int <[c]>;
DESCRIPTION
This function finds the first occurence of <[c]> (converted to
a char) in the string pointed to by <[string]> (including the
terminating null character).
RETURNS
Returns a pointer to the located character, or a null pointer
if <[c]> does not occur in <[string]>.
PORTABILITY
<<strchr>> is ANSI C.
<<strchr>> requires no supporting OS subroutines.
QUICKREF
strchr ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <limits.h>
/* Nonzero if X is not aligned on a "long" boundary. */
#define UNALIGNED(X) ((long)X & (sizeof (long) - 1))
/* How many bytes are loaded each iteration of the word copy loop. */
#define LBLOCKSIZE (sizeof (long))
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
/* Nonzero if X (a long int) contains a NULL byte. */
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
/* DETECTCHAR returns nonzero if (long)X contains the byte used
to fill (long)MASK. */
#define DETECTCHAR(X,MASK) (DETECTNULL(X ^ MASK))
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * _strchr(const char *s1 , int i)
{
const unsigned char *s = (const unsigned char *)s1;
unsigned char c = i;
#if !defined(PREFER_SIZE_OVER_SPEED)
unsigned long mask,j;
unsigned long *aligned_addr;
/* Special case for finding 0. */
if (!c)
{
while (UNALIGNED (s))
{
if (!*s)
return (char *) s;
s++;
}
/* Operate a word at a time. */
aligned_addr = (unsigned long *) s;
while (!DETECTNULL (*aligned_addr))
aligned_addr++;
/* Found the end of string. */
s = (const unsigned char *) aligned_addr;
while (*s)
s++;
return (char *) s;
}
/* All other bytes. Align the pointer, then search a long at a time. */
while (UNALIGNED (s))
{
if (!*s)
return NULL;
if (*s == c)
return (char *) s;
s++;
}
mask = c;
for (j = 8; j < LBLOCKSIZE * 8; j <<= 1)
mask = (mask << j) | mask;
aligned_addr = (unsigned long *) s;
while (!DETECTNULL (*aligned_addr) && !DETECTCHAR (*aligned_addr, mask))
aligned_addr++;
/* The block of bytes currently pointed to by aligned_addr
contains either a null or the target char, or both. We
catch it using the bytewise search. */
s = (unsigned char *) aligned_addr;
#endif /* not PREFER_SIZE_OVER_SPEED */
while (*s && *s != c)
s++;
if (*s == c)
return (char *)s;
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strchr.c
|
C
|
apache-2.0
| 2,924
|
/******************************************************************************
*
* Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved.
*
* 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 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.
*
******************************************************************************/
/*
FUNCTION
<<strcmp>>---character string compare
INDEX
strcmp
ANSI_SYNOPSIS
#include <string.h>
int strcmp(const char *<[a]>, const char *<[b]>);
TRAD_SYNOPSIS
#include <string.h>
int strcmp(<[a]>, <[b]>)
char *<[a]>;
char *<[b]>;
DESCRIPTION
<<strcmp>> compares the string at <[a]> to
the string at <[b]>.
RETURNS
If <<*<[a]>>> sorts lexicographically after <<*<[b]>>>,
<<strcmp>> returns a number greater than zero. If the two
strings match, <<strcmp>> returns zero. If <<*<[a]>>>
sorts lexicographically before <<*<[b]>>>, <<strcmp>> returns a
number less than zero.
PORTABILITY
<<strcmp>> is ANSI C.
<<strcmp>> requires no supporting OS subroutines.
QUICKREF
strcmp ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <limits.h>
/* Nonzero if either X or Y is not aligned on a "long" boundary. */
#define UNALIGNED(X, Y) \
(((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
/* DETECTNULL returns nonzero if (long)X contains a NULL byte. */
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
int _strcmp(const char *s1 , const char *s2)
{
#if defined(PREFER_SIZE_OVER_SPEED)
while (*s1 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
return (*(unsigned char *) s1) - (*(unsigned char *) s2);
#else
unsigned long *a1;
unsigned long *a2;
/* If s1 or s2 are unaligned, then compare bytes. */
if (!UNALIGNED (s1, s2))
{
/* If s1 and s2 are word-aligned, compare them a word at a time. */
a1 = (unsigned long*)s1;
a2 = (unsigned long*)s2;
while (*a1 == *a2)
{
/* To get here, *a1 == *a2, thus if we find a null in *a1,
then the strings must be equal, so return zero. */
if (DETECTNULL (*a1))
return 0;
a1++;
a2++;
}
/* A difference was detected in last few bytes of s1, so search bytewise */
s1 = (char*)a1;
s2 = (char*)a2;
}
while (*s1 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
return (*(unsigned char *) s1) - (*(unsigned char *) s2);
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strcmp.c
|
C
|
apache-2.0
| 3,289
|
/******************************************************************************
*
* Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved.
*
* 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 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.
*
******************************************************************************/
/*
FUNCTION
<<strcpy>>---copy string
INDEX
strcpy
ANSI_SYNOPSIS
#include <string.h>
char *strcpy(char *<[dst]>, const char *<[src]>);
TRAD_SYNOPSIS
#include <string.h>
char *strcpy(<[dst]>, <[src]>)
char *<[dst]>;
char *<[src]>;
DESCRIPTION
<<strcpy>> copies the string pointed to by <[src]>
(including the terminating null character) to the array
pointed to by <[dst]>.
RETURNS
This function returns the initial value of <[dst]>.
PORTABILITY
<<strcpy>> is ANSI C.
<<strcpy>> requires no supporting OS subroutines.
QUICKREF
strcpy ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <limits.h>
/*SUPPRESS 560*/
/*SUPPRESS 530*/
/* Nonzero if either X or Y is not aligned on a "long" boundary. */
#define UNALIGNED(X, Y) \
(((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
/* Nonzero if X (a long int) contains a NULL byte. */
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char* _strcpy(char *dst0 , const char *src0)
{
#if defined(PREFER_SIZE_OVER_SPEED)
char *s = dst0;
while (*dst0++ = *src0++)
;
return s;
#else
char *dst = dst0;
const char *src = src0;
long *aligned_dst;
const long *aligned_src;
/* If SRC or DEST is unaligned, then copy bytes. */
if (!UNALIGNED (src, dst))
{
aligned_dst = (long*)dst;
aligned_src = (long*)src;
/* SRC and DEST are both "long int" aligned, try to do "long int"
sized copies. */
while (!DETECTNULL(*aligned_src))
{
*aligned_dst++ = *aligned_src++;
}
dst = (char*)aligned_dst;
src = (char*)aligned_src;
}
while ((*dst++ = *src++))
;
return dst0;
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strcpy.c
|
C
|
apache-2.0
| 2,884
|
/******************************************************************************
*
* Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved.
*
* 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 License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
/**
* stricmp - A small but sufficient implementation for case insensitive strcmp.
* @str1:
* @str2:
* @note support from B CUT
*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ int _stricmp(const char* str1, const char* str2)
{
char c1, c2;
do {
c1 = *str1++;
c2 = *str2++;
if (c1 != c2) {
char c1_upc = c1 | 0x20;
if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
/* characters are not equal an one is in the alphabet range:
downcase both chars and check again */
char c2_upc = c2 | 0x20;
if (c1_upc != c2_upc) {
/* still not equal */
/* don't care for < or > */
return 1;
}
} else {
/* characters are not equal but none is in the alphabet range */
return 1;
}
}
} while (c1 != 0);
return 0;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/stricmp.c
|
C
|
apache-2.0
| 1,775
|
/*
FUNCTION
<<strlen>>---character string length
INDEX
strlen
ANSI_SYNOPSIS
#include <string.h>
size_t strlen(const char *<[str]>);
TRAD_SYNOPSIS
#include <string.h>
size_t strlen(<[str]>)
char *<[src]>;
DESCRIPTION
The <<strlen>> function works out the length of the string
starting at <<*<[str]>>> by counting chararacters until it
reaches a <<NULL>> character.
RETURNS
<<strlen>> returns the character count.
PORTABILITY
<<strlen>> is ANSI C.
<<strlen>> requires no supporting OS subroutines.
QUICKREF
strlen ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <_ansi.h>
#include <string.h>
#include <limits.h>
#define LBLOCKSIZE (sizeof (long))
#define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1))
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
/* Nonzero if X (a long int) contains a NULL byte. */
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
size_t _strlen(const char *str)
{
const char *start = str;
#if !defined(PREFER_SIZE_OVER_SPEED)
unsigned long *aligned_addr;
/* Align the pointer, so we can search a word at a time. */
while (UNALIGNED (str))
{
if (!*str)
return str - start;
str++;
}
/* If the string is word-aligned, we can check for the presence of
a null in each word-sized block. */
aligned_addr = (unsigned long *)str;
while (!DETECTNULL (*aligned_addr))
aligned_addr++;
/* Once a null is detected, we check each byte in that block for a
precise position of the null. */
str = (char *) aligned_addr;
#endif /* not PREFER_SIZE_OVER_SPEED */
while (*str)
str++;
return str - start;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strlen.c
|
C
|
apache-2.0
| 1,912
|
/*
FUNCTION
<<strncat>>---concatenate strings
INDEX
strncat
ANSI_SYNOPSIS
#include <string.h>
char *strncat(char *restrict <[dst]>, const char *restrict <[src]>,
size_t <[length]>);
TRAD_SYNOPSIS
#include <string.h>
char *strncat(<[dst]>, <[src]>, <[length]>)
char *<[dst]>;
char *<[src]>;
size_t <[length]>;
DESCRIPTION
<<strncat>> appends not more than <[length]> characters from
the string pointed to by <[src]> (including the terminating
null character) to the end of the string pointed to by
<[dst]>. The initial character of <[src]> overwrites the null
character at the end of <[dst]>. A terminating null character
is always appended to the result
WARNINGS
Note that a null is always appended, so that if the copy is
limited by the <[length]> argument, the number of characters
appended to <[dst]> is <<n + 1>>.
RETURNS
This function returns the initial value of <[dst]>
PORTABILITY
<<strncat>> is ANSI C.
<<strncat>> requires no supporting OS subroutines.
QUICKREF
strncat ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <limits.h>
/* Nonzero if X is aligned on a "long" boundary. */
#define ALIGNED(X) \
(((long)X & (sizeof (long) - 1)) == 0)
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
/* Nonzero if X (a long int) contains a NULL byte. */
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * _strncat(char *__restrict s1 , const char *__restrict s2 , size_t n)
{
#if defined(PREFER_SIZE_OVER_SPEED)
char *s = s1;
while (*s1)
s1++;
while (n-- != 0 && (*s1++ = *s2++))
{
if (n == 0)
*s1 = '\0';
}
return s;
#else
char *s = s1;
/* Skip over the data in s1 as quickly as possible. */
if (ALIGNED (s1))
{
unsigned long *aligned_s1 = (unsigned long *)s1;
while (!DETECTNULL (*aligned_s1))
aligned_s1++;
s1 = (char *)aligned_s1;
}
while (*s1)
s1++;
/* s1 now points to the its trailing null character, now copy
up to N bytes from S2 into S1 stopping if a NULL is encountered
in S2.
It is not safe to use strncpy here since it copies EXACTLY N
characters, NULL padding if necessary. */
while (n-- != 0 && (*s1++ = *s2++))
{
if (n == 0)
*s1 = '\0';
}
return s;
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strncat.c
|
C
|
apache-2.0
| 2,625
|
/******************************************************************************
*
* Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved.
*
* 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 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.
*
******************************************************************************/
/*
FUNCTION
<<strncmp>>---character string compare
INDEX
strncmp
ANSI_SYNOPSIS
#include <string.h>
int strncmp(const char *<[a]>, const char * <[b]>, size_t <[length]>);
TRAD_SYNOPSIS
#include <string.h>
int strncmp(<[a]>, <[b]>, <[length]>)
char *<[a]>;
char *<[b]>;
size_t <[length]>
DESCRIPTION
<<strncmp>> compares up to <[length]> characters
from the string at <[a]> to the string at <[b]>.
RETURNS
If <<*<[a]>>> sorts lexicographically after <<*<[b]>>>,
<<strncmp>> returns a number greater than zero. If the two
strings are equivalent, <<strncmp>> returns zero. If <<*<[a]>>>
sorts lexicographically before <<*<[b]>>>, <<strncmp>> returns a
number less than zero.
PORTABILITY
<<strncmp>> is ANSI C.
<<strncmp>> requires no supporting OS subroutines.
QUICKREF
strncmp ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <limits.h>
/* Nonzero if either X or Y is not aligned on a "long" boundary. */
#define UNALIGNED(X, Y) \
(((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
/* DETECTNULL returns nonzero if (long)X contains a NULL byte. */
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
int _strncmp(const char *s1 , const char *s2 , size_t n)
{
#if defined(PREFER_SIZE_OVER_SPEED)
if (n == 0)
return 0;
while (n-- != 0 && *s1 == *s2)
{
if (n == 0 || *s1 == '\0')
break;
s1++;
s2++;
}
return (*(unsigned char *) s1) - (*(unsigned char *) s2);
#else
unsigned long *a1;
unsigned long *a2;
if (n == 0)
return 0;
/* If s1 or s2 are unaligned, then compare bytes. */
if (!UNALIGNED (s1, s2))
{
/* If s1 and s2 are word-aligned, compare them a word at a time. */
a1 = (unsigned long*)s1;
a2 = (unsigned long*)s2;
while (n >= sizeof (long) && *a1 == *a2)
{
n -= sizeof (long);
/* If we've run out of bytes or hit a null, return zero
since we already know *a1 == *a2. */
if (n == 0 || DETECTNULL (*a1))
return 0;
a1++;
a2++;
}
/* A difference was detected in last few bytes of s1, so search bytewise */
s1 = (char*)a1;
s2 = (char*)a2;
}
while (n-- > 0 && *s1 == *s2)
{
/* If we've run out of bytes or hit a null, return zero
since we already know *s1 == *s2. */
if (n == 0 || *s1 == '\0')
return 0;
s1++;
s2++;
}
return (*(unsigned char *) s1) - (*(unsigned char *) s2);
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strncmp.c
|
C
|
apache-2.0
| 3,686
|
/*
FUNCTION
<<strncpy>>---counted copy string
INDEX
strncpy
ANSI_SYNOPSIS
#include <string.h>
char *strncpy(char *restrict <[dst]>, const char *restrict <[src]>,
size_t <[length]>);
TRAD_SYNOPSIS
#include <string.h>
char *strncpy(<[dst]>, <[src]>, <[length]>)
char *<[dst]>;
char *<[src]>;
size_t <[length]>;
DESCRIPTION
<<strncpy>> copies not more than <[length]> characters from the
the string pointed to by <[src]> (including the terminating
null character) to the array pointed to by <[dst]>. If the
string pointed to by <[src]> is shorter than <[length]>
characters, null characters are appended to the destination
array until a total of <[length]> characters have been
written.
RETURNS
This function returns the initial value of <[dst]>.
PORTABILITY
<<strncpy>> is ANSI C.
<<strncpy>> requires no supporting OS subroutines.
QUICKREF
strncpy ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <limits.h>
/*SUPPRESS 560*/
/*SUPPRESS 530*/
/* Nonzero if either X or Y is not aligned on a "long" boundary. */
#define UNALIGNED(X, Y) \
(((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
/* Nonzero if X (a long int) contains a NULL byte. */
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif
#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif
#define TOO_SMALL(LEN) ((LEN) < sizeof (long))
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * _strncpy(char *__restrict dst0 , const char *__restrict src0 , size_t count)
{
#if defined(PREFER_SIZE_OVER_SPEED)
char *dscan;
const char *sscan;
dscan = dst0;
sscan = src0;
while (count > 0)
{
--count;
if ((*dscan++ = *sscan++) == '\0')
break;
}
while (count-- > 0)
*dscan++ = '\0';
return dst0;
#else
char *dst = dst0;
const char *src = src0;
long *aligned_dst;
const long *aligned_src;
/* If SRC and DEST is aligned and count large enough, then copy words. */
if (!UNALIGNED (src, dst) && !TOO_SMALL (count))
{
aligned_dst = (long*)dst;
aligned_src = (long*)src;
/* SRC and DEST are both "long int" aligned, try to do "long int"
sized copies. */
while (count >= sizeof (long int) && !DETECTNULL(*aligned_src))
{
count -= sizeof (long int);
*aligned_dst++ = *aligned_src++;
}
dst = (char*)aligned_dst;
src = (char*)aligned_src;
}
while (count > 0)
{
--count;
if ((*dst++ = *src++) == '\0')
break;
}
while (count-- > 0)
*dst++ = '\0';
return dst0;
#endif /* not PREFER_SIZE_OVER_SPEED */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strncpy.c
|
C
|
apache-2.0
| 2,839
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ size_t _strnlen(const char *s, size_t count)
{
const char *sc;
for (sc = s; count-- && *sc != '\0'; ++sc)
;
return sc - s;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strnlen.c
|
C
|
apache-2.0
| 648
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
/**
* strpbrk - Find the first occurrence of a set of characters
* @cs: The string to be searched
* @ct: The characters to search for
*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ char *_strpbrk(const char *cs, const char *ct)
{
const char *sc1, *sc2;
for (sc1 = cs; *sc1 != '\0'; ++sc1) {
for (sc2 = ct; *sc2 != '\0'; ++sc2) {
if (*sc1 == *sc2)
return (char *)sc1;
}
}
return NULL;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strpbrk.c
|
C
|
apache-2.0
| 965
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#ifndef _STRPROC_H_
#define _STRPROC_H_
#include <stddef.h> /* for size_t */
#include <stdarg.h>
#include "platform_autoconf.h"
#include "basic_types.h"
#ifndef isprint
#define in_range(c, lo, up) ((u8)c >= lo && (u8)c <= up)
#define isprint(c) in_range(c, 0x20, 0x7f)
#define isdigit(c) in_range(c, '0', '9')
#define isxdigit(c) (isdigit(c) || in_range(c, 'a', 'f') || in_range(c, 'A', 'F'))
//#define islower(c) in_range(c, 'a', 'z')
#define isspace(c) (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v' || c == ',')
#define isupper(c) (((c)>='A')&&((c)<='Z'))
#define islower(c) (((c)>='a')&&((c)<='z'))
#define isalpha(c) (isupper(c) || islower(c))
#endif
extern _LONG_CALL_ int _vsscanf(const char *buf, const char *fmt, va_list args);
extern _LONG_CALL_ SIZE_T _strlen(const char *s);
extern _LONG_CALL_ int _strcmp(const char *cs, const char *ct);
extern _LONG_CALL_ char *_strncpy(char *dest, const char *src, size_t count);
extern _LONG_CALL_ char *_strcpy(char *dest, const char *src);
extern _LONG_CALL_ size_t _strlen(const char *s);
extern _LONG_CALL_ size_t _strnlen(const char *s, size_t count);
extern _LONG_CALL_ int _strncmp(const char *cs, const char *ct, size_t count);
extern _LONG_CALL_ int _sscanf(const char *buf, const char *fmt, ...);
extern _LONG_CALL_ char *_strsep(char **s, const char *ct);
extern _LONG_CALL_ char *_strpbrk(const char *cs, const char *ct);
extern _LONG_CALL_ char *_strchr(const char *s, int c);
extern _LONG_CALL_ int _stricmp(const char* str1, const char* str2);
extern _LONG_CALL_ u8* _strupr(IN u8 *string);
extern _LONG_CALL_ int _stratoi(IN const char * s);
extern _LONG_CALL_ char * _strstr(IN const char * str1, IN const char * str2);
extern _LONG_CALL_ char* _strtok(IN char *str, IN const char* delim);
extern _LONG_CALL_ long _strtol(const char *cp, char **endp, int base);
extern _LONG_CALL_ unsigned long _strtoul(const char *cp, char **endp, int base);
extern _LONG_CALL_ long long _strtoll(const char *cp, char **endp, unsigned int base);
extern _LONG_CALL_ unsigned long long _strtoull(const char *cp, char **endp, unsigned int base);
extern _LONG_CALL_ u8 _char2num(u8 ch);
extern _LONG_CALL_ u8 _2char2dec(u8 hch, u8 lch);
extern _LONG_CALL_ u8 _2char2hex(u8 hch, u8 lch);
#if 0
/*
* Fast implementation of tolower() for internal usage. Do not use in your
* code.
*/
static inline char _tolower(const char c)
{
return c | 0x20;
}
#endif
/* Fast check for octal digit */
static inline int isodigit(const char c)
{
return c >= '0' && c <= '7';
}
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strproc.h
|
C
|
apache-2.0
| 2,868
|
/* BSD strsep function */
/* Copyright 2002, Red Hat Inc. */
/* undef STRICT_ANSI so that strsep prototype will be defined */
#undef __STRICT_ANSI__
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
#include <_ansi.h>
#include <reent.h>
extern char *__strtok_r(char *, const char *, char **, int);
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * _strsep(register char **source_ptr , register const char *delim)
{
return __strtok_r(*source_ptr, delim, source_ptr, 0);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strsep.c
|
C
|
apache-2.0
| 493
|
/******************************************************************************
*
* Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved.
*
* 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 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.
*
******************************************************************************/
/*
FUNCTION
<<strstr>>---find string segment
INDEX
strstr
ANSI_SYNOPSIS
#include <string.h>
char *strstr(const char *<[s1]>, const char *<[s2]>);
TRAD_SYNOPSIS
#include <string.h>
char *strstr(<[s1]>, <[s2]>)
char *<[s1]>;
char *<[s2]>;
DESCRIPTION
Locates the first occurrence in the string pointed to by <[s1]> of
the sequence of characters in the string pointed to by <[s2]>
(excluding the terminating null character).
RETURNS
Returns a pointer to the located string segment, or a null
pointer if the string <[s2]> is not found. If <[s2]> points to
a string with zero length, <[s1]> is returned.
PORTABILITY
<<strstr>> is ANSI C.
<<strstr>> requires no supporting OS subroutines.
QUICKREF
strstr ansi pure
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
extern char * _strchr(const char *s1 , int i);
#if !defined(PREFER_SIZE_OVER_SPEED)
# define RETURN_TYPE char *
# define AVAILABLE(h, h_l, j, n_l) \
(! _memchr ((h) + (h_l), '\0', (j) + (n_l) - (h_l)) \
&& ((h_l) = (j) + (n_l)))
# include "str-two-way.h"
#endif
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * _strstr(const char *searchee , const char *lookfor)
{
#if defined(PREFER_SIZE_OVER_SPEED)
/* Less code size, but quadratic performance in the worst case. */
if (*searchee == 0)
{
if (*lookfor)
return (char *) NULL;
return (char *) searchee;
}
while (*searchee)
{
size_t i;
i = 0;
while (1)
{
if (lookfor[i] == 0)
{
return (char *) searchee;
}
if (lookfor[i] != searchee[i])
{
break;
}
i++;
}
searchee++;
}
return (char *) NULL;
#else /* compilation for speed */
/* Larger code size, but guaranteed linear performance. */
const char *haystack = searchee;
const char *needle = lookfor;
size_t needle_len; /* Length of NEEDLE. */
size_t haystack_len; /* Known minimum length of HAYSTACK. */
int ok = 1; /* True if NEEDLE is prefix of HAYSTACK. */
/* Determine length of NEEDLE, and in the process, make sure
HAYSTACK is at least as long (no point processing all of a long
NEEDLE if HAYSTACK is too short). */
while (*haystack && *needle)
ok &= *haystack++ == *needle++;
if (*needle)
return NULL;
if (ok)
return (char *) searchee;
/* Reduce the size of haystack using strchr, since it has a smaller
linear coefficient than the Two-Way algorithm. */
needle_len = needle - lookfor;
haystack = _strchr (searchee + 1, *lookfor);
if (!haystack || needle_len == 1)
return (char *) haystack;
haystack_len = (haystack > searchee + needle_len ? 1
: needle_len + searchee - haystack);
/* Perform the search. */
if (needle_len < LONG_NEEDLE_THRESHOLD)
return __rtl_two_way_short_needle ((const unsigned char *) haystack,
haystack_len,
(const unsigned char *) lookfor, needle_len);
return __rtl_two_way_long_needle ((const unsigned char *) haystack, haystack_len,
(const unsigned char *) lookfor, needle_len);
#endif /* compilation for speed */
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strstr.c
|
C
|
apache-2.0
| 3,884
|
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#define USHRT_MAX ((u16)(~0U))
#define SHRT_MAX ((s16)(USHRT_MAX>>1))
#define ULLONG_MAX (~0ULL)
#define STR_STORE_MAX_LEN 24
#define KSTRTOX_OVERFLOW (1U << 31)
/**
* div_u64_rem - unsigned 64bit divide with 32bit divisor with remainder
*
* This is commonly provided by 32bit archs to provide an optimized 64bit
* divide.
*/
//static inline
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static u64 div_u64_rem(u64 dividend, u32 divisor, u32 *remainder)
{
*remainder = (u32)dividend % divisor;
return (u32)dividend / divisor;
}
/**
* div_s64_rem - signed 64bit divide with 32bit divisor with remainder
*/
//static inline
//LIBC_ROM_TEXT_SECTION
//_LONG_CALL_ static s64 div_s64_rem(s64 dividend, s32 divisor, s32 *remainder)
//{
// *remainder = (s32)dividend % divisor;
// return (s32)dividend / divisor;
//}
/**
* div_u64 - unsigned 64bit divide with 32bit divisor
*
* This is the most common 64bit divide and should be used if possible,
* as many 32bit archs can optimize this variant better than a full 64bit
* divide.
*/
#ifndef div_u64
//static inline
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static u64 div_u64(u64 dividend, u32 divisor)
{
u32 remainder;
return div_u64_rem(dividend, divisor, &remainder);
}
#endif
/**
* div_s64 - signed 64bit divide with 32bit divisor
*/
#ifndef div_s64
//static inline
//LIBC_ROM_TEXT_SECTION
//_LONG_CALL_ static s64 div_s64(s64 dividend, s32 divisor)
//{
// s32 remainder;
// return div_s64_rem(dividend, divisor, &remainder);
//}
#endif
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static const char *_parse_integer_fixup_radix(const char *s, unsigned int *base)
{
if (*base == 0) {
if (s[0] == '0') {
if (_tolower(s[1]) == 'x' && isxdigit(s[2]))
*base = 16;
else
*base = 8;
} else
*base = 10;
}
if (*base == 16 && s[0] == '0' && _tolower(s[1]) == 'x')
s += 2;
return s;
}
/**
* mul64_8 - unsigned 64bit mul unsigned 8 bit
*add this function because we do not want link GCC in rom code.
| 32 | 8 | 24 |
* | 8 |
--------------------------------------------
| 24*8 |
+ | 8*8 |
+| 32*8 |
--------------------------------------------
+ | sum | low 24 bits |
*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static unsigned long long mul64_8 (unsigned long long u, unsigned char v)
{
//#if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
// struct DWstruct {int high, low;};
//#else
struct DWstruct {unsigned int low, high;};
//#endif
typedef union
{
struct DWstruct s;
unsigned long long ll;
} DWunion;
const DWunion uu = {.ll = u};
const unsigned char vv = v;
unsigned int temp;
DWunion w ;
w.s.low = uu.s.low * vv;
w.s.low &= 0xFFFFFF;
w.s.high = ( uu.s.low >> 24) * vv ;
w.s.high += (((uu.s.low & 0xFFFFFF)*vv)>>24);
temp = w.s.high <<24;
w.s.high = (w.s.high >> 8);
w.s.high += uu.s.high * vv;
w.s.low |= temp;
return w.ll;
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ static unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long *p)
{
unsigned long long res;
unsigned int rv;
int overflow;
res = 0;
rv = 0;
overflow = 0;
while (*s) {
unsigned int val;
if ('0' <= *s && *s <= '9')
val = *s - '0';
else if ('a' <= _tolower(*s) && _tolower(*s) <= 'f')
val = _tolower(*s) - 'a' + 10;
else
break;
if (val >= base)
break;
/*
* Check for overflow only if we are within range of
* it in the max base we support (16)
*/
if (unlikely(res & (~0ull << 60))) {
if (res > div_u64(ULLONG_MAX - val, base))
overflow = 1;
}
res = mul64_8(res , (unsigned char)base) + val;
rv++;
s++;
}
*p = res;
if (overflow)
rv |= KSTRTOX_OVERFLOW;
return rv;
}
/*
* _strtoull - convert a string to an unsigned long long
* @cp: The start of the string
* @endp: A pointer to the end of the parsed string will be placed here
* @base: The number base to use
*
* This function is obsolete. Please use kstrtoull instead.
*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ unsigned long long _strtoull(const char *cp, char **endp, unsigned int base)
{
unsigned long long result;
unsigned int rv;
cp = _parse_integer_fixup_radix(cp, &base);
rv = _parse_integer(cp, base, &result);
return result;
}
/**
* _strtoll - convert a string to a signed long long
* @cp: The start of the string
* @endp: A pointer to the end of the parsed string will be placed here
* @base: The number base to use
*
* This function is obsolete. Please use kstrtoll instead.
*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ long long _strtoll(const char *cp, char **endp, unsigned int base)
{
if (*cp == '-')
return -_strtoull(cp + 1, endp, base);
return _strtoull(cp, endp, base);
}
#pragma GCC diagnostic pop
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strtod.c
|
C
|
apache-2.0
| 6,129
|
/*
FUNCTION
<<strtod>>, <<strtof>>---string to double or float
INDEX
strtod
INDEX
_strtod_r
INDEX
strtof
ANSI_SYNOPSIS
#include <stdlib.h>
double strtod(const char *restrict <[str]>, char **restrict <[tail]>);
float strtof(const char *restrict <[str]>, char **restrict <[tail]>);
double _strtod_r(void *<[reent]>,
const char *restrict <[str]>, char **restrict <[tail]>);
TRAD_SYNOPSIS
#include <stdlib.h>
double strtod(<[str]>,<[tail]>)
char *<[str]>;
char **<[tail]>;
float strtof(<[str]>,<[tail]>)
char *<[str]>;
char **<[tail]>;
double _strtod_r(<[reent]>,<[str]>,<[tail]>)
char *<[reent]>;
char *<[str]>;
char **<[tail]>;
DESCRIPTION
The function <<strtod>> parses the character string <[str]>,
producing a substring which can be converted to a double
value. The substring converted is the longest initial
subsequence of <[str]>, beginning with the first
non-whitespace character, that has one of these formats:
.[+|-]<[digits]>[.[<[digits]>]][(e|E)[+|-]<[digits]>]
.[+|-].<[digits]>[(e|E)[+|-]<[digits]>]
.[+|-](i|I)(n|N)(f|F)[(i|I)(n|N)(i|I)(t|T)(y|Y)]
.[+|-](n|N)(a|A)(n|N)[<(>[<[hexdigits]>]<)>]
.[+|-]0(x|X)<[hexdigits]>[.[<[hexdigits]>]][(p|P)[+|-]<[digits]>]
.[+|-]0(x|X).<[hexdigits]>[(p|P)[+|-]<[digits]>]
The substring contains no characters if <[str]> is empty, consists
entirely of whitespace, or if the first non-whitespace
character is something other than <<+>>, <<->>, <<.>>, or a
digit, and cannot be parsed as infinity or NaN. If the platform
does not support NaN, then NaN is treated as an empty substring.
If the substring is empty, no conversion is done, and
the value of <[str]> is stored in <<*<[tail]>>>. Otherwise,
the substring is converted, and a pointer to the final string
(which will contain at least the terminating null character of
<[str]>) is stored in <<*<[tail]>>>. If you want no
assignment to <<*<[tail]>>>, pass a null pointer as <[tail]>.
<<strtof>> is identical to <<strtod>> except for its return type.
This implementation returns the nearest machine number to the
input decimal string. Ties are broken by using the IEEE
round-even rule. However, <<strtof>> is currently subject to
double rounding errors.
The alternate function <<_strtod_r>> is a reentrant version.
The extra argument <[reent]> is a pointer to a reentrancy structure.
RETURNS
<<strtod>> returns the converted substring value, if any. If
no conversion could be performed, 0 is returned. If the
correct value is out of the range of representable values,
plus or minus <<HUGE_VAL>> is returned, and <<ERANGE>> is
stored in errno. If the correct value would cause underflow, 0
is returned and <<ERANGE>> is stored in errno.
Supporting OS subroutines required: <<close>>, <<fstat>>, <<isatty>>,
<<lseek>>, <<read>>, <<sbrk>>, <<write>>.
*/
/****************************************************************
The author of this software is David M. Gay.
Copyright (C) 1998-2001 by Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
/* Please send bug reports to David M. Gay (dmg at acm dot org,
* with " at " changed at "@" and " dot " changed to "."). */
/* Original file gdtoa-strtod.c Modified 06-21-2006 by Jeff Johnston to work within newlib. */
#include <_ansi.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "mprec.h"
#include "gdtoa.h"
#include "gd_qnan.h"
/* #ifndef NO_FENV_H */
/* #include <fenv.h> */
/* #endif */
#include "locale.h"
#ifdef IEEE_Arith
#ifndef NO_IEEE_Scale
#define Avoid_Underflow
#undef tinytens
/* The factor of 2^106 in tinytens[4] helps us avoid setting the underflow */
/* flag unnecessarily. It leads to a song and dance at the end of strtod. */
static _CONST double tinytens[] = { 1e-16, 1e-32,
#ifdef _DOUBLE_IS_32BITS
0.0, 0.0, 0.0
#else
1e-64, 1e-128,
9007199254740992. * 9007199254740992.e-256
#endif
};
#endif
#endif
#ifdef Honor_FLT_ROUNDS
#define Rounding rounding
#undef Check_FLT_ROUNDS
#define Check_FLT_ROUNDS
#else
#define Rounding Flt_Rounds
#endif
#ifdef Avoid_Underflow /*{*/
static double
_DEFUN (sulp, (x, scale),
U x _AND
int scale)
{
U u;
double rv;
int i;
rv = ulp(dval(x));
if (!scale || (i = 2*P + 1 - ((dword0(x) & Exp_mask) >> Exp_shift)) <= 0)
return rv; /* Is there an example where i <= 0 ? */
dword0(u) = Exp_1 + (i << Exp_shift);
#ifndef _DOUBLE_IS_32BITS
dword1(u) = 0;
#endif
return rv * u.d;
}
#endif /*}*/
#ifndef NO_HEX_FP
HAL_ROM_TEXT_SECTION _LONG_CALL_
static void
ULtod(__ULong *L ,
__ULong *bits ,
Long exp ,
int k)
{
switch(k & STRTOG_Retmask) {
case STRTOG_NoNumber:
case STRTOG_Zero:
L[0] = L[1] = 0;
break;
case STRTOG_Denormal:
L[_1] = bits[0];
L[_0] = bits[1];
break;
case STRTOG_Normal:
case STRTOG_NaNbits:
L[_1] = bits[0];
L[_0] = (bits[1] & ~0x100000) | ((exp + 0x3ff + 52) << 20);
break;
case STRTOG_Infinite:
L[_0] = 0x7ff00000;
L[_1] = 0;
break;
case STRTOG_NaN:
L[_0] = 0x7fffffff;
L[_1] = (__ULong)-1;
}
if (k & STRTOG_Neg)
L[_0] |= 0x80000000L;
}
#endif /* !NO_HEX_FP */
#ifdef INFNAN_CHECK
HAL_ROM_TEXT_SECTION _LONG_CALL_
static int
match(
_CONST char **sp ,
char *t)
{
int c, d;
_CONST char *s = *sp;
while( (d = *t++) !=0) {
if ((c = *++s) >= 'A' && c <= 'Z')
c += 'a' - 'A';
if (c != d)
return 0;
}
*sp = s + 1;
return 1;
}
#endif /* INFNAN_CHECK */
HAL_ROM_TEXT_SECTION _LONG_CALL_
double
_strtod_r(
struct _reent *ptr ,
_CONST char *__restrict s00 ,
char **__restrict se)
{
#ifdef Avoid_Underflow
int scale;
#endif
int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, decpt, dsign,
e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
_CONST char *s, *s0, *s1;
double aadj, adj;
U aadj1, rv, rv0;
Long L;
__ULong y, z;
_Bigint *bb = NULL, *bb1, *bd = NULL, *bd0, *bs = NULL, *delta = NULL;
#ifdef Avoid_Underflow
__ULong Lsb, Lsb1;
#endif
#ifdef SET_INEXACT
int inexact, oldinexact;
#endif
#ifdef Honor_FLT_ROUNDS
int rounding;
#endif
delta = bs = bd = NULL;
sign = nz0 = nz = decpt = 0;
dval(rv) = 0.;
for(s = s00;;s++) switch(*s) {
case '-':
sign = 1;
/* no break */
case '+':
if (*++s)
goto break2;
/* no break */
case 0:
goto ret0;
case '\t':
case '\n':
case '\v':
case '\f':
case '\r':
case ' ':
continue;
default:
goto break2;
}
break2:
if (*s == '0') {
#ifndef NO_HEX_FP
{
static _CONST FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI };
Long exp;
__ULong bits[2];
switch(s[1]) {
case 'x':
case 'X':
/* If the number is not hex, then the parse of
0 is still valid. */
s00 = s + 1;
{
#if defined(FE_DOWNWARD) && defined(FE_TONEAREST) && defined(FE_TOWARDZERO) && defined(FE_UPWARD)
FPI fpi1 = fpi;
switch(fegetround()) {
case FE_TOWARDZERO: fpi1.rounding = 0; break;
case FE_UPWARD: fpi1.rounding = 2; break;
case FE_DOWNWARD: fpi1.rounding = 3;
}
#else
#define fpi1 fpi
#endif
switch((i = gethex(ptr, &s, &fpi1, &exp, &bb, sign)) & STRTOG_Retmask) {
case STRTOG_NoNumber:
s = s00;
sign = 0;
/* FALLTHROUGH */
case STRTOG_Zero:
break;
default:
if (bb) {
copybits(bits, fpi.nbits, bb);
Bfree(ptr,bb);
}
ULtod(rv.i, bits, exp, i);
}}
goto ret;
}
}
#endif
nz0 = 1;
while(*++s == '0') ;
if (!*s)
goto ret;
}
s0 = s;
y = z = 0;
for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
if (nd < 9)
y = 10*y + c - '0';
else
z = 10*z + c - '0';
nd0 = nd;
if (strncmp (s, _localeconv_r (ptr)->decimal_point,
strlen (_localeconv_r (ptr)->decimal_point)) == 0)
{
decpt = 1;
c = *(s += strlen (_localeconv_r (ptr)->decimal_point));
if (!nd) {
for(; c == '0'; c = *++s)
nz++;
if (c > '0' && c <= '9') {
s0 = s;
nf += nz;
nz = 0;
goto have_dig;
}
goto dig_done;
}
for(; c >= '0' && c <= '9'; c = *++s) {
have_dig:
nz++;
if (c -= '0') {
nf += nz;
for(i = 1; i < nz; i++)
if (nd++ < 9)
y *= 10;
else if (nd <= DBL_DIG + 1)
z *= 10;
if (nd++ < 9)
y = 10*y + c;
else if (nd <= DBL_DIG + 1)
z = 10*z + c;
nz = 0;
}
}
}
dig_done:
e = 0;
if (c == 'e' || c == 'E') {
if (!nd && !nz && !nz0) {
goto ret0;
}
s00 = s;
esign = 0;
switch(c = *++s) {
case '-':
esign = 1;
case '+':
c = *++s;
}
if (c >= '0' && c <= '9') {
while(c == '0')
c = *++s;
if (c > '0' && c <= '9') {
L = c - '0';
s1 = s;
while((c = *++s) >= '0' && c <= '9')
L = 10*L + c - '0';
if (s - s1 > 8 || L > 19999)
/* Avoid confusion from exponents
* so large that e might overflow.
*/
e = 19999; /* safe for 16 bit ints */
else
e = (int)L;
if (esign)
e = -e;
}
else
e = 0;
}
else
s = s00;
}
if (!nd) {
if (!nz && !nz0) {
#ifdef INFNAN_CHECK
/* Check for Nan and Infinity */
__ULong bits[2];
static _CONST FPI fpinan = /* only 52 explicit bits */
{ 52, 1-1023-53+1, 2046-1023-53+1, 1, SI };
if (!decpt)
switch(c) {
case 'i':
case 'I':
if (match(&s,"nf")) {
--s;
if (!match(&s,"inity"))
++s;
dword0(rv) = 0x7ff00000;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = 0;
#endif /*!_DOUBLE_IS_32BITS*/
goto ret;
}
break;
case 'n':
case 'N':
if (match(&s, "an")) {
#ifndef No_Hex_NaN
if (*s == '(' /*)*/
&& hexnan(&s, &fpinan, bits)
== STRTOG_NaNbits) {
dword0(rv) = 0x7ff00000 | bits[1];
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = bits[0];
#endif /*!_DOUBLE_IS_32BITS*/
}
else {
#endif
dword0(rv) = NAN_WORD0;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = NAN_WORD1;
#endif /*!_DOUBLE_IS_32BITS*/
#ifndef No_Hex_NaN
}
#endif
goto ret;
}
}
#endif /* INFNAN_CHECK */
ret0:
s = s00;
sign = 0;
}
goto ret;
}
e1 = e -= nf;
/* Now we have nd0 digits, starting at s0, followed by a
* decimal point, followed by nd-nd0 digits. The number we're
* after is the integer represented by those digits times
* 10**e */
if (!nd0)
nd0 = nd;
k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
dval(rv) = y;
if (k > 9) {
#ifdef SET_INEXACT
if (k > DBL_DIG)
oldinexact = get_inexact();
#endif
dval(rv) = tens[k - 9] * dval(rv) + z;
}
bd0 = 0;
if (nd <= DBL_DIG
#ifndef RND_PRODQUOT
#ifndef Honor_FLT_ROUNDS
&& Flt_Rounds == 1
#endif
#endif
) {
if (!e)
goto ret;
if (e > 0) {
if (e <= Ten_pmax) {
#ifdef VAX
goto vax_ovfl_check;
#else
#ifdef Honor_FLT_ROUNDS
/* round correctly FLT_ROUNDS = 2 or 3 */
if (sign) {
dval(rv) = -dval(rv);
sign = 0;
}
#endif
/* rv = */ rounded_product(dval(rv), tens[e]);
goto ret;
#endif
}
i = DBL_DIG - nd;
if (e <= Ten_pmax + i) {
/* A fancier test would sometimes let us do
* this for larger i values.
*/
#ifdef Honor_FLT_ROUNDS
/* round correctly FLT_ROUNDS = 2 or 3 */
if (sign) {
dval(rv) = -dval(rv);
sign = 0;
}
#endif
e -= i;
dval(rv) *= tens[i];
#ifdef VAX
/* VAX exponent range is so narrow we must
* worry about overflow here...
*/
vax_ovfl_check:
dword0(rv) -= P*Exp_msk1;
/* rv = */ rounded_product(dval(rv), tens[e]);
if ((dword0(rv) & Exp_mask)
> Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
goto ovfl;
dword0(rv) += P*Exp_msk1;
#else
/* rv = */ rounded_product(dval(rv), tens[e]);
#endif
goto ret;
}
}
#ifndef Inaccurate_Divide
else if (e >= -Ten_pmax) {
#ifdef Honor_FLT_ROUNDS
/* round correctly FLT_ROUNDS = 2 or 3 */
if (sign) {
dval(rv) = -dval(rv);
sign = 0;
}
#endif
/* rv = */ rounded_quotient(dval(rv), tens[-e]);
goto ret;
}
#endif
}
e1 += nd - k;
#ifdef IEEE_Arith
#ifdef SET_INEXACT
inexact = 1;
if (k <= DBL_DIG)
oldinexact = get_inexact();
#endif
#ifdef Avoid_Underflow
scale = 0;
#endif
#ifdef Honor_FLT_ROUNDS
if ((rounding = Flt_Rounds) >= 2) {
if (sign)
rounding = rounding == 2 ? 0 : 2;
else
if (rounding != 2)
rounding = 0;
}
#endif
#endif /*IEEE_Arith*/
/* Get starting approximation = rv * 10**e1 */
if (e1 > 0) {
if ( (i = e1 & 15) !=0)
dval(rv) *= tens[i];
if (e1 &= ~15) {
if (e1 > DBL_MAX_10_EXP) {
ovfl:
#ifndef NO_ERRNO
ptr->_errno = ERANGE;
#endif
/* Can't trust HUGE_VAL */
#ifdef IEEE_Arith
#ifdef Honor_FLT_ROUNDS
switch(rounding) {
case 0: /* toward 0 */
case 3: /* toward -infinity */
dword0(rv) = Big0;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = Big1;
#endif /*!_DOUBLE_IS_32BITS*/
break;
default:
dword0(rv) = Exp_mask;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = 0;
#endif /*!_DOUBLE_IS_32BITS*/
}
#else /*Honor_FLT_ROUNDS*/
dword0(rv) = Exp_mask;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = 0;
#endif /*!_DOUBLE_IS_32BITS*/
#endif /*Honor_FLT_ROUNDS*/
#ifdef SET_INEXACT
/* set overflow bit */
dval(rv0) = 1e300;
dval(rv0) *= dval(rv0);
#endif
#else /*IEEE_Arith*/
dword0(rv) = Big0;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = Big1;
#endif /*!_DOUBLE_IS_32BITS*/
#endif /*IEEE_Arith*/
if (bd0)
goto retfree;
goto ret;
}
e1 >>= 4;
for(j = 0; e1 > 1; j++, e1 >>= 1)
if (e1 & 1)
dval(rv) *= bigtens[j];
/* The last multiplication could overflow. */
dword0(rv) -= P*Exp_msk1;
dval(rv) *= bigtens[j];
if ((z = dword0(rv) & Exp_mask)
> Exp_msk1*(DBL_MAX_EXP+Bias-P))
goto ovfl;
if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
/* set to largest number */
/* (Can't trust DBL_MAX) */
dword0(rv) = Big0;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = Big1;
#endif /*!_DOUBLE_IS_32BITS*/
}
else
dword0(rv) += P*Exp_msk1;
}
}
else if (e1 < 0) {
e1 = -e1;
if ( (i = e1 & 15) !=0)
dval(rv) /= tens[i];
if (e1 >>= 4) {
if (e1 >= 1 << n_bigtens)
goto undfl;
#ifdef Avoid_Underflow
if (e1 & Scale_Bit)
scale = 2*P;
for(j = 0; e1 > 0; j++, e1 >>= 1)
if (e1 & 1)
dval(rv) *= tinytens[j];
if (scale && (j = 2*P + 1 - ((dword0(rv) & Exp_mask)
>> Exp_shift)) > 0) {
/* scaled rv is denormal; zap j low bits */
if (j >= 32) {
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = 0;
#endif /*!_DOUBLE_IS_32BITS*/
if (j >= 53)
dword0(rv) = (P+2)*Exp_msk1;
else
dword0(rv) &= 0xffffffff << (j-32);
}
#ifndef _DOUBLE_IS_32BITS
else
dword1(rv) &= 0xffffffff << j;
#endif /*!_DOUBLE_IS_32BITS*/
}
#else
for(j = 0; e1 > 1; j++, e1 >>= 1)
if (e1 & 1)
dval(rv) *= tinytens[j];
/* The last multiplication could underflow. */
dval(rv0) = dval(rv);
dval(rv) *= tinytens[j];
if (!dval(rv)) {
dval(rv) = 2.*dval(rv0);
dval(rv) *= tinytens[j];
#endif
if (!dval(rv)) {
undfl:
dval(rv) = 0.;
#ifndef NO_ERRNO
ptr->_errno = ERANGE;
#endif
if (bd0)
goto retfree;
goto ret;
}
#ifndef Avoid_Underflow
#ifndef _DOUBLE_IS_32BITS
dword0(rv) = Tiny0;
dword1(rv) = Tiny1;
#else
dword0(rv) = Tiny1;
#endif /*_DOUBLE_IS_32BITS*/
/* The refinement below will clean
* this approximation up.
*/
}
#endif
}
}
/* Now the hard part -- adjusting rv to the correct value.*/
/* Put digits into bd: true value = bd * 10^e */
bd0 = s2b(ptr, s0, nd0, nd, y);
if (bd0 == NULL)
goto ovfl;
for(;;) {
bd = Balloc(ptr,bd0->_k);
if (bd == NULL)
goto ovfl;
Bcopy(bd, bd0);
bb = d2b(ptr,dval(rv), &bbe, &bbbits); /* rv = bb * 2^bbe */
if (bb == NULL)
goto ovfl;
bs = i2b(ptr,1);
if (bs == NULL)
goto ovfl;
if (e >= 0) {
bb2 = bb5 = 0;
bd2 = bd5 = e;
}
else {
bb2 = bb5 = -e;
bd2 = bd5 = 0;
}
if (bbe >= 0)
bb2 += bbe;
else
bd2 -= bbe;
bs2 = bb2;
#ifdef Honor_FLT_ROUNDS
if (rounding != 1)
bs2++;
#endif
#ifdef Avoid_Underflow
Lsb = LSB;
Lsb1 = 0;
j = bbe - scale;
i = j + bbbits - 1; /* logb(rv) */
j = P + 1 - bbbits;
if (i < Emin) { /* denormal */
i = Emin - i;
j -= i;
if (i < 32)
Lsb <<= i;
else
Lsb1 = Lsb << (i-32);
}
#else /*Avoid_Underflow*/
#ifdef Sudden_Underflow
#ifdef IBM
j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
#else
j = P + 1 - bbbits;
#endif
#else /*Sudden_Underflow*/
j = bbe;
i = j + bbbits - 1; /* logb(rv) */
if (i < Emin) /* denormal */
j += P - Emin;
else
j = P + 1 - bbbits;
#endif /*Sudden_Underflow*/
#endif /*Avoid_Underflow*/
bb2 += j;
bd2 += j;
#ifdef Avoid_Underflow
bd2 += scale;
#endif
i = bb2 < bd2 ? bb2 : bd2;
if (i > bs2)
i = bs2;
if (i > 0) {
bb2 -= i;
bd2 -= i;
bs2 -= i;
}
if (bb5 > 0) {
bs = pow5mult(ptr, bs, bb5);
if (bs == NULL)
goto ovfl;
bb1 = mult(ptr, bs, bb);
if (bb1 == NULL)
goto ovfl;
Bfree(ptr, bb);
bb = bb1;
}
if (bb2 > 0) {
bb = lshift(ptr, bb, bb2);
if (bb == NULL)
goto ovfl;
}
if (bd5 > 0) {
bd = pow5mult(ptr, bd, bd5);
if (bd == NULL)
goto ovfl;
}
if (bd2 > 0) {
bd = lshift(ptr, bd, bd2);
if (bd == NULL)
goto ovfl;
}
if (bs2 > 0) {
bs = lshift(ptr, bs, bs2);
if (bs == NULL)
goto ovfl;
}
delta = diff(ptr, bb, bd);
if (delta == NULL)
goto ovfl;
dsign = delta->_sign;
delta->_sign = 0;
i = cmp(delta, bs);
#ifdef Honor_FLT_ROUNDS
if (rounding != 1) {
if (i < 0) {
/* Error is less than an ulp */
if (!delta->_x[0] && delta->_wds <= 1) {
/* exact */
#ifdef SET_INEXACT
inexact = 0;
#endif
break;
}
if (rounding) {
if (dsign) {
adj = 1.;
goto apply_adj;
}
}
else if (!dsign) {
adj = -1.;
if (!dword1(rv)
&& !(dword0(rv) & Frac_mask)) {
y = dword0(rv) & Exp_mask;
#ifdef Avoid_Underflow
if (!scale || y > 2*P*Exp_msk1)
#else
if (y)
#endif
{
delta = lshift(ptr, delta,Log2P);
if (cmp(delta, bs) <= 0)
adj = -0.5;
}
}
apply_adj:
#ifdef Avoid_Underflow
if (scale && (y = dword0(rv) & Exp_mask)
<= 2*P*Exp_msk1)
dword0(adj) += (2*P+1)*Exp_msk1 - y;
#else
#ifdef Sudden_Underflow
if ((dword0(rv) & Exp_mask) <=
P*Exp_msk1) {
dword0(rv) += P*Exp_msk1;
dval(rv) += adj*ulp(dval(rv));
dword0(rv) -= P*Exp_msk1;
}
else
#endif /*Sudden_Underflow*/
#endif /*Avoid_Underflow*/
dval(rv) += adj*ulp(dval(rv));
}
break;
}
adj = ratio(delta, bs);
if (adj < 1.)
adj = 1.;
if (adj <= 0x7ffffffe) {
/* adj = rounding ? ceil(adj) : floor(adj); */
y = adj;
if (y != adj) {
if (!((rounding>>1) ^ dsign))
y++;
adj = y;
}
}
#ifdef Avoid_Underflow
if (scale && (y = dword0(rv) & Exp_mask) <= 2*P*Exp_msk1)
dword0(adj) += (2*P+1)*Exp_msk1 - y;
#else
#ifdef Sudden_Underflow
if ((dword0(rv) & Exp_mask) <= P*Exp_msk1) {
dword0(rv) += P*Exp_msk1;
adj *= ulp(dval(rv));
if (dsign)
dval(rv) += adj;
else
dval(rv) -= adj;
dword0(rv) -= P*Exp_msk1;
goto cont;
}
#endif /*Sudden_Underflow*/
#endif /*Avoid_Underflow*/
adj *= ulp(dval(rv));
if (dsign) {
if (dword0(rv) == Big0 && dword1(rv) == Big1)
goto ovfl;
dval(rv) += adj;
else
dval(rv) -= adj;
goto cont;
}
#endif /*Honor_FLT_ROUNDS*/
if (i < 0) {
/* Error is less than half an ulp -- check for
* special case of mantissa a power of two.
*/
if (dsign || dword1(rv) || dword0(rv) & Bndry_mask
#ifdef IEEE_Arith
#ifdef Avoid_Underflow
|| (dword0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
#else
|| (dword0(rv) & Exp_mask) <= Exp_msk1
#endif
#endif
) {
#ifdef SET_INEXACT
if (!delta->x[0] && delta->wds <= 1)
inexact = 0;
#endif
break;
}
if (!delta->_x[0] && delta->_wds <= 1) {
/* exact result */
#ifdef SET_INEXACT
inexact = 0;
#endif
break;
}
delta = lshift(ptr,delta,Log2P);
if (cmp(delta, bs) > 0)
goto drop_down;
break;
}
if (i == 0) {
/* exactly half-way between */
if (dsign) {
if ((dword0(rv) & Bndry_mask1) == Bndry_mask1
&& dword1(rv) == (
#ifdef Avoid_Underflow
(scale && (y = dword0(rv) & Exp_mask) <= 2*P*Exp_msk1)
? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
#endif
0xffffffff)) {
/*boundary case -- increment exponent*/
if (dword0(rv) == Big0 && dword1(rv) == Big1)
goto ovfl;
dword0(rv) = (dword0(rv) & Exp_mask)
+ Exp_msk1
#ifdef IBM
| Exp_msk1 >> 4
#endif
;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = 0;
#endif /*!_DOUBLE_IS_32BITS*/
#ifdef Avoid_Underflow
dsign = 0;
#endif
break;
}
}
else if (!(dword0(rv) & Bndry_mask) && !dword1(rv)) {
drop_down:
/* boundary case -- decrement exponent */
#ifdef Sudden_Underflow /*{{*/
L = dword0(rv) & Exp_mask;
#ifdef IBM
if (L < Exp_msk1)
#else
#ifdef Avoid_Underflow
if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
#else
if (L <= Exp_msk1)
#endif /*Avoid_Underflow*/
#endif /*IBM*/
goto undfl;
L -= Exp_msk1;
#else /*Sudden_Underflow}{*/
#ifdef Avoid_Underflow
if (scale) {
L = dword0(rv) & Exp_mask;
if (L <= (2*P+1)*Exp_msk1) {
if (L > (P+2)*Exp_msk1)
/* round even ==> */
/* accept rv */
break;
/* rv = smallest denormal */
goto undfl;
}
}
#endif /*Avoid_Underflow*/
L = (dword0(rv) & Exp_mask) - Exp_msk1;
#endif /*Sudden_Underflow}*/
dword0(rv) = L | Bndry_mask1;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = 0xffffffff;
#endif /*!_DOUBLE_IS_32BITS*/
#ifdef IBM
goto cont;
#else
break;
#endif
}
#ifndef ROUND_BIASED
#ifdef Avoid_Underflow
if (Lsb1) {
if (!(dword0(rv) & Lsb1))
break;
}
else if (!(dword1(rv) & Lsb))
break;
#else
if (!(dword1(rv) & LSB))
break;
#endif
#endif
if (dsign)
#ifdef Avoid_Underflow
dval(rv) += sulp(rv, scale);
#else
dval(rv) += ulp(dval(rv));
#endif
#ifndef ROUND_BIASED
else {
#ifdef Avoid_Underflow
dval(rv) -= sulp(rv, scale);
#else
dval(rv) -= ulp(dval(rv));
#endif
#ifndef Sudden_Underflow
if (!dval(rv))
goto undfl;
#endif
}
#ifdef Avoid_Underflow
dsign = 1 - dsign;
#endif
#endif
break;
}
if ((aadj = ratio(delta, bs)) <= 2.) {
if (dsign)
aadj = dval(aadj1) = 1.;
else if (dword1(rv) || dword0(rv) & Bndry_mask) {
#ifndef Sudden_Underflow
if (dword1(rv) == Tiny1 && !dword0(rv))
goto undfl;
#endif
aadj = 1.;
dval(aadj1) = -1.;
}
else {
/* special case -- power of FLT_RADIX to be */
/* rounded down... */
if (aadj < 2./FLT_RADIX)
aadj = 1./FLT_RADIX;
else
aadj *= 0.5;
dval(aadj1) = -aadj;
}
}
else {
aadj *= 0.5;
dval(aadj1) = dsign ? aadj : -aadj;
#ifdef Check_FLT_ROUNDS
switch(Rounding) {
case 2: /* towards +infinity */
dval(aadj1) -= 0.5;
break;
case 0: /* towards 0 */
case 3: /* towards -infinity */
dval(aadj1) += 0.5;
}
#else
if (Flt_Rounds == 0)
dval(aadj1) += 0.5;
#endif /*Check_FLT_ROUNDS*/
}
y = dword0(rv) & Exp_mask;
/* Check for overflow */
if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
dval(rv0) = dval(rv);
dword0(rv) -= P*Exp_msk1;
adj = dval(aadj1) * ulp(dval(rv));
dval(rv) += adj;
if ((dword0(rv) & Exp_mask) >=
Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
if (dword0(rv0) == Big0 && dword1(rv0) == Big1)
goto ovfl;
dword0(rv) = Big0;
#ifndef _DOUBLE_IS_32BITS
dword1(rv) = Big1;
#endif /*!_DOUBLE_IS_32BITS*/
goto cont;
}
else
dword0(rv) += P*Exp_msk1;
}
else {
#ifdef Avoid_Underflow
if (scale && y <= 2*P*Exp_msk1) {
if (aadj <= 0x7fffffff) {
if ((z = aadj) == 0)
z = 1;
aadj = z;
dval(aadj1) = dsign ? aadj : -aadj;
}
dword0(aadj1) += (2*P+1)*Exp_msk1 - y;
}
adj = dval(aadj1) * ulp(dval(rv));
dval(rv) += adj;
#else
#ifdef Sudden_Underflow
if ((dword0(rv) & Exp_mask) <= P*Exp_msk1) {
dval(rv0) = dval(rv);
dword0(rv) += P*Exp_msk1;
adj = dval(aadj1) * ulp(dval(rv));
dval(rv) += adj;
#ifdef IBM
if ((dword0(rv) & Exp_mask) < P*Exp_msk1)
#else
if ((dword0(rv) & Exp_mask) <= P*Exp_msk1)
#endif
{
if (dword0(rv0) == Tiny0
&& dword1(rv0) == Tiny1)
goto undfl;
#ifndef _DOUBLE_IS_32BITS
dword0(rv) = Tiny0;
dword1(rv) = Tiny1;
#else
dword0(rv) = Tiny1;
#endif /*_DOUBLE_IS_32BITS*/
goto cont;
}
else
dword0(rv) -= P*Exp_msk1;
}
else {
adj = dval(aadj1) * ulp(dval(rv));
dval(rv) += adj;
}
#else /*Sudden_Underflow*/
/* Compute adj so that the IEEE rounding rules will
* correctly round rv + adj in some half-way cases.
* If rv * ulp(rv) is denormalized (i.e.,
* y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
* trouble from bits lost to denormalization;
* example: 1.2e-307 .
*/
if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
dval(aadj1) = (double)(int)(aadj + 0.5);
if (!dsign)
dval(aadj1) = -dval(aadj1);
}
adj = dval(aadj1) * ulp(dval(rv));
dval(rv) += adj;
#endif /*Sudden_Underflow*/
#endif /*Avoid_Underflow*/
}
z = dword0(rv) & Exp_mask;
#ifndef SET_INEXACT
#ifdef Avoid_Underflow
if (!scale)
#endif
if (y == z) {
/* Can we stop now? */
L = (Long)aadj;
aadj -= L;
/* The tolerances below are conservative. */
if (dsign || dword1(rv) || dword0(rv) & Bndry_mask) {
if (aadj < .4999999 || aadj > .5000001)
break;
}
else if (aadj < .4999999/FLT_RADIX)
break;
}
#endif
cont:
Bfree(ptr,bb);
Bfree(ptr,bd);
Bfree(ptr,bs);
Bfree(ptr,delta);
}
#ifdef SET_INEXACT
if (inexact) {
if (!oldinexact) {
dword0(rv0) = Exp_1 + (70 << Exp_shift);
#ifndef _DOUBLE_IS_32BITS
dword1(rv0) = 0;
#endif /*!_DOUBLE_IS_32BITS*/
dval(rv0) += 1.;
}
}
else if (!oldinexact)
clear_inexact();
#endif
#ifdef Avoid_Underflow
if (scale) {
dword0(rv0) = Exp_1 - 2*P*Exp_msk1;
#ifndef _DOUBLE_IS_32BITS
dword1(rv0) = 0;
#endif /*!_DOUBLE_IS_32BITS*/
dval(rv) *= dval(rv0);
#ifndef NO_ERRNO
/* try to avoid the bug of testing an 8087 register value */
if (dword0(rv) == 0 && dword1(rv) == 0)
ptr->_errno = ERANGE;
#endif
}
#endif /* Avoid_Underflow */
#ifdef SET_INEXACT
if (inexact && !(dword0(rv) & Exp_mask)) {
/* set underflow bit */
dval(rv0) = 1e-300;
dval(rv0) *= dval(rv0);
}
#endif
retfree:
Bfree(ptr,bb);
Bfree(ptr,bd);
Bfree(ptr,bs);
Bfree(ptr,bd0);
Bfree(ptr,delta);
ret:
if (se)
*se = (char *)s;
return sign ? -dval(rv) : dval(rv);
}
HAL_ROM_TEXT_SECTION _LONG_CALL_
double
strtod(_CONST char *__restrict s00 , char **__restrict se)
{
return _strtod_r (_REENT, s00, se);
}
HAL_ROM_TEXT_SECTION _LONG_CALL_
float
strtof(_CONST char *__restrict s00 ,
char **__restrict se)
{
double retval = _strtod_r (_REENT, s00, se);
if (isnan (retval)) {
return rtl_nanf ();
}
return (float)retval;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strtod_bk.c
|
C
|
apache-2.0
| 28,211
|
/*
FUNCTION
<<strtok>>, <<strtok_r>>, <<strsep>>---get next token from a string
INDEX
strtok
INDEX
strtok_r
INDEX
strsep
ANSI_SYNOPSIS
#include <string.h>
char *strtok(char *restrict <[source]>,
const char *restrict <[delimiters]>)
char *strtok_r(char *restrict <[source]>,
const char *restrict <[delimiters]>,
char **<[lasts]>)
char *strsep(char **<[source_ptr]>, const char *<[delimiters]>)
TRAD_SYNOPSIS
#include <string.h>
char *strtok(<[source]>, <[delimiters]>)
char *<[source]>;
char *<[delimiters]>;
char *strtok_r(<[source]>, <[delimiters]>, <[lasts]>)
char *<[source]>;
char *<[delimiters]>;
char **<[lasts]>;
char *strsep(<[source_ptr]>, <[delimiters]>)
char **<[source_ptr]>;
char *<[delimiters]>;
DESCRIPTION
The <<strtok>> function is used to isolate sequential tokens in a
null-terminated string, <<*<[source]>>>. These tokens are delimited
in the string by at least one of the characters in <<*<[delimiters]>>>.
The first time that <<strtok>> is called, <<*<[source]>>> should be
specified; subsequent calls, wishing to obtain further tokens from
the same string, should pass a null pointer instead. The separator
string, <<*<[delimiters]>>>, must be supplied each time and may
change between calls.
The <<strtok>> function returns a pointer to the beginning of each
subsequent token in the string, after replacing the separator
character itself with a null character. When no more tokens remain,
a null pointer is returned.
The <<strtok_r>> function has the same behavior as <<strtok>>, except
a pointer to placeholder <<*<[lasts]>>> must be supplied by the caller.
The <<strsep>> function is similar in behavior to <<strtok>>, except
a pointer to the string pointer must be supplied <<<[source_ptr]>>> and
the function does not skip leading delimiters. When the string starts
with a delimiter, the delimiter is changed to the null character and
the empty string is returned. Like <<strtok_r>> and <<strtok>>, the
<<*<[source_ptr]>>> is updated to the next character following the
last delimiter found or NULL if the end of string is reached with
no more delimiters.
RETURNS
<<strtok>>, <<strtok_r>>, and <<strsep>> all return a pointer to the
next token, or <<NULL>> if no more tokens can be found. For
<<strsep>>, a token may be the empty string.
NOTES
<<strtok>> is unsafe for multi-threaded applications. <<strtok_r>>
and <<strsep>> are thread-safe and should be used instead.
PORTABILITY
<<strtok>> is ANSI C.
<<strtok_r>> is POSIX.
<<strsep>> is a BSD extension.
<<strtok>>, <<strtok_r>>, and <<strsep>> require no supporting OS subroutines.
QUICKREF
strtok ansi impure
*/
/* undef STRICT_ANSI so that strtok_r prototype will be defined */
#undef __STRICT_ANSI__
#include <string.h>
#include <_ansi.h>
#include <reent.h>
#include <section_config.h>
#include <basic_types.h>
extern char *__strtok_r (char *, const char *, char **, int);
extern struct _reent* _rtl_impure_ptr;
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * _strtok(register char *s , register const char *delim)
{
//struct _reent *reent = _rtl_impure_ptr;
HAL_ROM_BSS_SECTION static char *_strtok_last;
//_REENT_CHECK_MISC(reent);
//return __strtok_r (s, delim, &(_REENT_STRTOK_LAST(reent)), 1);
return __strtok_r (s, delim, &_strtok_last, 1);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strtok.c
|
C
|
apache-2.0
| 3,401
|
/*
* Copyright (c) 1988 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <section_config.h>
#include <basic_types.h>
#include <string.h>
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * __strtok_r(register char *s , register const char *delim , char **lasts , int skip_leading_delim)
{
register char *spanp;
register int c, sc;
char *tok;
if (s == NULL && (s = *lasts) == NULL)
return (NULL);
/*
* Skip (span) leading delimiters (s += strspn(s, delim), sort of).
*/
cont:
c = *s++;
for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
if (c == sc) {
if (skip_leading_delim) {
goto cont;
}
else {
*lasts = s;
s[-1] = 0;
return (s - 1);
}
}
}
if (c == 0) { /* no non-delimiter characters */
*lasts = NULL;
return (NULL);
}
tok = s - 1;
/*
* Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
* Note that delim must have one NUL; we stop if we see that, too.
*/
for (;;) {
c = *s++;
spanp = (char *)delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = NULL;
else
s[-1] = 0;
*lasts = s;
return (tok);
}
} while (sc != 0);
}
/* NOTREACHED */
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
char * _strtok_r(register char *s , register const char *delim , char **lasts)
{
return __strtok_r(s, delim, lasts, 1);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strtok_r.c
|
C
|
apache-2.0
| 2,838
|
/*
FUNCTION
<<strtol>>---string to long
INDEX
strtol
INDEX
_strtol_r
ANSI_SYNOPSIS
#include <stdlib.h>
long strtol(const char *restrict <[s]>, char **restrict <[ptr]>,int <[base]>);
long _strtol_r(void *<[reent]>,
const char *restrict <[s]>, char **restrict <[ptr]>,int <[base]>);
TRAD_SYNOPSIS
#include <stdlib.h>
long strtol (<[s]>, <[ptr]>, <[base]>)
char *<[s]>;
char **<[ptr]>;
int <[base]>;
long _strtol_r (<[reent]>, <[s]>, <[ptr]>, <[base]>)
char *<[reent]>;
char *<[s]>;
char **<[ptr]>;
int <[base]>;
DESCRIPTION
The function <<strtol>> converts the string <<*<[s]>>> to
a <<long>>. First, it breaks down the string into three parts:
leading whitespace, which is ignored; a subject string consisting
of characters resembling an integer in the radix specified by <[base]>;
and a trailing portion consisting of zero or more unparseable characters,
and always including the terminating null character. Then, it attempts
to convert the subject string into a <<long>> and returns the
result.
If the value of <[base]> is 0, the subject string is expected to look
like a normal C integer constant: an optional sign, a possible `<<0x>>'
indicating a hexadecimal base, and a number. If <[base]> is between
2 and 36, the expected form of the subject is a sequence of letters
and digits representing an integer in the radix specified by <[base]>,
with an optional plus or minus sign. The letters <<a>>--<<z>> (or,
equivalently, <<A>>--<<Z>>) are used to signify values from 10 to 35;
only letters whose ascribed values are less than <[base]> are
permitted. If <[base]> is 16, a leading <<0x>> is permitted.
The subject sequence is the longest initial sequence of the input
string that has the expected form, starting with the first
non-whitespace character. If the string is empty or consists entirely
of whitespace, or if the first non-whitespace character is not a
permissible letter or digit, the subject string is empty.
If the subject string is acceptable, and the value of <[base]> is zero,
<<strtol>> attempts to determine the radix from the input string. A
string with a leading <<0x>> is treated as a hexadecimal value; a string with
a leading 0 and no <<x>> is treated as octal; all other strings are
treated as decimal. If <[base]> is between 2 and 36, it is used as the
conversion radix, as described above. If the subject string begins with
a minus sign, the value is negated. Finally, a pointer to the first
character past the converted subject string is stored in <[ptr]>, if
<[ptr]> is not <<NULL>>.
If the subject string is empty (or not in acceptable form), no conversion
is performed and the value of <[s]> is stored in <[ptr]> (if <[ptr]> is
not <<NULL>>).
The alternate function <<_strtol_r>> is a reentrant version. The
extra argument <[reent]> is a pointer to a reentrancy structure.
RETURNS
<<strtol>> returns the converted value, if any. If no conversion was
made, 0 is returned.
<<strtol>> returns <<LONG_MAX>> or <<LONG_MIN>> if the magnitude of
the converted value is too large, and sets <<errno>> to <<ERANGE>>.
PORTABILITY
<<strtol>> is ANSI.
No supporting OS subroutines are required.
*/
/*-
* Copyright (c) 1990 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 University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <errno.h>
#include <section_config.h>
#include <basic_types.h>
#include <strproc.h>
#include <string.h>
#include <limits.h>
/*
* Convert a string to a long integer.
*
* Ignores `locale' stuff. Assumes that the upper and lower case
* alphabets and digits are each contiguous.
*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
long
_strtol_r (
_CONST char * nptr ,
char ** endptr ,
int base)
{
register const unsigned char *s = (const unsigned char *)nptr;
register unsigned long acc;
register int c;
register unsigned long cutoff;
register int neg = 0, any, cutlim;
/*
* Skip white space and pick up leading +/- sign if any.
* If base is 0, allow 0x for hex and 0 for octal, else
* assume decimal; if base is already 16, allow 0x.
*/
do {
c = *s++;
} while (isspace(c));
if (c == '-') {
neg = 1;
c = *s++;
} else if (c == '+')
c = *s++;
if ((base == 0 || base == 16) &&
c == '0' && (*s == 'x' || *s == 'X')) {
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == '0' ? 8 : 10;
/*
* Compute the cutoff value between legal numbers and illegal
* numbers. That is the largest legal value, divided by the
* base. An input number that is greater than this value, if
* followed by a legal input character, is too big. One that
* is equal to this value may be valid or not; the limit
* between valid and invalid numbers is then based on the last
* digit. For instance, if the range for longs is
* [-2147483648..2147483647] and the input base is 10,
* cutoff will be set to 214748364 and cutlim to either
* 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
* a value > 214748364, or equal but the next digit is > 7 (or 8),
* the number is too big, and we will return a range error.
*
* Set any if any `digits' consumed; make it negative to indicate
* overflow.
*/
cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
cutlim = cutoff % (unsigned long)base;
cutoff /= (unsigned long)base;
for (acc = 0, any = 0;; c = *s++) {
if (isdigit(c))
c -= '0';
else if (isalpha(c))
c -= isupper(c) ? 'A' - 10 : 'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
any = -1;
else {
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0) {
acc = neg ? LONG_MIN : LONG_MAX;
//rptr->_errno = ERANGE;
} else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = (char *) (any ? (char *)s - 1 : nptr);
return (acc);
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
long
_strtol(_CONST char *__restrict s ,
char **__restrict ptr ,
int base)
{
return _strtol_r (s, ptr, base);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strtol.c
|
C
|
apache-2.0
| 7,712
|
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
/**
* _strtol - convert a string to a signed long
* @cp: The start of the string
* @endp: A pointer to the end of the parsed string will be placed here
* @base: The number base to use
*
* This function is obsolete. Please use kstrtol instead.
*/
HAL_ROM_TEXT_SECTION
_LONG_CALL_ long _strtol(const char *cp, char **endp, unsigned int base)
{
if (*cp == '-')
return -_strtoul(cp + 1, endp, base);
return _strtoul(cp, endp, base);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strtol_bk.c
|
C
|
apache-2.0
| 699
|
/*
FUNCTION
<<strtoul>>---string to unsigned long
INDEX
strtoul
INDEX
_strtoul_r
ANSI_SYNOPSIS
#include <stdlib.h>
unsigned long strtoul(const char *restrict <[s]>, char **restrict <[ptr]>,
int <[base]>);
unsigned long _strtoul_r(void *<[reent]>, const char *restrict <[s]>,
char **restrict <[ptr]>, int <[base]>);
TRAD_SYNOPSIS
#include <stdlib.h>
unsigned long strtoul(<[s]>, <[ptr]>, <[base]>)
char *<[s]>;
char **<[ptr]>;
int <[base]>;
unsigned long _strtoul_r(<[reent]>, <[s]>, <[ptr]>, <[base]>)
char *<[reent]>;
char *<[s]>;
char **<[ptr]>;
int <[base]>;
DESCRIPTION
The function <<strtoul>> converts the string <<*<[s]>>> to
an <<unsigned long>>. First, it breaks down the string into three parts:
leading whitespace, which is ignored; a subject string consisting
of the digits meaningful in the radix specified by <[base]>
(for example, <<0>> through <<7>> if the value of <[base]> is 8);
and a trailing portion consisting of one or more unparseable characters,
which always includes the terminating null character. Then, it attempts
to convert the subject string into an unsigned long integer, and returns the
result.
If the value of <[base]> is zero, the subject string is expected to look
like a normal C integer constant (save that no optional sign is permitted):
a possible <<0x>> indicating hexadecimal radix, and a number.
If <[base]> is between 2 and 36, the expected form of the subject is a
sequence of digits (which may include letters, depending on the
base) representing an integer in the radix specified by <[base]>.
The letters <<a>>--<<z>> (or <<A>>--<<Z>>) are used as digits valued from
10 to 35. If <[base]> is 16, a leading <<0x>> is permitted.
The subject sequence is the longest initial sequence of the input
string that has the expected form, starting with the first
non-whitespace character. If the string is empty or consists entirely
of whitespace, or if the first non-whitespace character is not a
permissible digit, the subject string is empty.
If the subject string is acceptable, and the value of <[base]> is zero,
<<strtoul>> attempts to determine the radix from the input string. A
string with a leading <<0x>> is treated as a hexadecimal value; a string with
a leading <<0>> and no <<x>> is treated as octal; all other strings are
treated as decimal. If <[base]> is between 2 and 36, it is used as the
conversion radix, as described above. Finally, a pointer to the first
character past the converted subject string is stored in <[ptr]>, if
<[ptr]> is not <<NULL>>.
If the subject string is empty (that is, if <<*>><[s]> does not start
with a substring in acceptable form), no conversion
is performed and the value of <[s]> is stored in <[ptr]> (if <[ptr]> is
not <<NULL>>).
The alternate function <<_strtoul_r>> is a reentrant version. The
extra argument <[reent]> is a pointer to a reentrancy structure.
RETURNS
<<strtoul>> returns the converted value, if any. If no conversion was
made, <<0>> is returned.
<<strtoul>> returns <<ULONG_MAX>> if the magnitude of the converted
value is too large, and sets <<errno>> to <<ERANGE>>.
PORTABILITY
<<strtoul>> is ANSI.
<<strtoul>> requires no supporting OS subroutines.
*/
/*
* Copyright (c) 1990 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 University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <errno.h>
#include <section_config.h>
#include <basic_types.h>
#include <strproc.h>
#include <string.h>
#include <limits.h>
/*
* Convert a string to an unsigned long integer.
*
* Ignores `locale' stuff. Assumes that the upper and lower case
* alphabets and digits are each contiguous.
*/
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
unsigned long
//_strtoul_r(struct _reent *rptr ,
_strtoul_r(
_CONST char * nptr ,
char ** endptr ,
int base)
{
register const unsigned char *s = (const unsigned char *)nptr;
register unsigned long acc;
register int c;
register unsigned long cutoff;
register int neg = 0, any, cutlim;
/*
* See strtol for comments as to the logic used.
*/
do {
c = *s++;
} while (isspace(c));
if (c == '-') {
neg = 1;
c = *s++;
} else if (c == '+')
c = *s++;
if ((base == 0 || base == 16) &&
c == '0' && (*s == 'x' || *s == 'X')) {
c = s[1];
s += 2;
base = 16;
}
if (base == 0)
base = c == '0' ? 8 : 10;
cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
for (acc = 0, any = 0;; c = *s++) {
if (isdigit(c))
c -= '0';
else if (isalpha(c))
c -= isupper(c) ? 'A' - 10 : 'a' - 10;
else
break;
if (c >= base)
break;
if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
any = -1;
else {
any = 1;
acc *= base;
acc += c;
}
}
if (any < 0) {
acc = ULONG_MAX;
//rptr->_errno = ERANGE;
} else if (neg)
acc = -acc;
if (endptr != 0)
*endptr = (char *) (any ? (char *)s - 1 : nptr);
return (acc);
}
LIBC_ROM_TEXT_SECTION
_LONG_CALL_
unsigned long
_strtoul(_CONST char * s ,
char ** ptr ,
int base)
{
//return _strtoul_r (_REENT, s, ptr, base);
return _strtoul_r (s, ptr, base);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strtoul.c
|
C
|
apache-2.0
| 6,917
|
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
/* Minimum and maximum values a `signed long int' can hold.
(Same as `int'). */
#ifndef __LONG_MAX__
#if defined (__alpha__) || (defined (__sparc__) && defined(__arch64__)) || defined (__sparcv9) || defined (__s390x__)
#define __LONG_MAX__ 9223372036854775807L
#else
#define __LONG_MAX__ 2147483647L
#endif /* __alpha__ || sparc64 */
#endif
#undef LONG_MIN
#define LONG_MIN (-LONG_MAX-1)
#undef LONG_MAX
#define LONG_MAX __LONG_MAX__
/* Maximum value an `unsigned long int' can hold. (Minimum is 0). */
#undef ULONG_MAX
#define ULONG_MAX (LONG_MAX * 2UL + 1)
#ifndef __LONG_LONG_MAX__
#define __LONG_LONG_MAX__ 9223372036854775807LL
#endif
HAL_ROM_TEXT_SECTION
static u32 Isspace(char ch)
{
return (u32)((ch - 9) < 5u || ch == ' ');
}
/**
* _strtoul - convert a string to an unsigned long
* @cp: The start of the string
* @endp: A pointer to the end of the parsed string will be placed here
* @base: The number base to use
*
* This function is obsolete. Please use kstrtoul instead.
*/
HAL_ROM_TEXT_SECTION
_LONG_CALL_ unsigned long _strtoul(const char *cp, char **endp, unsigned int base)
{
return _strtoull(cp, endp, base);
}
HAL_ROM_TEXT_SECTION _LONG_CALL_
u32 Strtoul(const u8 *nptr, u8 **endptr, u32 base)
{
u32 v=0;
while(Isspace(*nptr)) ++nptr;
if (*nptr == '+') ++nptr;
if (base==16 && nptr[0]=='0') goto skip0x;
if (!base) {
if (*nptr=='0') {
base=8;
skip0x:
if (nptr[1]=='x'||nptr[1]=='X') {
nptr+=2;
base=16;
}
} else
base=10;
}
while(*nptr) {
register u8 c=*nptr;
c=(c>='a'?c-'a'+10:c>='A'?c-'A'+10:c<='9'?c-'0':0xff);
if (c>=base) break;
{
register u32 w=v*base;
if (w<v) {
//errno=ERANGE;
return ULONG_MAX;
}
v=w+c;
}
++nptr;
}
if (endptr) *endptr=(u8 *)nptr;
//errno=0; /* in case v==ULONG_MAX, ugh! */
return v;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strtoul_bk.c
|
C
|
apache-2.0
| 2,051
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h> /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ u8*
_strupr(
IN u8 *string
){
u8 *pStr;
const u8 diff = 'a' - 'A';
pStr = string;
while(*pStr){
if ((*pStr >= 'a') && (*pStr <= 'z')){
*pStr -= diff;
}
pStr++;
}
return string;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/strupr.c
|
C
|
apache-2.0
| 750
|
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#ifndef _VA_LIST_H_
#define _VA_LIST_H_
#include "platform_autoconf.h"
#include "basic_types.h"
#ifndef va_arg //this part is adapted from linux (Linux/include/acpi/platform/acenv.h)
typedef s32 acpi_native_int;//this definition is in (Linux/include/acpi/actypes.h)
#ifndef _VALIST
#define _VALIST
typedef char *va_list;
#endif /* _VALIST */
/* Storage alignment properties */
#define _AUPBND (sizeof (acpi_native_int) - 1)
#define _ADNBND (sizeof (acpi_native_int) - 1)
/* Variable argument list macro definitions */
#define _bnd(X, bnd) (((sizeof (X)) + (bnd)) & (~(bnd)))
#define va_arg(ap, T) (*(T *)(((ap) += (_bnd (T, _AUPBND))) - (_bnd (T,_ADNBND))))
#define va_end(ap) (ap = (va_list) NULL)
#define va_start(ap, A) (void) ((ap) = (((char *) &(A)) + (_bnd (A,_AUPBND))))
#endif /* va_arg */
#endif //_VA_LIST_H_
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/swlib/string/va_list.h
|
C
|
apache-2.0
| 1,203
|
/*
* FreeRTOS Kernel V10.2.0
* Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/******************************************************************************
See http://www.freertos.org/a00110.html for an explanation of the
definitions contained in this file.
******************************************************************************/
#ifndef FREERTOS_CONFIG_H
#define FREERTOS_CONFIG_H
#if defined(__ICCARM__) || defined(__CC_ARM) || defined(__GNUC__)
#include <stdint.h>
extern uint32_t SystemCoreClock;
#endif
#ifndef __IASMARM__
#define __IASMARM__ 0 /* IAR */
#endif
#include "platform_autoconf.h"
/*-----------------------------------------------------------
* Application specific definitions.
*
* These definitions should be adjusted for your particular hardware and
* application requirements.
*
* THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
* FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.
*
* See http://www.freertos.org/a00110.html.
*----------------------------------------------------------*/
#define configUSE_SAU 1
#define configUSE_PREEMPTION 1
#define configUSE_IDLE_HOOK 0
#define configUSE_TICK_HOOK 0
#define configCPU_CLOCK_HZ ( SystemCoreClock )
#define configTICK_RATE_HZ ( ( uint32_t ) 1000)
#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 512 )
#ifdef CONFIG_WIFI_EN
#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 150 * 1024 ) ) //default
#if (defined CONFIG_HIGH_TP_TEST)
#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 100 * 1024 ) )
#endif
#else
#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 40 * 1024 ) )
#endif
#define configMAX_TASK_NAME_LEN ( 10 )
#define configUSE_TRACE_FACILITY 0
#define configUSE_16_BIT_TICKS 0
#define configIDLE_SHOULD_YIELD 0
#define configUSE_CO_ROUTINES 1
#define configUSE_MUTEXES 1
#define configUSE_TIMERS 1
#define configMAX_PRIORITIES ( 11 )
#define PRIORITIE_OFFSET ( 4 )
#define configMAX_CO_ROUTINE_PRIORITIES ( 2 )
#define configUSE_COUNTING_SEMAPHORES 1
#define configUSE_ALTERNATIVE_API 0
#define configCHECK_FOR_STACK_OVERFLOW 2
#define configUSE_RECURSIVE_MUTEXES 1
#define configQUEUE_REGISTRY_SIZE 0
#define configGENERATE_RUN_TIME_STATS 0
#if configGENERATE_RUN_TIME_STATS
#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() //( ulHighFrequencyTimerTicks = 0UL )
#define portGET_RUN_TIME_COUNTER_VALUE() RTIM_GetCount(0x48002000/*TIMM00*/) //ulHighFrequencyTimerTicks
#undef configUSE_TRACE_FACILITY
#define configUSE_TRACE_FACILITY 1
#define portCONFIGURE_STATS_PEROID_VALUE 1000 //unit Ticks
#endif
#define configTIMER_TASK_PRIORITY ( 1 )
#define configTIMER_QUEUE_LENGTH ( 10 )
#define configTIMER_TASK_STACK_DEPTH ( 512 ) //USE_MIN_STACK_SIZE modify from 512 to 256
#if (__IASMARM__ != 1)
extern void freertos_pre_sleep_processing(unsigned int *expected_idle_time);
extern void freertos_post_sleep_processing(unsigned int *expected_idle_time);
extern int freertos_ready_to_sleep(void);
/* Enable tickless power saving. */
#define configUSE_TICKLESS_IDLE 1
/* In wlan usage, this value is suggested to use value less than 80 milliseconds */
#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2
/* It's magic trick that let us can use our own sleep function */
#define configPRE_SLEEP_PROCESSING( x ) ( freertos_pre_sleep_processing((unsigned int *)&x) )
#define configPOST_SLEEP_PROCESSING( x ) ( freertos_post_sleep_processing((unsigned int *)&x) )
/* It's magic trick that let us can enable/disable tickless dynamically */
#define traceLOW_POWER_IDLE_BEGIN(); {
// portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime );
#define traceLOW_POWER_IDLE_END(); }
/* It's FreeRTOS related feature but it's not included in FreeRTOS design. */
#define configUSE_WAKELOCK_PMU 1
#endif // #if (__IASMARM__ != 1)
/* Set the following definitions to 1 to include the API function, or zero
to exclude the API function. */
#define INCLUDE_vTaskPrioritySet 1
#define INCLUDE_uxTaskPriorityGet 1
#define INCLUDE_vTaskDelete 1
#define INCLUDE_vTaskCleanUpResources 0
#define INCLUDE_vTaskSuspend 1
#define INCLUDE_vTaskDelayUntil 1
#define INCLUDE_vTaskDelay 1
#define INCLUDE_pcTaskGetTaskName 1
#define INCLUDE_xTimerPendFunctionCall 1
/* Cortex-M specific definitions. */
#ifdef __NVIC_PRIO_BITS
/* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */
#define configPRIO_BITS __NVIC_PRIO_BITS
#else
#define configPRIO_BITS 4 /* 15 priority levels */
#endif
/* The lowest interrupt priority that can be used in a call to a "set priority"
function. */
#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 0x0f
/* The highest interrupt priority that can be used by any interrupt service
routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL
INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER
PRIORITY THAN THIS! (higher priorities are lower numeric values. */
#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5
/* Interrupt priorities used by the kernel port layer itself. These are generic
to all Cortex-M ports, and do not rely on any particular library functions. */
#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!
See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */
#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
//#define RTK_MODE_TIMER
#endif /* FREERTOS_CONFIG_H */
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/project/realtek_amebaD_cm4_gcc_verification/inc/FreeRTOSConfig.h
|
C
|
apache-2.0
| 7,130
|
#ifndef MAIN_H
#define MAIN_H
#include <autoconf.h>
#include "platform_stdlib.h"
#ifndef CONFIG_WLAN
#define CONFIG_WLAN 1
#endif
/* Header file declaration*/
void wlan_network(void);
extern int mbedtls_platform_set_calloc_free(
void * (*calloc_func)( unsigned int, unsigned int ),
void (*free_func)( void * )
);
extern void SystemSetCpuClk(unsigned char CpuClk);
extern void rtw_efuse_boot_write(void);
extern void pre_example_entry(void);
extern void example_entry(void);
/* Interactive Mode */
#define SERIAL_DEBUG_RX 1
/* WLAN and Netork */
#define STA_MODE_SSID "ap" /* Set SSID here */
#define AP_MODE_SSID "wlan_ap_ssid" /* Set SSID here */
#define AP_DEFAULT_CH 6
#define WLAN0_NAME "wlan0"
#define WLAN1_NAME "wlan1"
#define WPA_PASSPHRASE "1234567890" /* Max 32 cahracters */
#define WEP40_KEY {0x12, 0x34, 0x56, 0x78, 0x90}
#define ATVER_1 1 // For First AT command
#define ATVER_2 2 // For UART Module AT command
#if CONFIG_EXAMPLE_UART_ATCMD
#define ATCMD_VER ATVER_2
#else
#define ATCMD_VER ATVER_1
#endif
#if ATCMD_VER == ATVER_2
#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 1
extern unsigned char sta_ip[4], sta_netmask[4], sta_gw[4];
extern unsigned char ap_ip[4], ap_netmask[4], ap_gw[4];
/*Static IP ADDRESS*/
#define IP_ADDR0 sta_ip[0]
#define IP_ADDR1 sta_ip[1]
#define IP_ADDR2 sta_ip[2]
#define IP_ADDR3 sta_ip[3]
/*NETMASK*/
#define NETMASK_ADDR0 sta_netmask[0]
#define NETMASK_ADDR1 sta_netmask[1]
#define NETMASK_ADDR2 sta_netmask[2]
#define NETMASK_ADDR3 sta_netmask[3]
/*Gateway Address*/
#define GW_ADDR0 sta_gw[0]
#define GW_ADDR1 sta_gw[1]
#define GW_ADDR2 sta_gw[2]
#define GW_ADDR3 sta_gw[3]
/*******************************************/
/*Static IP ADDRESS*/
#define AP_IP_ADDR0 ap_ip[0]
#define AP_IP_ADDR1 ap_ip[1]
#define AP_IP_ADDR2 ap_ip[2]
#define AP_IP_ADDR3 ap_ip[3]
/*NETMASK*/
#define AP_NETMASK_ADDR0 ap_netmask[0]
#define AP_NETMASK_ADDR1 ap_netmask[1]
#define AP_NETMASK_ADDR2 ap_netmask[2]
#define AP_NETMASK_ADDR3 ap_netmask[3]
/*Gateway Address*/
#define AP_GW_ADDR0 ap_gw[0]
#define AP_GW_ADDR1 ap_gw[1]
#define AP_GW_ADDR2 ap_gw[2]
#define AP_GW_ADDR3 ap_gw[3]
#else
/*Static IP ADDRESS*/
#define IP_ADDR0 192
#define IP_ADDR1 168
#define IP_ADDR2 1
#define IP_ADDR3 80
/*NETMASK*/
#define NETMASK_ADDR0 255
#define NETMASK_ADDR1 255
#define NETMASK_ADDR2 255
#define NETMASK_ADDR3 0
/*Gateway Address*/
#define GW_ADDR0 192
#define GW_ADDR1 168
#define GW_ADDR2 1
#define GW_ADDR3 1
/*******************************************/
/*Static IP ADDRESS*/
#define AP_IP_ADDR0 192
#define AP_IP_ADDR1 168
#define AP_IP_ADDR2 43
#define AP_IP_ADDR3 1
/*NETMASK*/
#define AP_NETMASK_ADDR0 255
#define AP_NETMASK_ADDR1 255
#define AP_NETMASK_ADDR2 255
#define AP_NETMASK_ADDR3 0
/*Gateway Address*/
#define AP_GW_ADDR0 192
#define AP_GW_ADDR1 168
#define AP_GW_ADDR2 43
#define AP_GW_ADDR3 1
#endif //#if ATCMD_VER == ATVER_2
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/project/realtek_amebaD_cm4_gcc_verification/inc/main.h
|
C
|
apache-2.0
| 3,060
|
/******************************************************************************
*
* Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved.
*
* 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 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.
*
******************************************************************************/
/*
* Automatically generated by make menuconfig: don't edit
*/
#define AUTOCONF_INCLUDED
/*
* < MENUCONFIG FOR CHIP CONFIG
*/
/*
* < CONFIG CHIP
*/
#define CONFIG_RTL8721D 1
#define ARM_CORE_CM4 1
#undef CONFIG_FPGA
#define CONFIG_CHIP_A_CUT 1
#undef CONFIG_CHIP_B_CUT
/*
* < CONFIG CPU CLK
*/
#define CONFIG_CPU_CLK 1
#define CONFIG_CPU_200MHZ 1
#undef CONFIG_CPU_100MHZ
#undef CONFIG_CPU_50MHZ
#undef CONFIG_CPU_25MHZ
#undef CONFIG_CPU_XTAL
#undef CONFIG_FPGA_CLK
#define PLATFORM_CLOCK (200000000)
#define CPU_CLOCK_SEL_VALUE (0)
/*
* < CONFIG TEST MODE
*/
#undef CONFIG_MP
#undef CONFIG_CP
#undef CONFIG_FT
#undef CONFIG_EQC
/*
* < CONFIG OS
*/
#define CONFIG_KERNEL 1
//#define PLATFORM_FREERTOS 1
#define PLATFORM_ALIOS 1
#define TASK_SCHEDULER_DISABLED (0)
/*
* < CONFIG SOC PS
*/
#define CONFIG_SOC_PS_EN 1
#define CONFIG_SOC_PS_MODULE 1
/*
* < CONFIG SDIO Device
*/
#define CONFIG_SDIO_DEVICE_EN 1
#define CONFIG_SDIO_DEVICE_NORMAL 1
#define CONFIG_SDIO_DEVICE_MODULE 1
/*
* < CONFIG PINMUX
*/
#undef CONFIG_PINMAP_ENABLE
/*
* < MBED_API
*/
#define CONFIG_MBED_API_EN 1
/*
* < CONFIG FUNCTION TEST
*/
#undef CONFIG_PER_TEST
/*
* < CONFIG SECURE TEST
*/
#undef CONFIG_SEC_VERIFY
/*
* < CONFIG BT
*/
#define CONFIG_BT_EN 1
#define CONFIG_BT 1
#undef CONFIG_BT_PERIPHERAL
#undef CONFIG_BT_CENTRAL
#define CONFIG_BT_CONFIG 1
#undef CONFIG_BT_BEACON
#undef CONFIG_BT_MP
/*
* < CONFIG WIFI
*/
#define CONFIG_WIFI_EN 1
#undef CONFIG_HIGH_TP_TEST
#undef WIFI_PERFORMANCE_MONITOR
#define CONFIG_WIFI_NORMAL 1
#undef CONFIG_WIFI_TEST
#define CONFIG_WIFI_MODULE 1
/*
* < CONFIG NETWORK
*/
#define CONFIG_NETWORK 1
/*
* < CONFIG USB
*/
#undef CONFIG_USB_OTG_EN
/*
* < SSL Config
*/
#define CONFIG_USE_MBEDTLS_ROM 1
#define CONFIG_MBED_TLS_ENABLED 1
#undef CONFIG_SSL_ROM_TEST
/*
* < DuerOS Config
*/
#undef CONFIG_BAIDU_DUER
/*
* < MQTT Config
*/
#define CONFIG_MQTT_EN 1
/*
* < GUI Config
*/
#undef CONFIG_GUI_EN
/*
* To set debug msg flag
*/
#define CONFIG_DEBUG_LOG 1
/*
* < Build Option
*/
#define CONFIG_TOOLCHAIN_ASDK 1
#undef CONFIG_TOOLCHAIN_ARM_GCC
#undef CONFIG_LINK_ROM_LIB
#define CONFIG_LINK_ROM_SYMB 1
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/project/realtek_amebaD_cm4_gcc_verification/inc/platform_autoconf.h
|
C
|
apache-2.0
| 3,036
|
/**
******************************************************************************
*This file contains general configurations for ameba platform
******************************************************************************
*/
#ifndef __PLATFORM_OPTS_H__
#define __PLATFORM_OPTS_H__
#include "platform_autoconf.h"
#ifdef CONFIG_BT_EN
#include "platform_opts_bt.h"
#endif
/*For MP mode setting*/
//#define SUPPORT_MP_MODE 1
/**
* For AT cmd Log service configurations
*/
#define SUPPORT_LOG_SERVICE 0
#if SUPPORT_LOG_SERVICE
#define LOG_SERVICE_BUFLEN 100 //can't larger than UART_LOG_CMD_BUFLEN(127)
#define CONFIG_LOG_HISTORY 0
#if CONFIG_LOG_HISTORY
#define LOG_HISTORY_LEN 5
#endif
#define CONFIG_ATCMD_MP 1 //support MP AT command
#define SUPPORT_INTERACTIVE_MODE 0//on/off wifi_interactive_mode
#define CONFIG_LOG_SERVICE_LOCK 0
#endif
/**
* For interactive mode configurations, depents on log service
*/
#if SUPPORT_INTERACTIVE_MODE
#define CONFIG_INTERACTIVE_MODE 1
#define CONFIG_INTERACTIVE_EXT 0
#else
#define CONFIG_INTERACTIVE_MODE 0
#define CONFIG_INTERACTIVE_EXT 0
#endif
/**
* For FreeRTOS tickless configurations
*/
#define FREERTOS_PMU_TICKLESS_SUSPEND_SDRAM 1 // In sleep mode, 1: suspend SDRAM, 0: no act
/******************************************************************************/
/**
* For common flash usage
*/
#define AP_SETTING_SECTOR 0x000FE000
#define UART_SETTING_SECTOR 0x000FC000
#define SPI_SETTING_SECTOR 0x000FC000
#if defined(CONFIG_BAIDU_DUER) && CONFIG_BAIDU_DUER
#define FAST_RECONNECT_DATA 0x1FF000
#else
#define FAST_RECONNECT_DATA 0x105000
#endif
#define CONFIG_ENABLE_RDP 0
/**
* For Wlan configurations
*/
#define CONFIG_WLAN 1
#if CONFIG_WLAN
#define CONFIG_LWIP_LAYER 1
#define CONFIG_INIT_NET 1 //init lwip layer when start up
#define CONFIG_WIFI_IND_USE_THREAD 0 // wifi indicate worker thread
//on/off relative commands in log service
#define CONFIG_SSL_CLIENT 0
#define CONFIG_WEBSERVER 0
#define CONFIG_OTA_UPDATE 0
#define CONFIG_BSD_TCP 1//NOTE : Enable CONFIG_BSD_TCP will increase about 11KB code size
#define CONFIG_AIRKISS 0//on or off tencent airkiss
#define CONFIG_UART_SOCKET 0
#define CONFIG_JOYLINK 0//on or off for jdsmart or joylink
#define CONFIG_QQ_LINK 0//on or off for qqlink
#define CONFIG_UART_XMODEM 0//support uart xmodem upgrade or not
#define CONFIG_GOOGLE_NEST 0//on or off the at command control for google nest
#define CONFIG_TRANSPORT 0//on or off the at command for transport socket
#define CONFIG_ALINK 0//on or off for alibaba alink
#define CONFIG_HILINK 0//on or off for huawei hilink
//#define CONFIG_BAIDU_DUER 1
#define CONFIG_DMIC_SEL 0
/* For WPS and P2P */
#define CONFIG_ENABLE_WPS 1
#define CONFIG_ENABLE_P2P 0//on/off p2p cmd in log_service or interactive mode
#define CONFIG_ENABLE_WPS_DISCOVERY 0
#if CONFIG_ENABLE_P2P
#define CONFIG_ENABLE_WPS_AP 1
#undef CONFIG_WIFI_IND_USE_THREAD
#define CONFIG_WIFI_IND_USE_THREAD 1
#endif
#if (CONFIG_ENABLE_P2P && ((CONFIG_ENABLE_WPS_AP == 0) || (CONFIG_ENABLE_WPS == 0)))
#error "If CONFIG_ENABLE_P2P, need to define CONFIG_ENABLE_WPS_AP 1"
#endif
/* For SSL/TLS */
#define CONFIG_USE_POLARSSL 0
#define CONFIG_USE_MBEDTLS 1
#if ((CONFIG_USE_POLARSSL == 0) && (CONFIG_USE_MBEDTLS == 0)) || ((CONFIG_USE_POLARSSL == 1) && (CONFIG_USE_MBEDTLS == 1))
#undef CONFIG_USE_POLARSSL
#define CONFIG_USE_POLARSSL 1
#undef CONFIG_USE_MBEDTLS
#define CONFIG_USE_MBEDTLS 0
#endif
/* For Simple Link */
#define CONFIG_INCLUDE_SIMPLE_CONFIG 1
/*For fast reconnection*/
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0
/*For wowlan service settings*/
#define CONFIG_WOWLAN_SERVICE 0
#define CONFIG_GAGENT 0
/*Disable CONFIG_EXAMPLE_WLAN_FAST_CONNECT when CONFIG_GAGENT is enabled,because
reconnect to previous AP is not suitable when re-configuration.
*/
#if CONFIG_GAGENT
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0
#endif
#define CONFIG_JOINLINK 0
#endif //end of #if CONFIG_WLAN
/*******************************************************************************/
/**
* For Ethernet configurations
*/
#define CONFIG_ETHERNET 0
#if CONFIG_ETHERNET
#define CONFIG_LWIP_LAYER 1
#define CONFIG_INIT_NET 1 //init lwip layer when start up
//on/off relative commands in log service
#define CONFIG_SSL_CLIENT 0
#define CONFIG_BSD_TCP 0//NOTE : Enable CONFIG_BSD_TCP will increase about 11KB code size
#endif
/**
* For user to adjust SLEEP_INTERVAL
*/
#define CONFIG_DYNAMIC_TICKLESS 1
/*******************************************************************************/
/**
* For iNIC configurations
*/
//#define CONFIG_INIC_EN 0//enable iNIC mode
#if defined(CONFIG_INIC_EN) && CONFIG_INIC_EN
#ifndef CONFIG_LWIP_LAYER
#define CONFIG_LWIP_LAYER 0
#endif
#ifndef CONFIG_INIC_SDIO_HCI
#define CONFIG_INIC_SDIO_HCI 0 //for SDIO or USB iNIC
#endif
#ifndef CONFIG_INIC_CMD_RSP
#define CONFIG_INIC_CMD_RSP 0
#endif
#ifndef CONFIG_INIC_USB_HCI
#define CONFIG_INIC_USB_HCI 0
#endif
#endif
/******************End of iNIC configurations*******************/
/* For aj_basic_example */
#define CONFIG_EXAMPLE_AJ_BASIC 0
/*For aj_ameba_led example*/
#define CONFIG_EXAMPLE_AJ_AMEBA_LED 0
/* For WIFI GET BEACON FRAME example */
#define CONFIG_EXAMPLE_GET_BEACON_FRAME 0
/* For WIFI MAC MONITOR example */
#define CONFIG_EXAMPLE_WIFI_MAC_MONITOR 0
/* For HTTP CLIENT example */
#define CONFIG_EXAMPLE_HTTP_CLIENT 0
/* For MQTT example */
#define CONFIG_EXAMPLE_MQTT 0
/* For WiGadget example */
#define CONFIG_EXAMPLE_WIGADGET 0
/*For google nest example*/
#define CONFIG_EXAMPLE_GOOGLE_NEST 0
/* For mDNS example */
#define CONFIG_EXAMPLE_MDNS 0
/* For multicast example */
#define CONFIG_EXAMPLE_MCAST 0
/* For XML example */
#define CONFIG_EXAMPLE_XML 0
/* For socket select example */
#define CONFIG_EXAMPLE_SOCKET_SELECT 0
/* For socket nonblocking connect example */
#define CONFIG_EXAMPLE_NONBLOCK_CONNECT 0
/* For socket TCP bidirectional transmission example */
#define CONFIG_EXAMPLE_SOCKET_TCP_TRX 0
/* For ssl download example */
#define CONFIG_EXAMPLE_SSL_DOWNLOAD 0
/* For http download example */
#define CONFIG_EXAMPLE_HTTP_DOWNLOAD 0
/* For http ota update example */
#define CONFIG_EXAMPLE_OTA_HTTP 0
/* For https ota update example */
#define CONFIG_EXAMPLE_OTA_HTTPS 0
/* For tcp keepalive example */
#define CONFIG_EXAMPLE_TCP_KEEPALIVE 0
/* For sntp show time example */
#define CONFIG_EXAMPLE_SNTP_SHOWTIME 0
/* For pppoe example */
#define CONFIG_EXAMPLE_PPPOE 0
/* For websocket client example */
#define CONFIG_EXAMPLE_WEBSOCKET 0
/*For promisc softap mode example */
#define CONFIG_EXAMPLE_PROMISC_SOFTAP_CONFIG 0
/*For Audio example */
#define CONFIG_EXAMPLE_AUDIO 0
#if CONFIG_EXAMPLE_AUDIO
#define FATFS_DISK_SD 1
#define CONFIG_EXAMPLE_CODEC_SGTL5000 0
#define CONFIG_EXAMPLE_CODEC_ALC5651 1
#endif
#define CONFIG_EXAMPLE_AUDIO_MP3 0
#if CONFIG_EXAMPLE_AUDIO_MP3
#define FATFS_DISK_SD 1
#endif
#define CONFIG_EXAMPLE_AUDIO_AMR 0
#if CONFIG_EXAMPLE_AUDIO_AMR
#define FATFS_DISK_SD 1
#endif
#define CONFIG_EXAMPLE_AUDIO_AMR_FLASH 0
#define CONFIG_EXAMPLE_AUDIO_AC3 0
#ifdef CONFIG_EXAMPLE_AUDIO_AC3
#define FATFS_DISK_SD 1
#endif
#define CONFIG_EXAMPLE_AUDIO_HELIX_AAC 0
#define CONFIG_EXAMPLE_AUDIO_HELIX_MP3 0
#define CONFIG_EXAMPLE_AUDIO_PCM_UPLOAD 0
#define CONFIG_EXAMPLE_AUDIO_HLS 0
#if CONFIG_EXAMPLE_AUDIO_HLS
#define FATFS_DISK_SD 1
#endif
#define CONFIG_EXAMPLE_AUDIO_RECORDER 0
#if CONFIG_EXAMPLE_AUDIO_RECORDER
#define FATFS_DISK_SD 1
#endif
#define CONFIG_EXAMPLE_AUDIO_M4A_SELFPARSE 0
#if CONFIG_EXAMPLE_AUDIO_M4A_SELFPARSE
#define FATFS_DISK_SD 1
#endif
#define CONFIG_EXAMPLE_AUDIO_M4A 0
#if CONFIG_EXAMPLE_AUDIO_M4A
#define FATFS_DISK_SD 1
#endif
#define CONFIG_EXAMPLE_AUDIO_FLAC 0
#if CONFIG_EXAMPLE_AUDIO_FLAC
#define FATFS_DISK_SD 1
#endif
#define AUDIO_SIGNAL_GENERATE 0
#define CONFIG_EXAMPLE_AUDIO_TTS 0
/* For UART Module AT command example */
#define CONFIG_EXAMPLE_UART_ATCMD 0
#if CONFIG_EXAMPLE_UART_ATCMD
#undef CONFIG_OTA_UPDATE
#define CONFIG_OTA_UPDATE 1
#undef CONFIG_TRANSPORT
#define CONFIG_TRANSPORT 1
#undef LOG_SERVICE_BUFLEN
#define LOG_SERVICE_BUFLEN 1600
#undef CONFIG_LOG_SERVICE_LOCK
#define CONFIG_LOG_SERVICE_LOCK 1
#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0
#endif
/* For SPI Module AT command example */
#define CONFIG_EXAMPLE_SPI_ATCMD 0
#if CONFIG_EXAMPLE_SPI_ATCMD
#undef CONFIG_OTA_UPDATE
#define CONFIG_OTA_UPDATE 1
#undef CONFIG_TRANSPORT
#define CONFIG_TRANSPORT 1
#undef LOG_SERVICE_BUFLEN
#define LOG_SERVICE_BUFLEN 1600
#undef CONFIG_LOG_SERVICE_LOCK
#define CONFIG_LOG_SERVICE_LOCK 1
#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0
#endif
/* For uvc example */
#ifdef CONFIG_UVC
/*for uvc_FATFS feature*/
#define CONFIG_UVC_SD_EN 0
#if CONFIG_UVC_SD_EN
#define CONFIG_FATFS_EN 1
#if CONFIG_FATFS_EN
// fatfs version
#define FATFS_R_10C
// fatfs disk interface
#define FATFS_DISK_USB 0
#define FATFS_DISK_SD 1
#endif
#endif
#endif
#define CONFIG_EXAMPLE_MEDIA_SS 0
#define CONFIG_EXAMPLE_MEDIA_MS 0
#define CONFIG_EXAMPLE_MEDIA_GEO_RTP 0
// Use media source/sink example
#if (CONFIG_EXAMPLE_MEDIA_SS==1) || (CONFIG_EXAMPLE_MEDIA_MS==1)
#undef CONFIG_INCLUDE_SIMPLE_CONFIG
#define CONFIG_INCLUDE_SIMPLE_CONFIG 0
#define CONFIG_ENABLE_WPS 0
#endif
/* For Mjpeg capture example*/
#define CONFIG_EXAMPLE_MJPEG_CAPTURE 0
#if CONFIG_EXAMPLE_MJPEG_CAPTURE
#define FATFS_DISK_SD 1
#endif
/****************** For EAP method example *******************/
#define CONFIG_EXAMPLE_EAP 0
// on/off specified eap method
#define CONFIG_ENABLE_PEAP 0
#define CONFIG_ENABLE_TLS 0
#define CONFIG_ENABLE_TTLS 0
// optional feature: whether to verify the cert of radius server
#define ENABLE_EAP_SSL_VERIFY_SERVER 0
#if CONFIG_ENABLE_PEAP || CONFIG_ENABLE_TLS || CONFIG_ENABLE_TTLS
#define CONFIG_ENABLE_EAP
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0
#endif
#if CONFIG_ENABLE_TLS
#define ENABLE_EAP_SSL_VERIFY_CLIENT 1
#else
#define ENABLE_EAP_SSL_VERIFY_CLIENT 0
#endif
/******************End of EAP configurations*******************/
/* For usb mass storage example */
#define CONFIG_EXAMPLE_USB_MASS_STORAGE 0
/* For usb device isoc example */
#define CONFIG_EXAMPLE_USB_ISOC_DEVICE 0
/* For usb host vendor specific example */
#define CONFIG_EXAMPLE_USB_VENDOR_SPECIFIC 0
/* For FATFS example*/
#define CONFIG_EXAMPLE_FATFS 0
#if CONFIG_EXAMPLE_FATFS
#define CONFIG_FATFS_EN 1
#if CONFIG_FATFS_EN
// fatfs version
#define FATFS_R_10C
// fatfs disk interface
#define FATFS_DISK_USB 0
#define FATFS_DISK_SD 1
#endif
#endif
/* For iNIC host example*/
#ifdef CONFIG_INIC_GSPI_HOST //this flag is defined in IAR project
#define CONFIG_EXAMPLE_INIC_GSPI_HOST 1
#if CONFIG_EXAMPLE_INIC_GSPI_HOST
#define CONFIG_INIC_HOST 1
#undef CONFIG_WLAN
#define CONFIG_WLAN 0
#undef CONFIG_INCLUDE_SIMPLE_CONFIG
#define CONFIG_INCLUDE_SIMPLE_CONFIG 0
#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0
#undef CONFIG_LWIP_LAYER
#define CONFIG_LWIP_LAYER 1
#undef CONFIG_BSD_TCP
#define CONFIG_BSD_TCP 1
#endif
#endif
/*For uart update example*/
#define CONFIG_UART_UPDATE 0
#if CONFIG_UART_UPDATE
#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0
#endif
/*For arduino wifi shield example */
#define CONFIG_EXAMPLE_ARDUINO_WIFI 0
#if CONFIG_EXAMPLE_ARDUINO_WIFI
#undef CONFIG_WIFI_NORMAL
#endif
/* For uart adapter example */
/* Please also configure LWIP_UART_ADAPTER to 1
in lwip_opt.h for support uart adapter*/
#define CONFIG_EXAMPLE_UART_ADAPTER 0
#if CONFIG_EXAMPLE_UART_ADAPTER
#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 1
#undef CONFIG_EXAMPLE_MDNS
#define CONFIG_EXAMPLE_MDNS 1
#endif
#if CONFIG_EXAMPLE_PROMISC_SOFTAP_CONFIG
#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT
#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 1
#endif
/* For wifi scenarios example (Wi-Fi, WPS enrollee, P2P GO) */
// also need to enable WPS and P2P
#define CONFIG_EXAMPLE_WLAN_SCENARIO 0
/* For broadcast example */
#define CONFIG_EXAMPLE_BCAST 0
/* For high-load memory use case memory usage */
#define CONFIG_EXAMPLE_HIGH_LOAD_MEMORY_USE 0
/* For rarp example */
#define CONFIG_EXAMPLE_RARP 0
/* For ssl server example */
#define CONFIG_EXAMPLE_SSL_SERVER 0
#if CONFIG_QQ_LINK
#define FATFS_R_10C
#define FATFS_DISK_USB 0
#define FATFS_DISK_SD 1
#endif
#if CONFIG_ENABLE_WPS
#define WPS_CONNECT_RETRY_COUNT 4
#define WPS_CONNECT_RETRY_INTERVAL 5000 // in ms
#endif
#define AUTO_RECONNECT_COUNT 8
#define AUTO_RECONNECT_INTERVAL 5 // in sec
#if defined(CONFIG_INIC_EN) && CONFIG_INIC_EN
#undef CONFIG_INCLUDE_SIMPLE_CONFIG
#define CONFIG_INCLUDE_SIMPLE_CONFIG 0
#define SUPPORT_INTERACTIVE_MODE 0
#define CONFIG_INTERACTIVE_MODE 0
#define CONFIG_INTERACTIVE_EXT 0
#define CONFIG_OTA_UPDATE 0
#endif
//#define CONFIG_EXAMPLE_COMPETITIVE_HEADPHONES 1
//#define CONFIG_EXAMPLE_COMPETITIVE_HEADPHONES_DONGLE 1
/* For fast DHCP */
#if CONFIG_EXAMPLE_WLAN_FAST_CONNECT
#define CONFIG_FAST_DHCP 1
#else
#define CONFIG_FAST_DHCP 0
#endif
#endif
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/project/realtek_amebaD_cm4_gcc_verification/inc/platform_opts.h
|
C
|
apache-2.0
| 13,297
|
#ifndef __PLATFORM_OPTS_BT_H__
#define __PLATFORM_OPTS_BT_H__
#if defined CONFIG_BT_CENTRAL && CONFIG_BT_CENTRAL
#define CONFIG_BT_USER_COMMAND 0
#endif
#endif // __PLATFORM_OPTS_BT_H__
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/sdk/project/realtek_amebaD_cm4_gcc_verification/inc/platform_opts_bt.h
|
C
|
apache-2.0
| 190
|
#!/bin/sh
echo "test bash script..."
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/test.sh
|
Shell
|
apache-2.0
| 37
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <aos/kernel.h>
#include "yunit.h"
#include "cutest/cut.h"
#ifndef SYSINFO_ARCH
#define SYSINFO_ARCH "unknown"
#endif
#ifndef SYSINFO_MCU
#define SYSINFO_MCU "unknown"
#endif
#ifndef SYSINFO_DEVICE_NAME
#define SYSINFO_DEVICE_NAME "unknown"
#endif
#ifndef SYSINFO_APP_VERSION
#define SYSINFO_APP_VERSION "unknown"
#endif
#define SYSINFO_KERNEL "AOS"
/* dynamic memory alloc test */
#ifndef TEST_CONFIG_MM_ENABLED
#define TEST_CONFIG_MM_ENABLED (1)
#endif
#if (TEST_CONFIG_MM_ENABLED > 0)
#ifndef TEST_CONFIG_MALLOC_MAX_SIZE
#define TEST_CONFIG_MALLOC_MAX_SIZE (1024)
#endif
#ifndef TEST_CONFIG_MALLOC_FREE_TIMES
#define TEST_CONFIG_MALLOC_FREE_TIMES (100000)
#endif
#endif
/* task test */
#ifndef TEST_CONFIG_TASK_ENABLED
#define TEST_CONFIG_TASK_ENABLED (1)
#endif
#if (TEST_CONFIG_TASK_ENABLED > 0)
#ifndef TEST_CONFIG_STACK_SIZE
#define TEST_CONFIG_STACK_SIZE (512)
#endif
#ifndef TEST_CONFIG_MAX_TASK_COUNT
#define TEST_CONFIG_MAX_TASK_COUNT (10)
#endif
#ifndef TEST_CONFIG_CREATE_TASK_TIMES
#define TEST_CONFIG_CREATE_TASK_TIMES (10000)
#endif
#endif
/* task communication test */
#ifndef TEST_CONFIG_TASK_COMM_ENABLED
#define TEST_CONFIG_TASK_COMM_ENABLED (1)
#endif
#if (TEST_CONFIG_TASK_COMM_ENABLED > 0)
#ifndef TEST_CONFIG_STACK_SIZE
#define TEST_CONFIG_STACK_SIZE (512)
#endif
#ifndef TEST_CONFIG_SYNC_TIMES
#define TEST_CONFIG_SYNC_TIMES (100000)
#endif
#ifndef TEST_CONFIG_QUEUE_BUF_SIZE
#define TEST_CONFIG_QUEUE_BUF_SIZE (32)
#endif
#endif
/* timer test */
#ifndef TEST_CONFIG_TIMER_ENABLED
#define TEST_CONFIG_TIMER_ENABLED (1)
#endif
/* kv test */
#ifndef TEST_CONFIG_KV_ENABLED
#define TEST_CONFIG_KV_ENABLED (1)
#endif
#if (TEST_CONFIG_KV_ENABLED > 0)
#ifndef TEST_CONFIG_KV_TIMES
#define TEST_CONFIG_KV_TIMES (10000)
#endif
#endif
static unsigned int g_var = 0;
static aos_sem_t g_sem_taskexit_sync;
static aos_mutex_t g_mutex;
static aos_sem_t g_sem;
static aos_queue_t g_queue;
static aos_timer_t g_timer;
static char queue_buf[TEST_CONFIG_QUEUE_BUF_SIZE];
static aos_queue_t g_queue1;
static char queue1_buf[TEST_CONFIG_QUEUE_BUF_SIZE];
static aos_queue_t g_queue2;
static char queue2_buf[TEST_CONFIG_QUEUE_BUF_SIZE];
static aos_queue_t g_queue3;
static char queue3_buf[TEST_CONFIG_QUEUE_BUF_SIZE];
static int dump_test_config(void)
{
#define _PARSE(x) #x
#define PARSE(x) _PARSE(x)
#define PRINT_CONFIG(x) printf("\33[0;35m%s=%s\33[0m\r\n", #x, PARSE(x))
if (strlen(SYSINFO_ARCH)==0 || strlen(SYSINFO_MCU) == 0 || strlen(SYSINFO_DEVICE_NAME)==0) {
printf("Please set your device info first!\r\n");
return -1;
}
else {
PRINT_CONFIG(SYSINFO_ARCH);
PRINT_CONFIG(SYSINFO_MCU);
PRINT_CONFIG(SYSINFO_DEVICE_NAME);
PRINT_CONFIG(SYSINFO_KERNEL);
PRINT_CONFIG(aos_version_get());
PRINT_CONFIG(SYSINFO_APP_VERSION);
}
PRINT_CONFIG(TEST_CONFIG_MM_ENABLED);
#if (TEST_CONFIG_MM_ENABLED > 0)
PRINT_CONFIG(TEST_CONFIG_MALLOC_MAX_SIZE);
PRINT_CONFIG(TEST_CONFIG_MALLOC_FREE_TIMES);
#endif
PRINT_CONFIG(TEST_CONFIG_TASK_ENABLED);
#if (TEST_CONFIG_TASK_ENABLED > 0)
PRINT_CONFIG(TEST_CONFIG_MAX_TASK_COUNT);
PRINT_CONFIG(TEST_CONFIG_CREATE_TASK_TIMES);
#endif
PRINT_CONFIG(TEST_CONFIG_TASK_COMM_ENABLED);
#if (TEST_CONFIG_TASK_COMM_ENABLED > 0)
PRINT_CONFIG(TEST_CONFIG_SYNC_TIMES);
#endif
PRINT_CONFIG(TEST_CONFIG_TIMER_ENABLED);
PRINT_CONFIG(TEST_CONFIG_KV_ENABLED);
#if (TEST_CONFIG_KV_ENABLED > 0)
PRINT_CONFIG(TEST_CONFIG_KV_TIMES);
#endif
return 0;
}
#if (TEST_CONFIG_MM_ENABLED > 0)
CASE(test_mm, aos_1_001)
{
unsigned int size = 512;
unsigned char *ptr = NULL;
ptr = aos_malloc(size);
ASSERT_NOT_NULL(ptr);
aos_free(ptr);
}
CASE(test_mm, aos_1_002)
{
unsigned int size = 512;
unsigned char *ptr = NULL;
int i = 0;
ptr = aos_zalloc(size);
ASSERT_NOT_NULL(ptr);
for (; i<size; i++) {
if (*(ptr+i) != 0) {
aos_free(ptr);
ASSERT_FAIL();
}
}
aos_free(ptr);
}
CASE(test_mm, aos_1_003)
{
unsigned int size1 = 512;
unsigned int size2 = 1024;
unsigned char *ptr = NULL;
int i = 0;
ptr = aos_malloc(size1);
ASSERT_NOT_NULL(ptr);
memset(ptr, 0x5A, size1);
ptr = aos_realloc(ptr, size2);
ASSERT_NOT_NULL(ptr);
memset(ptr+size1, 0xA5, size2-size1);
for(i=0; i<size1; i++) {
if(*(ptr+i) != 0x5A) {
aos_free(ptr);
ASSERT_FAIL();
}
}
for(; i<size2; i++) {
if(*(ptr+i) != 0xA5) {
aos_free(ptr);
ASSERT_FAIL();
}
}
aos_free(ptr);
}
CASE(test_mm, aos_1_004)
{
unsigned int size1 = 512;
unsigned int size2 = 256;
unsigned char *ptr = NULL;
int i = 0;
ptr = aos_malloc(size1);
ASSERT_NOT_NULL(ptr);
memset(ptr, 0x5A, size1);
ptr = aos_realloc(ptr, size2);
ASSERT_NOT_NULL(ptr);
for(i=0; i<size2; i++) {
if(*(ptr+i) != 0x5A) {
aos_free(ptr);
ASSERT_FAIL();
}
}
aos_free(ptr);
}
CASE(test_mm, aos_1_005)
{
unsigned int size = 1024;
unsigned char *ptr = NULL;
int i = TEST_CONFIG_MALLOC_FREE_TIMES;
while(i--) {
ptr = aos_malloc(size);
ASSERT_NOT_NULL(ptr);
memset(ptr, 0x5A, size);
aos_free(ptr);
}
}
#endif /* TEST_CONFIG_MM_ENABLED */
/* memory manager test suite */
SUITE(test_mm) = {
#if (TEST_CONFIG_MM_ENABLED > 0)
ADD_CASE(test_mm, aos_1_001),
ADD_CASE(test_mm, aos_1_002),
ADD_CASE(test_mm, aos_1_003),
ADD_CASE(test_mm, aos_1_004),
ADD_CASE(test_mm, aos_1_005),
#endif
ADD_CASE_NULL
};
static void task0(void *arg)
{
aos_sem_signal(&g_sem_taskexit_sync);
aos_task_exit(0);
}
/* task: print task name */
static void task1(void *arg)
{
printf("task name: %s\r\n", aos_task_name());
aos_sem_signal(&g_sem_taskexit_sync);
aos_task_exit(0);
}
/* task: create task key */
static void task2(void *arg)
{
int i = 0;
int ret = -1;
aos_task_key_t task_key;
for(; i<10; i++) {
ret = aos_task_key_create(&task_key);
ASSERT_EQ(ret, 0);
printf("%s task key: %d\r\n", aos_task_name(), task_key);
aos_task_key_delete(task_key);
}
aos_sem_signal(&g_sem_taskexit_sync);
aos_task_exit(0);
}
/* task: set/get task-specific value */
static void task3(void *arg)
{
int ret = -1;
aos_task_key_t task_key;
void *task_value = NULL;
ret = aos_task_key_create(&task_key);
ASSERT_EQ(ret, 0);
printf("%s task key: %d\r\n", aos_task_name(), task_key);
g_var = 0x5A5A;
ret = aos_task_setspecific(task_key, &g_var);
ASSERT_EQ(ret, 0);
task_value = aos_task_getspecific(task_key);
ASSERT_NOT_NULL(task_value);
ASSERT_EQ(*(int*)(task_value), g_var);
g_var = 0xA5A5;
task_value = aos_task_getspecific(task_key);
ASSERT_NOT_NULL(task_value);
ASSERT_EQ(*(int*)(task_value), g_var);
aos_task_key_delete(task_key);
aos_sem_signal(&g_sem_taskexit_sync);
aos_task_exit(0);
}
/* task: decrease g_var with mutex*/
static void task4(void *arg)
{
int i = 0;
printf("task name %s: decrease\r\n", aos_task_name());
for(i=0; i<TEST_CONFIG_SYNC_TIMES; i++) {
aos_mutex_lock(&g_mutex, -1);
g_var--;
aos_mutex_unlock(&g_mutex);
}
aos_sem_signal(&g_sem_taskexit_sync);
aos_task_exit(0);
}
/* task: increase g_var with mutex*/
static void task5(void *arg)
{
int i = 0;
printf("task name %s: increase\r\n", aos_task_name());
for(i=0; i<TEST_CONFIG_SYNC_TIMES; i++) {
aos_mutex_lock(&g_mutex, -1);
g_var++;
aos_mutex_unlock(&g_mutex);
}
aos_sem_signal(&g_sem_taskexit_sync);
aos_task_exit(0);
}
/* task: decrease g_var with sem */
static void task6(void *arg)
{
int i = 0;
printf("task name %s: decrease\r\n", aos_task_name());
for(i=0; i<TEST_CONFIG_SYNC_TIMES; i++) {
aos_sem_wait(&g_sem, -1);
g_var--;
aos_sem_signal(&g_sem);
}
aos_sem_signal(&g_sem_taskexit_sync);
aos_task_exit(0);
}
/* task: increase g_var with sem */
static void task7(void *arg)
{
int i = 0;
printf("task name %s: increase\r\n", aos_task_name());
for(i=0; i<TEST_CONFIG_SYNC_TIMES; i++) {
aos_sem_wait(&g_sem, -1);
g_var++;
aos_sem_signal(&g_sem);
}
aos_sem_signal(&g_sem_taskexit_sync);
aos_task_exit(0);
}
/* task: g_queue1 -> g_queue2 */
static void task8(void *arg)
{
int msg = -1;
unsigned int size = 0;
while(1) {
aos_queue_recv(&g_queue1, -1, &msg, &size);
aos_queue_send(&g_queue2, &msg, size);
if(msg == TEST_CONFIG_SYNC_TIMES) {
break;
}
}
printf("%s exit!\r\n", aos_task_name());
aos_task_exit(0);
}
/* task: g_queue2 -> g_queue3 */
static void task9(void *arg)
{
int msg = -1;
unsigned int size = 0;
while(1) {
aos_queue_recv(&g_queue2, -1, &msg, &size);
aos_queue_send(&g_queue3, &msg, size);
if(msg == TEST_CONFIG_SYNC_TIMES) {
break;
}
}
printf("%s exit!\r\n", aos_task_name());
aos_task_exit(0);
}
#if (TEST_CONFIG_TASK_ENABLED > 0)
CASE(test_task, aos_1_006)
{
unsigned int stack_size = 1024;
int ret = -1;
aos_sem_new(&g_sem_taskexit_sync, 0);
ret = aos_task_new("task1", task1, NULL, stack_size);
ASSERT_EQ(ret, 0);
aos_sem_wait(&g_sem_taskexit_sync, -1);
printf("task1 exit!\r\n");
aos_sem_free(&g_sem_taskexit_sync);
}
CASE(test_task, aos_1_007)
{
unsigned int stack_size = 1024;
aos_task_t task;
int ret = -1;
aos_sem_new(&g_sem_taskexit_sync, 0);
ret = aos_task_new_ext(&task, "task1", task1, NULL, stack_size, 10);
ASSERT_EQ(ret, 0);
aos_sem_wait(&g_sem_taskexit_sync, -1);
printf("task1 exit!\r\n");
aos_sem_free(&g_sem_taskexit_sync);
}
CASE(test_task, aos_1_008)
{
unsigned int stack_size = 1024;
int ret = -1;
aos_sem_new(&g_sem_taskexit_sync, 0);
ret = aos_task_new("task2", task2, NULL, stack_size);
ASSERT_EQ(ret, 0);
aos_sem_wait(&g_sem_taskexit_sync, -1);
printf("task2 exit!\r\n");
aos_sem_free(&g_sem_taskexit_sync);
}
CASE(test_task, aos_1_009)
{
unsigned int stack_size = 1024;
int ret = -1;
aos_sem_new(&g_sem_taskexit_sync, 0);
ret = aos_task_new("task2", task2, NULL, stack_size);
ASSERT_EQ(ret, 0);
aos_sem_wait(&g_sem_taskexit_sync, -1);
printf("task2 exit!\r\n");
aos_sem_free(&g_sem_taskexit_sync);
}
CASE(test_task, aos_1_010)
{
unsigned int stack_size = 1024;
int ret = -1;
aos_sem_new(&g_sem_taskexit_sync, 0);
ret = aos_task_new("task3", task3, NULL, stack_size);
ASSERT_EQ(ret, 0);
aos_sem_wait(&g_sem_taskexit_sync, -1);
printf("task3 exit!\r\n");
aos_sem_free(&g_sem_taskexit_sync);
}
CASE(test_task, aos_1_011)
{
unsigned int stack_size = 1024;
char task_name[10] = {0};
int ret = -1;
int i = 0;
aos_sem_new(&g_sem_taskexit_sync, 0);
for(i=0; i<TEST_CONFIG_MAX_TASK_COUNT; i++) {
memset(task_name, 0, sizeof(task_name));
snprintf(task_name, 10, "task%02d", i);
ret = aos_task_new(task_name, task1, NULL, stack_size);
ASSERT_EQ(ret, 0);
aos_msleep(1);
}
for(i=0; i<TEST_CONFIG_MAX_TASK_COUNT; i++) {
aos_sem_wait(&g_sem_taskexit_sync, -1);
}
printf("%d tasks exit!\r\n", TEST_CONFIG_MAX_TASK_COUNT);
aos_sem_free(&g_sem_taskexit_sync);
}
CASE(test_task, aos_1_012)
{
unsigned int stack_size = 1024;
char task_name[10] = {0};
int ret = -1;
int i = 0;
for(i=0; i<TEST_CONFIG_CREATE_TASK_TIMES; i++) {
memset(task_name, 0, sizeof(task_name));
snprintf(task_name, 10, "task%02d", i);
if(i % 500 == 0) {
printf("create task: %d/%d\r\n", i, TEST_CONFIG_CREATE_TASK_TIMES);
}
aos_sem_new(&g_sem_taskexit_sync, 0);
ret = aos_task_new(task_name, task0, NULL, stack_size);
ASSERT_EQ(ret, 0);
aos_sem_wait(&g_sem_taskexit_sync, -1);
aos_sem_free(&g_sem_taskexit_sync);
aos_msleep(1);
}
}
#endif /* TEST_CONFIG_TASK_ENABLED */
/* task test suite */
SUITE(test_task) = {
#if (TEST_CONFIG_TASK_ENABLED > 0)
ADD_CASE(test_task, aos_1_006),
ADD_CASE(test_task, aos_1_007),
ADD_CASE(test_task, aos_1_008),
ADD_CASE(test_task, aos_1_009),
ADD_CASE(test_task, aos_1_010),
ADD_CASE(test_task, aos_1_011),
ADD_CASE(test_task, aos_1_012),
#endif
ADD_CASE_NULL
};
#if (TEST_CONFIG_TASK_COMM_ENABLED > 0)
CASE(test_task_comm, aos_1_013)
{
int ret = -1;
ret = aos_mutex_new(&g_mutex);
ASSERT_EQ(ret, 0);
ret = aos_mutex_is_valid(&g_mutex);
ASSERT_EQ(ret, 1);
ret = aos_mutex_lock(&g_mutex, 1000);
ASSERT_EQ(ret, 0);
ret = aos_mutex_lock(&g_mutex, 1000);
ASSERT_EQ(ret, 0);
ret = aos_mutex_unlock(&g_mutex);
ASSERT_EQ(ret, 0);
aos_mutex_free(&g_mutex);
}
CASE(test_task_comm, aos_1_014)
{
unsigned int stack_size = 1024;
char task_name[10] = {0};
unsigned int task_count = 4;
int ret = -1;
int i = 0;
ASSERT_TRUE(task_count%2 == 0);
aos_sem_new(&g_sem_taskexit_sync, 0);
aos_mutex_new(&g_mutex);
g_var = 0;
for(i=0; i<4; i++) {
snprintf(task_name, 10, "task%d", i+1);
if(i < 2) {
ret = aos_task_new(task_name, task4, NULL, stack_size);
ASSERT_EQ(ret, 0);
}
else {
ret = aos_task_new(task_name, task5, NULL, stack_size);
ASSERT_EQ(ret, 0);
}
aos_msleep(10);
}
for(i=0; i<4; i++) {
aos_sem_wait(&g_sem_taskexit_sync, -1);
}
printf("g_var = %d\r\n", g_var);
ASSERT_EQ(g_var, 0);
aos_sem_free(&g_sem_taskexit_sync);
aos_mutex_free(&g_mutex);
}
CASE(test_task_comm, aos_1_015)
{
int ret = -1;
ret = aos_sem_new(&g_sem, 0);
ASSERT_EQ(ret, 0);
ret = aos_sem_is_valid(&g_sem);
ASSERT_EQ(ret, 1);
ret = aos_sem_wait(&g_sem, 100);
ASSERT_NE(ret, 0);
aos_sem_signal(&g_sem);
ret = aos_sem_wait(&g_sem, 100);
ASSERT_EQ(ret, 0);
aos_sem_free(&g_sem);
}
CASE(test_task_comm, aos_1_016)
{
unsigned int stack_size = 1024;
char task_name[10] = {0};
unsigned int task_count = 4;
int ret = -1;
int i = 0;
ASSERT_TRUE(task_count%2 == 0);
aos_sem_new(&g_sem_taskexit_sync, 0);
aos_sem_new(&g_sem, 1);
g_var = 0;
for(i=0; i<task_count; i++) {
snprintf(task_name, 10, "task%d", i+1);
if(i < 2) {
ret = aos_task_new(task_name, task6, NULL, stack_size);
ASSERT_EQ(ret, 0);
}
else {
ret = aos_task_new(task_name, task7, NULL, stack_size);
ASSERT_EQ(ret, 0);
}
aos_msleep(10);
}
for(i=0; i<task_count; i++) {
aos_sem_wait(&g_sem_taskexit_sync, -1);
}
printf("g_var = %d\r\n", g_var);
ASSERT_EQ(g_var, 0);
aos_sem_free(&g_sem_taskexit_sync);
aos_sem_free(&g_sem);
}
CASE(test_task_comm, aos_1_017)
{
int ret = -1;
char msg_send[TEST_CONFIG_QUEUE_BUF_SIZE] = {0};
char msg_recv[TEST_CONFIG_QUEUE_BUF_SIZE] = {0};
unsigned int size_send = 16;
unsigned int size_recv = 16;
ret = aos_queue_new(&g_queue, queue_buf, TEST_CONFIG_QUEUE_BUF_SIZE, TEST_CONFIG_QUEUE_BUF_SIZE);
ASSERT_EQ(ret, 0);
ret = aos_queue_is_valid(&g_queue);
ASSERT_EQ(ret, 1);
ret = aos_queue_recv(&g_queue, 100, msg_recv, &size_recv);
ASSERT_NE(ret, 0);
snprintf(msg_send, size_send, "hello,queue!");
size_send = strlen(msg_send);
ret = aos_queue_send(&g_queue, msg_send, size_send);
ASSERT_EQ(ret, 0);
memset(msg_recv, 0, size_recv);
ret = aos_queue_recv(&g_queue, 100, msg_recv, &size_recv);
ASSERT_EQ(ret, 0);
ASSERT_STR_EQ(msg_recv, msg_send);
//ASSERT_EQ(size_send, size_recv);
aos_queue_free(&g_queue);
}
CASE(test_task_comm, aos_1_018)
{
int ret = -1;
unsigned int stack_size = 1024;
unsigned int msg_send = 0;
unsigned int msg_recv = 0;
unsigned int size_send = sizeof(msg_send);
unsigned int size_recv = 0;
int i = 0;
ret = aos_queue_new(&g_queue1, queue1_buf, TEST_CONFIG_QUEUE_BUF_SIZE, sizeof(int));
ASSERT_EQ(ret, 0);
ret = aos_queue_new(&g_queue2, queue2_buf, TEST_CONFIG_QUEUE_BUF_SIZE, sizeof(int));
ASSERT_EQ(ret, 0);
ret = aos_queue_new(&g_queue3, queue3_buf, TEST_CONFIG_QUEUE_BUF_SIZE, sizeof(int));
ASSERT_EQ(ret, 0);
ret = aos_task_new("task1", task8, NULL, stack_size);
ASSERT_EQ(ret, 0);
ret = aos_task_new("task2", task9, NULL, stack_size);
ASSERT_EQ(ret, 0);
for(i=1; i<=TEST_CONFIG_SYNC_TIMES; i++) {
msg_send = i;
ret = aos_queue_send(&g_queue1, &msg_send, size_send);
ASSERT_EQ(ret, 0);
ret = aos_queue_recv(&g_queue3, -1, &msg_recv, &size_recv);
ASSERT_EQ(ret, 0);
ASSERT_EQ(msg_send, msg_recv);
//ASSERT_EQ(size_send, size_recv);
if(i%(TEST_CONFIG_SYNC_TIMES/10) == 0) {
printf("%d/%d\r\n", i, TEST_CONFIG_SYNC_TIMES);
}
}
ASSERT_EQ(msg_recv, TEST_CONFIG_SYNC_TIMES);
aos_queue_free(&g_queue1);
aos_queue_free(&g_queue2);
aos_queue_free(&g_queue3);
}
#endif /* TEST_CONFIG_TASK_COMM_ENABLED */
/* task commication */
SUITE(test_task_comm) = {
#if (TEST_CONFIG_TASK_COMM_ENABLED > 0)
ADD_CASE(test_task_comm, aos_1_013),
ADD_CASE(test_task_comm, aos_1_014),
ADD_CASE(test_task_comm, aos_1_015),
ADD_CASE(test_task_comm, aos_1_016),
ADD_CASE(test_task_comm, aos_1_017),
ADD_CASE(test_task_comm, aos_1_018),
#endif
ADD_CASE_NULL
};
#if (TEST_CONFIG_TIMER_ENABLED > 0)
static void timer_handler(void *arg1, void* arg2)
{
printf("timer handler\r\n");
if(++g_var == 10) {
aos_sem_signal(&g_sem);
}
}
CASE(test_timer, aos_1_019)
{
int ret = -1;
g_var = 0;
ret = aos_sem_new(&g_sem, 0);
ASSERT_EQ(ret, 0);
ret = aos_timer_new(&g_timer, timer_handler, NULL, 200, 1);
ASSERT_EQ(ret, 0);
aos_sem_wait(&g_sem, -1);
aos_sem_free(&g_sem);
aos_timer_stop(&g_timer);
aos_timer_free(&g_timer);
}
CASE(test_timer, aos_1_020)
{
int ret = -1;
g_var = 0;
ret = aos_sem_new(&g_sem, 0);
ASSERT_EQ(ret, 0);
ret = aos_timer_new(&g_timer, timer_handler, NULL, 200, 1);
ASSERT_EQ(ret, 0);
aos_msleep(1000);
aos_timer_stop(&g_timer);
printf("timer stopped!\r\n");
aos_msleep(1000);
aos_timer_change(&g_timer, 1000);
printf("timer changed!\r\n");
aos_timer_start(&g_timer);
printf("timer started!\r\n");
aos_sem_wait(&g_sem, -1);
aos_sem_free(&g_sem);
aos_timer_stop(&g_timer);
aos_timer_free(&g_timer);
}
#endif /* TEST_CONFIG_TIMER_ENABLED */
/* timer test suite */
SUITE(test_timer) = {
#if (TEST_CONFIG_TIMER_ENABLED > 0)
ADD_CASE(test_timer, aos_1_019),
ADD_CASE(test_timer, aos_1_020),
#endif
ADD_CASE_NULL
};
#if (TEST_CONFIG_KV_ENABLED > 0)
#include <aos/kv.h>
CASE(test_kv, aos_2_001)
{
char *key = "test_kv_key";
char *set_value = "test_kv_value";
int set_len = strlen(set_value);
char get_value[32] = {0};
int get_len = 32;
int ret = -1;
ret = aos_kv_set(key, set_value, set_len, 1);
ASSERT_EQ(ret, 0);
ret = aos_kv_get(key, get_value, &get_len);
ASSERT_EQ(ret, 0);
ASSERT_EQ(get_len, set_len);
ASSERT_STR_EQ(get_value, set_value);
}
CASE(test_kv, aos_2_002)
{
char *key = "test_kv_key";
char *set_value = "test_kv_value";
int set_len = strlen(set_value);
char get_value[32] = {0};
int get_len = 32;
int ret = -1;
aos_kv_del(key);
ret = aos_kv_set(key, set_value, set_len, 1);
ASSERT_EQ(ret, 0);
ret = aos_kv_del(key);
ASSERT_EQ(ret, 0);
ret = aos_kv_get(key, get_value, &get_len);
ASSERT_NE(ret, 0);
}
CASE(test_kv, aos_2_003)
{
char key[64] = {0};
char set_value[64] = {0};
int set_len = 0;
char get_value[64] = {0};
int get_len = 0;
int ret = -1;
int i = 0;
while(i++ < TEST_CONFIG_KV_TIMES) {
memset(key, 0, sizeof(key));
memset(set_value, 0, sizeof(set_value));
memset(get_value, 0, sizeof(get_value));
sprintf(key, "this_is_key_%d", i);
sprintf(set_value, "this_is_value_%d", i);
set_len = strlen(set_value);
ret = aos_kv_set(key, set_value, set_len, 1);
ASSERT_EQ(ret, 0);
get_len = sizeof(get_value);
ret = aos_kv_get(key, get_value, &get_len);
ASSERT_EQ(ret, 0);
ASSERT_EQ(get_len, set_len);
ASSERT_TRUE(0 == memcmp(get_value, set_value, set_len));
ret = aos_kv_del(key);
ASSERT_EQ(ret, 0);
if(i%100 == 0) {
printf("kv test: %d/%d\r\n", i, TEST_CONFIG_KV_TIMES);
}
aos_msleep(1);
}
}
#if (KV_CONFIG_SECURE_SUPPORT > 0) && (KV_CONFIG_SECURE_CRYPT_IMPL == 1)
#include "kv_adapt.h"
uint8_t aes_key[32] = {
0x86, 0xf6, 0xd2, 0xbe, 0x45, 0xb5, 0xab, 0x9c,
0xc7, 0xd5, 0x96, 0xf7, 0xaf, 0x45, 0xfa, 0xf7,
0xbe, 0x6a, 0x5d, 0xb0, 0x04, 0xc4, 0xde, 0xb5,
0xf5, 0x0c, 0x4f, 0xc3, 0x71, 0x19, 0x3e, 0xe8
};
uint8_t aes_iv[16] = {
0xef, 0x80, 0x18, 0xdc, 0xa3, 0x72, 0x72, 0x31,
0x99, 0x2e, 0x3a, 0xba, 0x60, 0xf5, 0x0b, 0xd4
};
uint8_t* kv_secure_get_key(uint32_t len)
{
if ((len <= 0) || (len > sizeof(aes_key))) {
return NULL;
}
return aes_key;
}
uint8_t* kv_secure_get_iv(uint32_t len)
{
if ((len <= 0) || (len > sizeof(aes_iv))) {
return NULL;
}
return aes_iv;
}
#endif
#endif /* TEST_CONFIG_KV_ENABLED */
/* kv test suite */
SUITE(test_kv) = {
#if (TEST_CONFIG_KV_ENABLED > 0)
ADD_CASE(test_kv, aos_2_001),
ADD_CASE(test_kv, aos_2_002),
ADD_CASE(test_kv, aos_2_003),
#endif
ADD_CASE_NULL
};
void test_certificate(void)
{
if (0 == dump_test_config()) {
printf("test start!\r\n");
ADD_SUITE(test_mm);
ADD_SUITE(test_task);
ADD_SUITE(test_task_comm);
ADD_SUITE(test_timer);
ADD_SUITE(test_kv);
cut_main(0, NULL);
printf("test finished!\r\n");
}
else {
printf("test error!\r\n");
}
}
AOS_TESTCASE(test_certificate);
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/test/aos_test.c
|
C
|
apache-2.0
| 22,830
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include "cut.h"
struct cut_runtime cut;
static void filter(int argc, char** argv)
{
int i = 0;
struct cut_case *c = NULL;
if(argc==2 && 0==strcmp(argv[1], "all"))
return;
for (i = 0; i < cut.ccnt_total; i++) {
c = cut.clist[i];
if ((argc==2 && (NULL==strstr(c->sname, argv[1]))) ||
(argc==3 && (NULL==strstr(c->sname, argv[1]) || NULL==strstr(c->cname, argv[2])))) {
cut.clist[i]->skip = 1;
cut.ccnt_skip++;
}
}
}
static void usage(const char* me)
{
cut_printf("Usage: %s [OPTION] [SUITE] [CASE]\r\n\r\n" \
"OPTION:\r\n" \
" --help : print this help\r\n" \
" --list : list cases\r\n" \
" --count : print case count\r\n" \
" SUITE : suite name filter, e.g. '%s all' means run all suites\r\n" \
" CASE : case name filter\r\n", me, me);
}
static int parse_arg(int argc, char** argv)
{
if (argc >= 2) {
if (0 == strcmp(argv[1], "--list")) {
int i = 0;
int cnt = 0;
cut_printf("\33[1;34mCASE_LIST_BEGIN\33[0m\r\n");
for(i=0; i<cut.ccnt_total; i++) {
struct cut_case *c = cut.clist[i];
if(argc==2 ||
(argc==3 && 0==strcmp(argv[2], "all")) ||
(argc==3 && NULL!=strstr(c->sname, argv[2])) ||
(argc==4 && NULL!=strstr(c->sname, argv[2]) && NULL!=strstr(c->cname, argv[3])))
cut_printf("\33[1;34m[%02d] %s.%s\33[0m\r\n", ++cnt, c->sname, c->cname);
}
cut_printf("\33[1;34mCASE_LIST_END\33[0m\r\n");
return 0;
}
if (0 == strcmp(argv[1], "--count")) {
cut_printf("total %d case(s).\r\n", cut.ccnt_total);
return 0;
}
if (0 == strcmp(argv[1], "--help")) {
usage(argv[0]);
return 0;
}
}
return 1;
}
static void cut_result_report(struct cut_runtime *cut)
{
int i = 0;
/* print test result locally */
cut_printf("===========================================================================\r\n");
if (cut->ccnt_fail > 0) {
cut_printf("FAIL LIST:\r\n");
for (i = 0; i < cut->ccnt_fail; i++) {
cut_printf(" [%02d] %s\r\n", i + 1, cut->cerrmsg[i]);
cut_free(cut->cerrmsg[i]);
}
cut_printf("---------------------------------------------------------------------------\r\n");
}
cut_printf("SUMMARY:\r\n" \
" TOTAL: %d\r\n" \
" SKIPPED: %d\r\n" \
" MATCHED: %d\r\n" \
" PASS: %d\r\n" \
" FAILED: %d\r\n", cut->ccnt_total, cut->ccnt_skip,
cut->ccnt_total-cut->ccnt_skip, cut->ccnt_pass, cut->ccnt_fail);
cut_printf("===========================================================================\r\n");
}
int cut_main(int argc, char** argv)
{
int i = 0, cnt = 0;
char *_argv[2] = {"None", "--list"};
cut.ccnt_pass = 0;
cut.ccnt_fail = 0;
cut.ccnt_skip = 0;
for(i=0; i<cut.ccnt_total; i++) {
cut.clist[i]->skip = 0;
cut.clist[i]->flag = 1;
}
if (0 == parse_arg(argc, argv))
return 0;
parse_arg(2, _argv);
filter(argc, argv);
for(i=0; i < cut.ccnt_total; i++) {
cut.ccur = cut.clist[i];
if (cut.ccur->skip)
continue;
cut_printf("\33[1;33mTEST [%d/%d] %s.%s...\33[0m\r\n",
++cnt, cut.ccnt_total-cut.ccnt_skip, cut.ccur->sname, cut.ccur->cname);
if (cut.ccur->setup)
cut.ccur->setup(cut.ccur->data);
cut.ccur->run((struct cut_case *)(cut.ccur->data));
if (cut.ccur->teardown)
cut.ccur->teardown(cut.ccur->data);
if (cut.ccur->flag) {
cut_printf("\33[1;32m[OK]\33[0m\r\n\r\n");
cut.ccnt_pass++;
}
else {
cut_printf("\33[1;31m[FAIL]: %s\33[0m\r\n\r\n", cut.cerrmsg[cut.ccnt_fail]);
cut.ccnt_fail++;
}
}
cut_result_report(&cut);
return cut.ccnt_fail;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/test/cutest/cut.c
|
C
|
apache-2.0
| 4,195
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef __CUT_H__
#define __CUT_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <string.h>
#define cut_printf printf
#define cut_snprintf snprintf
#define cut_malloc malloc
#define cut_free free
#define CUT_CASE_MAX_CNT (64)
#define CUT_MSG_MAX_LEN (64)
extern int cut_main(int argc, char** argv);
extern struct cut_runtime cut;
struct cut_case {
const char* sname;
const char* cname;
void *data;
void (*run)(void*);
void (*setup)(void*);
void (*teardown)(void*);
int skip;
int flag;
};
struct cut_runtime {
int scnt_total;
int ccnt_total;
int ccnt_pass;
int ccnt_fail;
int ccnt_skip;
struct cut_case *clist[CUT_CASE_MAX_CNT];
struct cut_case *ccur;
char *cerrmsg[CUT_CASE_MAX_CNT];
};
#define CUT_CASE_RUNNER(sname, cname) cut_##sname##_##cname##_run
#define CUT_CASE_NAME(sname, cname) cut_##sname##_##cname
#define CUT_CASE_DATA(sname) cut_##sname##_data
#define CUT_CASE_SETUP(sname) cut_##sname##_setup
#define CUT_CASE_TEARDOWN(sname) cut_##sname##_teardown
#define DATA(sname) \
struct CUT_CASE_DATA(sname)
#define SETUP(sname) \
static void CUT_CASE_SETUP(sname)(struct CUT_CASE_DATA(sname) *data)
#define TEARDOWN(sname) \
static void CUT_CASE_TEARDOWN(sname)(struct CUT_CASE_DATA(sname) *data)
/*
* @brief: construct a test case structor and a test case runner
* @sname: suite name
* @cname: case name
* e.g.
CASE(mysuite, mycase1) {
// do something here
ASSERT_TRUE(1);
}
*/
#define CASE(sname, cname) \
static void CUT_CASE_RUNNER(sname, cname)(void *null); \
static struct cut_case CUT_CASE_NAME(sname, cname) = { \
#sname, #cname, NULL, CUT_CASE_RUNNER(sname, cname), NULL, NULL, 0}; \
static void CUT_CASE_RUNNER(sname, cname)(void *null)
/*
* @brief: construct a test case structor and a test case runner
* with case_data/setup/teardown for each case.
* @sname: suite name
* @cname: case name
* e.g.
DATA(mysuite) {
int errmsg;
char *errcode;
};
SETUP(mysuite) {
data->errcode = 0;
data->errmsg = (char*)malloc(100);
}
TEARDOWN(mysuite) {
if(data->errmsg) {
free(data->errmsg);
data->errmsg = NULL;
}
}
CASE2(mysuite, mycase1) {
data->errcode = 1;
strcpy(data->errmsg, "timeout error");
ASSERT_TRUE(1);
}
*/
#define CASE2(sname, cname) \
static struct CUT_CASE_DATA(sname) CUT_CASE_DATA(sname); \
static void CUT_CASE_RUNNER(sname, cname)(struct CUT_CASE_DATA(sname) * data); \
static struct cut_case CUT_CASE_NAME(sname, cname) = { \
#sname, #cname, &CUT_CASE_DATA(sname), (void(*)(void*))CUT_CASE_RUNNER(sname, cname), \
(void(*)(void*))CUT_CASE_SETUP(sname), (void(*)(void*))CUT_CASE_TEARDOWN(sname), 0}; \
static void CUT_CASE_RUNNER(sname, cname)(struct CUT_CASE_DATA(sname) * data)
/*
* @brief: construct a test suite by adding test case(s)
* @sname: suite name
* e.g.
SUITE(mysuite) = {
ADD_CASE(mysuite, mycase1),
ADD_CASE(mysuite, mycase2),
ADD_CASE_NULL
};
*/
#define SUITE(sname) struct cut_case *cut_suite_##sname[]
/*
* @brief: add a test case into a test suite
* @sname: suite name
* @cname: case name
*/
#define ADD_CASE(sname, cname) &CUT_CASE_NAME(sname, cname)
#define ADD_CASE_NULL (struct cut_case*)(NULL)
/*
* @brief: add a test suite into case list
* @sname: suite name
*/
#define ADD_SUITE(sname) \
do { \
int i = 0; \
extern struct cut_case *cut_suite_##sname[]; \
struct cut_case *c = cut_suite_##sname[i]; \
if (cut.ccnt_total >= CUT_CASE_MAX_CNT) { \
cut_printf("reaches maximum case count:%d\n", \
CUT_CASE_MAX_CNT); \
break; \
} \
while (c) { \
*(cut.clist + cut.ccnt_total++) = c; \
c = *(cut_suite_##sname + (++i)); \
} \
} while (0)
#define TRY //if(0==setjmp(cut.jmpbuf))
#define EXCEPT //else
#define RAISE_EXCEPTION_WITH_MSG(msg) \
do \
{ \
int ret = 0, i = cut.ccnt_fail; \
cut.cerrmsg[i] = (char *)cut_malloc(CUT_MSG_MAX_LEN); \
assert(cut.cerrmsg[i] != NULL); \
memset(cut.cerrmsg[i], 0, CUT_MSG_MAX_LEN); \
ret = cut_snprintf(cut.cerrmsg[i], \
CUT_MSG_MAX_LEN - 1, \
"%s.%s in %s(%d) expected %s", \
cut.ccur->sname, cut.ccur->cname, \
__FILE__, __LINE__, msg); \
if (ret >= CUT_MSG_MAX_LEN) \
cut_snprintf(cut.cerrmsg[i] + CUT_MSG_MAX_LEN - 4, \
4, "..."); \
cut.ccur->flag = 0; \
return; \
} while (0)
#define ASSERT_TRUE(cond) \
do { \
if (!(cond)) \
RAISE_EXCEPTION_WITH_MSG("[True]"); \
} while (0)
#define ASSERT_INT(expected, compare, actual) \
do { \
if (!((expected)compare(actual))) \
RAISE_EXCEPTION_WITH_MSG("[" #expected " " #compare " " #actual "]"); \
} while (0)
#define ASSERT_STR(expected, compare, actual) \
do { \
if (!(strcmp((expected), (actual)) compare 0)) \
RAISE_EXCEPTION_WITH_MSG("[" #expected " " #compare " " #actual "]"); \
} while (0)
#define ASSERT_IN(expected1, actual, expected2) \
do { \
if ((actual) < (expected1) || (actual) > (expected2)) \
RAISE_EXCEPTION_WITH_MSG("[" #expected1 " <= " #actual " <=" #expected2); \
} while (0)
#define ASSERT_FAIL() RAISE_EXCEPTION_WITH_MSG("[should not be here]")
#define ASSERT_FALSE(cond) ASSERT_TRUE(!(cond))
#define ASSERT_NULL(ptr) ASSERT_INT(ptr, ==, NULL)
#define ASSERT_NOT_NULL(ptr) ASSERT_INT(ptr, !=, NULL)
#define ASSERT_EQ(actual, expected) ASSERT_INT(actual, ==, expected)
#define ASSERT_NE(actual, expected) ASSERT_INT(actual, !=, expected)
#define ASSERT_GT(actual, expected) ASSERT_INT(actual, >, expected)
#define ASSERT_GE(actual, expected) ASSERT_INT(actual, >=, expected)
#define ASSERT_LT(actual, expected) ASSERT_INT(actual, <, expected)
#define ASSERT_LE(actual, expected) ASSERT_INT(actual, <=, expected)
#define ASSERT_STR_EQ(actual, expected) ASSERT_STR(actual, ==, expected)
#define ASSERT_STR_NE(actual, expected) ASSERT_STR(actual, !=, expected)
#define ASSERT_STR_GT(actual, expected) ASSERT_STR(actual, >, expected)
#define ASSERT_STR_LT(actual, expected) ASSERT_STR(actual, <, expected)
#ifdef __cplusplus
}
#endif
#endif /* __CUT_H__ */
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/test/cutest/cut.h
|
C
|
apache-2.0
| 8,362
|
@echo off
DownloadServer 8082 New_Project.bin
set /p DUMMY=Press Enter to Continue ...
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/tools/DownloadServer(HTTP)/start.bat
|
Batchfile
|
apache-2.0
| 86
|
@echo off
DownloadServer 8082 ota.bin
set /p DUMMY=Press Enter to Continue ...
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/tools/DownloadServer/start.bat
|
Batchfile
|
apache-2.0
| 78
|
@echo off
setlocal enableDelayedExpansion
REM patch files to sdk (for customer)
REM Owen Chiu
echo ... patch files to sdk ...
set FILE_LIST=patch_list
set SDK_PATH=..\..
set UNZIP_PATH=unzip_tmp
echo Please drag in the patch file you want to use:
set /p PATCH_PATH=
if NOT "%PATCH_PATH:~-4%" == ".zip" (
echo Not zip file
pause
exit /b
)
if exist %UNZIP_PATH% rmdir %UNZIP_PATH% /s/q
mkdir %UNZIP_PATH%
call :getFileName %PATCH_PATH:~0,-4% PATCH_NAME
REM unzip patch file
echo Unzip %PATCH_NAME%
call :genUnzipScript
CScript _unzip.vbs %PATCH_PATH% %UNZIP_PATH%
if NOT exist %UNZIP_PATH%\%FILE_LIST% (
echo patch_list not included in the patch file, cannot use auto patch
if exist %UNZIP_PATH% rmdir %UNZIP_PATH% /s/q
del _unzip.vbs /q
pause
exit /b
)
for /f "skip=1 delims=" %%i in (%UNZIP_PATH%\%FILE_LIST%) do (
set line=%%i
if "!line:~-1!" == "\" (
REM is directory
call :getFileName !line:~0,-1! DIR_NAME
xcopy "%UNZIP_PATH%\!DIR_NAME!\*.*" "%SDK_PATH%\%%i" /e/y
) else (
REM is file
call :getFileName !line! FILE_NAME
call :getPrefix %%i PREFIX_PATH
xcopy "%UNZIP_PATH%\!FILE_NAME!" "%SDK_PATH%\!PREFIX_PATH!\" /y
)
)
if exist %UNZIP_PATH% rmdir %UNZIP_PATH% /s/q
del _unzip.vbs /q
echo.
echo Patch %PATCH_NAME% done
pause
exit /b
:genUnzipScript
echo Set objArgs = WScript.Arguments > _unzip.vbs
echo ZipFile=objArgs(0) >> _unzip.vbs
echo ExtractTo=objArgs(1)>> _unzip.vbs
echo Set fso = CreateObject("Scripting.FileSystemObject") >> _unzip.vbs
echo If NOT fso.FolderExists(ExtractTo) Then >> _unzip.vbs
echo fso.CreateFolder(ExtractTo) >> _unzip.vbs
echo End If >> _unzip.vbs
echo set objShell = CreateObject("Shell.Application") >> _unzip.vbs
echo set FilesInZip=objShell.NameSpace(ZipFile).items >> _unzip.vbs
echo objShell.NameSpace(fso.GetAbsolutePathName(ExtractTo)).CopyHere(FilesInZip) >> _unzip.vbs
echo Set fso = Nothing >> _unzip.vbs
echo Set objShell = Nothing >> _unzip.vbs
goto :eof
:getPrefix
set str=%1
call :lastindexof "%str%" "\"
set /a lastindex=!errorlevel!
set %2=!str:~0,%lastindex%!
goto :eof
:getFileName
set str=%1
call :lastindexof "%str%" "\"
set /a lastindex=!errorlevel!+1
set %2=!str:~%lastindex%!
goto :eof
:lastindexof [%1 - string ; %2 - find last index of ; %3 - if defined will store the result in variable with same name]
setlocal enableDelayedExpansion
set "str=%~1"
set "splitter=%~2"
set LF=^
REM ** Two empty lines are required
echo off
for %%L in ("!LF!") DO (
for /f "delims=" %%R in ("!splitter!") do (
set "var=!str:%%R=%%L!"
)
)
for /f delims^=^" %%P in ("!var!") DO (
set "last_part=%%~P"
)
if "!last_part!" equ "" if "%~3" NEQ "" (
echo "not contained" >2
endlocal
set %~3=-1
exit
) else (
echo "not contained" >2
endlocal
echo -1
)
setlocal DisableDelayedExpansion
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
set $strLen=for /L %%n in (1 1 2) do if %%n==2 (%\n%
for /F "tokens=1,2 delims=, " %%1 in ("!argv!") do (%\n%
set "str=A!%%~2!"%\n%
set "len=0"%\n%
for /l %%A in (12,-1,0) do (%\n%
set /a "len|=1<<%%A"%\n%
for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"%\n%
)%\n%
for %%v in (!len!) do endlocal^&if "%%~b" neq "" (set "%%~1=%%v") else echo %%v%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
%$strlen% strlen,str
%$strlen% plen,last_part
%$strlen% slen,splitter
set /a lio=strlen-plen-slen
REM endlocal & if "%~3" NEQ "" (set %~3=%lio%) else echo %lio%
exit /b %lio%
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/tools/autopatch/auto_patch.bat
|
Batchfile
|
apache-2.0
| 3,525
|
#include "autoconf.h"
#if !defined(CONFIG_PLATFORM_8195A) && !defined(CONFIG_PLATFORM_8711B)
#include <flash/stm32_flash.h>
#if defined(STM32F2XX)
#include <stm32f2xx_flash.h>
#elif defined(STM32F4XX)
#include <stm32f4xx_flash.h>
#elif defined(STM32f1xx)
#include <stm32f10x_flash.h>
#endif
#include "cloud_updater.h"
#else
#include "flash_api.h"
#include "device_lock.h"
#endif
#define BUF_LEN 512
#define CONFIG_MD5_USE_SSL
#ifdef CONFIG_MD5_USE_SSL
#include "md5.h"
#define file_md5_context md5_context
#define file_md5_init(ctx) md5_init(ctx)
#define file_md5_starts(ctx) md5_starts(ctx)
#define file_md5_update(ctx, input, len) md5_update(ctx, input, len)
#define file_md5_finish(ctx, output) md5_finish(ctx, output)
#define file_md5_free(ctx) md5_free(ctx)
#else
#include "rom_md5.h"
#define file_md5_context md5_ctx
#define file_md5_init(ctx) rt_md5_init(ctx)
#define file_md5_starts(ctx)
#define file_md5_update(ctx, input, len) rt_md5_append(ctx, input, len)
#define file_md5_finish(ctx, output) rt_md5_final(output, ctx)
#define file_md5_free(ctx)
#endif
int file_check_sum(uint32_t addr, uint32_t image_len, u8* check_sum)
{
int ret = -1 ;
flash_t flash;
file_md5_context md5;
unsigned char buf[BUF_LEN];
uint32_t read_addr = addr;
int len = 0;
file_md5_init(&md5);
file_md5_starts(&md5);
while(len < image_len){
if ((image_len-len) >= BUF_LEN){
device_mutex_lock(RT_DEV_LOCK_FLASH);
flash_stream_read(&flash, read_addr, BUF_LEN, buf);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
file_md5_update(&md5, buf, BUF_LEN);
}else{
device_mutex_lock(RT_DEV_LOCK_FLASH);
flash_stream_read(&flash, read_addr, (image_len-len), buf);
device_mutex_unlock(RT_DEV_LOCK_FLASH);
file_md5_update(&md5, buf, (image_len-len));
}
len += BUF_LEN;
read_addr = read_addr + BUF_LEN;
}
file_md5_finish(&md5, check_sum);
file_md5_free(&md5);
}
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/tools/file_check_sum/file_checksum.c
|
C
|
apache-2.0
| 1,932
|
SET TOOLS_FOLDER=%~dp0
%TOOLS_FOLDER%\mklittlefs.exe -c %TOOLS_FOLDER%\..\\prebuild\\data\\ -d 5 -b 4096 -p 256 -s 684032 %TOOLS_FOLDER%\..\\prebuild\\littlefs.bin
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/tools/genfs.bat
|
Batchfile
|
apache-2.0
| 165
|
#!/usr/bin/env bash
TOOLS_FOLDER=$(dirname "$0")
if [ "$(uname)" = "Darwin" ]; then
${TOOLS_FOLDER}/mklittlefs_osx -c ${TOOLS_FOLDER}/../prebuild/data/ -d 5 -b 4096 -p 256 -s 684032 ${TOOLS_FOLDER}/../prebuild/littlefs.bin
elif [ "$(expr substr $(uname -s) 1 5)" = "Linux" ]; then
${TOOLS_FOLDER}/mklittlefs_linux -c ${TOOLS_FOLDER}/../prebuild/data/ -d 5 -b 4096 -p 256 -s 684032 ${TOOLS_FOLDER}/../prebuild/littlefs.bin
elif [ "$(expr substr $(uname -s) 1 10)" = "MINGW32_NT" ]; then
echo
fi
|
YifuLiu/AliOS-Things
|
hardware/chip/rtl872xd/tools/genfs.sh
|
Shell
|
apache-2.0
| 500
|
/*
* * Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include "aos/debug.h"
#include <ck_usart.h>
/* use for printk */
int alios_debug_print(const char *buf, int size)
{
uint32_t timecount = 0;
uint32_t trans_num = 0;
uint8_t *ch = (uint8_t *)buf;
ck_usart_reg_t *addr = (ck_usart_reg_t *)0x10015000;
while (trans_num < (int32_t)size) {
while ((!(addr->LSR & DW_LSR_TRANS_EMPTY)))
;
trans_num++;
addr->THR = *ch++;
}
return trans_num;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/aos/aos.c
|
C
|
apache-2.0
| 566
|
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* 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 the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __CC_H__
#define __CC_H__
#include <stdio.h>
#include <stdint.h>
#include "ulog/ulog.h"
#define LWIP_MAILBOX_QUEUE 1
#define LWIP_TIMEVAL_PRIVATE 0
#define LWIP_NO_INTTYPES_H 0
#if defined(__GNUC__)
#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_STRUCT __attribute__((packed))
#define PACK_STRUCT_FIELD(x) x
#elif defined(__ICCARM__)
#define PACK_STRUCT_BEGIN __packed
#define PACK_STRUCT_STRUCT
#define PACK_STRUCT_FIELD(x) x
#else
#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_STRUCT
#define PACK_STRUCT_FIELD(x) x
#endif
#if LWIP_NO_INTTYPES_H
#define U8_F "2d"
#define X8_F "2x"
#define U16_F "4d"
#define S16_F "4d"
#define X16_F "x"
#define U32_F "8ld"
#define S32_F "8ld"
#define X32_F "lx"
#define SZT_F U32_F
#endif
#define LWIP_PLATFORM_TAG "DEBUG"
/*
* Platform specific diagnostic output -
* LWIP_PLATFORM_DIAG(x) - non-fatal, print a message.
* LWIP_PLATFORM_ASSERT(x) - fatal, print message and abandon execution.
* Portability defines for printf formatters:
* U16_F, S16_F, X16_F, U32_F, S32_F, X32_F, SZT_F
*/
#ifndef LWIP_PLATFORM_ASSERT
#define LWIP_PLATFORM_ASSERT(x) \
do { \
LOGE(LWIP_PLATFORM_TAG, "Assertion \"%s\" failed at line %d in %s\n", x, __LINE__, __FILE__); \
} while (0)
#endif
#ifndef LWIP_ULOG_DIAG
#define LWIP_ULOG_DIAG(x, ...) LOGI(LWIP_PLATFORM_TAG, x, ##__VA_ARGS__)
#endif
#ifndef LWIP_PLATFORM_DIAG
#define LWIP_PLATFORM_DIAG(x) do {LWIP_ULOG_DIAG x; } while (0)
#endif
/*
* unknow defination
*/
/* cup byte order */
#ifndef BYTE_ORDER
#define BYTE_ORDER LITTLE_ENDIAN
#endif
#ifndef LWIP_RAND
#define LWIP_RAND() ((uint32_t)aos_rand())
#endif
#endif /* __CC_H__ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/aos/arch/cc.h
|
C
|
apache-2.0
| 3,286
|
/**
******************************************************************************
* @file lwipopts.h
* @author MCD Application Team
* @version V1.0.0
* @date 11/20/2009
* @brief lwIP Options Configuration.
* This file is based on Utilities\lwip-1.3.1\src\include\lwip\opt.h
* and contains the lwIP configuration for the STM32F107 demonstration.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2009 STMicroelectronics</center></h2>
*/
#ifndef __LWIPOPTS_H__
#define __LWIPOPTS_H__
#define LWIP_NOASSERT 1
// move from opt.h for bes adapter
#define LWIP_TCPIP_CORE_LOCKING 1
#define MEMP_NUM_SELECT_CB 8
#define MEMP_NUM_TCPIP_MSG_API 16
#define ETH_PAD_SIZE 2
#define LWIP_RAW 1
#define LWIP_DNS 1
#define SO_REUSE 1
#define SO_REUSE_RXTOALL 1
#define SNTP_SERVER_DNS 1
#define SNTP_STARTUP_DELAY 0
#define SNTP_RECV_TIMEOUT 5000
#define MAX_MSG_IN_LWIP_MBOX 50
/*----------------Thread Priority---------------------------------------------*/
/* #define TCPIP_THREAD_PRIO osPriorityHigh */
/* #define DEFAULT_THREAD_PRIO osPriorityNormal */
#define TCPIP_THREAD_PRIO 31
#define DEFAULT_THREAD_PRIO 32
/**
* SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain
* critical regions during buffer allocation, deallocation and memory
* allocation and deallocation.
*/
#define SYS_LIGHTWEIGHT_PROT 1
/**
* NO_SYS==1: Provides VERY minimal functionality. Otherwise,
* use lwIP facilities.
*/
#define NO_SYS 0
/* ---------- Memory options ---------- */
#define MEM_LIBC_MALLOC 1
#define mem_clib_free free
#define mem_clib_malloc malloc
#define mem_clib_calloc calloc
#define MEMP_MEM_MALLOC 1
#define LWIP_COMPAT_MUTEX_ALLOWED (1)
/* MEM_ALIGNMENT: should be set to the alignment of the CPU for which
lwIP is compiled. 4 byte alignment -> define MEM_ALIGNMENT to 4, 2
byte alignment -> define MEM_ALIGNMENT to 2. */
#define MEM_ALIGNMENT 4
/* MEM_SIZE: the size of the heap memory. If the application will send
a lot of data that needs to be copied, this should be set high. */
#define MEM_SIZE (20 * 1024) /* used for Lwip malloc */
#define MAX_SOCKETS_TCP 12
#define MAX_LISTENING_SOCKETS_TCP 4
#define MAX_SOCKETS_UDP 22
#define TCP_SND_BUF_COUNT 5
#define TCP_MEM_SIZE (MAX_SOCKETS_TCP * \
PBUF_POOL_BUFSIZE * (TCP_SND_BUF / TCP_MSS))
/* Buffer size needed for UDP: Max. number of UDP sockets * Size of pbuf
*/
#define UDP_MEM_SIZE (MAX_SOCKETS_UDP * PBUF_POOL_BUFSIZE)
/* MEMP_NUM_PBUF: the number of memp struct pbufs. If the application
sends a lot of data out of ROM (or other static memory), this
should be set high. */
#define MEMP_NUM_PBUF 10
/* MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One
per active UDP "connection". */
#define MEMP_NUM_UDP_PCB (MAX_SOCKETS_UDP + 2)
/* MEMP_NUM_TCP_PCB: the number of simulatenously active TCP
connections. */
#define MEMP_NUM_TCP_PCB MAX_SOCKETS_TCP
/* MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP
connections. */
#define MEMP_NUM_TCP_PCB_LISTEN MAX_LISTENING_SOCKETS_TCP
/* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP
segments. */
/**
* MEMP_NUM_SYS_TIMEOUT: the number of simulateously active timeouts.
* (requires NO_SYS==0)
*/
#define MEMP_NUM_SYS_TIMEOUT 12
/**
* MEMP_NUM_NETBUF: the number of struct netbufs.
* (only needed if you use the sequential API, like api_lib.c)
*/
#define MEMP_NUM_NETBUF 16
/**
* MEMP_NUM_NETCONN: the number of struct netconns.
* (only needed if you use the sequential API, like api_lib.c)
*
* This number corresponds to the maximum number of active sockets at any
* given point in time. This number must be sum of max. TCP sockets, max. TCP
* sockets used for listening, and max. number of UDP sockets
*/
#define MEMP_NUM_NETCONN (MAX_SOCKETS_TCP + \
MAX_LISTENING_SOCKETS_TCP + MAX_SOCKETS_UDP)
/* ---------- Pbuf options ---------- */
/* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */
#define PBUF_POOL_SIZE 30
/* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */
#define PBUF_POOL_BUFSIZE 1536
/* Enable IPv4 Auto IP */
#ifdef CONFIG_AUTOIP
#define LWIP_AUTOIP 1
#define LWIP_DHCP_AUTOIP_COOP 1
#define LWIP_DHCP_AUTOIP_COOP_TRIES 5
#endif
#define DNS_TABLE_SIZE 2 /* number of table entries, default 4 */
/* #define DNS_MAX_NAME_LENGTH 64 */ // max. name length, default 256
#define DNS_MAX_SERVERS 2 /* number of DNS servers, default 2 */
#define DNS_DOES_NAME_CHECK 1 /* compare received name with given,def 0 */
#define DNS_MSG_SIZE 512
#define MDNS_MSG_SIZE 512
#define MDNS_TABLE_SIZE 1 /* number of mDNS table entries */
#define MDNS_MAX_SERVERS 1 /* number of mDNS multicast addresses */
/* TODO: Number of active UDP PCBs is equal to number of active UDP sockets plus
* two. Need to find the users of these 2 PCBs
*/
/* ---------- TCP options ---------- */
#define LWIP_TCP 1
#define TCP_TTL 255
#define TCPIP_THREAD_STACKSIZE 25600
/* Controls if TCP should queue segments that arrive out of
order. Define to 0 if your device is low on memory. */
#define TCP_QUEUE_OOSEQ 1
/**
* TCPIP_MBOX_SIZE: The mailbox size for the tcpip thread messages
* The queue size value itself is platform-dependent, but is passed to
* sys_mbox_new() when tcpip_init is called.
*/
#define MEMP_NUM_TCPIP_MSG_INPKT 64
#define TCPIP_MBOX_SIZE 64
/**
* DEFAULT_TCP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a
* NETCONN_TCP. The queue size value itself is platform-dependent, but is passed
* to sys_mbox_new() when the recvmbox is created.
*/
#define DEFAULT_ACCEPTMBOX_SIZE 8
#define DEFAULT_RAW_RECVMBOX_SIZE 4
#define DEFAULT_TCP_RECVMBOX_SIZE 20
/* TCP Maximum segment size. */
#define TCP_MSS (1500 - 40) /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */
/* TCP sender buffer space (bytes). */
#define TCP_SND_BUF (44 * TCP_MSS)
/* TCP sender buffer space (pbufs). This must be at least = 2 *
TCP_SND_BUF/TCP_MSS for things to work. */
#define TCP_SND_QUEUELEN (4 * TCP_SND_BUF / TCP_MSS)
/* TCP receive window. */
#define TCP_WND (10 * TCP_MSS)
/**
* Enable TCP_KEEPALIVE
*/
#define LWIP_TCP_KEEPALIVE 1
/**
* TCP_SYNMAXRTX: Maximum number of retransmissions of SYN segments.
*/
#define TCP_SYNMAXRTX 10
#define TCP_MAX_ACCEPT_CONN 5
#define MEMP_NUM_TCP_SEG (TCP_SND_QUEUELEN * 2)
#define IP_REASS_MAX_PBUFS 0
#define IP_REASSEMBLY 0
#define IP_REASS_MAX_PBUFS 0
#define IP_REASSEMBLY 0
#define MEMP_NUM_REASSDATA 0
#define IP_FRAG 0
/* ---------- ICMP options ---------- */
#define LWIP_ICMP 1
/* ---------- DHCP options ---------- */
/* Define LWIP_DHCP to 1 if you want DHCP configuration of
interfaces. DHCP is not implemented in lwIP 0.5.1, however, so
turning this on does currently not work. */
#define LWIP_DHCP 1
#define DHCP_DOES_ARP_CHECK 0
/* ---------- UDP options ---------- */
#define LWIP_UDP 1
#define UDP_TTL 255
#define DEFAULT_UDP_RECVMBOX_SIZE MAX_MSG_IN_LWIP_MBOX
/* ---------- Statistics options ---------- */
#define LWIP_STATS 0
#define LWIP_IGMP 1
#if LWIP_IGMP
#ifndef LWIP_RAND
#define LWIP_RAND() ((u32_t)aos_rand())
#endif
#endif
#define LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS 1
#define IP_FORWARD 0
#define LWIP_NETIF_STATUS_CALLBACK 1
#include <errno.h>
#define ERRNO 1
/*
--------------------------------------
---------- Checksum options ----------
--------------------------------------
*/
/*
The STM32F107 allows computing and verifying the IP, UDP, TCP and ICMP checksums by hardware:
- To use this feature let the following define uncommented.
- To disable it and process by CPU comment the the checksum.
*/
#define CHECKSUM_BY_HARDWARE
#ifdef CHECKSUM_BY_HARDWARE
/* CHECKSUM_GEN_IP==0: Generate checksums by hardware for outgoing IP packets.*/
#define CHECKSUM_GEN_IP 1
/* CHECKSUM_GEN_UDP==0: Generate checksums by hardware for outgoing UDP packets.*/
#define CHECKSUM_GEN_UDP 0
/* CHECKSUM_GEN_TCP==0: Generate checksums by hardware for outgoing TCP packets.*/
#define CHECKSUM_GEN_TCP 0
/* CHECKSUM_CHECK_IP==0: Check checksums by hardware for incoming IP packets.*/
#define CHECKSUM_CHECK_IP 1
/* CHECKSUM_CHECK_UDP==0: Check checksums by hardware for incoming UDP packets.*/
#define CHECKSUM_CHECK_UDP 0
/* CHECKSUM_CHECK_TCP==0: Check checksums by hardware for incoming TCP packets.*/
#define CHECKSUM_CHECK_TCP 0
#else
/* CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets.*/
#define CHECKSUM_GEN_IP 1
/* CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets.*/
#define CHECKSUM_GEN_UDP 1
/* CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets.*/
#define CHECKSUM_GEN_TCP 1
/* CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets.*/
#define CHECKSUM_CHECK_IP 1
/* CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets.*/
#define CHECKSUM_CHECK_UDP 1
/* CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets.*/
#define CHECKSUM_CHECK_TCP 1
#endif
/*
----------------------------------------------
---------- Sequential layer options ----------
----------------------------------------------
*/
/**
* LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c)
*/
#define LWIP_NETCONN 1
/*
------------------------------------
---------- Socket options ----------
------------------------------------
*/
/**
* LWIP_SOCKET==1: Enable Socket API (require to use sockets.c)
*/
#define LWIP_SOCKET 1
#define LWIP_NETIF_API 1
/**
* LWIP_RECV_CB==1: Enable callback when a socket receives data.
*/
#define LWIP_RECV_CB 1
/**
* SO_REUSE==1: Enable SO_REUSEADDR option.
*/
#define SO_REUSE 1
#define SO_REUSE_RXTOALL 1
#define LWIP_SO_RCVTIMEO 1
#define LWIP_SO_SNDTIMEO 1
#define LWIP_SO_RCVBUF 1
#define LWIP_SO_RCVTCPBUF 1
#define TCP_LISTEN_BACKLOG 1
#define ARP_QUEUEING 1
#define LWIP_DHCP_MAX_NTP_SERVERS 3
#if defined(LWIP_FULLDUPLEX_SUPPORT)
/* #define LWIP_NETCONN_FULLDUPLEX 1 */
#define LWIP_NETCONN_SEM_PER_THREAD 1
#endif
/* #define LWIP_PROVIDE_ERRNO 1 */
#define LWIP_MAILBOX_QUEUE 1
#define LWIP_TIMEVAL_PRIVATE 0
// add for alios things compatible
#define LWIP_IPV6 0
#ifdef CONFIG_AOS_MESH
#define LWIP_DECLARE_HOOK \
struct netif *lwip_hook_ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest); \
int lwip_hook_mesh_is_mcast_subscribed(const ip6_addr_t *dest);
#define LWIP_HOOK_IP6_ROUTE(src, dest) lwip_hook_ip6_route(src, dest)
#define LWIP_HOOK_MESH_IS_MCAST_SUBSCRIBED(dest) lwip_hook_mesh_is_mcast_subscribed(dest)
#define LWIP_ICMP6 1
#define CHECKSUM_CHECK_ICMP6 0
#define LWIP_MULTICAST_PING 1
#endif
/*
------------------------------------
--------- customize macros ---------
------------------------------------
*/
/**
* LWIP_THREAD_EXIT_HOOK==1: bes add for thread exit proc
*/
#define LWIP_THREAD_EXIT_HOOK 1
/**
* LWIP_NTP_HOOK==1: bes add for ntp maintain
*/
#define LWIP_NTP_HOOK 1
/**
* DHCP_REBIND_PRE_ADDR: bes add for DHCP
*/
/* uncommented below define to try to rebind last offerred address when link get reconnected*/
/* #define DHCP_REBIND_PRE_ADDR */
#ifdef DHCP_REBIND_PRE_ADDR
/* dhcp retry interval ms */
#define DHCP_RETRY_INTERVAL 500
#endif
/**
* LWIP_ARP_ENHANCEMENT==1: bes add for arp
*/
#define LWIP_ARP_ENHANCEMENT 1
/**
* LWIP_NET_STATUS==0: bes add for net flow customize
*/
#define LWIP_NET_STATUS 0
/**
* LWIP_PBUF_NEW_API==1: bes add new PBUF api
*/
#define LWIP_PBUF_NEW_API 1
/**
* LWIP_PBUF_NEW_MEMCPY==1: bes add for PBUF use mymemcpy
*/
#define LWIP_PBUF_NEW_MEMCPY 1
/**
* LWIP_IN_ADDR_TYPE_CSTM==1: bes add for in_addr use u32_t s_addr
*/
#define LWIP_IN_ADDR_TYPE_CSTM 1
/*
* LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname
* field.
*/
#define LWIP_NETIF_HOSTNAME 1
/**
* Loopback demo related options.
*/
#define LWIP_NETIF_LOOPBACK 1
#define LWIP_HAVE_LOOPIF 1
#define LWIP_NETIF_LOOPBACK_MULTITHREADING 1
#define LWIP_LOOPBACK_MAX_PBUFS 8
#define LWIP_TIMERS 1
#define LWIP_TCPIP_TIMEOUT 1
/**
* TCP_RESOURCE_FAIL_RETRY_LIMIT: limit for retrying sending of tcp segment
* on resource failure error returned by driver.
*/
#define TCP_RESOURCE_FAIL_RETRY_LIMIT 50
/*
---------------------------------------
---------- Debugging options ----------
---------------------------------------
*/
#define LWIP_DEBUG
#define DNS_DEBUG LWIP_DBG_OFF
#define PKTPRINT_DEBUG LWIP_DBG_ON
#define ETHARP_DEBUG LWIP_DBG_OFF
#define REENTER_DEBUG LWIP_DBG_OFF
#define ARP_DEBUG LWIP_DBG_OFF
#define DNSCLI_DEBUG LWIP_DBG_ON
#define IPERF_DEBUG LWIP_DBG_ON
#define PING_DEBUG LWIP_DBG_ON
#define IFCONFIG_DEBUG LWIP_DBG_ON
#define SOCKET_ALLOC_DEBUG LWIP_DBG_OFF
#endif /* __LWIPOPTS_H__ */
/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/aos/arch/lwipopts.h
|
C
|
apache-2.0
| 15,218
|
#include "k_api.h"
#include "aos/hal/uart.h"
#include "drv_usart.h"
#include <csi_config.h>
#include <csi_core.h>
#include "pin.h"
#include "k_config.h"
#include "board.h"
#define MAX_BUF_UART_BYTES 128
kbuf_queue_t g_buf_queue_uart;
char g_buf_uart[MAX_BUF_UART_BYTES];
//static uint8_t rx_buffer[1];
extern usart_handle_t console_handle;
usart_handle_t console_handle = NULL;
/* can not get data here
void usart_hal_event_fun(int32_t idx, usart_event_e event);
{
if(idx != CONSOLE_IDX || event != USART_EVENT_RECEIVE_COMPLETE){
return;
}
}*/
int32_t hal_uart_init(uart_dev_t *uart)
{
int32_t ret;
kstat_t err_code;
if(NULL == uart || uart->port != CONSOLE_IDX){
return -1;
}
err_code = krhino_buf_queue_create(&g_buf_queue_uart, "buf_queue_uart",
g_buf_uart, MAX_BUF_UART_BYTES, 1);
if(err_code){
return -1;
}
console_handle = csi_usart_initialize(uart->port, NULL);
/* config the UART */
ret = csi_usart_config(console_handle, 115200, USART_MODE_ASYNCHRONOUS, USART_PARITY_NONE, USART_STOP_BITS_1, USART_DATA_BITS_8);
return ret;
}
int32_t hal_uart_recv_II(uart_dev_t *uart, void *data, uint32_t expect_size,
uint32_t *recv_size, uint32_t timeout)
{
uint8_t *pdata = (uint8_t *)data;
int i = 0;
uint32_t rx_count = 0;
int32_t ret = -1;
size_t rev_size;
if (data == NULL) {
return -1;
}
for (i = 0; i < expect_size; i++)
{
ret = krhino_buf_queue_recv(&g_buf_queue_uart, RHINO_WAIT_FOREVER, &pdata[i], &rev_size);
if((ret == 0) && (rev_size == 1))
{
rx_count++;
}else {
break;
}
}
if (recv_size)
{
*recv_size = rx_count;
}
if(rx_count != 0)
{
ret = 0;
}
else
{
ret = -1;
}
return ret;
}
int32_t hal_uart_send(uart_dev_t *uart, const void *data, uint32_t size, uint32_t timeout)
{
uint32_t i;
uint8_t byte;
uint32_t ret = 0;
for(i=0;i<size;i++)
{
byte = *((uint8_t *)data + i);
ret |= csi_usart_putchar(console_handle, byte);
}
return ret;
}
void hal_reboot(void)
{
}
int32_t hal_uart_finalize(uart_dev_t *uart)
{
}
char uart_input_read(void)
{
uint8_t ch = 0;
csi_usart_getchar(console_handle, &ch);
return (char)ch;
}
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/hal/uart.c
|
C
|
apache-2.0
| 2,383
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_aes.h
* @brief Header File for AES Driver
* @version V1.0
* @date 02. June 2017
* @model aes
******************************************************************************/
#ifndef _CSI_AES_H_
#define _CSI_AES_H_
#include <stdint.h>
#include <drv_common.h>
#include <drv_errno.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for aes handle.
typedef void *aes_handle_t;
/****** AES specific error codes *****/
typedef enum {
AES_ERROR_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported
AES_ERROR_DATA_BITS, ///< Specified number of Data bits not supported
AES_ERROR_ENDIAN ///< Specified endian not supported
} aes_error_e;
/*----- AES Control Codes: Mode -----*/
typedef enum {
AES_MODE_ECB = 0, ///< ECB Mode
AES_MODE_CBC, ///< CBC Mode
AES_MODE_CFB1, ///< CFB1 Mode
AES_MODE_CFB8, ///< CFB8 Mode
AES_MODE_CFB128, ///< CFB128 Mode
AES_MODE_OFB, ///< OFB Mode
AES_MODE_CTR ///< CTR Mode
} aes_mode_e;
/*----- AES Control Codes: Crypto Mode -----*/
typedef enum {
AES_CRYPTO_MODE_ENCRYPT = 0, ///< encrypt Mode
AES_CRYPTO_MODE_DECRYPT, ///< decrypt Mode
} aes_crypto_mode_e;
/*----- AES Control Codes: Mode Parameters: Key length -----*/
typedef enum {
AES_KEY_LEN_BITS_128 = 0, ///< 128 Data bits
AES_KEY_LEN_BITS_192, ///< 192 Data bits
AES_KEY_LEN_BITS_256 ///< 256 Data bits
} aes_key_len_bits_e;
/*----- AES Control Codes: Mode Parameters: Endian -----*/
typedef enum {
AES_ENDIAN_LITTLE = 0, ///< Little Endian
AES_ENDIAN_BIG ///< Big Endian
} aes_endian_mode_e;
/**
\brief AES Status
*/
typedef struct {
uint32_t busy : 1; ///< busy flag
} aes_status_t;
/****** AES Event *****/
typedef enum {
AES_EVENT_CRYPTO_COMPLETE = 0 ///< Encrypt completed
} aes_event_e;
typedef void (*aes_event_cb_t)(int32_t idx, aes_event_e event); ///< Pointer to \ref aes_event_cb_t : AES Event call back.
/**
\brief AES Device Driver Capabilities.
*/
typedef struct {
uint32_t ecb_mode : 1; ///< supports ECB mode
uint32_t cbc_mode : 1; ///< supports CBC mode
uint32_t cfb1_mode : 1; ///< supports CFB1 mode
uint32_t cfb8_mode : 1; ///< supports CFB8 mode
uint32_t cfb128_mode : 1; ///< supports CFB128 mode
uint32_t ofb_mode : 1; ///< supports OFB mode
uint32_t ctr_mode : 1; ///< supports CTR mode
uint32_t bits_128 : 1; ///< supports 128bits key length
uint32_t bits_192 : 1; ///< supports 192bits key length
uint32_t bits_256 : 1; ///< supports 256bits key length
} aes_capabilities_t;
// Function documentation
/**
\brief Initialize AES Interface. 1. Initializes the resources needed for the AES interface 2.registers event callback function
\param[in] idx device id
\param[in] cb_event event callback function \ref aes_event_cb_t
\return if success return aes handle else return NULL
*/
aes_handle_t csi_aes_initialize(int32_t idx, aes_event_cb_t cb_event);
/**
\brief De-initialize AES Interface. stops operation and releases the software resources used by the interface
\param[in] handle aes handle to operate.
\return error code
*/
int32_t csi_aes_uninitialize(aes_handle_t handle);
/**
\brief control aes power.
\param[in] handle aes handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_aes_power_control(aes_handle_t handle, csi_power_stat_e state);
/**
\brief Get driver capabilities.
\param[in] idx device id
\return \ref aes_capabilities_t
*/
aes_capabilities_t csi_aes_get_capabilities(int32_t idx);
/**
\brief config aes mode.
\param[in] handle aes handle to operate.
\param[in] mode \ref aes_mode_e
\param[in] keylen_bits \ref aes_key_len_bits_e
\param[in] endian \ref aes_endian_mode_e
\return error code
*/
int32_t csi_aes_config(aes_handle_t handle,
aes_mode_e mode,
aes_key_len_bits_e keylen_bits,
aes_endian_mode_e endian
);
/**
\brief set crypto key.
\param[in] handle aes handle to operate.
\param[in] context aes information context
\param[in] key Pointer to the key buf
\param[in] key_len Pointer to \ref aes_key_len_bits_e
\param[in] enc \ref aes_crypto_mode_e
\return error code
*/
int32_t csi_aes_set_key(aes_handle_t handle, void *context, void *key, aes_key_len_bits_e key_len, aes_crypto_mode_e enc);
/**
\brief aes ecb encrypt or decrypt
\param[in] handle aes handle to operate.
\param[in] context aes information context
\param[in] in Pointer to the Source data
\param[out] out Pointer to the Result data.
\param[in] len the Source data len.
\return error code
*/
int32_t csi_aes_ecb_crypto(aes_handle_t handle, void *context, void *in, void *out, uint32_t len);
/**
\brief aes cbc encrypt or decrypt
\param[in] handle aes handle to operate.
\param[in] context aes information context
\param[in] in Pointer to the Source data
\param[out] out Pointer to the Result data.
\param[in] len the Source data len.
\param[in] iv Pointer to initialization vector
\return error code
*/
int32_t csi_aes_cbc_crypto(aes_handle_t handle, void *context, void *in, void *out, uint32_t len, uint8_t iv[16]);
/**
\brief aes cfb1 encrypt or decrypt
\param[in] handle aes handle to operate.
\param[in] context aes information context
\param[in] in Pointer to the Source data
\param[out] out Pointer to the Result data.
\param[in] len the Source data len.
\param[in] iv Pointer to initialization vector
\return error code
*/
int32_t csi_aes_cfb1_crypto(aes_handle_t handle, void *context, void *in, void *out, uint32_t len, uint8_t iv[16]);
/**
\brief aes cfb8 encrypt or decrypt
\param[in] handle aes handle to operate.
\param[in] context aes information context
\param[in] in Pointer to the Source data
\param[out] out Pointer to the Result data.
\param[in] len the Source data len.
\param[in] iv Pointer to initialization vector
\return error code
*/
int32_t csi_aes_cfb8_crypto(aes_handle_t handle, void *context, void *in, void *out, uint32_t len, uint8_t iv[16]);
/**
\brief aes cfb128 encrypt or decrypt
\param[in] handle aes handle to operate.
\param[in] context aes information context
\param[in] in Pointer to the Source data
\param[out] out Pointer to the Result data.
\param[in] len the Source data len.
\param[in] iv Pointer to initialization vector
\param[in] num the number of the 128-bit block we have used
\return error code
*/
int32_t csi_aes_cfb128_crypto(aes_handle_t handle, void *context, void *in, void *out, uint32_t len, uint8_t iv[16], uint32_t *num);
/**
\brief aes ofb encrypt or decrypt
\param[in] handle aes handle to operate.
\param[in] context aes information context
\param[in] in Pointer to the Source data
\param[out] out Pointer to the Result data.
\param[in] len the Source data len.
\param[in] iv Pointer to initialization vector
\param[in] num the number of the 128-bit block we have used
\return error code
*/
int32_t csi_aes_ofb_crypto(aes_handle_t handle, void *context, void *in, void *out, uint32_t len, uint8_t iv[16], uint32_t *num);
/**
\brief aes ctr encrypt or decrypt
\param[in] handle aes handle to operate.
\param[in] context aes information context
\param[in] in Pointer to the Source data
\param[out] out Pointer to the Result data.
\param[in] len the Source data len.
\param[in] nonce_counter Pointer to the 128-bit nonce and counter
\param[in] stream_block Pointer to the saved stream-block for resuming
\param[in] num the number of the 128-bit block we have used
\return error code
*/
int32_t csi_aes_ctr_crypto(aes_handle_t handle, void *context, void *in, void *out, uint32_t len, uint8_t nonce_counter[16], uint8_t stream_block[16], uint32_t *num);
/**
\brief Get AES status.
\param[in] handle aes handle to operate.
\return AES status \ref aes_status_t
*/
aes_status_t csi_aes_get_status(aes_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_AES_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_aes.h
|
C
|
apache-2.0
| 9,072
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_common.h
* @brief Header File for Common Driver
* @version V1.0
* @date 19. Feb 2019
* @model common
******************************************************************************/
#ifndef _DRV_COMMON_H_
#define _DRV_COMMON_H_
#include <stdint.h>
#include <drv_errno.h>
#ifdef __cplusplus
extern "C" {
#endif
/// \details driver handle
typedef void *drv_handle_t;
#ifndef CONFIG_PARAM_NOT_CHECK
#define HANDLE_PARAM_CHK(para, err) \
do { \
if ((int64_t)para == (int64_t)NULL) { \
return (err); \
} \
} while (0)
#define HANDLE_PARAM_CHK_NORETVAL(para, err) \
do { \
if ((int64_t)para == (int64_t)NULL) { \
return; \
} \
} while (0)
#else
#define HANDLE_PARAM_CHK(para, err)
#define HANDLE_PARAM_CHK_NORETVAL(para, err)
#endif
/**
\brief General power states
*/
typedef enum {
DRV_POWER_OFF, ///< Power off: no operation possible
DRV_POWER_LOW, ///< Low Power mode: retain state, detect and signal wake-up events
DRV_POWER_FULL, ///< Power on: full operation at maximum performance
DRV_POWER_SUSPEND, ///< Power suspend: power saving operation
} csi_power_stat_e;
#ifdef __cplusplus
}
#endif
#endif /* _DRV_COMMON_H */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_common.h
|
C
|
apache-2.0
| 2,219
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_crc.h
* @brief Header File for CRC Driver
* @version V1.0
* @date 02. June 2017
* @model crc
******************************************************************************/
#ifndef _CSI_CRC_H_
#define _CSI_CRC_H_
#include <stdint.h>
#include <drv_errno.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/****** CRC specific error codes *****/
#define CRC_ERROR_MODE (DRV_ERROR_SPECIFIC + 1) ///< Specified Mode not supported
/// definition for crc handle.
typedef void *crc_handle_t;
/*----- CRC Control Codes: Mode -----*/
typedef enum {
CRC_MODE_CRC8 = 0, ///< Mode CRC8
CRC_MODE_CRC16, ///< Mode CRC16
CRC_MODE_CRC32 ///< Mode CRC32
} crc_mode_e;
/*----- CRC Control Codes: Mode Parameters: Key length -----*/
typedef enum {
CRC_STANDARD_CRC_ROHC = 0, ///< Standard CRC RHOC
CRC_STANDARD_CRC_MAXIM, ///< Standard CRC MAXIAM
CRC_STANDARD_CRC_X25, ///< Standard CRC X25
CRC_STANDARD_CRC_CCITT, ///< Standard CRC CCITT
CRC_STANDARD_CRC_CCITT_FALSE, ///< Standard CRC CCITT-FALSE
CRC_STANDARD_CRC_USB, ///< Standard CRC USB
CRC_STANDARD_CRC_IBM, ///< Standard CRC IBM
CRC_STANDARD_CRC_MODBUS, ///< Standard CRC MODBUS
CRC_STANDARD_CRC_ITU, ///< Standard CRC ITU
CRC_STANDARD_CRC_PMEQ_2, ///< Standard CRC PMEQ_2
CRC_STANDARD_CRC_XMODEM, ///< Standard CRC XMODEM
CRC_STANDARD_CRC_DNP, ///< Standard CRC DNP
CRC_STANDARD_CRC_NONE, ///< Standard CRC NONE
} crc_standard_crc_e;
/**
\brief CRC Status
*/
typedef struct {
uint32_t busy : 1; ///< busy flag
} crc_status_t;
/****** CRC Event *****/
typedef enum {
CRC_EVENT_CALCULATE_COMPLETE = 0, ///< Calculate completed
} crc_event_e;
typedef void (*crc_event_cb_t)(int32_t idx, crc_event_e event); ///< Pointer to \ref crc_event_cb_t : CRC Event call back.
/**
\brief CRC Device Driver Capabilities.
*/
typedef struct {
uint32_t ROHC : 1; ///< supports ROHC mode
uint32_t MAXIM : 1; ///< supports MAXIM mode
uint32_t X25 : 1; ///< supports X25 mode
uint32_t CCITT : 1; ///< supports CCITT mode
uint32_t CCITT_FALSE : 1; ///< supports CCITT-FALSE mode
uint32_t USB : 1; ///< supports USB mode
uint32_t IBM : 1; ///< supports IBM mode
uint32_t MODBUS : 1; ///< supports MODBUS mode
uint32_t ITU : 1; ///< supports ITU mode
uint32_t PMEQ_2 : 1; ///< supports PMEQ_2 mode
uint32_t XMODEM : 1; ///< supports XMODEM mode
uint32_t DNP : 1; ///< supports DNP mode
uint32_t NONE : 1; ///< supports NONE mode
} crc_capabilities_t;
// Function documentation
/**
\brief Initialize CRC Interface. 1. Initializes the resources needed for the CRC interface 2.registers event callback function
\param[in] idx device id
\param[in] cb_event event callback function \ref crc_event_cb_t
\return return crc handle if success
*/
crc_handle_t csi_crc_initialize(int32_t idx, crc_event_cb_t cb_event);
/**
\brief De-initialize CRC Interface. stops operation and releases the software resources used by the interface
\param[in] handle crc handle to operate.
\return error code
*/
int32_t csi_crc_uninitialize(crc_handle_t handle);
/**
\brief control crc power.
\param[in] handle crc handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_crc_power_control(crc_handle_t handle, csi_power_stat_e state);
/**
\brief Get driver capabilities.
\param[in] idx device id
\return \ref crc_capabilities_t
*/
crc_capabilities_t csi_crc_get_capabilities(int32_t idx);
/**
\brief config crc mode.
\param[in] handle crc handle to operate.
\param[in] mode \ref crc_mode_e
\param[in] standard \ref crc_standard_crc_e
\return error code
*/
int32_t csi_crc_config(crc_handle_t handle,
crc_mode_e mode,
crc_standard_crc_e standard
);
/**
\brief calculate crc. this function will pad zero if input data is not word aligned
\param[in] handle crc handle to operate.
\param[in] in Pointer to the input data
\param[out] out Pointer to the result.
\param[in] len intput data len.
\return error code
*/
int32_t csi_crc_calculate(crc_handle_t handle, const void *in, void *out, uint32_t len);
/**
\brief Get CRC status.
\param[in] handle crc handle to operate.
\return CRC status \ref crc_status_t
*/
crc_status_t csi_crc_get_status(crc_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_CRC_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_crc.h
|
C
|
apache-2.0
| 5,275
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_dmac.h
* @brief header file for dmac driver
* @version V1.0
* @date 02. June 2017
* @model dmac
******************************************************************************/
#ifndef _CSI_DMA_H_
#define _CSI_DMA_H_
#include <stdint.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
\brief DMA Driver Capabilities.
*/
typedef struct {
uint32_t unalign_addr : 1; ///< support for unalign address transfer when memory is source
} dma_capabilities_t;
typedef enum {
DMA_STATE_FREE = 0, ///< DMA channel not yet initialized or disabled
DMA_STATE_READY, ///< DMA channel process success and ready for use, but not start yet
DMA_STATE_BUSY, ///< DMA channel process is ongoing
DMA_STATE_DONE, ///< DMA channel transfer done
DMA_STATE_ERROR, ///< DMA channel transfer error
} dma_status_e;
/****** DMA specific error codes *****/
typedef enum {
EDRV_DMA_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported
} dma_error_e;
/****** DMA Event *****/
typedef enum {
DMA_EVENT_TRANSFER_DONE = 0, ///< transfer complete
DMA_EVENT_TRANSFER_HALF_DONE = 1, ///< transfer half done
DMA_EVENT_TRANSFER_MODE_DONE = 2, ///< transfer complete in a certain dma trigger mode.
DMA_EVENT_CAHNNEL_PEND = 3, ///< it happens when there is a low priority channel was preempted by a high priority channel
DMA_EVENT_TRANSFER_ERROR = 4, ///< transfer error
} dma_event_e;
typedef enum {
DMA_ADDR_INC = 0,
DMA_ADDR_DEC,
DMA_ADDR_CONSTANT
} dma_addr_inc_e;
typedef enum {
DMA_MEM2MEM = 0,
DMA_MEM2PERH,
DMA_PERH2MEM,
DMA_PERH2PERH,
} dma_trans_type_e;
typedef enum {
DMA_SINGLE_TRIGGER = 0,
DMA_GROUP_TRIGGER,
DMA_BLOCK_TRIGGER
} dma_trig_trans_mode_e;
typedef enum {
DMA_DIR_DEST = 0,
DMA_DIR_SOURCE
} dma_single_dir_e;
typedef enum {
DMA_ADDR_LITTLE = 0,
DMA_ADDR_BIG
} dma_addr_endian_e;
typedef enum {
DMA_MODE_HARDWARE = 0,
DMA_MODE_SOFTWARE
} dma_channel_req_mode_e;
typedef struct {
dma_addr_inc_e src_inc; ///< source address increment
dma_addr_inc_e dst_inc; ///< destination address increment
dma_addr_endian_e src_endian; ///< source read data little-big endian change control.
dma_addr_endian_e dst_endian; ///< destination write data little-big endian change control.
uint8_t src_tw; ///< source transfer width in byte
uint8_t dst_tw; ///< destination transfer width in byte
uint8_t hs_if; ///< a hardware handshaking interface (optional).
uint8_t preemption; ///< determine whether if a channel can be preempted by a higher priority channel, 0 -- not allow preempt, 1 -- allow preempt.
dma_trans_type_e type; ///< transfer type
dma_trig_trans_mode_e mode; ///< channel trigger mode
dma_channel_req_mode_e ch_mode; ///< software or hardware to tigger dma channel work.
dma_single_dir_e single_dir; ///< after select single mode control for source(read) or destination(write) transfer.
uint32_t group_len; ///< group transaction length (unit: bytes) when use DMA_GROUP_TRIGGER mode.
uint32_t src_reload_en; ///< 1:dma enable src addr auto reload, 0:disable
uint32_t dest_reload_en; ///< 1:dma enable dst addr auto reload, 0:disable
} dma_config_t;
typedef void (*dma_event_cb_t)(int32_t ch, dma_event_e event, void *arg); ///< Pointer to \ref dma_event_cb_t : dmac event call back.
/**
\brief get one free dma channel
\param[in] ch channel num. if -1 then allocate a free channal in this dma
else allocate a fix channal
\return dma channel num. if -1 alloc channle error
*/
int32_t csi_dma_alloc_channel_ex(int32_t ch);
/**
\brief get one free dma channel
\return dma channel num. if -1 alloc channle error
*/
int32_t csi_dma_alloc_channel(void);
/**
\brief control dma power.
\param[in] ch dma channel num
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_dma_power_control(int32_t ch, csi_power_stat_e state);
/**
\brief Get driver capabilities.
\param[in] ch dma channel num
\return \ref dma_capabilities_t
*/
dma_capabilities_t csi_dma_get_capabilities(int32_t ch);
/**
\brief release dma channel and related resources
\param[in] ch dma channel num
\return error code
*/
void csi_dma_release_channel(int32_t ch);
/**
\brief config dma channel
\param[in] ch dma channel num
\param[in] config dma channel transfer configure
\param[in] cb_event Pointer to \ref dma_event_cb_t
\return error code
*/
int32_t csi_dma_config_channel(int32_t ch, dma_config_t *config, dma_event_cb_t cb_event, void *cb_arg);
/**
\brief start generate dma channel signal.
\param[in] ch dma channel num
\param[in] psrcaddr dma transfer source address
\param[in] pdstaddr dma transfer destination address
\param[in] length dma transfer length (unit: bytes).
*/
void csi_dma_start(int32_t ch, void *psrcaddr, void *pdstaddr, uint32_t length);
/**
\brief Stop generate dma channel signal.
\param[in] ch dma channel num
*/
void csi_dma_stop(int32_t ch);
/**
\brief start generate dma channel cyclic transfer.
\param[in] ch dma channel num
\param[in] psrcaddr dma transfer source address
\param[in] pdstaddr dma transfer destination address
\param[in] cycle_len The length of a cycle
\param[in] cycle_num the number of a cycle
\return error code
*/
int32_t csi_dma_cyclic_prep(int32_t ch, void *psrcaddr, void *pdstaddr, uint32_t cycle_len, uint32_t cycle_num);
/**
\brief start generate dma channel cyclic transfer.
\param[in] ch dma channel num
*/
void csi_dma_cyclic_start(int32_t ch);
/**
\brief Stop generate dma channel cyclic transfer.
\param[in] ch dma channel num
*/
void csi_dma_cyclic_stop(int32_t ch);
/**
\brief Get DMA channel status.
\param[in] ch dma channel num
\return DMA status \ref dma_status_e
*/
dma_status_e csi_dma_get_status(int32_t ch);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_DMA_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_dmac.h
|
C
|
apache-2.0
| 6,690
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*
* 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 License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/******************************************************************************
* @file drv_eflash.h
* @brief header file for eflash driver
* @version V1.0
* @date 02. June 2017
* @model eflash
******************************************************************************/
#ifndef _CSI_EFLASH_H_
#define _CSI_EFLASH_H_
#include <stdint.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for eflash handle.
typedef void *eflash_handle_t;
/**
\brief Flash information
*/
typedef struct {
uint32_t start; ///< Chip Start address
uint32_t end; ///< Chip End address (start+size-1)
uint32_t sector_count; ///< Number of sectors
uint32_t sector_size; ///< Uniform sector size in bytes
uint32_t page_size; ///< Optimal programming page size in bytes
uint32_t program_unit; ///< Smallest programmable unit in bytes
uint8_t erased_value; ///< Contents of erased memory (usually 0xFF)
} eflash_info_t;
/**
\brief Flash Status
*/
typedef struct {
uint32_t busy : 1; ///< Flash busy flag
uint32_t error : 1; ///< Read/Program/Erase error flag (cleared on start of next operation)
} eflash_status_t;
/****** EFLASH Event *****/
typedef enum {
EFLASH_EVENT_READY = 0, ///< Flash Ready
EFLASH_EVENT_ERROR, ///< Read/Program/Erase Error
} eflash_event_e;
typedef void (*eflash_event_cb_t)(int32_t idx, eflash_event_e event); ///< Pointer to \ref eflash_event_cb_t : EFLASH Event call back.
/**
\brief Flash Driver Capabilities.
*/
typedef struct {
uint32_t event_ready : 1; ///< Signal Flash Ready event
uint32_t data_width : 2; ///< Data width: 0=8-bit, 1=16-bit, 2=32-bit
uint32_t erase_chip : 1; ///< Supports EraseChip operation
} eflash_capabilities_t;
// Function documentation
/**
\brief Initialize EFLASH Interface. 1. Initializes the resources needed for the EFLASH interface 2.registers event callback function
\param[in] idx device id
\param[in] cb_event event callback function \ref eflash_event_cb_t
\return pointer to eflash handle
*/
eflash_handle_t csi_eflash_initialize(int32_t idx, eflash_event_cb_t cb_event);
/**
\brief De-initialize EFLASH Interface. stops operation and releases the software resources used by the interface
\param[in] handle eflash handle to operate.
\return error code
*/
int32_t csi_eflash_uninitialize(eflash_handle_t handle);
/**
\brief Get driver capabilities.
\param[in] idx device id
\return \ref eflash_capabilities_t
*/
eflash_capabilities_t csi_eflash_get_capabilities(int32_t idx);
/**
\brief control eflash power.
\param[in] handle eflash handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_eflash_power_control(eflash_handle_t handle, csi_power_stat_e state);
/**
\brief Read data from Flash.
\param[in] handle eflash handle to operate.
\param[in] addr Data address.
\param[out] data Pointer to a buffer storing the data read from Flash.
\param[in] cnt Number of data items to read.
\return number of data items read or error code
*/
int32_t csi_eflash_read(eflash_handle_t handle, uint32_t addr, void *data, uint32_t cnt);
/**
\brief Program data to Flash.
\param[in] handle eflash handle to operate.
\param[in] addr Data address.
\param[in] data Pointer to a buffer containing the data to be programmed to Flash.
\param[in] cnt Number of data items to program.
\return number of data items programmed or error code
*/
int32_t csi_eflash_program(eflash_handle_t handle, uint32_t addr, const void *data, uint32_t cnt);
/**
\brief Erase Flash Sector.
\param[in] handle eflash handle to operate.
\param[in] addr Sector address
\return error code
*/
int32_t csi_eflash_erase_sector(eflash_handle_t handle, uint32_t addr);
/**
\brief Erase complete Flash.
\param[in] handle eflash handle to operate.
\return error code
*/
int32_t csi_eflash_erase_chip(eflash_handle_t handle);
/**
\brief Get Flash information.
\param[in] handle eflash handle to operate.
\return Pointer to Flash information \ref eflash_info_t
*/
eflash_info_t *csi_eflash_get_info(eflash_handle_t handle);
/**
\brief Get FLASH status.
\param[in] handle eflash handle to operate.
\return EFLASH status \ref eflash_status_t
*/
eflash_status_t csi_eflash_get_status(eflash_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_EFLASH_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_eflash.h
|
C
|
apache-2.0
| 5,465
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_errno.h
* @brief header file for error num
* @version V1.2
* @date 22. May 2019
******************************************************************************/
#ifndef _DRV_ERRNO_H_
#define _DRV_ERRNO_H_
#include <errno.h>
#ifdef __cplusplus
extern "C" {
#endif
#define ERRNO_DRV_START 0X80
/* driver General error codes */
typedef enum {
DRV_ERROR = ERRNO_DRV_START, ///< Unspecified error
DRV_ERROR_BUSY, ///< Driver is busy
DRV_ERROR_TIMEOUT, ///< Timeout occurred
DRV_ERROR_UNSUPPORTED, ///< Operation not supported
DRV_ERROR_PARAMETER, ///< Parameter error
DRV_ERROR_SPECIFIC ///< Start of driver specific errors
} drv_err_e;
/** Get error type */
#define GET_ERROR_TYPE(errno) \
(error & 0xFF000000 >> 24)
/** Get error module */
#define GET_ERROR_MODULE(error) \
(error & 0x00FF0000 >> 16)
/** Get error API */
#define GET_ERROR_API(error) \
(error & 0x0000FF00 >> 8)
/** Get errno */
#define GET_ERROR_NUM(error) \
(error & 0x000000FF)
#ifndef CSI_DRV_ERRNO_BASE
#define CSI_DRV_ERRNO_BASE 0x81000000
#endif
/** driver module id definition*/
#define CSI_DRV_ERRNO_GPIO_BASE 0x81010000
#define CSI_DRV_ERRNO_USART_BASE 0x81020000
#define CSI_DRV_ERRNO_SPI_BASE 0x81030000
#define CSI_DRV_ERRNO_IIC_BASE 0x81040000
#define CSI_DRV_ERRNO_PWM_BASE 0x81050000
#define CSI_DRV_ERRNO_RTC_BASE 0x81060000
#define CSI_DRV_ERRNO_TIMER_BASE 0x81070000
#define CSI_DRV_ERRNO_WDT_BASE 0x81080000
#define CSI_DRV_ERRNO_AES_BASE 0x81090000
#define CSI_DRV_ERRNO_CRC_BASE 0x810A0000
#define CSI_DRV_ERRNO_RSA_BASE 0x810B0000
#define CSI_DRV_ERRNO_SHA_BASE 0x810C0000
#define CSI_DRV_ERRNO_TRNG_BASE 0x810D0000
#define CSI_DRV_ERRNO_EFLASH_BASE 0x810E0000
#define CSI_DRV_ERRNO_DMA_BASE 0x810F0000
#define CSI_DRV_ERRNO_NORFLASH_BASE 0x81100000
#define CSI_DRV_ERRNO_INTC_BASE 0x81110000
#define CSI_DRV_ERRNO_SPU_BASE 0x81120000
#define CSI_DRV_ERRNO_ADC_BASE 0x81130000
#define CSI_DRV_ERRNO_PMU_BASE 0x81140000
#define CSI_DRV_ERRNO_BMU_BASE 0x81150000
#define CSI_DRV_ERRNO_ETB_BASE 0x81160000
#define CSI_DRV_ERRNO_I2S_BASE 0x81170000
#define CSI_DRV_ERRNO_USI_BASE 0x81180000
#define CSI_DRV_ERRNO_SPIFLASH_BASE 0x81190000
#define CSI_DRV_ERRNO_ACMP_BASE 0x811A0000
#define CSI_DRV_ERRNO_MAILBOX_BASE 0x811B0000
#define CSI_DRV_ERRNO_EFUSEC_BASE 0x811C0000
#define CSI_DRV_ERRNO_CODEC_BASE 0x811D0000
#define CSI_DRV_ERRNO_DPU_BASE 0x811E0000
#define CSI_DRV_ERRNO_VPU_BASE 0x811F0000
#define CSI_DRV_ERRNO_CAMERA_BASE 0x81200000
#define CSI_DRV_ERRNO_MIPI_CSI_BASE 0x81210000
#define CSI_DRV_ERRNO_MIPI_CSI_READER_BASE 0x81220000
#define CSI_DRV_ERRNO_GMAC_BASE 0x81230000
#define CSI_DRV_ERRNO_ETHPHY_BASE 0x81240000
#define CSI_DRV_ERRNO_QW_EFUSE_BASE 0x81250000
#define CSI_DRV_ERRNO_RESET_BASE 0x81260000
#ifdef __cplusplus
}
#endif
#endif /* CSI_DRV_ERRNO_H */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_errno.h
|
C
|
apache-2.0
| 3,497
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_gpio.h
* @brief header file for gpio driver
* @version V1.0
* @date 02. June 2017
* @model gpio
******************************************************************************/
#ifndef _CSI_GPIO_H_
#define _CSI_GPIO_H_
#include <stdint.h>
#include <stdbool.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for gpio pin handle.
typedef void *gpio_pin_handle_t;
/****** GPIO specific error codes *****/
typedef enum {
GPIO_ERROR_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported
GPIO_ERROR_DIRECTION, ///< Specified direction not supported
GPIO_ERROR_IRQ_MODE, ///< Specified irq mode not supported
} gpio_error_e;
/*----- GPIO Control Codes: Mode -----*/
typedef enum {
GPIO_MODE_PULLNONE = 0, ///< pull none for input
GPIO_MODE_PULLUP, ///< pull up for input
GPIO_MODE_PULLDOWN, ///< pull down for input
GPIO_MODE_OPEN_DRAIN, ///< open drain mode for output
GPIO_MODE_PUSH_PULL, ///< push-pull mode for output
} gpio_mode_e;
/*----- GPIO Control Codes: Mode Parameters: Data Bits -----*/
typedef enum {
GPIO_DIRECTION_INPUT = 0, ///< gpio as input
GPIO_DIRECTION_OUTPUT, ///< gpio as output
} gpio_direction_e;
/*----- GPIO Control Codes: Mode Parameters: Parity -----*/
typedef enum {
GPIO_IRQ_MODE_RISING_EDGE = 0, ///< interrupt mode for rising edge
GPIO_IRQ_MODE_FALLING_EDGE, ///< interrupt mode for falling edge
GPIO_IRQ_MODE_DOUBLE_EDGE, ///< interrupt mode for double edge
GPIO_IRQ_MODE_LOW_LEVEL, ///< interrupt mode for low level
GPIO_IRQ_MODE_HIGH_LEVEL, ///< interrupt mode for high level
} gpio_irq_mode_e;
typedef void (*gpio_event_cb_t)(int32_t idx); ///< gpio Event call back.
/**
\brief Initialize GPIO handle.
\param[in] gpio_pin gpio pin idx.
\param[in] cb_event event callback function \ref gpio_event_cb_t
\return gpio_pin_handle
*/
gpio_pin_handle_t csi_gpio_pin_initialize(int32_t gpio_pin, gpio_event_cb_t cb_event);
/**
\brief De-initialize GPIO pin handle.stops operation and releases the software resources used by the handle.
\param[in] handle gpio pin handle to operate.
\return error code
*/
int32_t csi_gpio_pin_uninitialize(gpio_pin_handle_t handle);
/**
\brief control gpio power.
\param[in] handle gpio handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_gpio_power_control(gpio_pin_handle_t handle, csi_power_stat_e state);
/**
\brief config pin mode
\param[in] pin gpio pin handle to operate.
\param[in] mode \ref gpio_mode_e
\return error code
*/
int32_t csi_gpio_pin_config_mode(gpio_pin_handle_t handle,
gpio_mode_e mode);
/**
\brief config pin direction
\param[in] pin gpio pin handle to operate.
\param[in] dir \ref gpio_direction_e
\return error code
*/
int32_t csi_gpio_pin_config_direction(gpio_pin_handle_t handle,
gpio_direction_e dir);
/**
\brief config pin
\param[in] pin gpio pin handle to operate.
\param[in] mode \ref gpio_mode_e
\param[in] dir \ref gpio_direction_e
\return error code
*/
int32_t csi_gpio_pin_config(gpio_pin_handle_t handle,
gpio_mode_e mode,
gpio_direction_e dir);
/**
\brief Set one or zero to the selected GPIO pin.
\param[in] pin gpio pin handle to operate.
\param[in] value value to be set
\return error code
*/
int32_t csi_gpio_pin_write(gpio_pin_handle_t handle, bool value);
/**
\brief Get the value of selected GPIO pin.
\param[in] pin gpio pin handle to operate.
\param[out] value buffer to store the pin value
\return error code
*/
int32_t csi_gpio_pin_read(gpio_pin_handle_t handle, bool *value);
/**
\brief set GPIO interrupt mode.
\param[in] pin gpio pin handle to operate.
\param[in] mode irq mode to be set
\param[in] enable enable flag
\return error code
*/
int32_t csi_gpio_pin_set_irq(gpio_pin_handle_t handle, gpio_irq_mode_e mode, bool enable);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_GPIO_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_gpio.h
|
C
|
apache-2.0
| 4,697
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_i2s.h
* @brief header file for i2s driver
* @version V1.0
* @date 02. June 2017
* @model i2s
******************************************************************************/
#ifndef _DRV_I2S_H_
#define _DRV_I2S_H_
#include <stdint.h>
#include <stdbool.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for i2s handle.
typedef void *i2s_handle_t;
/****** i2s specific error codes *****/
typedef enum {
I2S_ERROR_SYNCHRONIZATION = (DRV_ERROR_SPECIFIC + 1), ///< Specified Synchronization not supported
I2S_ERROR_PROTOCOL, ///< Specified Protocol not supported
I2S_ERROR_DATA_SIZE, ///< Specified Data size not supported
I2S_ERROR_BIT_ORDER, ///< Specified Bit order not supported
I2S_ERROR_MONO_MODE, ///< Specified Mono mode not supported
I2S_ERROR_COMPANDING, ///< Specified Companding not supported
I2S_ERROR_CLOCK_POLARITY, ///< Specified Clock polarity not supported
I2S_ERROR_AUDIO_FREQ, ///< Specified Audio frequency not supported
I2S_ERROR_MCLK_PIN, ///< Specified MCLK Pin setting not supported
I2S_ERROR_MCLK_PRESCALER, ///< Specified MCLK Prescaler not supported
I2S_ERROR_FRAME_LENGHT, ///< Specified Frame length not supported
I2S_ERROR_FRAME_SYNC_WIDTH, ///< Specified Frame Sync width not supported
I2S_ERROR_FRAME_SYNC_POLARITY, ///< Specified Frame Sync polarity not supported
I2S_ERROR_FRAME_SYNC_EARLY, ///< Specified Frame Sync early not supported
I2S_ERROR_SLOT_COUNT, ///< Specified Slot count not supported
I2S_ERROR_SLOT_SIZE, ///< Specified Slot size not supported
I2S_ERROR_SLOT_OFFESET ///< Specified Slot offset not supported
} i2s_error_e;
typedef enum {
I2S_MODE_TX_MASTER, ///< i2s transmitter master mode
I2S_MODE_TX_SLAVE, ///< i2s transmitter slave mode
I2S_MODE_RX_MASTER, ///< i2s receiver master mode
I2S_MODE_RX_SLAVE, ///< i2s receiver slave mode
///< full duplex mode only for idx0, if used full duplex mode, rx and tx must used same rate, mclk_freq, sclk_freq.
I2S_MODE_FULL_DUPLEX_MASTER, ///< i2s full duplex master mode
I2S_MODE_FULL_DUPLEX_SLAVE, ///< i2s full duplex slave mode
} i2s_mode_e;
typedef enum {
I2S_PROTOCOL_I2S, ///< i2s bus
I2S_PROTOCOL_MSB_JUSTIFIED, ///< MSB (left) justified
I2S_PROTOCOL_LSB_JUSTIFIED, ///< LSB (right) justified
I2S_PROTOCOL_PCM,
} i2s_protocol_e;
typedef enum {
I2S_SAMPLE_16BIT,
I2S_SAMPLE_24BIT,
I2S_SAMPLE_32BIT,
} i2s_sample_width_e;
typedef enum {
I2S_LEFT_POLARITY_LOW,
I2S_LEFT_POLARITY_HITH,
} i2s_left_channel_polarity_e;
typedef enum {
I2S_SCLK_32FS, ///< SCLK Freq = 32 * sample_rate, freq must >= sample_rate * sample_witch
I2S_SCLK_48FS,
I2S_SCLK_64FS,
I2S_SCLK_16FS,
} i2s_sclk_freq_e;
typedef enum {
I2S_MCLK_256FS = 256,
I2S_MCLK_384FS = 384,
} i2s_mclk_freq_e;
/**
\brief I2S Status
*/
typedef struct {
uint32_t tx_runing : 1; ///< Transmitter runing flag
uint32_t rx_runing : 1; ///< Receiver runing flag
uint32_t tx_fifo_empty : 1; ///< Transmit data underflow detected (cleared on start of next send operation)
uint32_t rx_fifo_full : 1; ///< Receive data overflow detected (cleared on start of next receive operation)
uint32_t frame_error : 1; ///< Sync Frame error detected (cleared on start of next send/receive operation)
} i2s_status_t;
/****** I2S Event *****/
typedef enum {
I2S_EVENT_SEND_COMPLETE = (0x01 << 0), ///< Send completed
I2S_EVENT_RECEIVE_COMPLETE = (0x01 << 1), ///< Receive completed
I2S_EVENT_TX_BUFFER_EMPYT = (0x01 << 2), ///< Transmit buffer empty
I2S_EVENT_TX_UNDERFLOW = (0x01 << 3), ///< Transmit data not available
I2S_EVENT_RX_BUFFER_FULL = (0x01 << 4),
I2S_EVENT_RX_OVERFLOW = (0x01 << 5), ///< Receive data overflow
I2S_EVENT_FRAME_ERROR = (0x01 << 6), ///< Sync Frame error in Slave mode (optional)
} i2s_event_e;
/**
\brief i2s ctrl cmd.
*/
typedef enum {
I2S_STREAM_PAUSE,
I2S_STREAM_RESUME,
I2S_STREAM_STOP,
I2S_STREAM_START,
} i2s_ctrl_e;
/**
\brief i2s Driver Capabilities.
*/
typedef struct {
uint32_t protocol_user : 1; ///< supports user defined Protocol
uint32_t protocol_i2s : 1; ///< supports I2S Protocol
uint32_t protocol_justified : 1; ///< supports MSB/LSB justified Protocol
uint32_t protocol_pcm : 1;
uint32_t mono_mode : 1; ///< supports Mono mode
uint32_t full_duplex : 1;
uint32_t mclk_pin : 1; ///< supports MCLK (Master Clock) pin
uint32_t event_frame_error : 1; ///< supports Frame error event: ARM_SAI_EVENT_FRAME_ERROR
} i2s_capabilities_t;
typedef enum {
I2S_RX_RIGHT_CHANNEL,
I2S_RX_LEFT_CHANNEL,
} i2s_rx_mono_channel;
typedef struct {
i2s_mode_e mode;
i2s_protocol_e protocol;
i2s_sample_width_e width;
i2s_left_channel_polarity_e left_polarity; ///< set ws signel left channle polarity
i2s_sclk_freq_e sclk_freq; ///< I2S sclk freq select. example:32fs = 32 * sample_rate
i2s_mclk_freq_e mclk_freq; ///< I2S mclk freq select. example:256fs = 256 * sample_rate
int32_t tx_mono_enable; ///< used for tx or full duplex mode, tx mono mode enable. 1 eanble, 0 disable
int32_t rx_mono_enable; ///< used for rx or full duplex mode,rx mono mode enable. 1 eanble, 0 disable
i2s_rx_mono_channel rx_mono_select_ch; ///< used for rx or full duplex mode,
} i2s_config_type_t;
typedef struct {
i2s_config_type_t cfg;
uint32_t rate;
uint32_t tx_period; ///< i2s send bytes tigger cb
uint32_t rx_period; ///< i2s receive bytes tigger cb
uint8_t *tx_buf; ///< i2s send buf
uint32_t tx_buf_length; ///< i2s send buf length
uint8_t *rx_buf; ///< i2s recv buf
uint32_t rx_buf_length; ///< i2s recv buf length
} i2s_config_t;
typedef void (*i2s_event_cb_t)(int32_t idx, i2s_event_e event, void *arg); ///< Pointer to \ref i2s_event_cb_t : i2s Event call back.
/**
\brief Initialize I2S Interface. 1. Initializes the resources needed for the I2S index 2.registers event callback function
\param[in] idx i2s index
\param[in] cb_event Pointer to \ref i2s_event_cb_t
\param[in] cb_arg event callback arg
\return pointer to i2s instances
*/
i2s_handle_t csi_i2s_initialize(int32_t idx, i2s_event_cb_t cb_event, void *cb_arg);
/**
\brief De-initialize I2S Interface. stops operation and releases the software resources used by the interface
\param[in] handle i2s handle to operate.
\return 0 for success, negative for error code
*/
int32_t csi_i2s_uninitialize(i2s_handle_t handle);
/**
\brief enable the i2s module
\param[in] handle i2s handle to operate.
\param[in] en: 1 enable, 0 disable
\return none
*/
void csi_i2s_enable(i2s_handle_t handle, int en);
/**
\brief Get driver capabilities.
\param[in] idx i2s index.
\return \ref i2s_capabilities_t
*/
i2s_capabilities_t csi_i2s_get_capabilities(int32_t idx);
/**
\brief config i2s attributes.
\param[in] handle i2s handle to operate.
\param[in] config i2s config.
\return 0 for success, negative for error code
*/
int32_t csi_i2s_config(i2s_handle_t handle, i2s_config_t *config);
/**
\brief sending data to i2s transmitter.
\param[in] handle i2s handle to operate.
\param[in] data Pointer to buffer for data to send
\param[in] data_size size of tranmitter data
\return send data size.(bytes)
*/
uint32_t csi_i2s_send(i2s_handle_t handle, const uint8_t *data, uint32_t length);
/**
\brief receiving data from i2s receiver.
\param[in] handle i2s handle to operate.
\param[in] data Pointer to buffer for data to receive from i2s receiver
\param[in] data_size size of receiver data
\return receive data size.(bytes)
*/
uint32_t csi_i2s_receive(i2s_handle_t handle, uint8_t *buf, uint32_t length);
/**
\brief control the i2s transfer.
\param[in] handle i2s handle to operate.
\param[in] cmd i2s ctrl command
\return 0 for success, negative for error code
*/
int32_t csi_i2s_send_ctrl(i2s_handle_t handle, i2s_ctrl_e cmd);
/**
\brief control the i2s receive.
\param[in] handle i2s handle to operate.
\param[in] cmd i2s ctrl command
\return 0 for success, negative for error code
*/
int32_t csi_i2s_receive_ctrl(i2s_handle_t handle, i2s_ctrl_e cmd);
/**
\brief Get i2s status.
\param[in] handle i2s handle to operate.
\return i2s status \ref i2s_status_e
*/
i2s_status_t csi_i2s_get_status(i2s_handle_t handle);
/**
\brief control I2S power.
\param[in] handle i2s handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_i2s_power_control(i2s_handle_t handle, csi_power_stat_e state);
#ifdef __cplusplus
}
#endif
#endif /* _DRV_I2S_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_i2s.h
|
C
|
apache-2.0
| 10,025
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*
* 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 License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/******************************************************************************
* @file drv_iic.h
* @brief header file for iic driver
* @version V1.0
* @date 02. June 2017
* @model iic
******************************************************************************/
#ifndef _CSI_IIC_H_
#define _CSI_IIC_H_
#include <stdint.h>
#include <stdbool.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for iic handle.
typedef void *iic_handle_t;
/*----- IIC Control Codes: Mode -----*/
typedef enum {
IIC_MODE_MASTER, ///< IIC Master
IIC_MODE_SLAVE ///< IIC Slave
} iic_mode_e;
/*----- IIC Control Codes: IIC Bus Speed -----*/
typedef enum {
IIC_BUS_SPEED_STANDARD = 0, ///< Standard Speed (100kHz)
IIC_BUS_SPEED_FAST = 1, ///< Fast Speed (400kHz)
IIC_BUS_SPEED_FAST_PLUS = 2, ///< Fast+ Speed ( 1MHz)
IIC_BUS_SPEED_HIGH = 3 ///< High Speed (3.4MHz)
} iic_speed_e;
/*----- IIC Control Codes: IIC Address Mode -----*/
typedef enum {
IIC_ADDRESS_7BIT = 0, ///< 7-bit address mode
IIC_ADDRESS_10BIT = 1 ///< 10-bit address mode
} iic_address_mode_e;
/**
\brief IIC Status
*/
typedef struct {
uint32_t busy : 1; ///< Transmitter/Receiver busy flag
uint32_t mode : 1; ///< Mode: 0=Slave, 1=Master
uint32_t direction : 1; ///< Direction: 0=Transmitter, 1=Receiver
uint32_t general_call : 1; ///< General Call(address 0) indication (cleared on start of next Slave operation)
uint32_t arbitration_lost : 1; ///< Master lost arbitration(in case of multi-masters) (cleared on start of next Master operation)
uint32_t bus_error : 1; ///< Bus error detected (cleared on start of next Master/Slave operation)
} iic_status_t;
/****** IIC Event *****/
typedef enum {
IIC_EVENT_TRANSFER_DONE = 0, ///< Master/Slave Transmit/Receive finished
IIC_EVENT_TRANSFER_INCOMPLETE = 1, ///< Master/Slave Transmit/Receive incomplete transfer
IIC_EVENT_SLAVE_TRANSMIT = 2, ///< Slave Transmit operation requested
IIC_EVENT_SLAVE_RECEIVE = 3, ///< Slave Receive operation requested
IIC_EVENT_ADDRESS_NACK = 4, ///< Address not acknowledged from Slave
IIC_EVENT_GENERAL_CALL = 5, ///< General Call indication
IIC_EVENT_ARBITRATION_LOST = 6, ///< Master lost arbitration
IIC_EVENT_BUS_ERROR = 7, ///< Bus error detected (START/STOP at illegal position)
IIC_EVENT_BUS_CLEAR = 8 ///< Bus clear finished
} iic_event_e;
typedef void (*iic_event_cb_t)(int32_t idx, iic_event_e event); ///< Pointer to \ref iic_event_cb_t : IIC Event call back.
/**
\brief IIC Driver Capabilities.
*/
typedef struct {
uint32_t address_10_bit : 1; ///< supports 10-bit addressing
} iic_capabilities_t;
/**
\brief Initialize IIC Interface specified by pins. \n
1. Initializes the resources needed for the IIC interface 2.registers event callback function
\param[in] idx iic index
\param[in] cb_event event callback function \ref iic_event_cb_t
\return 0 for success, negative for error code
*/
iic_handle_t csi_iic_initialize(int32_t idx, iic_event_cb_t cb_event);
/**
\brief De-initialize IIC Interface. stops operation and releases the software resources used by the interface
\param[in] handle iic handle to operate.
\return 0 for success, negative for error code
*/
int32_t csi_iic_uninitialize(iic_handle_t handle);
/**
\brief Get driver capabilities.
\param[in] idx iic index
\return \ref iic_capabilities_t
*/
iic_capabilities_t csi_iic_get_capabilities(int32_t idx);
/**
\brief config iic attributes.
\param[in] handle iic handle to operate.
\param[in] mode iic mode \ref iic_mode_e. if negative, then this attribute not changed.
\param[in] speed iic speed \ref iic_speed_e. if negative, then this attribute not changed.
\param[in] addr_mode iic address mode \ref iic_address_mode_e. if negative, then this attribute not changed.
\param[in] slave_addr iic address of slave. if negative, then this attribute not changed.
\return 0 for success, negative for error code
*/
int32_t csi_iic_config(iic_handle_t handle,
iic_mode_e mode,
iic_speed_e speed,
iic_address_mode_e addr_mode,
int32_t slave_addr);
/**
\brief Start transmitting data as IIC Master.
This function is non-blocking,\ref iic_event_e is signaled when transfer completes or error happens.
\ref csi_iic_get_status can get operating status.
\param[in] handle iic handle to operate.
\param[in] devaddr iic addrress of slave device. |_BIT[7:1]devaddr_|_BIT[0]R/W_|
eg: BIT[7:0] = 0xA0, devaddr = 0x50.
\param[in] data data to send to IIC Slave
\param[in] num Number of data items to send
\param[in] xfer_pending Transfer operation is pending - Stop condition will not be generated
Master generates STOP condition (if xfer_pending is "false")
\return 0 for success, negative for error code
*/
int32_t csi_iic_master_send(iic_handle_t handle, uint32_t devaddr, const void *data, uint32_t num, bool xfer_pending);
/**
\brief Start receiving data as IIC Master.
This function is non-blocking,\ref iic_event_e is signaled when transfer completes or error happens.
\ref csi_iic_get_status can get operating status.
\param[in] handle iic handle to operate.
\param[in] devaddr iic addrress of slave device.
\param[out] data Pointer to buffer for data to receive from IIC receiver
\param[in] num Number of data items to receive
\param[in] xfer_pending Transfer operation is pending - Stop condition will not be generated
\return 0 for success, negative for error code
*/
int32_t csi_iic_master_receive(iic_handle_t handle, uint32_t devaddr, void *data, uint32_t num, bool xfer_pending);
/**
\brief Start transmitting data as IIC Slave.
This function is non-blocking,\ref iic_event_e is signaled when transfer completes or error happens.
\ref csi_iic_get_status can get operating status.
\param[in] handle iic handle to operate.
\param[in] data Pointer to buffer with data to transmit to IIC Master
\param[in] num Number of data items to send
\return 0 for success, negative for error code
*/
int32_t csi_iic_slave_send(iic_handle_t handle, const void *data, uint32_t num);
/**
\brief Start receiving data as IIC Slave.
This function is non-blocking,\ref iic_event_e is signaled when transfer completes or error happens.
\ref csi_iic_get_status can get operating status.
\param[in] handle iic handle to operate.
\param[out] data Pointer to buffer for data to receive from IIC Master
\param[in] num Number of data items to receive
\return 0 for success, negative for error code
*/
int32_t csi_iic_slave_receive(iic_handle_t handle, void *data, uint32_t num);
/**
\brief abort transfer.
\param[in] handle iic handle to operate.
\return 0 for success, negative for error code
*/
int32_t csi_iic_abort_transfer(iic_handle_t handle);
/**
\brief Get IIC status.
\param[in] handle iic handle to operate.
\return IIC status \ref iic_status_t
*/
iic_status_t csi_iic_get_status(iic_handle_t handle);
/**
\brief control IIC power.
\param[in] handle iic handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_iic_power_control(iic_handle_t handle, csi_power_stat_e state);
/**
\brief config iic mode.
\param[in] handle iic handle to operate.
\param[in] mode \ref iic_mode_e
\return error code
*/
int32_t csi_iic_config_mode(iic_handle_t handle, iic_mode_e mode);
/**
\brief config iic speed.
\param[in] handle iic handle to operate.
\param[in] speed \ref iic_speed_e
\return error code
*/
int32_t csi_iic_config_speed(iic_handle_t handle, iic_speed_e speed);
/**
\brief config iic address mode.
\param[in] handle iic handle to operate.
\param[in] addr_mode \ref iic_address_mode_e
\return error code
*/
int32_t csi_iic_config_addr_mode(iic_handle_t handle, iic_address_mode_e addr_mode);
/**
\brief config iic slave address.
\param[in] handle iic handle to operate.
\param[in] slave_addr slave address
\return error code
*/
int32_t csi_iic_config_slave_addr(iic_handle_t handle, int32_t slave_addr);
/**
\brief Get IIC transferred data count.
\param[in] handle iic handle to operate.
\return the number of the currently transferred data items
*/
uint32_t csi_iic_get_data_count(iic_handle_t handle);
/**
\brief Send START command.
\param[in] handle iic handle to operate.
\return error code
*/
int32_t csi_iic_send_start(iic_handle_t handle);
/**
\brief Send STOP command.
\param[in] handle iic handle to operate.
\return error code
*/
int32_t csi_iic_send_stop(iic_handle_t handle);
/**
\brief Reset IIC peripheral.
\param[in] handle iic handle to operate.
\return error code
*/
int32_t csi_iic_reset(iic_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_IIC_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_iic.h
|
C
|
apache-2.0
| 10,318
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*
* 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 License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/******************************************************************************
* @file drv_intc.h
* @brief header file for intc driver
* @version V1.0
* @date 02. June 2017
* @model intc
******************************************************************************/
#ifndef _CSI_INTC_H_
#define _CSI_INTC_H_
#include <stdint.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum int_trigger_mode_t {
INT_MODE_LOW_LEVEL,
INT_MODE_HIGH_LEVEL,
INT_MODE_RISING_EDGE,
INT_MODE_FALLING_EDGE,
INT_MODE_DOUBLE_EDGE,
}
int_trigger_mode_t;
/**
\brief initialize the INTC interrupt controller
\param [in] prio_bits the priority bits of INTC interrupt controller.
*/
void csi_intc_init(void);
/**
\brief Enable External Interrupt
\details Enables a device-specific interrupt in the INTC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
void csi_intc_enable_irq(int32_t IRQn);
/**
\brief Disable External Interrupt
\details Disables a device-specific interrupt in the INTC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
void csi_intc_disable_irq(int32_t IRQn);
/**
\brief Get Pending Interrupt
\details Reads the pending register in the INTC 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.
*/
uint32_t csi_intc_get_pending_irq(int32_t IRQn);
/**
\brief Set Pending Interrupt
\details Sets the pending bit of an external interrupt.
\param [in] IRQn Interrupt number. Value cannot be negative.
*/
void csi_intc_set_pending_irq(int32_t IRQn);
/**
\brief Clear Pending Interrupt
\details Clears the pending bit of an external interrupt.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
void csi_intc_clear_pending_irq(int32_t IRQn);
/**
\brief Get Wake up Interrupt
\details Reads the wake up register in the INTC and returns the pending bit for the specified interrupt.
\param [in] IRQn Interrupt number.
\return 0 Interrupt is not set as wake up interrupt.
\return 1 Interrupt is set as wake up interrupt.
*/
uint32_t csi_intc_get_wakeup_irq(int32_t IRQn);
/**
\brief Set Wake up Interrupt
\details Sets the wake up bit of an external interrupt.
\param [in] IRQn Interrupt number. Value cannot be negative.
*/
void csi_intc_set_wakeup_irq(int32_t IRQn);
/**
\brief Clear Wake up Interrupt
\details Clears the wake up bit of an external interrupt.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
void csi_intc_clear_wakeup_irq(int32_t IRQn);
/**
\brief Get Active Interrupt
\details Reads the active register in the INTC and returns the active bit for the device specific interrupt.
\param [in] IRQn Device specific interrupt number.
\return 0 Interrupt status is not active.
\return 1 Interrupt status is active.
\note IRQn must not be negative.
*/
uint32_t csi_intc_get_active(int32_t IRQn);
/**
\brief Set Threshold register
\details set the threshold register in the INTC.
\param [in] VectThreshold specific vecter threshold.
\param [in] PrioThreshold specific priority threshold.
*/
void csi_intc_set_threshold(uint32_t VectThreshold, uint32_t PrioThreshold);
/**
\brief Set Interrupt Priority
\details 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.
*/
void csi_intc_set_prio(int32_t IRQn, uint32_t priority);
/**
\brief Get Interrupt Priority
\details 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.
*/
uint32_t csi_intc_get_prio(int32_t IRQn);
/**
\brief funciton is acknowledge the IRQ. this interface is internally used by irq system
\param[in] irq irq number to operate
\return 0 on success; -1 on failure
*/
int csi_intc_ack_irq(int32_t IRQn);
/**
\briefThis function is set the attributes of an IRQ.
\param[in] irq irq number to operate
\param[in] priority interrupt priority
\param[in] trigger_mode interrupt trigger_mode
\return 0 on success; -1 on failure
*/
int csi_intc_set_attribute(int32_t IRQn, uint32_t priority, int_trigger_mode_t trigger_mode);
/**
\brief Set interrupt handler
\details Set the interrupt handler according to the interrupt num, the handler will be filled in g_irqvector[].
\param [in] IRQn Interrupt number.
\param [in] handler Interrupt handler.
*/
void csi_intc_set_vector(int32_t IRQn, uint32_t handler);
/**
\brief Get interrupt handler
\details Get the address of interrupt handler function.
\param [in] IRQn Interrupt number.
*/
uint32_t csi_intc_get_vector(int32_t IRQn);
#endif /* _CSI_INTC_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_intc.h
|
C
|
apache-2.0
| 6,099
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_irq.h
* @brief header File for IRQ Driver
* @version V1.0
* @date 21. Dec 2018
* @model irq
******************************************************************************/
#include <stdint.h>
/**
\brief enable irq.
\param[in] irq_num Number of IRQ.
\return None.
*/
void drv_irq_enable(uint32_t irq_num);
/**
\brief disable irq.
\param[in] irq_num Number of IRQ.
\return None.
*/
void drv_irq_disable(uint32_t irq_num);
/**
\brief register irq handler.
\param[in] irq_num Number of IRQ.
\param[in] irq_handler IRQ Handler.
\return None.
*/
void drv_irq_register(uint32_t irq_num, void *irq_handler);
/**
\brief unregister irq handler.
\param[in] irq_num Number of IRQ.
\param[in] irq_handler IRQ Handler.
\return None.
*/
void drv_irq_unregister(uint32_t irq_num);
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_irq.h
|
C
|
apache-2.0
| 1,033
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_pmu.h
* @brief header file for pmu driver
* @version V1.0
* @date 02. June 2017
* @model pmu
******************************************************************************/
#ifndef _CSI_PMU_H_
#define _CSI_PMU_H_
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for pmu handle.
typedef void *pmu_handle_t;
/****** PMU specific error codes *****/
typedef enum {
EDRV_PMU_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported
} pmu_error_e;
/*----- PMU Control Codes: Mode -----*/
typedef enum {
PMU_MODE_RUN = 0, ///< Running mode
PMU_MODE_SLEEP, ///< Sleep mode
PMU_MODE_DOZE, ///< Doze mode
PMU_MODE_DORMANT, ///< Dormant mode
PMU_MODE_STANDBY, ///< Standby mode
PMU_MODE_SHUTDOWN ///< Shutdown mode
} pmu_mode_e;
/*----- PMU Control Codes: Wakeup type -----*/
typedef enum {
PMU_WAKEUP_TYPE_PULSE = 0, ///< Pulse interrupt
PMU_WAKEUP_TYPE_LEVEL ///< Level interrupt
} pmu_wakeup_type_e;
/*----- PMU Control Codes: Wakeup polarity -----*/
typedef enum {
PMU_WAKEUP_POL_LOW = 0, ///< Low or negedge
PMU_WAKEUP_POL_HIGH ///< High or posedge
} pmu_wakeup_pol_e;
/****** PMU Event *****/
typedef enum {
PMU_EVENT_SLEEP_DONE = 0, ///< Send completed; however PMU may still transmit data
PMU_EVENT_PREPARE_SLEEP = 1
} pmu_event_e;
typedef void (*pmu_event_cb_t)(int32_t idx, pmu_event_e event, pmu_mode_e mode); ///< Pointer to \ref pmu_event_cb_t : PMU Event call back.
/**
\brief Initialize PMU Interface. 1. Initializes the resources needed for the PMU interface 2.registers event callback function
\param[in] idx the id of the pmu
\param[in] cb_event Pointer to \ref pmu_event_cb_t
\return return pmu handle if success
*/
pmu_handle_t csi_pmu_initialize(int32_t idx, pmu_event_cb_t cb_event);
/**
\brief De-initialize PMU Interface. stops operation and releases the software resources used by the interface
\param[in] handle pmu handle to operate.
\return error code
*/
int32_t csi_pmu_uninitialize(pmu_handle_t handle);
/**
\brief choose the pmu mode to enter
\param[in] handle pmu handle to operate.
\param[in] mode \ref pmu_mode_e
\return error code
*/
int32_t csi_pmu_enter_sleep(pmu_handle_t handle, pmu_mode_e mode);
/**
\brief control pmu power.
\param[in] handle pmu handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_pmu_power_control(pmu_handle_t handle, csi_power_stat_e state);
/**
\brief Config the wakeup source.
\param[in] handle pmu handle to operate
\param[in] wakeup_num wakeup source num
\param[in] type \ref pmu_wakeup_type
\param[in] pol \ref pmu_wakeup_pol
\param[in] enable flag control the wakeup source is enable or not
\return error code
*/
int32_t csi_pmu_config_wakeup_source(pmu_handle_t handle, uint32_t wakeup_num, pmu_wakeup_type_e type, pmu_wakeup_pol_e pol, uint8_t enable);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_PMU_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_pmu.h
|
C
|
apache-2.0
| 3,425
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_pwm.h
* @brief header file for pwm driver
* @version V1.0
* @date 19. Feb 2019
* @model pwm
******************************************************************************/
#ifndef _CSI_PWM_H_
#define _CSI_PWM_H_
#include <stdint.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for pwm handle.
typedef void *pwm_handle_t;
/****** PWM specific error codes *****/
typedef enum {
EDRV_PWM_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported
} csi_pwm_error_e;
/*----- PWM Input Capture Mode -----*/
typedef enum {
PWM_INPUT_MODE_EDGE_TIME = 0, ///< Input Edge Time Mode
PWM_INPUT_MODE_EDGE_COUNT = 1 ///< Input Edge Count Mode
} pwm_input_mode_e;
typedef enum {
PWM_INPUT_EVENT_MODE_POSEDGE = 0, ///< Posedge Edge
PWM_INPUT_EVENT_MODE_NEGEDGE = 1, ///< Negedge Edge
PWM_INPUT_EVENT_MODE_BOTHEDGE = 2 ///< Both Edge
} pwm_input_event_mode_e;
typedef struct {
pwm_input_mode_e input_mode; ///< Input Mode
pwm_input_event_mode_e event_mode; ///< Input Event Mode
uint32_t count; ///< Capture Mode Count
} pwm_input_config_t;
typedef enum {
PWM_CAPTURE_EVENT_COUNT = 0, ///< Capture Count Event
PWM_CAPTURE_EVENT_TIME = 1, ///< Capture Time Event
PWM_TIMER_EVENT_TIMEOUT = 2 ///< Timer Timeout Event
} pwm_event_e;
typedef void (*pwm_event_cb_t)(int32_t ch, pwm_event_e event, uint32_t val);
/**
\brief Initialize PWM Interface. 1. Initializes the resources needed for the PWM interface 2.registers event callback function
\param[in] idx pwm idx
\return handle pwm handle to operate.
*/
pwm_handle_t csi_pwm_initialize(uint32_t idx);
/**
\brief De-initialize PWM Interface. stops operation and releases the software resources used by the interface
\param[in] handle pwm handle to operate.
*/
void csi_pwm_uninitialize(pwm_handle_t handle);
/**
\brief control pwm power.
\param[in] handle pwm handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_pwm_power_control(pwm_handle_t handle, csi_power_stat_e state);
/**
\brief config pwm mode.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
\param[in] period_us the PWM period in us
\param[in] pulse_width_us the PMW pulse width in us
\return error code
*/
int32_t csi_pwm_config(pwm_handle_t handle,
uint8_t channel,
uint32_t period_us,
uint32_t pulse_width_us);
/**
\brief start generate pwm signal.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
*/
void csi_pwm_start(pwm_handle_t handle, uint8_t channel);
/**
\brief stop generate pwm signal.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
*/
void csi_pwm_stop(pwm_handle_t handle, uint8_t channel);
/**
\brief config pwm clock division.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
\param[in] div clock div.
*/
void drv_pwm_config_clockdiv(pwm_handle_t handle, uint8_t channel, uint32_t div);
/**
\brief get pwm clock division.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
\return clock div.
*/
uint32_t drv_pwm_get_clockdiv(pwm_handle_t handle, uint8_t channel);
/**
\brief config pwm clock division.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
\param[in] cb_event event callback.
*/
void drv_pwm_config_cb(pwm_handle_t handle, uint8_t channel, pwm_event_cb_t cb_event);
/**
\brief set pwm timeout.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
\param[in] timeout the timeout value in microseconds(us).
*/
void drv_pwm_timer_set_timeout(pwm_handle_t handle, uint8_t channel, uint32_t timeout);
/**
\brief start pwm timer.
\param[in] handle pwm handle to operate.
\param[in] channel chnnel num.
*/
void drv_pwm_timer_start(pwm_handle_t handle, uint8_t channel);
/**
\brief stop pWM timer.
\param[in] handle pwm handle to operate.
\param[in] channel chnnel num.
*/
void drv_pwm_timer_stop(pwm_handle_t handle, uint8_t channel);
/**
\brief get pwm timer current value
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
\param[out] value timer current value
*/
void drv_pwm_timer_get_current_value(pwm_handle_t handle, uint8_t channel, uint32_t *value);
/**
\brief get pwm timer reload value
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
\param[out] value timer reload value
*/
void drv_pwm_timer_get_load_value(pwm_handle_t handle, uint8_t channel, uint32_t *value);
/**
\brief config pwm capture mode.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
\param[in] config capture config.
*/
void drv_pwm_capture_config(pwm_handle_t handle, uint8_t channel, pwm_input_config_t *config);
/**
\brief start pwm capture.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
*/
void drv_pwm_capture_start(pwm_handle_t handle, uint8_t channel);
/**
\brief stop pwm capture.
\param[in] handle pwm handle to operate.
\param[in] channel channel num.
*/
void drv_pwm_capture_stop(pwm_handle_t handle, uint8_t channel);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_PWM_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_pwm.h
|
C
|
apache-2.0
| 5,947
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_rsa.h
* @brief header file for rsa driver
* @version V1.0
* @date 02. June 2017
* @model rsa
******************************************************************************/
#ifndef _CSI_RSA_H_
#define _CSI_RSA_H_
#include <stdint.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for rsa handle.
typedef void *rsa_handle_t;
/****** RSA specific error codes *****/
typedef enum {
RSA_ERROR_DATA_BITS = (DRV_ERROR_SPECIFIC + 1), ///< Specified number of Data bits not supported
RSA_ERROR_ENDIAN ///< Specified endian not supported
} rsa_error_e;
/*----- RSA Control Codes: Mode Parameters: Data Bits -----*/
typedef enum {
RSA_DATA_BITS_192 = 0, ///< 192 Data bits
RSA_DATA_BITS_256, ///< 256 Data bits
RSA_DATA_BITS_512, ///< 512 Data bits
RSA_DATA_BITS_1024, ///< 1024 Data bits
RSA_DATA_BITS_2048, ///< 2048 Data bits
RSA_DATA_BITS_3072 ///< 3072 Data bits
} rsa_data_bits_e;
/*----- RSA Control Codes: Mode Parameters: Endian -----*/
typedef enum {
RSA_ENDIAN_MODE_LITTLE = 0, ///< RSA Little Endian Mode
RSA_ENDIAN_MODE_BIG ///< RSA Big Endian Mode
} rsa_endian_mode_e;
typedef enum {
RSA_PADDING_MODE_PKCS1 = 1, ///< RSA PKCS1 Padding Mode
RSA_PADDING_MODE_NO, ///< RSA NO Padding Mode
RSA_PADDING_MODE_SSLV23, ///< RSA SSLV23 Padding Mode
RSA_PADDING_MODE_PKCS1_OAEP, ///< RSA PKCS1 OAEP Padding Mode
RSA_PADDING_MODE_X931, ///< RSA X931 Padding Mode
RSA_PADDING_MODE_PSS ///< RSA PSS Padding Mode
} rsa_padding_type_e;
typedef enum {
RSA_HASH_TYPE_MD5 = 0,
RSA_HASH_TYPE_SHA1,
RSA_HASH_TYPE_SHA224,
RSA_HASH_TYPE_SHA256,
RSA_HASH_TYPE_SHA384,
RSA_HASH_TYPE_SHA512
} rsa_hash_type_e;
/*----- RSA Control Codes: Mode Parameters: Padding mode -----*/
typedef struct {
rsa_padding_type_e padding_type;
rsa_hash_type_e hash_type;
} rsa_padding_t;
/**
\brief RSA Status
*/
typedef struct {
uint32_t busy : 1; ///< Calculate busy flag
} rsa_status_t;
/****** RSA Event *****/
typedef enum {
RSA_EVENT_ENCRYPT_COMPLETE = 0, ///< Encrypt completed
RSA_EVENT_DECRYPT_COMPLETE, ///< Decrypt completed
RSA_EVENT_SIGN_COMPLETE, ///< Sign completed
RSA_EVENT_VERIFY_COMPLETE, ///< Verify completed
} rsa_event_e;
typedef void (*rsa_event_cb_t)(int32_t idx, rsa_event_e event); ///< Pointer to \ref rsa_event_cb_t : RSA Event call back.
/**
\brief RSA Device Driver Capabilities.
*/
typedef struct {
uint32_t bits_192 : 1; ///< supports 192bits modular length
uint32_t bits_256 : 1; ///< supports 256bits modular length
uint32_t bits_512 : 1; ///< supports 512bits modular length
uint32_t bits_1024 : 1; ///< supports 1024bits modular length
uint32_t bits_2048 : 1; ///< supports 2048bits modular length
uint32_t bits_3072 : 1; ///< supports 30728bits modular length
} rsa_capabilities_t;
// Function documentation
/**
\brief Initialize RSA Interface. 1. Initializes the resources needed for the RSA interface 2.registers event callback function
\param[in] idx device id
\param[in] cb_event event callback function \ref rsa_event_cb_t
\return pointer to rsa handle
*/
rsa_handle_t csi_rsa_initialize(int32_t idx, rsa_event_cb_t cb_event);
/**
\brief De-initialize RSA Interface. stops operation and releases the software resources used by the interface
\param[in] handle rsa handle to operate.
\return error code
*/
int32_t csi_rsa_uninitialize(rsa_handle_t handle);
/**
\brief control rsa power.
\param[in] handle rsa handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_rsa_power_control(rsa_handle_t handle, csi_power_stat_e state);
/**
\brief Get driver capabilities.
\param[in] idx device id
\return \ref rsa_capabilities_t
*/
rsa_capabilities_t csi_rsa_get_capabilities(int32_t idx);
/**
\brief config rsa mode.
\param[in] handle rsa handle to operate.
\param[in] data_bits \ref rsa_data_bits_e
\param[in] endian \ref rsa_endian_mode_e
\param[in] arg the addr of modulus value
\return error code
*/
int32_t csi_rsa_config(rsa_handle_t handle,
rsa_data_bits_e data_bits,
rsa_endian_mode_e endian,
void *arg
);
/**
\brief encrypt
\param[in] handle rsa handle to operate.
\param[in] n Pointer to the public modulus
\param[in] e Pointer to the public exponent
\param[in] src Pointer to the source data.
\param[in] src_size the source data len
\param[out] out Pointer to the result buffer
\param[out] out_size the result size
\param[in] padding \ref rsa_padding_t
\return error code
*/
int32_t csi_rsa_encrypt(rsa_handle_t handle, void *n, void *e, void *src, uint32_t src_size, void *out, uint32_t *out_size, rsa_padding_t padding);
/**
\brief decrypt
\param[in] handle rsa handle to operate.
\param[in] n Pointer to the public modulus
\param[in] d Pointer to the privte exponent
\param[in] src Pointer to the source data.
\param[in] src_size the source data len
\param[out] out Pointer to the result buffer
\param[out] out_size the result size
\param[in] padding \ref rsa_padding_t
\return error code
*/
int32_t csi_rsa_decrypt(rsa_handle_t handle, void *n, void *d, void *src, uint32_t src_size, void *out, uint32_t *out_size, rsa_padding_t padding);
/**
\brief rsa sign
\param[in] handle rsa handle to operate.
\param[in] n Pointer to the public modulus
\param[in] d Pointer to the privte exponent
\param[in] src Pointer to the source data.
\param[in] src_size the source data len
\param[out] signature Pointer to the signature
\param[out] sig_size the signature size
\param[in] padding \ref rsa_padding_t
\return error code
*/
int32_t csi_rsa_sign(rsa_handle_t handle, void *n, void *d, void *src, uint32_t src_size, void *signature, uint32_t *sig_size, rsa_padding_t padding);
/**
\brief rsa verify
\param[in] handle rsa handle to operate.
\param[in] n Pointer to the public modulus
\param[in] e Pointer to the public exponent
\param[in] src Pointer to the source data.
\param[in] src_size the source data len
\param[in] signature Pointer to the signature
\param[in] sig_size the signature size
\param[out] result Pointer to the result
\param[in] padding \ref rsa_padding_t
\return error code
*/
int32_t csi_rsa_verify(rsa_handle_t handle, void *n, void *e, void *src, uint32_t src_size, void *signature, uint32_t sig_size, void *result, rsa_padding_t padding);
/**
\brief Get RSA status.
\param[in] handle rsa handle to operate.
\return RSA status \ref rsa_status_t
*/
rsa_status_t csi_rsa_get_status(rsa_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_RSA_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_rsa.h
|
C
|
apache-2.0
| 7,637
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_rtc.h
* @brief header file for rtc driver
* @version V1.0
* @date 02. June 2017
* @model rtc
******************************************************************************/
#ifndef _CSI_RTC_H_
#define _CSI_RTC_H_
#include <stdint.h>
#include <drv_common.h>
#include <time.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for rtc handle.
typedef void *rtc_handle_t;
/****** rtc specific error codes *****/
typedef enum {
RTC_ERROR_TIME = (DRV_ERROR_SPECIFIC + 1), ///<invalid data time
} rtc_error_e;
/**
\brief RTC Status
*/
typedef struct {
uint32_t active : 1; ///< rtc is running or not
} rtc_status_t;
/****** RTC Event *****/
typedef enum {
RTC_EVENT_TIMER_INTRERRUPT = 0 ///< generate interrupt
} rtc_event_e;
typedef void (*rtc_event_cb_t)(int32_t idx, rtc_event_e event); ///< Pointer to \ref rtc_event_cb_t : RTC Event call back.
/**
\brief RTC Device Driver Capabilities.
*/
typedef struct {
uint32_t interrupt_mode : 1; ///< supports Interrupt mode
uint32_t wrap_mode : 1; ///< supports wrap mode
} rtc_capabilities_t;
/**
\brief Initialize RTC Interface. 1. Initializes the resources needed for the RTC interface 2.registers event callback function
\param[in] idx rtc index
\param[in] cb_event event callback function \ref rtc_event_cb_t
\return pointer to rtc instance
*/
rtc_handle_t csi_rtc_initialize(int32_t idx, rtc_event_cb_t cb_event);
/**
\brief De-initialize RTC Interface. stops operation and releases the software resources used by the interface
\param[in] handle rtc handle to operate.
\return error code
*/
int32_t csi_rtc_uninitialize(rtc_handle_t handle);
/**
\brief control rtc power.
\param[in] handle rtc handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_rtc_power_control(rtc_handle_t handle, csi_power_stat_e state);
/**
\brief Get driver capabilities.
\param[in] idx rtc index
\return \ref rtc_capabilities_t
*/
rtc_capabilities_t csi_rtc_get_capabilities(int32_t idx);
/**
\brief Set system date.
\param[in] handle rtc handle to operate.
\param[in] rtctime pointer to rtc time
\return error code
*/
int32_t csi_rtc_set_time(rtc_handle_t handle, const struct tm *rtctime);
/**
\brief Get system date.
\param[in] handle rtc handle to operate.
\param[out] rtctime pointer to rtc time
\return error code
*/
int32_t csi_rtc_get_time(rtc_handle_t handle, struct tm *rtctime);
/**
\brief Start RTC timer.
\param[in] handle rtc handle to operate.
\return error code
*/
int32_t csi_rtc_start(rtc_handle_t handle);
/**
\brief Stop RTC timer.
\param[in] handle rtc handle to operate.
\return error code
*/
int32_t csi_rtc_stop(rtc_handle_t handle);
/**
\brief Get RTC status.
\param[in] handle rtc handle to operate.
\return RTC status \ref rtc_status_t
*/
rtc_status_t csi_rtc_get_status(rtc_handle_t handle);
/**
\brief config RTC timer.
\param[in] handle rtc handle to operate.
\param[in] rtctime time to wake up
\return error code
*/
int32_t csi_rtc_set_alarm(rtc_handle_t handle, const struct tm *rtctime);
/**
\brief disable or enable RTC timer.
\param[in] handle rtc handle to operate.
\param[in] flag 1 - enable rtc alarm 0 - disable rtc alarm
\return error code
*/
int32_t csi_rtc_enable_alarm(rtc_handle_t handle, uint8_t flag);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_RTC_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_rtc.h
|
C
|
apache-2.0
| 3,804
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_sha.h
* @brief header file for sha driver
* @version V1.0
* @date 02. June 2017
* @model sha
******************************************************************************/
#ifndef _CSI_SHA_H_
#define _CSI_SHA_H_
#include <stdint.h>
#include <drv_common.h>
#include <drv_errno.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for sha handle.
typedef void *sha_handle_t;
/****** SHA specific error codes *****/
typedef enum {
SHA_ERROR_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported
SHA_ERROR_ENDIAN ///< Specified endian not supported
} sha_error_e;
/*----- SHA Control Codes: Mode -----*/
typedef enum {
SHA_MODE_1 = 1, ///< SHA_1 mode
SHA_MODE_256, ///< SHA_256 mode
SHA_MODE_224, ///< SHA_224 mode
SHA_MODE_512, ///< SHA_512 mode
SHA_MODE_384, ///< SHA_384 mode
SHA_MODE_512_256, ///< SHA_512_256 mode
SHA_MODE_512_224 ///< SHA_512_224 mode
} sha_mode_e;
/*----- SHA Control Codes: Mode Parameters: Endian -----*/
typedef enum {
SHA_ENDIAN_MODE_BIG = 0, ///< Big Endian Mode
SHA_ENDIAN_MODE_LITTLE, ///< Little Endian Mode
} sha_endian_mode_e;
/**
\brief SHA Status
*/
typedef struct {
uint32_t busy : 1; ///< calculate busy flag
} sha_status_t;
/****** SHA Event *****/
typedef enum {
SHA_EVENT_COMPLETE = 0 ///< calculate completed
} sha_event_e;
typedef void (*sha_event_cb_t)(int32_t idx, sha_event_e event); ///< Pointer to \ref sha_event_cb_t : SHA Event call back.
/**
\brief SHA Device Driver Capabilities.
*/
typedef struct {
uint32_t sha1 : 1; ///< supports sha1 mode
uint32_t sha224 : 1; ///< supports sha224 mode
uint32_t sha256 : 1; ///< supports sha256 mode
uint32_t sha384 : 1; ///< supports sha384 mode
uint32_t sha512 : 1; ///< supports sha512 mode
uint32_t sha512_224 : 1; ///< supports sha512_224 mode
uint32_t sha512_256 : 1; ///< supports sha512_256 mode
uint32_t endianmode : 1; ///< supports endian mode control
uint32_t interruptmode : 1; ///< supports interrupt mode
} sha_capabilities_t;
// Function documentation
/**
\brief Initialize SHA Interface. 1. Initializes the resources needed for the SHA interface 2.registers event callback function
\param[in] idx index of sha
\param[in] context Pointer to the buffer storing the sha context
\param[in] cb_event event callback function \ref sha_event_cb_t
\return return sha handle if success
*/
sha_handle_t csi_sha_initialize(int32_t idx, void *context, sha_event_cb_t cb_event);
/**
\brief De-initialize SHA Interface. stops operation and releases the software resources used by the interface
\param[in] handle sha handle to operate.
\return error code
*/
int32_t csi_sha_uninitialize(sha_handle_t handle);
/**
\brief control sha power.
\param[in] handle sha handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_sha_power_control(sha_handle_t handle, csi_power_stat_e state);
/**
\brief Get driver capabilities.
\param[in] idx device id
\return \ref sha_capabilities_t
*/
sha_capabilities_t csi_sha_get_capabilities(int32_t idx);
/**
\brief config sha mode.
\param[in] handle sha handle to operate.
\param[in] mode \ref sha_mode_e
\param[in] endian \ref sha_endian_mode_e
\return error code
*/
int32_t csi_sha_config(sha_handle_t handle,
sha_mode_e mode,
sha_endian_mode_e endian
);
/**
\brief start the engine
\param[in] handle sha handle to operate.
\param[in] context Pointer to the buffer storing the sha context
\return error code
*/
int32_t csi_sha_start(sha_handle_t handle, void *context);
/**
\brief update the engine
\param[in] handle sha handle to operate.
\param[in] context Pointer to the buffer storing the sha context
\param[in] input Pointer to the Source data
\param[in] len the data len
\return error code
*/
int32_t csi_sha_update(sha_handle_t handle, void *context, const void *input, uint32_t len);
/**
\brief finish the engine
\param[in] handle sha handle to operate.
\param[in] context Pointer to the buffer storing the sha context
\param[out] output Pointer to the result data
\return error code
*/
int32_t csi_sha_finish(sha_handle_t handle, void *context, void *output);
/**
\brief Get SHA status.
\param[in] handle sha handle to operate.
\return SHA status \ref sha_status_t
*/
sha_status_t csi_sha_get_status(sha_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_SHA_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_sha.h
|
C
|
apache-2.0
| 5,255
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*
* 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 License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/******************************************************************************
* @file drv_spi.h
* @brief header file for spi driver
* @version V1.0
* @date 02. June 2017
* @model spi
******************************************************************************/
#ifndef _CSI_SPI_H_
#define _CSI_SPI_H_
#include <stdint.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for spi handle.
typedef void *spi_handle_t;
/****** SPI specific error codes *****/
typedef enum {
SPI_ERROR_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported
SPI_ERROR_FRAME_FORMAT, ///< Specified Frame Format not supported
SPI_ERROR_DATA_BITS, ///< Specified number of Data bits not supported
SPI_ERROR_BIT_ORDER, ///< Specified Bit order not supported
SPI_ERROR_SS_MODE ///< Specified Slave Select Mode not supported
} spi_error_e;
/*----- SPI Control Codes: Mode -----*/
typedef enum {
SPI_MODE_INACTIVE = 0, ///< SPI Inactive
SPI_MODE_MASTER, ///< SPI Master (Output on MOSI, Input on MISO); arg = Bus Speed in bps
SPI_MODE_SLAVE, ///< SPI Slave (Output on MISO, Input on MOSI)
SPI_MODE_MASTER_SIMPLEX, ///< SPI Master (Output/Input on MOSI); arg = Bus Speed in bps
SPI_MODE_SLAVE_SIMPLEX ///< SPI Slave (Output/Input on MISO)
} spi_mode_e;
/*----- SPI Control Codes: Mode Parameters: Frame Format -----*/
typedef enum {
SPI_FORMAT_CPOL0_CPHA0 = 0, ///< Clock Polarity 0, Clock Phase 0
SPI_FORMAT_CPOL0_CPHA1, ///< Clock Polarity 0, Clock Phase 1
SPI_FORMAT_CPOL1_CPHA0, ///< Clock Polarity 1, Clock Phase 0
SPI_FORMAT_CPOL1_CPHA1, ///< Clock Polarity 1, Clock Phase 1
} spi_format_e;
/*----- SPI Control Codes: Mode Parameters: Bit Order -----*/
typedef enum {
SPI_ORDER_MSB2LSB = 0, ///< SPI Bit order from MSB to LSB
SPI_ORDER_LSB2MSB ///< SPI Bit order from LSB to MSB
} spi_bit_order_e;
/*----- SPI Control Codes: Mode Parameters: Data Width in bits -----*/
#define SPI_DATAWIDTH_MAX 32 /* 1 ~ 32 bit*/
/*----- SPI Control Codes: Mode Parameters: Slave Select Mode -----*/
typedef enum {
/*options for SPI_MODE_MASTER/SPI_MODE_MASTER_SIMPLEX */
SPI_SS_MASTER_UNUSED = 0, ///< SPI Slave Select when Master: Not used.SS line is not controlled by master, For example,SS line connected to a fixed low level
SPI_SS_MASTER_SW, ///< SPI Slave Select when Master: Software controlled. SS line is configured by software
SPI_SS_MASTER_HW_OUTPUT, ///< SPI Slave Select when Master: Hardware controlled Output.SS line is activated or deactivated automatically by hardware
SPI_SS_MASTER_HW_INPUT, ///< SPI Slave Select when Master: Hardware monitored Input.Used in multi-master configuration where a master does not drive the Slave Select when driving the bus, but rather monitors it
/*options for SPI_MODE_SLAVE/SPI_MODE_SLAVE_SIMPLEX */
SPI_SS_SLAVE_HW, ///< SPI Slave Select when Slave: Hardware monitored.Hardware monitors the Slave Select line and accepts transfers only when the line is active
SPI_SS_SLAVE_SW ///< SPI Slave Select when Slave: Software controlled.Used only when the Slave Select line is not used. Software controls if the slave is responding or not(enables or disables transfers)
} spi_ss_mode_e;
/****** SPI Slave Select Signal definitions *****/
typedef enum {
SPI_SS_INACTIVE = 0, ///< SPI Slave Select Signal/line Inactive
SPI_SS_ACTIVE ///< SPI Slave Select Signal/line Active
} spi_ss_stat_e;
/**
\brief SPI Status
*/
typedef struct {
uint32_t busy : 1; ///< Transmitter/Receiver busy flag
uint32_t data_lost : 1; ///< Data lost: Receive overflow / Transmit underflow (cleared on start of transfer operation)
uint32_t mode_fault : 1; ///< Mode fault detected; optional (cleared on start of transfer operation)
} spi_status_t;
/****** SPI Event *****/
typedef enum {
SPI_EVENT_TRANSFER_COMPLETE = 0, ///< Data Transfer completed. Occurs after call to csi_spi_send, csi_spi_receive, or csi_spi_transfer to indicate that all the data has been transferred. The driver is ready for the next transfer operation
SPI_EVENT_TX_COMPLETE, ///< Data Transfer completed. Occurs after call to csi_spi_send, csi_spi_receive, or csi_spi_transfer to indicate that all the data has been transferred. The driver is ready for the next transfer operation
SPI_EVENT_RX_COMPLETE, ///< Data Transfer completed. Occurs after call to csi_spi_send, csi_spi_receive, or csi_spi_transfer to indicate that all the data has been transferred. The driver is ready for the next transfer operation
SPI_EVENT_DATA_LOST, ///< Data lost: Receive overflow / Transmit underflow. Occurs in slave mode when data is requested/sent by master but send/receive/transfer operation has not been started and indicates that data is lost. Occurs also in master mode when driver cannot transfer data fast enough.
SPI_EVENT_MODE_FAULT ///< Master Mode Fault (SS deactivated when Master).Occurs in master mode when Slave Select is deactivated and indicates Master Mode Fault. The driver is ready for the next transfer operation.
} spi_event_e;
typedef void (*spi_event_cb_t)(int32_t idx, spi_event_e event); ///< Pointer to \ref spi_event_cb_t : SPI Event call back.
/**
\brief SPI Driver Capabilities.
*/
typedef struct {
uint32_t simplex : 1; ///< supports Simplex Mode (Master and Slave)
uint32_t ti_ssi : 1; ///< supports TI Synchronous Serial Interface
uint32_t microwire : 1; ///< supports Microwire Interface
uint32_t event_mode_fault : 1; ///< Signal Mode Fault event: \ref spi_event_e
} spi_capabilities_t;
/**
\brief Initialize SPI Interface. 1. Initializes the resources needed for the SPI interface 2.registers event callback function
\param[in] idx spi index
\param[in] cb_event event callback function \ref spi_event_cb_t
\param[in] cb_arg argument for call back function
\return return spi handle if success
*/
spi_handle_t csi_spi_initialize(int32_t idx, spi_event_cb_t cb_event);
/**
\brief De-initialize SPI Interface. stops operation and releases the software resources used by the interface
\param[in] handle spi handle to operate.
\return error code
*/
int32_t csi_spi_uninitialize(spi_handle_t handle);
/**
\brief Get driver capabilities.
\param[in] idx spi index
\return \ref spi_capabilities_t
*/
spi_capabilities_t csi_spi_get_capabilities(int32_t idx);
/**
\brief config spi mode.
\param[in] handle spi handle to operate.
\param[in] baud spi baud rate. if negative, then this attribute not changed
\param[in] mode \ref spi_mode_e . if negative, then this attribute not changed
\param[in] format \ref spi_format_e . if negative, then this attribute not changed
\param[in] order \ref spi_bit_order_e . if negative, then this attribute not changed
\param[in] ss_mode \ref spi_ss_mode_e . if negative, then this attribute not changed
\param[in] bit_width spi data bitwidth: (1 ~ SPI_DATAWIDTH_MAX) . if negative, then this attribute not changed
\return error code
*/
int32_t csi_spi_config(spi_handle_t handle,
int32_t baud,
spi_mode_e mode,
spi_format_e format,
spi_bit_order_e order,
spi_ss_mode_e ss_mode,
int32_t bit_width);
/**
\brief sending data to SPI transmitter,(received data is ignored).
if non-blocking mode, this function only starts the sending,
\ref spi_event_e is signaled when operation completes or error happens.
\ref csi_spi_get_status can get operation status.
if blocking mode, this function returns after operation completes or error happens.
\param[in] handle spi handle to operate.
\param[in] data Pointer to buffer with data to send to SPI transmitter. data_type is : uint8_t for 1..8 data bits, uint16_t for 9..16 data bits,uint32_t for 17..32 data bits,
\param[in] num Number of data items to send.
\return error code
*/
int32_t csi_spi_send(spi_handle_t handle, const void *data, uint32_t num);
/**
\brief receiving data from SPI receiver. if non-blocking mode, this function only starts the receiving,
\ref spi_event_e is signaled when operation completes or error happens.
\ref csi_spi_get_status can get operation status.
if blocking mode, this function returns after operation completes or error happens.
\param[in] handle spi handle to operate.
\param[out] data Pointer to buffer for data to receive from SPI receiver
\param[in] num Number of data items to receive
\return error code
*/
int32_t csi_spi_receive(spi_handle_t handle, void *data, uint32_t num);
/**
\brief sending/receiving data to/from SPI transmitter/receiver.
if non-blocking mode, this function only starts the transfer,
\ref spi_event_e is signaled when operation completes or error happens.
\ref csi_spi_get_status can get operation status.
if blocking mode, this function returns after operation completes or error happens.
\param[in] handle spi handle to operate.
\param[in] data_out Pointer to buffer with data to send to SPI transmitter
\param[out] data_in Pointer to buffer for data to receive from SPI receiver
\param[in] num_out Number of data items to send
\param[in] num_in Number of data items to receive
\return error code
*/
int32_t csi_spi_transfer(spi_handle_t handle, const void *data_out, void *data_in, uint32_t num_out, uint32_t num_in);
/**
\brief abort spi transfer.
\param[in] handle spi handle to operate.
\return error code
*/
int32_t csi_spi_abort_transfer(spi_handle_t handle);
/**
\brief Get SPI status.
\param[in] handle spi handle to operate.
\return SPI status \ref spi_status_t
*/
spi_status_t csi_spi_get_status(spi_handle_t handle);
/**
\brief config the SPI mode.
\param[in] handle spi handle
\param[in] mode spi mode. \ref spi_mode_e
\return error code
*/
int32_t csi_spi_config_mode(spi_handle_t handle, spi_mode_e mode);
/**
\brief config the SPI block mode.
\param[in] handle spi handle
\param[in] flag 1 - enbale the block mode. 0 - disable the block mode
\return error code
*/
int32_t csi_spi_config_block_mode(spi_handle_t handle, int32_t flag);
/**
\brief Set the SPI baudrate.
\param[in] handle spi handle
\param[in] baud spi baud rate
\return error code
*/
int32_t csi_spi_config_baudrate(spi_handle_t handle, uint32_t baud);
/**
\brief config the SPI bit order.
\param[in] handle spi handle
\param[in] order spi bit order.\ref spi_bit_order_e
\return error code
*/
int32_t csi_spi_config_bit_order(spi_handle_t handle, spi_bit_order_e order);
/**
\brief Set the SPI datawidth.
\param[in] handle spi handle
\param[in] datawidth date frame size in bits
\return error code
*/
int32_t csi_spi_config_datawidth(spi_handle_t handle, uint32_t datawidth);
/**
\brief config the SPI format.
\param[in] handle spi handle
\param[in] format spi format. \ref spi_format_e
\return error code
*/
int32_t csi_spi_config_format(spi_handle_t handle, spi_format_e format);
/**
\brief config the SPI slave select mode.
\param[in] handle spi handle
\param[in] ss_mode spi slave select mode. \ref spi_ss_mode_e
\return error code
*/
int32_t csi_spi_config_ss_mode(spi_handle_t handle, spi_ss_mode_e ss_mode);
/**
\brief Get the number of the currently transferred.
\param[in] handle spi handle to operate.
\return the number of the currently transferred data items
*/
uint32_t csi_spi_get_data_count(spi_handle_t handle);
/**
\brief control spi power.
\param[in] handle spi handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_spi_power_control(spi_handle_t handle, csi_power_stat_e state);
/**
\brief Control the Slave Select signal (SS).
\param[in] handle spi handle to operate.
\param[in] stat SS state. \ref spi_ss_stat_e.
\return error code
*/
int32_t csi_spi_ss_control(spi_handle_t handle, spi_ss_stat_e stat);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_SPI_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_spi.h
|
C
|
apache-2.0
| 13,638
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_spiflash.h
* @brief header file for spiflash driver
* @version V1.0
* @date 02. June 2017
* @model spiflash
******************************************************************************/
#ifndef _CSI_SPIFLASH_H_
#define _CSI_SPIFLASH_H_
#include <stdint.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for spiflash handle.
typedef void *spiflash_handle_t;
/**
\brief Flash information
*/
typedef struct {
uint32_t start; ///< Chip Start address
uint32_t end; ///< Chip End address (start+size-1)
uint32_t sector_count; ///< Number of sectors
uint32_t sector_size; ///< Uniform sector size in bytes (0=sector_info used)
uint32_t page_size; ///< Optimal programming page size in bytes
uint32_t program_unit; ///< Smallest programmable unit in bytes
uint8_t erased_value; ///< Contents of erased memory (usually 0xFF)
} spiflash_info_t;
/**
\brief Flash Status
*/
typedef struct {
uint32_t busy : 1; ///< Flash busy flag
uint32_t error : 1; ///< Read/Program/Erase error flag (cleared on start of next operation)
} spiflash_status_t;
/****** SPIFLASH Event *****/
typedef enum {
SPIFLASH_EVENT_READY = 0, ///< Flash Ready
SPIFLASH_EVENT_ERROR, ///< Read/Program/Erase Error
} spiflash_event_e;
typedef enum {
SPIFLASH_DATA_1_LINE = 1,
SPIFLASH_DATA_2_LINES = 2,
SPIFLASH_DATA_4_LINES = 4
} spiflash_data_line_e;
typedef void (*spiflash_event_cb_t)(int32_t idx, spiflash_event_e event); ///< Pointer to \ref spiflash_event_cb_t : SPIFLASH Event call back.
/**
\brief Flash Driver Capabilities.
*/
typedef struct {
uint32_t event_ready : 1; ///< Signal Flash Ready event
uint32_t data_width : 2; ///< Data width: 0=8-bit, 1=16-bit, 2=32-bit
uint32_t erase_chip : 1; ///< Supports EraseChip operation
} spiflash_capabilities_t;
// Function documentation
/**
\brief Initialize SPIFLASH Interface. 1. Initializes the resources needed for the SPIFLASH interface 2.registers event callback function
\param[in] idx device id
\param[in] cb_event Pointer to \ref spiflash_event_cb_t
\return pointer to spiflash handle
*/
spiflash_handle_t csi_spiflash_initialize(int32_t idx, spiflash_event_cb_t cb_event);
/**
\brief De-initialize SPIFLASH Interface. stops operation and releases the software resources used by the interface
\param[in] handle spiflash handle to operate.
\return error code
*/
int32_t csi_spiflash_uninitialize(spiflash_handle_t handle);
/**
\brief Get driver capabilities.
\param[in] handle spiflash handle to operate.
\return \ref spiflash_capabilities_t
*/
spiflash_capabilities_t csi_spiflash_get_capabilities(int32_t idx);
/**
\brief Set QSPI data line
\param[in] handle spiflash handle to operate
\param[in] line spiflash data line mode
\return error code
*/
int32_t csi_spiflash_config_data_line(spiflash_handle_t handle, spiflash_data_line_e line);
/**
\brief Read data from Flash.
\param[in] handle spiflash handle to operate.
\param[in] addr Data address.
\param[out] data Pointer to a buffer storing the data read from Flash.
\param[in] cnt Number of data items to read.
\return number of data items read or error code
*/
int32_t csi_spiflash_read(spiflash_handle_t handle, uint32_t addr, void *data, uint32_t cnt);
/**
\brief Program data to Flash.
\param[in] handle spiflash handle to operate.
\param[in] addr Data address.
\param[in] data Pointer to a buffer containing the data to be programmed to Flash..
\param[in] cnt Number of data items to program.
\return number of data items programmed or error code
*/
int32_t csi_spiflash_program(spiflash_handle_t handle, uint32_t addr, const void *data, uint32_t cnt);
/**
\brief Erase Flash Sector.
\param[in] handle spiflash handle to operate.
\param[in] addr Sector address
\return error code
*/
int32_t csi_spiflash_erase_sector(spiflash_handle_t handle, uint32_t addr);
/**
\brief Erase complete Flash.
\param[in] handle spiflash handle to operate.
\return error code
*/
int32_t csi_spiflash_erase_chip(spiflash_handle_t handle);
/**
\brief Flash power down.
\param[in] handle spiflash handle to operate.
\return error code
*/
int32_t csi_spiflash_power_down(spiflash_handle_t handle);
/**
\brief Flash release power down.
\param[in] handle spiflash handle to operate.
\return error code
*/
int32_t csi_spiflash_release_power_down(spiflash_handle_t handle);
/**
\brief Get Flash information.
\param[in] handle spiflash handle to operate.
\return Pointer to Flash information \ref spiflash_info_t
*/
spiflash_info_t *csi_spiflash_get_info(spiflash_handle_t handle);
/**
\brief Get SPIFLASH status.
\param[in] handle spiflash handle to operate.
\return SPIFLASH status \ref spiflash_status_t
*/
spiflash_status_t csi_spiflash_get_status(spiflash_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_SPIFLASH_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_spiflash.h
|
C
|
apache-2.0
| 5,509
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_timer.h
* @brief header file for timer driver
* @version V1.0
* @date 02. June 2017
* @model timer
******************************************************************************/
#ifndef _CSI_TIMER_H_
#define _CSI_TIMER_H_
#include <stdint.h>
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for timer handle.
typedef void *timer_handle_t;
/*----- TIMER Control Codes: Mode -----*/
typedef enum {
TIMER_MODE_FREE_RUNNING = 0, ///< free running mode
TIMER_MODE_RELOAD ///< reload mode
} timer_mode_e;
/**
\brief TIMER Status
*/
typedef struct {
uint32_t active : 1; ///< timer active flag
uint32_t timeout : 1; ///< timeout flag
} timer_status_t;
/**
\brief TIMER Event
*/
typedef enum {
TIMER_EVENT_TIMEOUT = 0 ///< time out event
} timer_event_e;
typedef void (*timer_event_cb_t)(int32_t idx, timer_event_e event); ///< Pointer to \ref timer_event_cb_t : TIMER Event call back.
/**
\brief Initialize TIMER Interface. 1. Initializes the resources needed for the TIMER interface 2.registers event callback function
\param[in] idx timer index
\param[in] cb_event event call back function \ref timer_event_cb_t
\param[in] cb_arg arguments of cb_event
\return pointer to timer instance
*/
timer_handle_t csi_timer_initialize(int32_t idx, timer_event_cb_t cb_event);
/**
\brief De-initialize TIMER Interface. stops operation and releases the software resources used by the interface
\param[in] handle timer handle to operate.
\return error code
*/
int32_t csi_timer_uninitialize(timer_handle_t handle);
/**
\brief control timer power.
\param[in] handle timer handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_timer_power_control(timer_handle_t handle, csi_power_stat_e state);
/**
\brief config timer mode.
\param[in] handle timer handle to operate.
\param[in] mode \ref timer_mode_e
\return error code
*/
int32_t csi_timer_config(timer_handle_t handle, timer_mode_e mode);
/**
\brief Set timeout just for the reload mode.
\param[in] handle timer handle to operate.
\param[in] timeout the timeout value in microseconds(us).
\return error code
*/
int32_t csi_timer_set_timeout(timer_handle_t handle, uint32_t timeout);
/**
\brief Start timer.
\param[in] handle timer handle to operate.
\return error code
*/
int32_t csi_timer_start(timer_handle_t handle);
/**
\brief Stop timer.
\param[in] handle timer handle to operate.
\return error code
*/
int32_t csi_timer_stop(timer_handle_t handle);
/**
\brief suspend timer.
\param[in] handle timer handle to operate.
\return error code
*/
int32_t csi_timer_suspend(timer_handle_t handle);
/**
\brief resume timer.
\param[in] handle timer handle to operate.
\return error code
*/
int32_t csi_timer_resume(timer_handle_t handle);
/**
\brief get timer current value
\param[in] handle timer handle to operate.
\param[out] value timer current value
\return error code
*/
int32_t csi_timer_get_current_value(timer_handle_t handle, uint32_t *value);
/**
\brief Get TIMER status.
\param[in] handle timer handle to operate.
\return TIMER status \ref timer_status_t
*/
timer_status_t csi_timer_get_status(timer_handle_t handle);
/**
\brief get timer reload value
\param[in] handle timer handle to operate.
\param[out] value timer reload value
\return error code
*/
int32_t csi_timer_get_load_value(timer_handle_t handle, uint32_t *value);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_TIMER_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_timer.h
|
C
|
apache-2.0
| 4,003
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
/******************************************************************************
* @file drv_trng.h
* @brief header file for trng driver
* @version V1.0
* @date 02. June 2017
* @model trng
******************************************************************************/
#ifndef _CSI_TRNG_H_
#define _CSI_TRNG_H_
#include "drv_common.h"
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for trng handle.
typedef void *trng_handle_t;
/****** TRNG specific error codes *****/
typedef enum {
TRNG_ERROR_MODE = (DRV_ERROR_SPECIFIC + 1) ///< Specified Mode not supported
} trng_error_e;
/**
\brief TRNG Status
*/
typedef struct {
uint32_t busy : 1;
uint32_t data_valid : 1; ///< Data is valid flag
} trng_status_t;
/****** TRNG Event *****/
typedef enum {
TRNG_EVENT_DATA_GENERATE_COMPLETE = 0 ///< True random number generates completely
} trng_event_e;
typedef void (*trng_event_cb_t)(int32_t idx, trng_event_e event); ///< Pointer to \ref trng_event_cb_t : TRNG Event call back.
/**
\brief TRNG Device Driver Capabilities.
*/
typedef struct {
uint32_t lowper_mode : 1; ///< supports low power mode
} trng_capabilities_t;
// Function documentation
/**
\brief Initialize TRNG Interface. 1. Initializes the resources needed for the TRNG interface 2.registers event callback function
\param[in] idx device id
\param[in] cb_event event call back function \ref trng_event_cb_t
\return pointer to trng handle
*/
trng_handle_t csi_trng_initialize(int32_t idx, trng_event_cb_t cb_event);
/**
\brief De-initialize TRNG Interface. stops operation and releases the software resources used by the interface
\param[in] handle trng handle to operate.
\return error code
*/
int32_t csi_trng_uninitialize(trng_handle_t handle);
/**
\brief control trng power.
\param[in] handle trng handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_trng_power_control(trng_handle_t handle, csi_power_stat_e state);
/**
\brief Get driver capabilities.
\param[in] idx device id.
\return \ref trng_capabilities_t
*/
trng_capabilities_t csi_trng_get_capabilities(int32_t idx);
/**
\brief Get data from the TRNG.
\param[in] handle trng handle to operate.
\param[out] data Pointer to buffer with data get from TRNG
\param[in] num Number of data items to obtain
\return error code
*/
int32_t csi_trng_get_data(trng_handle_t handle, void *data, uint32_t num);
/**
\brief Get TRNG status.
\param[in] handle trng handle to operate.
\return TRNG status \ref trng_status_t
*/
trng_status_t csi_trng_get_status(trng_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_TRNG_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_trng.h
|
C
|
apache-2.0
| 2,939
|
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*
* 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 License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/******************************************************************************
* @file drv_usart.h
* @brief header file for usart driver
* @version V1.0
* @date 02. June 2017
* @model usart
******************************************************************************/
#ifndef _CSI_USART_H_
#define _CSI_USART_H_
#include <drv_common.h>
#ifdef __cplusplus
extern "C" {
#endif
/// definition for usart handle.
typedef void *usart_handle_t;
/****** USART specific error codes *****/
typedef enum {
USART_ERROR_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported
USART_ERROR_BAUDRATE, ///< Specified baudrate not supported
USART_ERROR_DATA_BITS, ///< Specified number of Data bits not supported
USART_ERROR_PARITY, ///< Specified Parity not supported
USART_ERROR_STOP_BITS, ///< Specified number of Stop bits not supported
USART_ERROR_FLOW_CONTROL, ///< Specified Flow Control not supported
USART_ERROR_CPOL, ///< Specified Clock Polarity not supported
USART_ERROR_CPHA ///< Specified Clock Phase not supported
} usart_error_e;
/*----- USART Control Codes: Mode -----*/
typedef enum {
USART_MODE_ASYNCHRONOUS = 0, ///< USART (Asynchronous)
USART_MODE_SYNCHRONOUS_MASTER, ///< Synchronous Master
USART_MODE_SYNCHRONOUS_SLAVE, ///< Synchronous Slave (external clock signal)
USART_MODE_SINGLE_WIRE, ///< USART Single-wire (half-duplex)
USART_MODE_SINGLE_IRDA, ///< UART IrDA
USART_MODE_SINGLE_SMART_CARD, ///< UART Smart Card
} usart_mode_e;
/*----- USART Control Codes: Mode Parameters: Data Bits -----*/
typedef enum {
USART_DATA_BITS_5 = 0, ///< 5 Data bits
USART_DATA_BITS_6, ///< 6 Data bit
USART_DATA_BITS_7, ///< 7 Data bits
USART_DATA_BITS_8, ///< 8 Data bits (default)
USART_DATA_BITS_9 ///< 9 Data bits
} usart_data_bits_e;
/*----- USART Control Codes: Mode Parameters: Parity -----*/
typedef enum {
USART_PARITY_NONE = 0, ///< No Parity (default)
USART_PARITY_EVEN, ///< Even Parity
USART_PARITY_ODD, ///< Odd Parity
USART_PARITY_1, ///< Parity forced to 1
USART_PARITY_0 ///< Parity forced to 0
} usart_parity_e;
/*----- USART Control Codes: Mode Parameters: Stop Bits -----*/
typedef enum {
USART_STOP_BITS_1 = 0, ///< 1 Stop bit (default)
USART_STOP_BITS_2, ///< 2 Stop bits
USART_STOP_BITS_1_5, ///< 1.5 Stop bits
USART_STOP_BITS_0_5 ///< 0.5 Stop bits
} usart_stop_bits_e;
/*----- USART Control Codes: Mode Parameters: Clock Polarity (Synchronous mode) -----*/
typedef enum {
USART_CPOL0 = 0, ///< CPOL = 0 (default). data are captured on rising edge (low->high transition)
USART_CPOL1 ///< CPOL = 1. data are captured on falling edge (high->lowh transition)
} usart_cpol_e;
/*----- USART Control Codes: Mode Parameters: Clock Phase (Synchronous mode) -----*/
typedef enum {
USART_CPHA0 = 0, ///< CPHA = 0 (default). sample on first (leading) edge
USART_CPHA1 ///< CPHA = 1. sample on second (trailing) edge
} usart_cpha_e;
/*----- USART Control Codes: flush data type-----*/
typedef enum {
USART_FLUSH_WRITE,
USART_FLUSH_READ
} usart_flush_type_e;
/*----- USART Control Codes: flow control type-----*/
typedef enum {
USART_FLOWCTRL_NONE,
USART_FLOWCTRL_CTS,
USART_FLOWCTRL_RTS,
USART_FLOWCTRL_CTS_RTS
} usart_flowctrl_type_e;
/*----- USART Modem Control -----*/
typedef enum {
USART_RTS_CLEAR, ///< Deactivate RTS
USART_RTS_SET, ///< Activate RTS
USART_DTR_CLEAR, ///< Deactivate DTR
USART_DTR_SET ///< Activate DTR
} usart_modem_ctrl_e;
/*----- USART Modem Status -----*/
typedef struct {
uint32_t cts : 1; ///< CTS state: 1=Active, 0=Inactive
uint32_t dsr : 1; ///< DSR state: 1=Active, 0=Inactive
uint32_t dcd : 1; ///< DCD state: 1=Active, 0=Inactive
uint32_t ri : 1; ///< RI state: 1=Active, 0=Inactive
} usart_modem_stat_t;
/*----- USART Control Codes: on-off intrrupte type-----*/
typedef enum {
USART_INTR_WRITE,
USART_INTR_READ
} usart_intr_type_e;
/**
\brief USART Status
*/
typedef struct {
uint32_t tx_busy : 1; ///< Transmitter busy flag
uint32_t rx_busy : 1; ///< Receiver busy flag
uint32_t tx_underflow : 1; ///< Transmit data underflow detected (cleared on start of next send operation)(Synchronous Slave)
uint32_t rx_overflow : 1; ///< Receive data overflow detected (cleared on start of next receive operation)
uint32_t rx_break : 1; ///< Break detected on receive (cleared on start of next receive operation)
uint32_t rx_framing_error : 1; ///< Framing error detected on receive (cleared on start of next receive operation)
uint32_t rx_parity_error : 1; ///< Parity error detected on receive (cleared on start of next receive operation)
uint32_t tx_enable : 1; ///< Transmitter enable flag
uint32_t rx_enable : 1; ///< Receiver enbale flag
} usart_status_t;
/****** USART Event *****/
typedef enum {
USART_EVENT_SEND_COMPLETE = 0, ///< Send completed; however USART may still transmit data
USART_EVENT_RECEIVE_COMPLETE = 1, ///< Receive completed
USART_EVENT_TRANSFER_COMPLETE = 2, ///< Transfer completed
USART_EVENT_TX_COMPLETE = 3, ///< Transmit completed (optional)
USART_EVENT_TX_UNDERFLOW = 4, ///< Transmit data not available (Synchronous Slave)
USART_EVENT_RX_OVERFLOW = 5, ///< Receive data overflow
USART_EVENT_RX_TIMEOUT = 6, ///< Receive character timeout (optional)
USART_EVENT_RX_BREAK = 7, ///< Break detected on receive
USART_EVENT_RX_FRAMING_ERROR = 8, ///< Framing error detected on receive
USART_EVENT_RX_PARITY_ERROR = 9, ///< Parity error detected on receive
USART_EVENT_CTS = 10, ///< CTS state changed (optional)
USART_EVENT_DSR = 11, ///< DSR state changed (optional)
USART_EVENT_DCD = 12, ///< DCD state changed (optional)
USART_EVENT_RI = 13, ///< RI state changed (optional)
USART_EVENT_RECEIVED = 14, ///< Data Received, only in usart fifo, call receive()/transfer() get the data
} usart_event_e;
typedef void (*usart_event_cb_t)(int32_t idx, usart_event_e event); ///< Pointer to \ref usart_event_cb_t : USART Event call back.
/**
\brief USART Driver Capabilities.
*/
typedef struct {
uint32_t asynchronous : 1; ///< supports UART (Asynchronous) mode
uint32_t synchronous_master : 1; ///< supports Synchronous Master mode
uint32_t synchronous_slave : 1; ///< supports Synchronous Slave mode
uint32_t single_wire : 1; ///< supports UART Single-wire mode
uint32_t irda : 1; ///< supports UART IrDA mode
uint32_t smart_card : 1; ///< supports UART Smart Card mode
uint32_t smart_card_clock : 1; ///< Smart Card Clock generator available
uint32_t flow_control_rts : 1; ///< RTS Flow Control available
uint32_t flow_control_cts : 1; ///< CTS Flow Control available
uint32_t event_tx_complete : 1; ///< Transmit completed event: \ref USART_EVENT_TX_COMPLETE
uint32_t event_rx_timeout : 1; ///< Signal receive character timeout event: \ref USART_EVENT_RX_TIMEOUT
uint32_t rts : 1; ///< RTS Line: 0=not available, 1=available
uint32_t cts : 1; ///< CTS Line: 0=not available, 1=available
uint32_t dtr : 1; ///< DTR Line: 0=not available, 1=available
uint32_t dsr : 1; ///< DSR Line: 0=not available, 1=available
uint32_t dcd : 1; ///< DCD Line: 0=not available, 1=available
uint32_t ri : 1; ///< RI Line: 0=not available, 1=available
uint32_t event_cts : 1; ///< Signal CTS change event: \ref USART_EVENT_CTS
uint32_t event_dsr : 1; ///< Signal DSR change event: \ref USART_EVENT_DSR
uint32_t event_dcd : 1; ///< Signal DCD change event: \ref USART_EVENT_DCD
uint32_t event_ri : 1; ///< Signal RI change event: \ref USART_EVENT_RI
} usart_capabilities_t;
/**
\brief Initialize USART Interface. 1. Initializes the resources needed for the USART interface 2.registers event callback function
\param[in] idx usart index
\param[in] cb_event event call back function \ref usart_event_cb_t
\return return usart handle if success
*/
usart_handle_t csi_usart_initialize(int32_t idx, usart_event_cb_t cb_event);
/**
\brief De-initialize USART Interface. stops operation and releases the software resources used by the interface
\param[in] handle usart handle to operate.
\return error code
*/
int32_t csi_usart_uninitialize(usart_handle_t handle);
/**
\brief Get driver capabilities.
\param[in] idx usart index
\return \ref usart_capabilities_t
*/
usart_capabilities_t csi_usart_get_capabilities(int32_t idx);
/**
\brief config usart mode.
\param[in] handle usart handle to operate.
\param[in] baud baud rate.
\param[in] mode \ref usart_mode_e .
\param[in] parity \ref usart_parity_e .
\param[in] stopbits \ref usart_stop_bits_e .
\param[in] bits \ref usart_data_bits_e .
\return error code
*/
int32_t csi_usart_config(usart_handle_t handle,
uint32_t baud,
usart_mode_e mode,
usart_parity_e parity,
usart_stop_bits_e stopbits,
usart_data_bits_e bits);
/**
\brief Start sending data to USART transmitter,(received data is ignored).
This function is non-blocking,\ref usart_event_e is signaled when operation completes or error happens.
\ref csi_usart_get_status can get operation status.
\param[in] handle usart handle to operate.
\param[in] data Pointer to buffer with data to send to USART transmitter. data_type is : uint8_t for 5..8 data bits, uint16_t for 9 data bits
\param[in] num Number of data items to send
\return error code
*/
int32_t csi_usart_send(usart_handle_t handle, const void *data, uint32_t num);
/**
\brief Abort Send data to USART transmitter
\param[in] handle usart handle to operate.
\return error code
*/
int32_t csi_usart_abort_send(usart_handle_t handle);
/**
\brief Start receiving data from USART receiver. \n
This function is non-blocking,\ref usart_event_e is signaled when operation completes or error happens.
\ref csi_usart_get_status can get operation status.
\param[in] handle usart handle to operate.
\param[out] data Pointer to buffer for data to receive from USART receiver.data_type is : uint8_t for 5..8 data bits, uint16_t for 9 data bits
\param[in] num Number of data items to receive
\return error code
*/
int32_t csi_usart_receive(usart_handle_t handle, void *data, uint32_t num);
/**
\brief query data from UART receiver FIFO.
\param[in] handle usart handle to operate.
\param[out] data Pointer to buffer for data to receive from UART receiver
\param[in] num Number of data items to receive
\return fifo data num to receive
*/
int32_t csi_usart_receive_query(usart_handle_t handle, void *data, uint32_t num);
/**
\brief Abort Receive data from USART receiver
\param[in] handle usart handle to operate.
\return error code
*/
int32_t csi_usart_abort_receive(usart_handle_t handle);
/**
\brief Start synchronously sends data to the USART transmitter and receives data from the USART receiver. used in synchronous mode
This function is non-blocking,\ref usart_event_e is signaled when operation completes or error happens.
\ref csi_usart_get_status can get operation status.
\param[in] handle usart handle to operate.
\param[in] data_out Pointer to buffer with data to send to USART transmitter.data_type is : uint8_t for 5..8 data bits, uint16_t for 9 data bits
\param[out] data_in Pointer to buffer for data to receive from USART receiver.data_type is : uint8_t for 5..8 data bits, uint16_t for 9 data bits
\param[in] num Number of data items to transfer
\return error code
*/
int32_t csi_usart_transfer(usart_handle_t handle, const void *data_out, void *data_in, uint32_t num);
/**
\brief abort sending/receiving data to/from USART transmitter/receiver.
\param[in] handle usart handle to operate.
\return error code
*/
int32_t csi_usart_abort_transfer(usart_handle_t handle);
/**
\brief Get USART status.
\param[in] handle usart handle to operate.
\return USART status \ref usart_status_t
*/
usart_status_t csi_usart_get_status(usart_handle_t handle);
/**
\brief flush receive/send data.
\param[in] handle usart handle to operate.
\param[in] type \ref usart_flush_type_e .
\return error code
*/
int32_t csi_usart_flush(usart_handle_t handle, usart_flush_type_e type);
/**
\brief set interrupt mode.
\param[in] handle usart handle to operate.
\param[in] type \ref usart_intr_type_e.
\param[in] flag 0-OFF, 1-ON.
\return error code
*/
int32_t csi_usart_set_interrupt(usart_handle_t handle, usart_intr_type_e type, int32_t flag);
/**
\brief set the baud rate of usart.
\param[in] baud usart base to operate.
\param[in] baudrate baud rate
\return error code
*/
int32_t csi_usart_config_baudrate(usart_handle_t handle, uint32_t baud);
/**
\brief config usart mode.
\param[in] handle usart handle to operate.
\param[in] mode \ref usart_mode_e
\return error code
*/
int32_t csi_usart_config_mode(usart_handle_t handle, usart_mode_e mode);
/**
\brief config usart parity.
\param[in] handle usart handle to operate.
\param[in] parity \ref usart_parity_e
\return error code
*/
int32_t csi_usart_config_parity(usart_handle_t handle, usart_parity_e parity);
/**
\brief config usart stop bit number.
\param[in] handle usart handle to operate.
\param[in] stopbits \ref usart_stop_bits_e
\return error code
*/
int32_t csi_usart_config_stopbits(usart_handle_t handle, usart_stop_bits_e stopbit);
/**
\brief config usart data length.
\param[in] handle usart handle to operate.
\param[in] databits \ref usart_data_bits_e
\return error code
*/
int32_t csi_usart_config_databits(usart_handle_t handle, usart_data_bits_e databits);
/**
\brief get character in query mode.
\param[in] handle usart handle to operate.
\param[out] ch the pointer to the received character.
\return error code
*/
int32_t csi_usart_getchar(usart_handle_t handle, uint8_t *ch);
/**
\brief transmit character in query mode.
\param[in] handle usart handle to operate.
\param[in] ch the input character
\return error code
*/
int32_t csi_usart_putchar(usart_handle_t handle, uint8_t ch);
/**
\brief Get usart send data count.
\param[in] handle usart handle to operate.
\return number of currently transmitted data bytes
*/
uint32_t csi_usart_get_tx_count(usart_handle_t handle);
/**
\brief Get usart received data count.
\param[in] handle usart handle to operate.
\return number of currently received data bytes
*/
uint32_t csi_usart_get_rx_count(usart_handle_t handle);
/**
\brief control usart power.
\param[in] handle usart handle to operate.
\param[in] state power state.\ref csi_power_stat_e.
\return error code
*/
int32_t csi_usart_power_control(usart_handle_t handle, csi_power_stat_e state);
/**
\brief config usart flow control type.
\param[in] handle usart handle to operate.
\param[in] flowctrl_type flow control type.\ref usart_flowctrl_type_e.
\return error code
*/
int32_t csi_usart_config_flowctrl(usart_handle_t handle,
usart_flowctrl_type_e flowctrl_type);
/**
\brief config usart clock Polarity and Phase.
\param[in] handle usart handle to operate.
\param[in] cpol Clock Polarity.\ref usart_cpol_e.
\param[in] cpha Clock Phase.\ref usart_cpha_e.
\return error code
*/
int32_t csi_usart_config_clock(usart_handle_t handle, usart_cpol_e cpol, usart_cpha_e cpha);
/**
\brief control the transmitter.
\param[in] handle usart handle to operate.
\param[in] enable 1 - enable the transmitter. 0 - disable the transmitter
\return error code
*/
int32_t csi_usart_control_tx(usart_handle_t handle, uint32_t enable);
/**
\brief control the receiver.
\param[in] handle usart handle to operate.
\param[in] enable 1 - enable the receiver. 0 - disable the receiver
\return error code
*/
int32_t csi_usart_control_rx(usart_handle_t handle, uint32_t enable);
/**
\brief control the break.
\param[in] handle usart handle to operate.
\param[in] enable 1- Enable continuous Break transmission,0 - disable continuous Break transmission
\return error code
*/
int32_t csi_usart_control_break(usart_handle_t handle, uint32_t enable);
#ifdef __cplusplus
}
#endif
#endif /* _CSI_USART_H_ */
|
YifuLiu/AliOS-Things
|
hardware/chip/smarth_rv64/include/drv_usart.h
|
C
|
apache-2.0
| 18,858
|