code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* Dongle BUS interface Abstraction layer
* target buses like USB, SDIO, SPI, etc.
*
* Copyright (C) 1999-2011, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: dbus.h 280946 2011-08-31 21:41:04Z $
*/
#ifndef __DBUS_H__
#define __DBUS_H__
#include "typedefs.h"
#define DBUSTRACE(args)
#define DBUSERR(args)
#define DBUSDBGLOCK(args)
enum {
DBUS_OK = 0,
DBUS_ERR = -200,
DBUS_ERR_TIMEOUT,
DBUS_ERR_DISCONNECT,
DBUS_ERR_NODEVICE,
DBUS_ERR_UNSUPPORTED,
DBUS_ERR_PENDING,
DBUS_ERR_NOMEM,
DBUS_ERR_TXFAIL,
DBUS_ERR_TXTIMEOUT,
DBUS_ERR_TXDROP,
DBUS_ERR_RXFAIL,
DBUS_ERR_RXDROP,
DBUS_ERR_TXCTLFAIL,
DBUS_ERR_RXCTLFAIL,
DBUS_ERR_REG_PARAM,
DBUS_STATUS_CANCELLED,
DBUS_ERR_NVRAM
};
#define ERR_CBMASK_TXFAIL 0x00000001
#define ERR_CBMASK_RXFAIL 0x00000002
#define ERR_CBMASK_ALL 0xFFFFFFFF
#define DBUS_CBCTL_WRITE 0
#define DBUS_CBCTL_READ 1
#define DBUS_CBINTR_POLL 2
#define DBUS_TX_RETRY_LIMIT 3 /* retries for failed txirb */
#define DBUS_TX_TIMEOUT_INTERVAL 250 /* timeout for txirb complete, in ms */
#define DBUS_BUFFER_SIZE_TX 16000
#define DBUS_BUFFER_SIZE_RX 5000
#define DBUS_BUFFER_SIZE_TX_NOAGG 2048
#define DBUS_BUFFER_SIZE_RX_NOAGG 2048
/* DBUS types */
enum {
DBUS_USB,
DBUS_SDIO,
DBUS_SPI,
DBUS_UNKNOWN
};
enum dbus_state {
DBUS_STATE_DL_PENDING,
DBUS_STATE_DL_DONE,
DBUS_STATE_UP,
DBUS_STATE_DOWN,
DBUS_STATE_PNP_FWDL,
DBUS_STATE_DISCONNECT,
DBUS_STATE_SLEEP
};
enum dbus_pnp_state {
DBUS_PNP_DISCONNECT,
DBUS_PNP_SLEEP,
DBUS_PNP_RESUME,
DBUS_PNP_HSIC_SATE,
DBUS_PNP_HSIC_AUTOSLEEP_ENABLE,
DBUS_PNP_HSIC_AUTOSLEEP_DISABLE,
DBUS_PNP_HSIC_AUTOSLEEP_STATE
};
typedef enum _DEVICE_SPEED {
INVALID_SPEED = -1,
LOW_SPEED = 1, /* USB 1.1: 1.5 Mbps */
FULL_SPEED, /* USB 1.1: 12 Mbps */
HIGH_SPEED, /* USB 2.0: 480 Mbps */
SUPER_SPEED, /* USB 3.0: 4.8 Gbps */
} DEVICE_SPEED;
typedef struct {
int bustype;
int vid;
int pid;
int devid;
int chiprev; /* chip revsion number */
int mtu;
int nchan; /* Data Channels */
int has_2nd_bulk_in_ep;
} dbus_attrib_t;
typedef struct {
uint32 rx_errors;
uint32 tx_errors;
uint32 rx_dropped;
uint32 tx_dropped;
} dbus_stats_t;
/*
* Configurable BUS parameters
*/
typedef struct {
bool rxctl_deferrespok;
} dbus_config_t;
struct dbus_callbacks;
struct exec_parms;
typedef void *(*probe_cb_t)(void *arg, const char *desc, uint32 bustype, uint32 hdrlen);
typedef void (*disconnect_cb_t)(void *arg);
typedef void *(*exec_cb_t)(struct exec_parms *args);
/* Client callbacks registered during dbus_attach() */
typedef struct dbus_callbacks {
void (*send_complete)(void *cbarg, void *info, int status);
void (*recv_buf)(void *cbarg, uint8 *buf, int len);
void (*recv_pkt)(void *cbarg, void *pkt);
void (*txflowcontrol)(void *cbarg, bool onoff);
void (*errhandler)(void *cbarg, int err);
void (*ctl_complete)(void *cbarg, int type, int status);
void (*state_change)(void *cbarg, int state);
void *(*pktget)(void *cbarg, uint len, bool send);
void (*pktfree)(void *cbarg, void *p, bool send);
} dbus_callbacks_t;
struct dbus_pub;
struct bcmstrbuf;
struct dbus_irb;
struct dbus_irb_rx;
struct dbus_irb_tx;
struct dbus_intf_callbacks;
typedef struct {
void* (*attach)(struct dbus_pub *pub, void *cbarg, struct dbus_intf_callbacks *cbs);
void (*detach)(struct dbus_pub *pub, void *bus);
int (*up)(void *bus);
int (*down)(void *bus);
int (*send_irb)(void *bus, struct dbus_irb_tx *txirb);
int (*recv_irb)(void *bus, struct dbus_irb_rx *rxirb);
int (*cancel_irb)(void *bus, struct dbus_irb_tx *txirb);
int (*send_ctl)(void *bus, uint8 *buf, int len);
int (*recv_ctl)(void *bus, uint8 *buf, int len);
int (*get_stats)(void *bus, dbus_stats_t *stats);
int (*get_attrib)(void *bus, dbus_attrib_t *attrib);
int (*pnp)(void *bus, int event);
int (*remove)(void *bus);
int (*resume)(void *bus);
int (*suspend)(void *bus);
int (*stop)(void *bus);
int (*reset)(void *bus);
/* Access to bus buffers directly */
void *(*pktget)(void *bus, int len);
void (*pktfree)(void *bus, void *pkt);
int (*iovar_op)(void *bus, const char *name, void *params, int plen, void *arg, int len,
bool set);
void (*dump)(void *bus, struct bcmstrbuf *strbuf);
int (*set_config)(void *bus, dbus_config_t *config);
int (*get_config)(void *bus, dbus_config_t *config);
bool (*device_exists)(void *bus);
bool (*dlneeded)(void *bus);
int (*dlstart)(void *bus, uint8 *fw, int len);
int (*dlrun)(void *bus);
bool (*recv_needed)(void *bus);
void *(*exec_rxlock)(void *bus, exec_cb_t func, struct exec_parms *args);
void *(*exec_txlock)(void *bus, exec_cb_t func, struct exec_parms *args);
void (*set_revinfo)(void *bus, uint32 chipid, uint32 chiprev);
void (*get_revinfo)(void *bus, uint32 *chipid, uint32 *chiprev);
int (*tx_timer_init)(void *bus);
int (*tx_timer_start)(void *bus, uint timeout);
int (*tx_timer_stop)(void *bus);
int (*sched_dpc)(void *bus);
int (*lock)(void *bus);
int (*unlock)(void *bus);
int (*sched_probe_cb)(void *bus);
int (*shutdown)(void *bus);
int (*recv_stop)(void *bus);
int (*recv_resume)(void *bus);
int (*recv_irb_from_ep)(void *bus, struct dbus_irb_rx *rxirb, uint ep_idx);
/* Add from the bottom */
} dbus_intf_t;
typedef struct dbus_pub {
struct osl_info *osh;
dbus_stats_t stats;
dbus_attrib_t attrib;
enum dbus_state busstate;
DEVICE_SPEED device_speed;
int ntxq, nrxq, rxsize;
void *bus;
struct shared_info *sh;
} dbus_pub_t;
#define BUS_INFO(bus, type) (((type *) bus)->pub->bus)
/*
* Public Bus Function Interface
*/
extern int dbus_register(int vid, int pid, probe_cb_t prcb, disconnect_cb_t discb, void *prarg,
void *param1, void *param2);
extern int dbus_deregister(void);
extern const dbus_pub_t *dbus_attach(struct osl_info *osh, int rxsize, int nrxq, int ntxq,
void *cbarg, dbus_callbacks_t *cbs, struct shared_info *sh);
extern void dbus_detach(const dbus_pub_t *pub);
extern int dbus_up(const dbus_pub_t *pub);
extern int dbus_down(const dbus_pub_t *pub);
extern int dbus_stop(const dbus_pub_t *pub);
extern int dbus_shutdown(const dbus_pub_t *pub);
extern void dbus_flowctrl_rx(const dbus_pub_t *pub, bool on);
extern int dbus_send_buf(const dbus_pub_t *pub, uint8 *buf, int len, void *info);
extern int dbus_send_pkt(const dbus_pub_t *pub, void *pkt, void *info);
extern int dbus_send_ctl(const dbus_pub_t *pub, uint8 *buf, int len);
extern int dbus_recv_ctl(const dbus_pub_t *pub, uint8 *buf, int len);
extern int dbus_recv_bulk(const dbus_pub_t *pub, uint32 ep_idx);
extern int dbus_poll_intr(const dbus_pub_t *pub);
extern int dbus_get_stats(const dbus_pub_t *pub, dbus_stats_t *stats);
extern int dbus_get_attrib(const dbus_pub_t *pub, dbus_attrib_t *attrib);
extern int dbus_get_device_speed(const dbus_pub_t *pub);
extern int dbus_set_config(const dbus_pub_t *pub, dbus_config_t *config);
extern int dbus_get_config(const dbus_pub_t *pub, dbus_config_t *config);
extern void *dbus_pktget(const dbus_pub_t *pub, int len);
extern void dbus_pktfree(const dbus_pub_t *pub, void* pkt);
extern int dbus_set_errmask(const dbus_pub_t *pub, uint32 mask);
extern int dbus_pnp_sleep(const dbus_pub_t *pub);
extern int dbus_pnp_resume(const dbus_pub_t *pub, int *fw_reload);
extern int dbus_pnp_disconnect(const dbus_pub_t *pub);
extern void dbus_set_revinfo(const dbus_pub_t *pub, uint32 chipid, uint32 chiprev);
extern void dbus_get_revinfo(const dbus_pub_t *pub, uint32 *chipid, uint32 *chiprev);
extern int dbus_iovar_op(const dbus_pub_t *pub, const char *name,
void *params, int plen, void *arg, int len, bool set);
extern int dbus_send_txdata(const dbus_pub_t *dbus, void *pktbuf);
extern void *dhd_dbus_txq(const dbus_pub_t *pub);
extern uint dhd_dbus_hdrlen(const dbus_pub_t *pub);
/*
* Private Common Bus Interface
*/
/* IO Request Block (IRB) */
typedef struct dbus_irb {
struct dbus_irb *next; /* it's casted from dbus_irb_tx or dbus_irb_rx struct */
} dbus_irb_t;
typedef struct dbus_irb_rx {
struct dbus_irb irb; /* Must be first */
uint8 *buf;
int buf_len;
int actual_len;
void *pkt;
void *info;
void *arg;
} dbus_irb_rx_t;
typedef struct dbus_irb_tx {
struct dbus_irb irb; /* Must be first */
uint8 *buf;
int len;
void *pkt;
int retry_count;
void *info;
void *arg;
void *send_buf; /* linear bufffer for LINUX when aggreagtion is enabled */
} dbus_irb_tx_t;
/* DBUS interface callbacks are different from user callbacks
* so, internally, different info can be passed to upper layer
*/
typedef struct dbus_intf_callbacks {
void (*send_irb_timeout)(void *cbarg, dbus_irb_tx_t *txirb);
void (*send_irb_complete)(void *cbarg, dbus_irb_tx_t *txirb, int status);
void (*recv_irb_complete)(void *cbarg, dbus_irb_rx_t *rxirb, int status);
void (*errhandler)(void *cbarg, int err);
void (*ctl_complete)(void *cbarg, int type, int status);
void (*state_change)(void *cbarg, int state);
bool (*isr)(void *cbarg, bool *wantdpc);
bool (*dpc)(void *cbarg, bool bounded);
void (*watchdog)(void *cbarg);
void *(*pktget)(void *cbarg, uint len, bool send);
void (*pktfree)(void *cbarg, void *p, bool send);
struct dbus_irb* (*getirb)(void *cbarg, bool send);
void (*rxerr_indicate)(void *cbarg, bool on);
} dbus_intf_callbacks_t;
/*
* Porting: To support new bus, port these functions below
*/
/*
* Bus specific Interface
* Implemented by dbus_usb.c/dbus_sdio.c
*/
extern int dbus_bus_register(int vid, int pid, probe_cb_t prcb, disconnect_cb_t discb, void *prarg,
dbus_intf_t **intf, void *param1, void *param2);
extern int dbus_bus_deregister(void);
/*
* Bus-specific and OS-specific Interface
* Implemented by dbus_usb_[linux/ndis].c/dbus_sdio_[linux/ndis].c
*/
extern int dbus_bus_osl_register(int vid, int pid, probe_cb_t prcb, disconnect_cb_t discb,
void *prarg, dbus_intf_t **intf, void *param1, void *param2);
extern int dbus_bus_osl_deregister(void);
/*
* Bus-specific, OS-specific, HW-specific Interface
* Mainly for SDIO Host HW controller
*/
extern int dbus_bus_osl_hw_register(int vid, int pid, probe_cb_t prcb, disconnect_cb_t discb,
void *prarg, dbus_intf_t **intf);
extern int dbus_bus_osl_hw_deregister(void);
extern uint usbdev_bulkin_eps(void);
#endif /* __DBUS_H__ */
| Michael-Pizzileo/lichee-3.0.8-leaked | modules/wifi/bcm40183/5.90.125.95.3/open-src/src/include/dbus.h | C | gpl-2.0 | 11,256 |
/* dvb-usb-ids.h is part of the DVB USB library.
*
* Copyright (C) 2004-5 Patrick Boettcher ([email protected]) see
* dvb-usb-init.c for copyright information.
*
* a header file containing define's for the USB device supported by the
* various drivers.
*/
#ifndef _DVB_USB_IDS_H_
#define _DVB_USB_IDS_H_
/* Vendor IDs */
#define USB_VID_ADSTECH 0x06e1
#define USB_VID_AFATECH 0x15a4
#define USB_VID_ALCOR_MICRO 0x058f
#define USB_VID_ALINK 0x05e3
#define USB_VID_AMT 0x1c73
#define USB_VID_ANCHOR 0x0547
#define USB_VID_ANSONIC 0x10b9
#define USB_VID_ANUBIS_ELECTRONIC 0x10fd
#define USB_VID_ASUS 0x0b05
#define USB_VID_AVERMEDIA 0x07ca
#define USB_VID_COMPRO 0x185b
#define USB_VID_COMPRO_UNK 0x145f
#define USB_VID_CONEXANT 0x0572
#define USB_VID_CYPRESS 0x04b4
#define USB_VID_DIBCOM 0x10b8
#define USB_VID_DPOSH 0x1498
#define USB_VID_DVICO 0x0fe9
#define USB_VID_E3C 0x18b4
#define USB_VID_ELGATO 0x0fd9
#define USB_VID_EMPIA 0xeb1a
#define USB_VID_GENPIX 0x09c0
#define USB_VID_GRANDTEC 0x5032
#define USB_VID_HANFTEK 0x15f4
#define USB_VID_HAUPPAUGE 0x2040
#define USB_VID_HYPER_PALTEK 0x1025
#define USB_VID_INTEL 0x8086
#define USB_VID_KWORLD 0xeb2a
#define USB_VID_KWORLD_2 0x1b80
#define USB_VID_KYE 0x0458
#define USB_VID_LEADTEK 0x0413
#define USB_VID_LITEON 0x04ca
#define USB_VID_MEDION 0x1660
#define USB_VID_MIGLIA 0x18f3
#define USB_VID_MSI 0x0db0
#define USB_VID_MSI_2 0x1462
#define USB_VID_OPERA1 0x695c
#define USB_VID_PINNACLE 0x2304
#define USB_VID_PCTV 0x2013
#define USB_VID_PIXELVIEW 0x1554
#define USB_VID_TECHNOTREND 0x0b48
#define USB_VID_TERRATEC 0x0ccd
#define USB_VID_TELESTAR 0x10b9
#define USB_VID_VISIONPLUS 0x13d3
#define USB_VID_SONY 0x1415
#define USB_VID_TWINHAN 0x1822
#define USB_VID_ULTIMA_ELECTRONIC 0x05d8
#define USB_VID_UNIWILL 0x1584
#define USB_VID_WIDEVIEW 0x14aa
#define USB_VID_GIGABYTE 0x1044
#define USB_VID_YUAN 0x1164
#define USB_VID_XTENSIONS 0x1ae7
#define USB_VID_HUMAX_COEX 0x10b9
#define USB_VID_774 0x7a69
#define USB_VID_EVOLUTEPC 0x1e59
#define USB_VID_AZUREWAVE 0x13d3
#define USB_VID_TECHNISAT 0x14f7
/* Product IDs */
#define USB_PID_ADSTECH_USB2_COLD 0xa333
#define USB_PID_ADSTECH_USB2_WARM 0xa334
#define USB_PID_AFATECH_AF9005 0x9020
#define USB_PID_AFATECH_AF9015_9015 0x9015
#define USB_PID_AFATECH_AF9015_9016 0x9016
#define USB_PID_TREKSTOR_DVBT 0x901b
#define USB_VID_ALINK_DTU 0xf170
#define USB_PID_ANSONIC_DVBT_USB 0x6000
#define USB_PID_ANYSEE 0x861f
#define USB_PID_AZUREWAVE_AD_TU700 0x3237
#define USB_PID_AVERMEDIA_DVBT_USB_COLD 0x0001
#define USB_PID_AVERMEDIA_DVBT_USB_WARM 0x0002
#define USB_PID_AVERMEDIA_DVBT_USB2_COLD 0xa800
#define USB_PID_AVERMEDIA_DVBT_USB2_WARM 0xa801
#define USB_PID_COMPRO_DVBU2000_COLD 0xd000
#define USB_PID_COMPRO_DVBU2000_WARM 0xd001
#define USB_PID_COMPRO_DVBU2000_UNK_COLD 0x010c
#define USB_PID_COMPRO_DVBU2000_UNK_WARM 0x010d
#define USB_PID_COMPRO_VIDEOMATE_U500 0x1e78
#define USB_PID_COMPRO_VIDEOMATE_U500_PC 0x1e80
#define USB_PID_CONCEPTRONIC_CTVDIGRCU 0xe397
#define USB_PID_CONEXANT_D680_DMB 0x86d6
#define USB_PID_DIBCOM_HOOK_DEFAULT 0x0064
#define USB_PID_DIBCOM_HOOK_DEFAULT_REENUM 0x0065
#define USB_PID_DIBCOM_MOD3000_COLD 0x0bb8
#define USB_PID_DIBCOM_MOD3000_WARM 0x0bb9
#define USB_PID_DIBCOM_MOD3001_COLD 0x0bc6
#define USB_PID_DIBCOM_MOD3001_WARM 0x0bc7
#define USB_PID_DIBCOM_STK7700P 0x1e14
#define USB_PID_DIBCOM_STK7700P_PC 0x1e78
#define USB_PID_DIBCOM_STK7700D 0x1ef0
#define USB_PID_DIBCOM_STK7700_U7000 0x7001
#define USB_PID_DIBCOM_STK7070P 0x1ebc
#define USB_PID_DIBCOM_STK7070PD 0x1ebe
#define USB_PID_DIBCOM_STK807XP 0x1f90
#define USB_PID_DIBCOM_STK807XPVR 0x1f98
#define USB_PID_DIBCOM_STK8096GP 0x1fa0
#define USB_PID_DIBCOM_ANCHOR_2135_COLD 0x2131
#define USB_PID_DIBCOM_STK7770P 0x1e80
#define USB_PID_DPOSH_M9206_COLD 0x9206
#define USB_PID_DPOSH_M9206_WARM 0xa090
#define USB_PID_E3C_EC168 0x1689
#define USB_PID_E3C_EC168_2 0xfffa
#define USB_PID_E3C_EC168_3 0xfffb
#define USB_PID_E3C_EC168_4 0x1001
#define USB_PID_E3C_EC168_5 0x1002
#define USB_PID_UNIWILL_STK7700P 0x6003
#define USB_PID_GENIUS_TVGO_DVB_T03 0x4012
#define USB_PID_GRANDTEC_DVBT_USB_COLD 0x0fa0
#define USB_PID_GRANDTEC_DVBT_USB_WARM 0x0fa1
#define USB_PID_INTEL_CE9500 0x9500
#define USB_PID_KWORLD_399U 0xe399
#define USB_PID_KWORLD_399U_2 0xe400
#define USB_PID_KWORLD_395U 0xe396
#define USB_PID_KWORLD_395U_2 0xe39b
#define USB_PID_KWORLD_395U_3 0xe395
#define USB_PID_KWORLD_MC810 0xc810
#define USB_PID_KWORLD_PC160_2T 0xc160
#define USB_PID_KWORLD_PC160_T 0xc161
#define USB_PID_KWORLD_VSTREAM_COLD 0x17de
#define USB_PID_KWORLD_VSTREAM_WARM 0x17df
#define USB_PID_TERRATEC_CINERGY_T_USB_XE 0x0055
#define USB_PID_TERRATEC_CINERGY_T_USB_XE_REV2 0x0069
#define USB_PID_TWINHAN_VP7041_COLD 0x3201
#define USB_PID_TWINHAN_VP7041_WARM 0x3202
#define USB_PID_TWINHAN_VP7020_COLD 0x3203
#define USB_PID_TWINHAN_VP7020_WARM 0x3204
#define USB_PID_TWINHAN_VP7045_COLD 0x3205
#define USB_PID_TWINHAN_VP7045_WARM 0x3206
#define USB_PID_TWINHAN_VP7021_COLD 0x3207
#define USB_PID_TWINHAN_VP7021_WARM 0x3208
#define USB_PID_TINYTWIN 0x3226
#define USB_PID_TINYTWIN_2 0xe402
#define USB_PID_DNTV_TINYUSB2_COLD 0x3223
#define USB_PID_DNTV_TINYUSB2_WARM 0x3224
#define USB_PID_ULTIMA_TVBOX_COLD 0x8105
#define USB_PID_ULTIMA_TVBOX_WARM 0x8106
#define USB_PID_ULTIMA_TVBOX_AN2235_COLD 0x8107
#define USB_PID_ULTIMA_TVBOX_AN2235_WARM 0x8108
#define USB_PID_ULTIMA_TVBOX_ANCHOR_COLD 0x2235
#define USB_PID_ULTIMA_TVBOX_USB2_COLD 0x8109
#define USB_PID_ULTIMA_TVBOX_USB2_WARM 0x810a
#define USB_PID_ARTEC_T14_COLD 0x810b
#define USB_PID_ARTEC_T14_WARM 0x810c
#define USB_PID_ARTEC_T14BR 0x810f
#define USB_PID_ULTIMA_TVBOX_USB2_FX_COLD 0x8613
#define USB_PID_ULTIMA_TVBOX_USB2_FX_WARM 0x1002
#define USB_PID_UNK_HYPER_PALTEK_COLD 0x005e
#define USB_PID_UNK_HYPER_PALTEK_WARM 0x005f
#define USB_PID_HANFTEK_UMT_010_COLD 0x0001
#define USB_PID_HANFTEK_UMT_010_WARM 0x0015
#define USB_PID_DTT200U_COLD 0x0201
#define USB_PID_DTT200U_WARM 0x0301
#define USB_PID_WT220U_ZAP250_COLD 0x0220
#define USB_PID_WT220U_COLD 0x0222
#define USB_PID_WT220U_WARM 0x0221
#define USB_PID_WT220U_FC_COLD 0x0225
#define USB_PID_WT220U_FC_WARM 0x0226
#define USB_PID_WT220U_ZL0353_COLD 0x022a
#define USB_PID_WT220U_ZL0353_WARM 0x022b
#define USB_PID_WINTV_NOVA_T_USB2_COLD 0x9300
#define USB_PID_WINTV_NOVA_T_USB2_WARM 0x9301
#define USB_PID_HAUPPAUGE_NOVA_T_500 0x9941
#define USB_PID_HAUPPAUGE_NOVA_T_500_2 0x9950
#define USB_PID_HAUPPAUGE_NOVA_T_500_3 0x8400
#define USB_PID_HAUPPAUGE_NOVA_T_STICK 0x7050
#define USB_PID_HAUPPAUGE_NOVA_T_STICK_2 0x7060
#define USB_PID_HAUPPAUGE_NOVA_T_STICK_3 0x7070
#define USB_PID_HAUPPAUGE_MYTV_T 0x7080
#define USB_PID_HAUPPAUGE_NOVA_TD_STICK 0x9580
#define USB_PID_HAUPPAUGE_NOVA_TD_STICK_52009 0x5200
#define USB_PID_HAUPPAUGE_TIGER_ATSC 0xb200
#define USB_PID_HAUPPAUGE_TIGER_ATSC_B210 0xb210
#define USB_PID_AVERMEDIA_EXPRESS 0xb568
#define USB_PID_AVERMEDIA_VOLAR 0xa807
#define USB_PID_AVERMEDIA_VOLAR_2 0xb808
#define USB_PID_AVERMEDIA_VOLAR_A868R 0xa868
#define USB_PID_AVERMEDIA_MCE_USB_M038 0x1228
#define USB_PID_AVERMEDIA_HYBRID_ULTRA_USB_M039R 0x0039
#define USB_PID_AVERMEDIA_HYBRID_ULTRA_USB_M039R_ATSC 0x1039
#define USB_PID_AVERMEDIA_HYBRID_ULTRA_USB_M039R_DVBT 0x2039
#define USB_PID_AVERMEDIA_VOLAR_X 0xa815
#define USB_PID_AVERMEDIA_VOLAR_X_2 0x8150
#define USB_PID_AVERMEDIA_A309 0xa309
#define USB_PID_AVERMEDIA_A310 0xa310
#define USB_PID_AVERMEDIA_A850 0x850a
#define USB_PID_AVERMEDIA_A805 0xa805
#define USB_PID_TECHNOTREND_CONNECT_S2400 0x3006
#define USB_PID_TERRATEC_CINERGY_DT_XS_DIVERSITY 0x005a
#define USB_PID_TERRATEC_CINERGY_DT_XS_DIVERSITY_2 0x0081
#define USB_PID_TERRATEC_CINERGY_HT_USB_XE 0x0058
#define USB_PID_TERRATEC_CINERGY_HT_EXPRESS 0x0060
#define USB_PID_TERRATEC_CINERGY_T_EXPRESS 0x0062
#define USB_PID_TERRATEC_CINERGY_T_XXS 0x0078
#define USB_PID_TERRATEC_CINERGY_T_XXS_2 0x00ab
#define USB_PID_TERRATEC_T3 0x10a0
#define USB_PID_TERRATEC_T5 0x10a1
#define USB_PID_PINNACLE_EXPRESSCARD_320CX 0x022e
#define USB_PID_PINNACLE_PCTV2000E 0x022c
#define USB_PID_PINNACLE_PCTV_DVB_T_FLASH 0x0228
#define USB_PID_PINNACLE_PCTV_DUAL_DIVERSITY_DVB_T 0x0229
#define USB_PID_PINNACLE_PCTV71E 0x022b
#define USB_PID_PINNACLE_PCTV72E 0x0236
#define USB_PID_PINNACLE_PCTV73E 0x0237
#define USB_PID_PINNACLE_PCTV310E 0x3211
#define USB_PID_PINNACLE_PCTV801E 0x023a
#define USB_PID_PINNACLE_PCTV801E_SE 0x023b
#define USB_PID_PINNACLE_PCTV73A 0x0243
#define USB_PID_PINNACLE_PCTV73ESE 0x0245
#define USB_PID_PINNACLE_PCTV74E 0x0246
#define USB_PID_PINNACLE_PCTV282E 0x0248
#define USB_PID_PIXELVIEW_SBTVD 0x5010
#define USB_PID_PCTV_200E 0x020e
#define USB_PID_PCTV_400E 0x020f
#define USB_PID_PCTV_450E 0x0222
#define USB_PID_NEBULA_DIGITV 0x0201
#define USB_PID_DVICO_BLUEBIRD_LGDT 0xd820
#define USB_PID_DVICO_BLUEBIRD_LG064F_COLD 0xd500
#define USB_PID_DVICO_BLUEBIRD_LG064F_WARM 0xd501
#define USB_PID_DVICO_BLUEBIRD_LGZ201_COLD 0xdb00
#define USB_PID_DVICO_BLUEBIRD_LGZ201_WARM 0xdb01
#define USB_PID_DVICO_BLUEBIRD_TH7579_COLD 0xdb10
#define USB_PID_DVICO_BLUEBIRD_TH7579_WARM 0xdb11
#define USB_PID_DVICO_BLUEBIRD_DUAL_1_COLD 0xdb50
#define USB_PID_DVICO_BLUEBIRD_DUAL_1_WARM 0xdb51
#define USB_PID_DVICO_BLUEBIRD_DUAL_2_COLD 0xdb58
#define USB_PID_DVICO_BLUEBIRD_DUAL_2_WARM 0xdb59
#define USB_PID_DVICO_BLUEBIRD_DUAL_4 0xdb78
#define USB_PID_DVICO_BLUEBIRD_DUAL_4_REV_2 0xdb98
#define USB_PID_DVICO_BLUEBIRD_DVB_T_NANO_2 0xdb70
#define USB_PID_DVICO_BLUEBIRD_DVB_T_NANO_2_NFW_WARM 0xdb71
#define USB_PID_DIGITALNOW_BLUEBIRD_DUAL_1_COLD 0xdb54
#define USB_PID_DIGITALNOW_BLUEBIRD_DUAL_1_WARM 0xdb55
#define USB_PID_MEDION_MD95700 0x0932
#define USB_PID_MSI_MEGASKY580 0x5580
#define USB_PID_MSI_MEGASKY580_55801 0x5581
#define USB_PID_KYE_DVB_T_COLD 0x701e
#define USB_PID_KYE_DVB_T_WARM 0x701f
#define USB_PID_LITEON_DVB_T_COLD 0xf000
#define USB_PID_LITEON_DVB_T_WARM 0xf001
#define USB_PID_DIGIVOX_MINI_SL_COLD 0xe360
#define USB_PID_DIGIVOX_MINI_SL_WARM 0xe361
#define USB_PID_GRANDTEC_DVBT_USB2_COLD 0x0bc6
#define USB_PID_GRANDTEC_DVBT_USB2_WARM 0x0bc7
#define USB_PID_WINFAST_DTV2000DS 0x6a04
#define USB_PID_WINFAST_DTV_DONGLE_COLD 0x6025
#define USB_PID_WINFAST_DTV_DONGLE_WARM 0x6026
#define USB_PID_WINFAST_DTV_DONGLE_STK7700P 0x6f00
#define USB_PID_WINFAST_DTV_DONGLE_H 0x60f6
#define USB_PID_WINFAST_DTV_DONGLE_STK7700P_2 0x6f01
#define USB_PID_WINFAST_DTV_DONGLE_GOLD 0x6029
#define USB_PID_GENPIX_8PSK_REV_1_COLD 0x0200
#define USB_PID_GENPIX_8PSK_REV_1_WARM 0x0201
#define USB_PID_GENPIX_8PSK_REV_2 0x0202
#define USB_PID_GENPIX_SKYWALKER_1 0x0203
#define USB_PID_GENPIX_SKYWALKER_CW3K 0x0204
#define USB_PID_SIGMATEK_DVB_110 0x6610
#define USB_PID_MSI_DIGI_VOX_MINI_II 0x1513
#define USB_PID_MSI_DIGIVOX_DUO 0x8801
#define USB_PID_OPERA1_COLD 0x2830
#define USB_PID_OPERA1_WARM 0x3829
#define USB_PID_LIFEVIEW_TV_WALKER_TWIN_COLD 0x0514
#define USB_PID_LIFEVIEW_TV_WALKER_TWIN_WARM 0x0513
#define USB_PID_GIGABYTE_U7000 0x7001
#define USB_PID_GIGABYTE_U8000 0x7002
#define USB_PID_ASUS_U3000 0x171f
#define USB_PID_ASUS_U3000H 0x1736
#define USB_PID_ASUS_U3100 0x173f
#define USB_PID_YUAN_EC372S 0x1edc
#define USB_PID_YUAN_STK7700PH 0x1f08
#define USB_PID_YUAN_PD378S 0x2edc
#define USB_PID_YUAN_MC770 0x0871
#define USB_PID_YUAN_STK7700D 0x1efc
#define USB_PID_YUAN_STK7700D_2 0x1e8c
#define USB_PID_DW2102 0x2102
#define USB_PID_XTENSIONS_XD_380 0x0381
#define USB_PID_TELESTAR_STARSTICK_2 0x8000
#define USB_PID_MSI_DIGI_VOX_MINI_III 0x8807
#define USB_PID_SONY_PLAYTV 0x0003
#define USB_PID_MYGICA_D689 0xd811
#define USB_PID_ELGATO_EYETV_DTT 0x0021
#define USB_PID_ELGATO_EYETV_DTT_Dlx 0x0020
#define USB_PID_DVB_T_USB_STICK_HIGH_SPEED_COLD 0x5000
#define USB_PID_DVB_T_USB_STICK_HIGH_SPEED_WARM 0x5001
#define USB_PID_FRIIO_WHITE 0x0001
#define USB_PID_TVWAY_PLUS 0x0002
#define USB_PID_SVEON_STV20 0xe39d
#define USB_PID_AZUREWAVE_AZ6027 0x3275
#define USB_PID_TERRATEC_DVBS2CI 0x3275
#define USB_PID_TECHNISAT_USB2_HDCI 0x0002
#endif
| ggsamsa/sched_casio | drivers/media/dvb/dvb-usb/dvb-usb-ids.h | C | gpl-2.0 | 12,626 |
/*
* This file is part of the Chelsio FCoE driver for Linux.
*
* Copyright (c) 2008-2012 Chelsio Communications, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/ctype.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/compiler.h>
#include <linux/export.h>
#include <linux/module.h>
#include <asm/unaligned.h>
#include <asm/page.h>
#include <scsi/scsi.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_transport_fc.h>
#include "csio_hw.h"
#include "csio_lnode.h"
#include "csio_rnode.h"
#include "csio_scsi.h"
#include "csio_init.h"
int csio_scsi_eqsize = 65536;
int csio_scsi_iqlen = 128;
int csio_scsi_ioreqs = 2048;
uint32_t csio_max_scan_tmo;
uint32_t csio_delta_scan_tmo = 5;
int csio_lun_qdepth = 32;
static int csio_ddp_descs = 128;
static int csio_do_abrt_cls(struct csio_hw *,
struct csio_ioreq *, bool);
static void csio_scsis_uninit(struct csio_ioreq *, enum csio_scsi_ev);
static void csio_scsis_io_active(struct csio_ioreq *, enum csio_scsi_ev);
static void csio_scsis_tm_active(struct csio_ioreq *, enum csio_scsi_ev);
static void csio_scsis_aborting(struct csio_ioreq *, enum csio_scsi_ev);
static void csio_scsis_closing(struct csio_ioreq *, enum csio_scsi_ev);
static void csio_scsis_shost_cmpl_await(struct csio_ioreq *, enum csio_scsi_ev);
/*
* csio_scsi_match_io - Match an ioreq with the given SCSI level data.
* @ioreq: The I/O request
* @sld: Level information
*
* Should be called with lock held.
*
*/
static bool
csio_scsi_match_io(struct csio_ioreq *ioreq, struct csio_scsi_level_data *sld)
{
struct scsi_cmnd *scmnd = csio_scsi_cmnd(ioreq);
switch (sld->level) {
case CSIO_LEV_LUN:
if (scmnd == NULL)
return false;
return ((ioreq->lnode == sld->lnode) &&
(ioreq->rnode == sld->rnode) &&
((uint64_t)scmnd->device->lun == sld->oslun));
case CSIO_LEV_RNODE:
return ((ioreq->lnode == sld->lnode) &&
(ioreq->rnode == sld->rnode));
case CSIO_LEV_LNODE:
return (ioreq->lnode == sld->lnode);
case CSIO_LEV_ALL:
return true;
default:
return false;
}
}
/*
* csio_scsi_gather_active_ios - Gather active I/Os based on level
* @scm: SCSI module
* @sld: Level information
* @dest: The queue where these I/Os have to be gathered.
*
* Should be called with lock held.
*/
static void
csio_scsi_gather_active_ios(struct csio_scsim *scm,
struct csio_scsi_level_data *sld,
struct list_head *dest)
{
struct list_head *tmp, *next;
if (list_empty(&scm->active_q))
return;
/* Just splice the entire active_q into dest */
if (sld->level == CSIO_LEV_ALL) {
list_splice_tail_init(&scm->active_q, dest);
return;
}
list_for_each_safe(tmp, next, &scm->active_q) {
if (csio_scsi_match_io((struct csio_ioreq *)tmp, sld)) {
list_del_init(tmp);
list_add_tail(tmp, dest);
}
}
}
static inline bool
csio_scsi_itnexus_loss_error(uint16_t error)
{
switch (error) {
case FW_ERR_LINK_DOWN:
case FW_RDEV_NOT_READY:
case FW_ERR_RDEV_LOST:
case FW_ERR_RDEV_LOGO:
case FW_ERR_RDEV_IMPL_LOGO:
return true;
}
return false;
}
/*
* csio_scsi_fcp_cmnd - Frame the SCSI FCP command paylod.
* @req: IO req structure.
* @addr: DMA location to place the payload.
*
* This routine is shared between FCP_WRITE, FCP_READ and FCP_CMD requests.
*/
static inline void
csio_scsi_fcp_cmnd(struct csio_ioreq *req, void *addr)
{
struct fcp_cmnd *fcp_cmnd = (struct fcp_cmnd *)addr;
struct scsi_cmnd *scmnd = csio_scsi_cmnd(req);
/* Check for Task Management */
if (likely(scmnd->SCp.Message == 0)) {
int_to_scsilun(scmnd->device->lun, &fcp_cmnd->fc_lun);
fcp_cmnd->fc_tm_flags = 0;
fcp_cmnd->fc_cmdref = 0;
memcpy(fcp_cmnd->fc_cdb, scmnd->cmnd, 16);
fcp_cmnd->fc_pri_ta = FCP_PTA_SIMPLE;
fcp_cmnd->fc_dl = cpu_to_be32(scsi_bufflen(scmnd));
if (req->nsge)
if (req->datadir == DMA_TO_DEVICE)
fcp_cmnd->fc_flags = FCP_CFL_WRDATA;
else
fcp_cmnd->fc_flags = FCP_CFL_RDDATA;
else
fcp_cmnd->fc_flags = 0;
} else {
memset(fcp_cmnd, 0, sizeof(*fcp_cmnd));
int_to_scsilun(scmnd->device->lun, &fcp_cmnd->fc_lun);
fcp_cmnd->fc_tm_flags = (uint8_t)scmnd->SCp.Message;
}
}
/*
* csio_scsi_init_cmd_wr - Initialize the SCSI CMD WR.
* @req: IO req structure.
* @addr: DMA location to place the payload.
* @size: Size of WR (including FW WR + immed data + rsp SG entry
*
* Wrapper for populating fw_scsi_cmd_wr.
*/
static inline void
csio_scsi_init_cmd_wr(struct csio_ioreq *req, void *addr, uint32_t size)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_rnode *rn = req->rnode;
struct fw_scsi_cmd_wr *wr = (struct fw_scsi_cmd_wr *)addr;
struct csio_dma_buf *dma_buf;
uint8_t imm = csio_hw_to_scsim(hw)->proto_cmd_len;
wr->op_immdlen = cpu_to_be32(FW_WR_OP_V(FW_SCSI_CMD_WR) |
FW_SCSI_CMD_WR_IMMDLEN(imm));
wr->flowid_len16 = cpu_to_be32(FW_WR_FLOWID_V(rn->flowid) |
FW_WR_LEN16_V(
DIV_ROUND_UP(size, 16)));
wr->cookie = (uintptr_t) req;
wr->iqid = cpu_to_be16(csio_q_physiqid(hw, req->iq_idx));
wr->tmo_val = (uint8_t) req->tmo;
wr->r3 = 0;
memset(&wr->r5, 0, 8);
/* Get RSP DMA buffer */
dma_buf = &req->dma_buf;
/* Prepare RSP SGL */
wr->rsp_dmalen = cpu_to_be32(dma_buf->len);
wr->rsp_dmaaddr = cpu_to_be64(dma_buf->paddr);
wr->r6 = 0;
wr->u.fcoe.ctl_pri = 0;
wr->u.fcoe.cp_en_class = 0;
wr->u.fcoe.r4_lo[0] = 0;
wr->u.fcoe.r4_lo[1] = 0;
/* Frame a FCP command */
csio_scsi_fcp_cmnd(req, (void *)((uintptr_t)addr +
sizeof(struct fw_scsi_cmd_wr)));
}
#define CSIO_SCSI_CMD_WR_SZ(_imm) \
(sizeof(struct fw_scsi_cmd_wr) + /* WR size */ \
ALIGN((_imm), 16)) /* Immed data */
#define CSIO_SCSI_CMD_WR_SZ_16(_imm) \
(ALIGN(CSIO_SCSI_CMD_WR_SZ((_imm)), 16))
/*
* csio_scsi_cmd - Create a SCSI CMD WR.
* @req: IO req structure.
*
* Gets a WR slot in the ingress queue and initializes it with SCSI CMD WR.
*
*/
static inline void
csio_scsi_cmd(struct csio_ioreq *req)
{
struct csio_wr_pair wrp;
struct csio_hw *hw = req->lnode->hwp;
struct csio_scsim *scsim = csio_hw_to_scsim(hw);
uint32_t size = CSIO_SCSI_CMD_WR_SZ_16(scsim->proto_cmd_len);
req->drv_status = csio_wr_get(hw, req->eq_idx, size, &wrp);
if (unlikely(req->drv_status != 0))
return;
if (wrp.size1 >= size) {
/* Initialize WR in one shot */
csio_scsi_init_cmd_wr(req, wrp.addr1, size);
} else {
uint8_t *tmpwr = csio_q_eq_wrap(hw, req->eq_idx);
/*
* Make a temporary copy of the WR and write back
* the copy into the WR pair.
*/
csio_scsi_init_cmd_wr(req, (void *)tmpwr, size);
memcpy(wrp.addr1, tmpwr, wrp.size1);
memcpy(wrp.addr2, tmpwr + wrp.size1, size - wrp.size1);
}
}
/*
* csio_scsi_init_ulptx_dsgl - Fill in a ULP_TX_SC_DSGL
* @hw: HW module
* @req: IO request
* @sgl: ULP TX SGL pointer.
*
*/
static inline void
csio_scsi_init_ultptx_dsgl(struct csio_hw *hw, struct csio_ioreq *req,
struct ulptx_sgl *sgl)
{
struct ulptx_sge_pair *sge_pair = NULL;
struct scatterlist *sgel;
uint32_t i = 0;
uint32_t xfer_len;
struct list_head *tmp;
struct csio_dma_buf *dma_buf;
struct scsi_cmnd *scmnd = csio_scsi_cmnd(req);
sgl->cmd_nsge = htonl(ULPTX_CMD_V(ULP_TX_SC_DSGL) | ULPTX_MORE_F |
ULPTX_NSGE_V(req->nsge));
/* Now add the data SGLs */
if (likely(!req->dcopy)) {
scsi_for_each_sg(scmnd, sgel, req->nsge, i) {
if (i == 0) {
sgl->addr0 = cpu_to_be64(sg_dma_address(sgel));
sgl->len0 = cpu_to_be32(sg_dma_len(sgel));
sge_pair = (struct ulptx_sge_pair *)(sgl + 1);
continue;
}
if ((i - 1) & 0x1) {
sge_pair->addr[1] = cpu_to_be64(
sg_dma_address(sgel));
sge_pair->len[1] = cpu_to_be32(
sg_dma_len(sgel));
sge_pair++;
} else {
sge_pair->addr[0] = cpu_to_be64(
sg_dma_address(sgel));
sge_pair->len[0] = cpu_to_be32(
sg_dma_len(sgel));
}
}
} else {
/* Program sg elements with driver's DDP buffer */
xfer_len = scsi_bufflen(scmnd);
list_for_each(tmp, &req->gen_list) {
dma_buf = (struct csio_dma_buf *)tmp;
if (i == 0) {
sgl->addr0 = cpu_to_be64(dma_buf->paddr);
sgl->len0 = cpu_to_be32(
min(xfer_len, dma_buf->len));
sge_pair = (struct ulptx_sge_pair *)(sgl + 1);
} else if ((i - 1) & 0x1) {
sge_pair->addr[1] = cpu_to_be64(dma_buf->paddr);
sge_pair->len[1] = cpu_to_be32(
min(xfer_len, dma_buf->len));
sge_pair++;
} else {
sge_pair->addr[0] = cpu_to_be64(dma_buf->paddr);
sge_pair->len[0] = cpu_to_be32(
min(xfer_len, dma_buf->len));
}
xfer_len -= min(xfer_len, dma_buf->len);
i++;
}
}
}
/*
* csio_scsi_init_read_wr - Initialize the READ SCSI WR.
* @req: IO req structure.
* @wrp: DMA location to place the payload.
* @size: Size of WR (including FW WR + immed data + rsp SG entry + data SGL
*
* Wrapper for populating fw_scsi_read_wr.
*/
static inline void
csio_scsi_init_read_wr(struct csio_ioreq *req, void *wrp, uint32_t size)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_rnode *rn = req->rnode;
struct fw_scsi_read_wr *wr = (struct fw_scsi_read_wr *)wrp;
struct ulptx_sgl *sgl;
struct csio_dma_buf *dma_buf;
uint8_t imm = csio_hw_to_scsim(hw)->proto_cmd_len;
struct scsi_cmnd *scmnd = csio_scsi_cmnd(req);
wr->op_immdlen = cpu_to_be32(FW_WR_OP_V(FW_SCSI_READ_WR) |
FW_SCSI_READ_WR_IMMDLEN(imm));
wr->flowid_len16 = cpu_to_be32(FW_WR_FLOWID_V(rn->flowid) |
FW_WR_LEN16_V(DIV_ROUND_UP(size, 16)));
wr->cookie = (uintptr_t)req;
wr->iqid = cpu_to_be16(csio_q_physiqid(hw, req->iq_idx));
wr->tmo_val = (uint8_t)(req->tmo);
wr->use_xfer_cnt = 1;
wr->xfer_cnt = cpu_to_be32(scsi_bufflen(scmnd));
wr->ini_xfer_cnt = cpu_to_be32(scsi_bufflen(scmnd));
/* Get RSP DMA buffer */
dma_buf = &req->dma_buf;
/* Prepare RSP SGL */
wr->rsp_dmalen = cpu_to_be32(dma_buf->len);
wr->rsp_dmaaddr = cpu_to_be64(dma_buf->paddr);
wr->r4 = 0;
wr->u.fcoe.ctl_pri = 0;
wr->u.fcoe.cp_en_class = 0;
wr->u.fcoe.r3_lo[0] = 0;
wr->u.fcoe.r3_lo[1] = 0;
csio_scsi_fcp_cmnd(req, (void *)((uintptr_t)wrp +
sizeof(struct fw_scsi_read_wr)));
/* Move WR pointer past command and immediate data */
sgl = (struct ulptx_sgl *)((uintptr_t)wrp +
sizeof(struct fw_scsi_read_wr) + ALIGN(imm, 16));
/* Fill in the DSGL */
csio_scsi_init_ultptx_dsgl(hw, req, sgl);
}
/*
* csio_scsi_init_write_wr - Initialize the WRITE SCSI WR.
* @req: IO req structure.
* @wrp: DMA location to place the payload.
* @size: Size of WR (including FW WR + immed data + rsp SG entry + data SGL
*
* Wrapper for populating fw_scsi_write_wr.
*/
static inline void
csio_scsi_init_write_wr(struct csio_ioreq *req, void *wrp, uint32_t size)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_rnode *rn = req->rnode;
struct fw_scsi_write_wr *wr = (struct fw_scsi_write_wr *)wrp;
struct ulptx_sgl *sgl;
struct csio_dma_buf *dma_buf;
uint8_t imm = csio_hw_to_scsim(hw)->proto_cmd_len;
struct scsi_cmnd *scmnd = csio_scsi_cmnd(req);
wr->op_immdlen = cpu_to_be32(FW_WR_OP_V(FW_SCSI_WRITE_WR) |
FW_SCSI_WRITE_WR_IMMDLEN(imm));
wr->flowid_len16 = cpu_to_be32(FW_WR_FLOWID_V(rn->flowid) |
FW_WR_LEN16_V(DIV_ROUND_UP(size, 16)));
wr->cookie = (uintptr_t)req;
wr->iqid = cpu_to_be16(csio_q_physiqid(hw, req->iq_idx));
wr->tmo_val = (uint8_t)(req->tmo);
wr->use_xfer_cnt = 1;
wr->xfer_cnt = cpu_to_be32(scsi_bufflen(scmnd));
wr->ini_xfer_cnt = cpu_to_be32(scsi_bufflen(scmnd));
/* Get RSP DMA buffer */
dma_buf = &req->dma_buf;
/* Prepare RSP SGL */
wr->rsp_dmalen = cpu_to_be32(dma_buf->len);
wr->rsp_dmaaddr = cpu_to_be64(dma_buf->paddr);
wr->r4 = 0;
wr->u.fcoe.ctl_pri = 0;
wr->u.fcoe.cp_en_class = 0;
wr->u.fcoe.r3_lo[0] = 0;
wr->u.fcoe.r3_lo[1] = 0;
csio_scsi_fcp_cmnd(req, (void *)((uintptr_t)wrp +
sizeof(struct fw_scsi_write_wr)));
/* Move WR pointer past command and immediate data */
sgl = (struct ulptx_sgl *)((uintptr_t)wrp +
sizeof(struct fw_scsi_write_wr) + ALIGN(imm, 16));
/* Fill in the DSGL */
csio_scsi_init_ultptx_dsgl(hw, req, sgl);
}
/* Calculate WR size needed for fw_scsi_read_wr/fw_scsi_write_wr */
#define CSIO_SCSI_DATA_WRSZ(req, oper, sz, imm) \
do { \
(sz) = sizeof(struct fw_scsi_##oper##_wr) + /* WR size */ \
ALIGN((imm), 16) + /* Immed data */ \
sizeof(struct ulptx_sgl); /* ulptx_sgl */ \
\
if (unlikely((req)->nsge > 1)) \
(sz) += (sizeof(struct ulptx_sge_pair) * \
(ALIGN(((req)->nsge - 1), 2) / 2)); \
/* Data SGE */ \
} while (0)
/*
* csio_scsi_read - Create a SCSI READ WR.
* @req: IO req structure.
*
* Gets a WR slot in the ingress queue and initializes it with
* SCSI READ WR.
*
*/
static inline void
csio_scsi_read(struct csio_ioreq *req)
{
struct csio_wr_pair wrp;
uint32_t size;
struct csio_hw *hw = req->lnode->hwp;
struct csio_scsim *scsim = csio_hw_to_scsim(hw);
CSIO_SCSI_DATA_WRSZ(req, read, size, scsim->proto_cmd_len);
size = ALIGN(size, 16);
req->drv_status = csio_wr_get(hw, req->eq_idx, size, &wrp);
if (likely(req->drv_status == 0)) {
if (likely(wrp.size1 >= size)) {
/* Initialize WR in one shot */
csio_scsi_init_read_wr(req, wrp.addr1, size);
} else {
uint8_t *tmpwr = csio_q_eq_wrap(hw, req->eq_idx);
/*
* Make a temporary copy of the WR and write back
* the copy into the WR pair.
*/
csio_scsi_init_read_wr(req, (void *)tmpwr, size);
memcpy(wrp.addr1, tmpwr, wrp.size1);
memcpy(wrp.addr2, tmpwr + wrp.size1, size - wrp.size1);
}
}
}
/*
* csio_scsi_write - Create a SCSI WRITE WR.
* @req: IO req structure.
*
* Gets a WR slot in the ingress queue and initializes it with
* SCSI WRITE WR.
*
*/
static inline void
csio_scsi_write(struct csio_ioreq *req)
{
struct csio_wr_pair wrp;
uint32_t size;
struct csio_hw *hw = req->lnode->hwp;
struct csio_scsim *scsim = csio_hw_to_scsim(hw);
CSIO_SCSI_DATA_WRSZ(req, write, size, scsim->proto_cmd_len);
size = ALIGN(size, 16);
req->drv_status = csio_wr_get(hw, req->eq_idx, size, &wrp);
if (likely(req->drv_status == 0)) {
if (likely(wrp.size1 >= size)) {
/* Initialize WR in one shot */
csio_scsi_init_write_wr(req, wrp.addr1, size);
} else {
uint8_t *tmpwr = csio_q_eq_wrap(hw, req->eq_idx);
/*
* Make a temporary copy of the WR and write back
* the copy into the WR pair.
*/
csio_scsi_init_write_wr(req, (void *)tmpwr, size);
memcpy(wrp.addr1, tmpwr, wrp.size1);
memcpy(wrp.addr2, tmpwr + wrp.size1, size - wrp.size1);
}
}
}
/*
* csio_setup_ddp - Setup DDP buffers for Read request.
* @req: IO req structure.
*
* Checks SGLs/Data buffers are virtually contiguous required for DDP.
* If contiguous,driver posts SGLs in the WR otherwise post internal
* buffers for such request for DDP.
*/
static inline void
csio_setup_ddp(struct csio_scsim *scsim, struct csio_ioreq *req)
{
#ifdef __CSIO_DEBUG__
struct csio_hw *hw = req->lnode->hwp;
#endif
struct scatterlist *sgel = NULL;
struct scsi_cmnd *scmnd = csio_scsi_cmnd(req);
uint64_t sg_addr = 0;
uint32_t ddp_pagesz = 4096;
uint32_t buf_off;
struct csio_dma_buf *dma_buf = NULL;
uint32_t alloc_len = 0;
uint32_t xfer_len = 0;
uint32_t sg_len = 0;
uint32_t i;
scsi_for_each_sg(scmnd, sgel, req->nsge, i) {
sg_addr = sg_dma_address(sgel);
sg_len = sg_dma_len(sgel);
buf_off = sg_addr & (ddp_pagesz - 1);
/* Except 1st buffer,all buffer addr have to be Page aligned */
if (i != 0 && buf_off) {
csio_dbg(hw, "SGL addr not DDP aligned (%llx:%d)\n",
sg_addr, sg_len);
goto unaligned;
}
/* Except last buffer,all buffer must end on page boundary */
if ((i != (req->nsge - 1)) &&
((buf_off + sg_len) & (ddp_pagesz - 1))) {
csio_dbg(hw,
"SGL addr not ending on page boundary"
"(%llx:%d)\n", sg_addr, sg_len);
goto unaligned;
}
}
/* SGL's are virtually contiguous. HW will DDP to SGLs */
req->dcopy = 0;
csio_scsi_read(req);
return;
unaligned:
CSIO_INC_STATS(scsim, n_unaligned);
/*
* For unaligned SGLs, driver will allocate internal DDP buffer.
* Once command is completed data from DDP buffer copied to SGLs
*/
req->dcopy = 1;
/* Use gen_list to store the DDP buffers */
INIT_LIST_HEAD(&req->gen_list);
xfer_len = scsi_bufflen(scmnd);
i = 0;
/* Allocate ddp buffers for this request */
while (alloc_len < xfer_len) {
dma_buf = csio_get_scsi_ddp(scsim);
if (dma_buf == NULL || i > scsim->max_sge) {
req->drv_status = -EBUSY;
break;
}
alloc_len += dma_buf->len;
/* Added to IO req */
list_add_tail(&dma_buf->list, &req->gen_list);
i++;
}
if (!req->drv_status) {
/* set number of ddp bufs used */
req->nsge = i;
csio_scsi_read(req);
return;
}
/* release dma descs */
if (i > 0)
csio_put_scsi_ddp_list(scsim, &req->gen_list, i);
}
/*
* csio_scsi_init_abrt_cls_wr - Initialize an ABORT/CLOSE WR.
* @req: IO req structure.
* @addr: DMA location to place the payload.
* @size: Size of WR
* @abort: abort OR close
*
* Wrapper for populating fw_scsi_cmd_wr.
*/
static inline void
csio_scsi_init_abrt_cls_wr(struct csio_ioreq *req, void *addr, uint32_t size,
bool abort)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_rnode *rn = req->rnode;
struct fw_scsi_abrt_cls_wr *wr = (struct fw_scsi_abrt_cls_wr *)addr;
wr->op_immdlen = cpu_to_be32(FW_WR_OP_V(FW_SCSI_ABRT_CLS_WR));
wr->flowid_len16 = cpu_to_be32(FW_WR_FLOWID_V(rn->flowid) |
FW_WR_LEN16_V(
DIV_ROUND_UP(size, 16)));
wr->cookie = (uintptr_t) req;
wr->iqid = cpu_to_be16(csio_q_physiqid(hw, req->iq_idx));
wr->tmo_val = (uint8_t) req->tmo;
/* 0 for CHK_ALL_IO tells FW to look up t_cookie */
wr->sub_opcode_to_chk_all_io =
(FW_SCSI_ABRT_CLS_WR_SUB_OPCODE(abort) |
FW_SCSI_ABRT_CLS_WR_CHK_ALL_IO(0));
wr->r3[0] = 0;
wr->r3[1] = 0;
wr->r3[2] = 0;
wr->r3[3] = 0;
/* Since we re-use the same ioreq for abort as well */
wr->t_cookie = (uintptr_t) req;
}
static inline void
csio_scsi_abrt_cls(struct csio_ioreq *req, bool abort)
{
struct csio_wr_pair wrp;
struct csio_hw *hw = req->lnode->hwp;
uint32_t size = ALIGN(sizeof(struct fw_scsi_abrt_cls_wr), 16);
req->drv_status = csio_wr_get(hw, req->eq_idx, size, &wrp);
if (req->drv_status != 0)
return;
if (wrp.size1 >= size) {
/* Initialize WR in one shot */
csio_scsi_init_abrt_cls_wr(req, wrp.addr1, size, abort);
} else {
uint8_t *tmpwr = csio_q_eq_wrap(hw, req->eq_idx);
/*
* Make a temporary copy of the WR and write back
* the copy into the WR pair.
*/
csio_scsi_init_abrt_cls_wr(req, (void *)tmpwr, size, abort);
memcpy(wrp.addr1, tmpwr, wrp.size1);
memcpy(wrp.addr2, tmpwr + wrp.size1, size - wrp.size1);
}
}
/*****************************************************************************/
/* START: SCSI SM */
/*****************************************************************************/
static void
csio_scsis_uninit(struct csio_ioreq *req, enum csio_scsi_ev evt)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_scsim *scsim = csio_hw_to_scsim(hw);
switch (evt) {
case CSIO_SCSIE_START_IO:
if (req->nsge) {
if (req->datadir == DMA_TO_DEVICE) {
req->dcopy = 0;
csio_scsi_write(req);
} else
csio_setup_ddp(scsim, req);
} else {
csio_scsi_cmd(req);
}
if (likely(req->drv_status == 0)) {
/* change state and enqueue on active_q */
csio_set_state(&req->sm, csio_scsis_io_active);
list_add_tail(&req->sm.sm_list, &scsim->active_q);
csio_wr_issue(hw, req->eq_idx, false);
CSIO_INC_STATS(scsim, n_active);
return;
}
break;
case CSIO_SCSIE_START_TM:
csio_scsi_cmd(req);
if (req->drv_status == 0) {
/*
* NOTE: We collect the affected I/Os prior to issuing
* LUN reset, and not after it. This is to prevent
* aborting I/Os that get issued after the LUN reset,
* but prior to LUN reset completion (in the event that
* the host stack has not blocked I/Os to a LUN that is
* being reset.
*/
csio_set_state(&req->sm, csio_scsis_tm_active);
list_add_tail(&req->sm.sm_list, &scsim->active_q);
csio_wr_issue(hw, req->eq_idx, false);
CSIO_INC_STATS(scsim, n_tm_active);
}
return;
case CSIO_SCSIE_ABORT:
case CSIO_SCSIE_CLOSE:
/*
* NOTE:
* We could get here due to :
* - a window in the cleanup path of the SCSI module
* (csio_scsi_abort_io()). Please see NOTE in this function.
* - a window in the time we tried to issue an abort/close
* of a request to FW, and the FW completed the request
* itself.
* Print a message for now, and return INVAL either way.
*/
req->drv_status = -EINVAL;
csio_warn(hw, "Trying to abort/close completed IO:%p!\n", req);
break;
default:
csio_dbg(hw, "Unhandled event:%d sent to req:%p\n", evt, req);
CSIO_DB_ASSERT(0);
}
}
static void
csio_scsis_io_active(struct csio_ioreq *req, enum csio_scsi_ev evt)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_scsim *scm = csio_hw_to_scsim(hw);
struct csio_rnode *rn;
switch (evt) {
case CSIO_SCSIE_COMPLETED:
CSIO_DEC_STATS(scm, n_active);
list_del_init(&req->sm.sm_list);
csio_set_state(&req->sm, csio_scsis_uninit);
/*
* In MSIX mode, with multiple queues, the SCSI compeltions
* could reach us sooner than the FW events sent to indicate
* I-T nexus loss (link down, remote device logo etc). We
* dont want to be returning such I/Os to the upper layer
* immediately, since we wouldnt have reported the I-T nexus
* loss itself. This forces us to serialize such completions
* with the reporting of the I-T nexus loss. Therefore, we
* internally queue up such up such completions in the rnode.
* The reporting of I-T nexus loss to the upper layer is then
* followed by the returning of I/Os in this internal queue.
* Having another state alongwith another queue helps us take
* actions for events such as ABORT received while we are
* in this rnode queue.
*/
if (unlikely(req->wr_status != FW_SUCCESS)) {
rn = req->rnode;
/*
* FW says remote device is lost, but rnode
* doesnt reflect it.
*/
if (csio_scsi_itnexus_loss_error(req->wr_status) &&
csio_is_rnode_ready(rn)) {
csio_set_state(&req->sm,
csio_scsis_shost_cmpl_await);
list_add_tail(&req->sm.sm_list,
&rn->host_cmpl_q);
}
}
break;
case CSIO_SCSIE_ABORT:
csio_scsi_abrt_cls(req, SCSI_ABORT);
if (req->drv_status == 0) {
csio_wr_issue(hw, req->eq_idx, false);
csio_set_state(&req->sm, csio_scsis_aborting);
}
break;
case CSIO_SCSIE_CLOSE:
csio_scsi_abrt_cls(req, SCSI_CLOSE);
if (req->drv_status == 0) {
csio_wr_issue(hw, req->eq_idx, false);
csio_set_state(&req->sm, csio_scsis_closing);
}
break;
case CSIO_SCSIE_DRVCLEANUP:
req->wr_status = FW_HOSTERROR;
CSIO_DEC_STATS(scm, n_active);
csio_set_state(&req->sm, csio_scsis_uninit);
break;
default:
csio_dbg(hw, "Unhandled event:%d sent to req:%p\n", evt, req);
CSIO_DB_ASSERT(0);
}
}
static void
csio_scsis_tm_active(struct csio_ioreq *req, enum csio_scsi_ev evt)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_scsim *scm = csio_hw_to_scsim(hw);
switch (evt) {
case CSIO_SCSIE_COMPLETED:
CSIO_DEC_STATS(scm, n_tm_active);
list_del_init(&req->sm.sm_list);
csio_set_state(&req->sm, csio_scsis_uninit);
break;
case CSIO_SCSIE_ABORT:
csio_scsi_abrt_cls(req, SCSI_ABORT);
if (req->drv_status == 0) {
csio_wr_issue(hw, req->eq_idx, false);
csio_set_state(&req->sm, csio_scsis_aborting);
}
break;
case CSIO_SCSIE_CLOSE:
csio_scsi_abrt_cls(req, SCSI_CLOSE);
if (req->drv_status == 0) {
csio_wr_issue(hw, req->eq_idx, false);
csio_set_state(&req->sm, csio_scsis_closing);
}
break;
case CSIO_SCSIE_DRVCLEANUP:
req->wr_status = FW_HOSTERROR;
CSIO_DEC_STATS(scm, n_tm_active);
csio_set_state(&req->sm, csio_scsis_uninit);
break;
default:
csio_dbg(hw, "Unhandled event:%d sent to req:%p\n", evt, req);
CSIO_DB_ASSERT(0);
}
}
static void
csio_scsis_aborting(struct csio_ioreq *req, enum csio_scsi_ev evt)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_scsim *scm = csio_hw_to_scsim(hw);
switch (evt) {
case CSIO_SCSIE_COMPLETED:
csio_dbg(hw,
"ioreq %p recvd cmpltd (wr_status:%d) "
"in aborting st\n", req, req->wr_status);
/*
* Use -ECANCELED to explicitly tell the ABORTED event that
* the original I/O was returned to driver by FW.
* We dont really care if the I/O was returned with success by
* FW (because the ABORT and completion of the I/O crossed each
* other), or any other return value. Once we are in aborting
* state, the success or failure of the I/O is unimportant to
* us.
*/
req->drv_status = -ECANCELED;
break;
case CSIO_SCSIE_ABORT:
CSIO_INC_STATS(scm, n_abrt_dups);
break;
case CSIO_SCSIE_ABORTED:
csio_dbg(hw, "abort of %p return status:0x%x drv_status:%x\n",
req, req->wr_status, req->drv_status);
/*
* Check if original I/O WR completed before the Abort
* completion.
*/
if (req->drv_status != -ECANCELED) {
csio_warn(hw,
"Abort completed before original I/O,"
" req:%p\n", req);
CSIO_DB_ASSERT(0);
}
/*
* There are the following possible scenarios:
* 1. The abort completed successfully, FW returned FW_SUCCESS.
* 2. The completion of an I/O and the receipt of
* abort for that I/O by the FW crossed each other.
* The FW returned FW_EINVAL. The original I/O would have
* returned with FW_SUCCESS or any other SCSI error.
* 3. The FW couldn't sent the abort out on the wire, as there
* was an I-T nexus loss (link down, remote device logged
* out etc). FW sent back an appropriate IT nexus loss status
* for the abort.
* 4. FW sent an abort, but abort timed out (remote device
* didnt respond). FW replied back with
* FW_SCSI_ABORT_TIMEDOUT.
* 5. FW couldn't genuinely abort the request for some reason,
* and sent us an error.
*
* The first 3 scenarios are treated as succesful abort
* operations by the host, while the last 2 are failed attempts
* to abort. Manipulate the return value of the request
* appropriately, so that host can convey these results
* back to the upper layer.
*/
if ((req->wr_status == FW_SUCCESS) ||
(req->wr_status == FW_EINVAL) ||
csio_scsi_itnexus_loss_error(req->wr_status))
req->wr_status = FW_SCSI_ABORT_REQUESTED;
CSIO_DEC_STATS(scm, n_active);
list_del_init(&req->sm.sm_list);
csio_set_state(&req->sm, csio_scsis_uninit);
break;
case CSIO_SCSIE_DRVCLEANUP:
req->wr_status = FW_HOSTERROR;
CSIO_DEC_STATS(scm, n_active);
csio_set_state(&req->sm, csio_scsis_uninit);
break;
case CSIO_SCSIE_CLOSE:
/*
* We can receive this event from the module
* cleanup paths, if the FW forgot to reply to the ABORT WR
* and left this ioreq in this state. For now, just ignore
* the event. The CLOSE event is sent to this state, as
* the LINK may have already gone down.
*/
break;
default:
csio_dbg(hw, "Unhandled event:%d sent to req:%p\n", evt, req);
CSIO_DB_ASSERT(0);
}
}
static void
csio_scsis_closing(struct csio_ioreq *req, enum csio_scsi_ev evt)
{
struct csio_hw *hw = req->lnode->hwp;
struct csio_scsim *scm = csio_hw_to_scsim(hw);
switch (evt) {
case CSIO_SCSIE_COMPLETED:
csio_dbg(hw,
"ioreq %p recvd cmpltd (wr_status:%d) "
"in closing st\n", req, req->wr_status);
/*
* Use -ECANCELED to explicitly tell the CLOSED event that
* the original I/O was returned to driver by FW.
* We dont really care if the I/O was returned with success by
* FW (because the CLOSE and completion of the I/O crossed each
* other), or any other return value. Once we are in aborting
* state, the success or failure of the I/O is unimportant to
* us.
*/
req->drv_status = -ECANCELED;
break;
case CSIO_SCSIE_CLOSED:
/*
* Check if original I/O WR completed before the Close
* completion.
*/
if (req->drv_status != -ECANCELED) {
csio_fatal(hw,
"Close completed before original I/O,"
" req:%p\n", req);
CSIO_DB_ASSERT(0);
}
/*
* Either close succeeded, or we issued close to FW at the
* same time FW compelted it to us. Either way, the I/O
* is closed.
*/
CSIO_DB_ASSERT((req->wr_status == FW_SUCCESS) ||
(req->wr_status == FW_EINVAL));
req->wr_status = FW_SCSI_CLOSE_REQUESTED;
CSIO_DEC_STATS(scm, n_active);
list_del_init(&req->sm.sm_list);
csio_set_state(&req->sm, csio_scsis_uninit);
break;
case CSIO_SCSIE_CLOSE:
break;
case CSIO_SCSIE_DRVCLEANUP:
req->wr_status = FW_HOSTERROR;
CSIO_DEC_STATS(scm, n_active);
csio_set_state(&req->sm, csio_scsis_uninit);
break;
default:
csio_dbg(hw, "Unhandled event:%d sent to req:%p\n", evt, req);
CSIO_DB_ASSERT(0);
}
}
static void
csio_scsis_shost_cmpl_await(struct csio_ioreq *req, enum csio_scsi_ev evt)
{
switch (evt) {
case CSIO_SCSIE_ABORT:
case CSIO_SCSIE_CLOSE:
/*
* Just succeed the abort request, and hope that
* the remote device unregister path will cleanup
* this I/O to the upper layer within a sane
* amount of time.
*/
/*
* A close can come in during a LINK DOWN. The FW would have
* returned us the I/O back, but not the remote device lost
* FW event. In this interval, if the I/O times out at the upper
* layer, a close can come in. Take the same action as abort:
* return success, and hope that the remote device unregister
* path will cleanup this I/O. If the FW still doesnt send
* the msg, the close times out, and the upper layer resorts
* to the next level of error recovery.
*/
req->drv_status = 0;
break;
case CSIO_SCSIE_DRVCLEANUP:
csio_set_state(&req->sm, csio_scsis_uninit);
break;
default:
csio_dbg(req->lnode->hwp, "Unhandled event:%d sent to req:%p\n",
evt, req);
CSIO_DB_ASSERT(0);
}
}
/*
* csio_scsi_cmpl_handler - WR completion handler for SCSI.
* @hw: HW module.
* @wr: The completed WR from the ingress queue.
* @len: Length of the WR.
* @flb: Freelist buffer array.
* @priv: Private object
* @scsiwr: Pointer to SCSI WR.
*
* This is the WR completion handler called per completion from the
* ISR. It is called with lock held. It walks past the RSS and CPL message
* header where the actual WR is present.
* It then gets the status, WR handle (ioreq pointer) and the len of
* the WR, based on WR opcode. Only on a non-good status is the entire
* WR copied into the WR cache (ioreq->fw_wr).
* The ioreq corresponding to the WR is returned to the caller.
* NOTE: The SCSI queue doesnt allocate a freelist today, hence
* no freelist buffer is expected.
*/
struct csio_ioreq *
csio_scsi_cmpl_handler(struct csio_hw *hw, void *wr, uint32_t len,
struct csio_fl_dma_buf *flb, void *priv, uint8_t **scsiwr)
{
struct csio_ioreq *ioreq = NULL;
struct cpl_fw6_msg *cpl;
uint8_t *tempwr;
uint8_t status;
struct csio_scsim *scm = csio_hw_to_scsim(hw);
/* skip RSS header */
cpl = (struct cpl_fw6_msg *)((uintptr_t)wr + sizeof(__be64));
if (unlikely(cpl->opcode != CPL_FW6_MSG)) {
csio_warn(hw, "Error: Invalid CPL msg %x recvd on SCSI q\n",
cpl->opcode);
CSIO_INC_STATS(scm, n_inval_cplop);
return NULL;
}
tempwr = (uint8_t *)(cpl->data);
status = csio_wr_status(tempwr);
*scsiwr = tempwr;
if (likely((*tempwr == FW_SCSI_READ_WR) ||
(*tempwr == FW_SCSI_WRITE_WR) ||
(*tempwr == FW_SCSI_CMD_WR))) {
ioreq = (struct csio_ioreq *)((uintptr_t)
(((struct fw_scsi_read_wr *)tempwr)->cookie));
CSIO_DB_ASSERT(virt_addr_valid(ioreq));
ioreq->wr_status = status;
return ioreq;
}
if (*tempwr == FW_SCSI_ABRT_CLS_WR) {
ioreq = (struct csio_ioreq *)((uintptr_t)
(((struct fw_scsi_abrt_cls_wr *)tempwr)->cookie));
CSIO_DB_ASSERT(virt_addr_valid(ioreq));
ioreq->wr_status = status;
return ioreq;
}
csio_warn(hw, "WR with invalid opcode in SCSI IQ: %x\n", *tempwr);
CSIO_INC_STATS(scm, n_inval_scsiop);
return NULL;
}
/*
* csio_scsi_cleanup_io_q - Cleanup the given queue.
* @scm: SCSI module.
* @q: Queue to be cleaned up.
*
* Called with lock held. Has to exit with lock held.
*/
void
csio_scsi_cleanup_io_q(struct csio_scsim *scm, struct list_head *q)
{
struct csio_hw *hw = scm->hw;
struct csio_ioreq *ioreq;
struct list_head *tmp, *next;
struct scsi_cmnd *scmnd;
/* Call back the completion routines of the active_q */
list_for_each_safe(tmp, next, q) {
ioreq = (struct csio_ioreq *)tmp;
csio_scsi_drvcleanup(ioreq);
list_del_init(&ioreq->sm.sm_list);
scmnd = csio_scsi_cmnd(ioreq);
spin_unlock_irq(&hw->lock);
/*
* Upper layers may have cleared this command, hence this
* check to avoid accessing stale references.
*/
if (scmnd != NULL)
ioreq->io_cbfn(hw, ioreq);
spin_lock_irq(&scm->freelist_lock);
csio_put_scsi_ioreq(scm, ioreq);
spin_unlock_irq(&scm->freelist_lock);
spin_lock_irq(&hw->lock);
}
}
#define CSIO_SCSI_ABORT_Q_POLL_MS 2000
static void
csio_abrt_cls(struct csio_ioreq *ioreq, struct scsi_cmnd *scmnd)
{
struct csio_lnode *ln = ioreq->lnode;
struct csio_hw *hw = ln->hwp;
int ready = 0;
struct csio_scsim *scsim = csio_hw_to_scsim(hw);
int rv;
if (csio_scsi_cmnd(ioreq) != scmnd) {
CSIO_INC_STATS(scsim, n_abrt_race_comp);
return;
}
ready = csio_is_lnode_ready(ln);
rv = csio_do_abrt_cls(hw, ioreq, (ready ? SCSI_ABORT : SCSI_CLOSE));
if (rv != 0) {
if (ready)
CSIO_INC_STATS(scsim, n_abrt_busy_error);
else
CSIO_INC_STATS(scsim, n_cls_busy_error);
}
}
/*
* csio_scsi_abort_io_q - Abort all I/Os on given queue
* @scm: SCSI module.
* @q: Queue to abort.
* @tmo: Timeout in ms
*
* Attempt to abort all I/Os on given queue, and wait for a max
* of tmo milliseconds for them to complete. Returns success
* if all I/Os are aborted. Else returns -ETIMEDOUT.
* Should be entered with lock held. Exits with lock held.
* NOTE:
* Lock has to be held across the loop that aborts I/Os, since dropping the lock
* in between can cause the list to be corrupted. As a result, the caller
* of this function has to ensure that the number of I/os to be aborted
* is finite enough to not cause lock-held-for-too-long issues.
*/
static int
csio_scsi_abort_io_q(struct csio_scsim *scm, struct list_head *q, uint32_t tmo)
{
struct csio_hw *hw = scm->hw;
struct list_head *tmp, *next;
int count = DIV_ROUND_UP(tmo, CSIO_SCSI_ABORT_Q_POLL_MS);
struct scsi_cmnd *scmnd;
if (list_empty(q))
return 0;
csio_dbg(hw, "Aborting SCSI I/Os\n");
/* Now abort/close I/Os in the queue passed */
list_for_each_safe(tmp, next, q) {
scmnd = csio_scsi_cmnd((struct csio_ioreq *)tmp);
csio_abrt_cls((struct csio_ioreq *)tmp, scmnd);
}
/* Wait till all active I/Os are completed/aborted/closed */
while (!list_empty(q) && count--) {
spin_unlock_irq(&hw->lock);
msleep(CSIO_SCSI_ABORT_Q_POLL_MS);
spin_lock_irq(&hw->lock);
}
/* all aborts completed */
if (list_empty(q))
return 0;
return -ETIMEDOUT;
}
/*
* csio_scsim_cleanup_io - Cleanup all I/Os in SCSI module.
* @scm: SCSI module.
* @abort: abort required.
* Called with lock held, should exit with lock held.
* Can sleep when waiting for I/Os to complete.
*/
int
csio_scsim_cleanup_io(struct csio_scsim *scm, bool abort)
{
struct csio_hw *hw = scm->hw;
int rv = 0;
int count = DIV_ROUND_UP(60 * 1000, CSIO_SCSI_ABORT_Q_POLL_MS);
/* No I/Os pending */
if (list_empty(&scm->active_q))
return 0;
/* Wait until all active I/Os are completed */
while (!list_empty(&scm->active_q) && count--) {
spin_unlock_irq(&hw->lock);
msleep(CSIO_SCSI_ABORT_Q_POLL_MS);
spin_lock_irq(&hw->lock);
}
/* all I/Os completed */
if (list_empty(&scm->active_q))
return 0;
/* Else abort */
if (abort) {
rv = csio_scsi_abort_io_q(scm, &scm->active_q, 30000);
if (rv == 0)
return rv;
csio_dbg(hw, "Some I/O aborts timed out, cleaning up..\n");
}
csio_scsi_cleanup_io_q(scm, &scm->active_q);
CSIO_DB_ASSERT(list_empty(&scm->active_q));
return rv;
}
/*
* csio_scsim_cleanup_io_lnode - Cleanup all I/Os of given lnode.
* @scm: SCSI module.
* @lnode: lnode
*
* Called with lock held, should exit with lock held.
* Can sleep (with dropped lock) when waiting for I/Os to complete.
*/
int
csio_scsim_cleanup_io_lnode(struct csio_scsim *scm, struct csio_lnode *ln)
{
struct csio_hw *hw = scm->hw;
struct csio_scsi_level_data sld;
int rv;
int count = DIV_ROUND_UP(60 * 1000, CSIO_SCSI_ABORT_Q_POLL_MS);
csio_dbg(hw, "Gathering all SCSI I/Os on lnode %p\n", ln);
sld.level = CSIO_LEV_LNODE;
sld.lnode = ln;
INIT_LIST_HEAD(&ln->cmpl_q);
csio_scsi_gather_active_ios(scm, &sld, &ln->cmpl_q);
/* No I/Os pending on this lnode */
if (list_empty(&ln->cmpl_q))
return 0;
/* Wait until all active I/Os on this lnode are completed */
while (!list_empty(&ln->cmpl_q) && count--) {
spin_unlock_irq(&hw->lock);
msleep(CSIO_SCSI_ABORT_Q_POLL_MS);
spin_lock_irq(&hw->lock);
}
/* all I/Os completed */
if (list_empty(&ln->cmpl_q))
return 0;
csio_dbg(hw, "Some I/Os pending on ln:%p, aborting them..\n", ln);
/* I/Os are pending, abort them */
rv = csio_scsi_abort_io_q(scm, &ln->cmpl_q, 30000);
if (rv != 0) {
csio_dbg(hw, "Some I/O aborts timed out, cleaning up..\n");
csio_scsi_cleanup_io_q(scm, &ln->cmpl_q);
}
CSIO_DB_ASSERT(list_empty(&ln->cmpl_q));
return rv;
}
static ssize_t
csio_show_hw_state(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct csio_lnode *ln = shost_priv(class_to_shost(dev));
struct csio_hw *hw = csio_lnode_to_hw(ln);
if (csio_is_hw_ready(hw))
return snprintf(buf, PAGE_SIZE, "ready\n");
else
return snprintf(buf, PAGE_SIZE, "not ready\n");
}
/* Device reset */
static ssize_t
csio_device_reset(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct csio_lnode *ln = shost_priv(class_to_shost(dev));
struct csio_hw *hw = csio_lnode_to_hw(ln);
if (*buf != '1')
return -EINVAL;
/* Delete NPIV lnodes */
csio_lnodes_exit(hw, 1);
/* Block upper IOs */
csio_lnodes_block_request(hw);
spin_lock_irq(&hw->lock);
csio_hw_reset(hw);
spin_unlock_irq(&hw->lock);
/* Unblock upper IOs */
csio_lnodes_unblock_request(hw);
return count;
}
/* disable port */
static ssize_t
csio_disable_port(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct csio_lnode *ln = shost_priv(class_to_shost(dev));
struct csio_hw *hw = csio_lnode_to_hw(ln);
bool disable;
if (*buf == '1' || *buf == '0')
disable = (*buf == '1') ? true : false;
else
return -EINVAL;
/* Block upper IOs */
csio_lnodes_block_by_port(hw, ln->portid);
spin_lock_irq(&hw->lock);
csio_disable_lnodes(hw, ln->portid, disable);
spin_unlock_irq(&hw->lock);
/* Unblock upper IOs */
csio_lnodes_unblock_by_port(hw, ln->portid);
return count;
}
/* Show debug level */
static ssize_t
csio_show_dbg_level(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct csio_lnode *ln = shost_priv(class_to_shost(dev));
return snprintf(buf, PAGE_SIZE, "%x\n", ln->params.log_level);
}
/* Store debug level */
static ssize_t
csio_store_dbg_level(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct csio_lnode *ln = shost_priv(class_to_shost(dev));
struct csio_hw *hw = csio_lnode_to_hw(ln);
uint32_t dbg_level = 0;
if (!isdigit(buf[0]))
return -EINVAL;
if (sscanf(buf, "%i", &dbg_level))
return -EINVAL;
ln->params.log_level = dbg_level;
hw->params.log_level = dbg_level;
return 0;
}
static DEVICE_ATTR(hw_state, S_IRUGO, csio_show_hw_state, NULL);
static DEVICE_ATTR(device_reset, S_IWUSR, NULL, csio_device_reset);
static DEVICE_ATTR(disable_port, S_IWUSR, NULL, csio_disable_port);
static DEVICE_ATTR(dbg_level, S_IRUGO | S_IWUSR, csio_show_dbg_level,
csio_store_dbg_level);
static struct device_attribute *csio_fcoe_lport_attrs[] = {
&dev_attr_hw_state,
&dev_attr_device_reset,
&dev_attr_disable_port,
&dev_attr_dbg_level,
NULL,
};
static ssize_t
csio_show_num_reg_rnodes(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct csio_lnode *ln = shost_priv(class_to_shost(dev));
return snprintf(buf, PAGE_SIZE, "%d\n", ln->num_reg_rnodes);
}
static DEVICE_ATTR(num_reg_rnodes, S_IRUGO, csio_show_num_reg_rnodes, NULL);
static struct device_attribute *csio_fcoe_vport_attrs[] = {
&dev_attr_num_reg_rnodes,
&dev_attr_dbg_level,
NULL,
};
static inline uint32_t
csio_scsi_copy_to_sgl(struct csio_hw *hw, struct csio_ioreq *req)
{
struct scsi_cmnd *scmnd = (struct scsi_cmnd *)csio_scsi_cmnd(req);
struct scatterlist *sg;
uint32_t bytes_left;
uint32_t bytes_copy;
uint32_t buf_off = 0;
uint32_t start_off = 0;
uint32_t sg_off = 0;
void *sg_addr;
void *buf_addr;
struct csio_dma_buf *dma_buf;
bytes_left = scsi_bufflen(scmnd);
sg = scsi_sglist(scmnd);
dma_buf = (struct csio_dma_buf *)csio_list_next(&req->gen_list);
/* Copy data from driver buffer to SGs of SCSI CMD */
while (bytes_left > 0 && sg && dma_buf) {
if (buf_off >= dma_buf->len) {
buf_off = 0;
dma_buf = (struct csio_dma_buf *)
csio_list_next(dma_buf);
continue;
}
if (start_off >= sg->length) {
start_off -= sg->length;
sg = sg_next(sg);
continue;
}
buf_addr = dma_buf->vaddr + buf_off;
sg_off = sg->offset + start_off;
bytes_copy = min((dma_buf->len - buf_off),
sg->length - start_off);
bytes_copy = min((uint32_t)(PAGE_SIZE - (sg_off & ~PAGE_MASK)),
bytes_copy);
sg_addr = kmap_atomic(sg_page(sg) + (sg_off >> PAGE_SHIFT));
if (!sg_addr) {
csio_err(hw, "failed to kmap sg:%p of ioreq:%p\n",
sg, req);
break;
}
csio_dbg(hw, "copy_to_sgl:sg_addr %p sg_off %d buf %p len %d\n",
sg_addr, sg_off, buf_addr, bytes_copy);
memcpy(sg_addr + (sg_off & ~PAGE_MASK), buf_addr, bytes_copy);
kunmap_atomic(sg_addr);
start_off += bytes_copy;
buf_off += bytes_copy;
bytes_left -= bytes_copy;
}
if (bytes_left > 0)
return DID_ERROR;
else
return DID_OK;
}
/*
* csio_scsi_err_handler - SCSI error handler.
* @hw: HW module.
* @req: IO request.
*
*/
static inline void
csio_scsi_err_handler(struct csio_hw *hw, struct csio_ioreq *req)
{
struct scsi_cmnd *cmnd = (struct scsi_cmnd *)csio_scsi_cmnd(req);
struct csio_scsim *scm = csio_hw_to_scsim(hw);
struct fcp_resp_with_ext *fcp_resp;
struct fcp_resp_rsp_info *rsp_info;
struct csio_dma_buf *dma_buf;
uint8_t flags, scsi_status = 0;
uint32_t host_status = DID_OK;
uint32_t rsp_len = 0, sns_len = 0;
struct csio_rnode *rn = (struct csio_rnode *)(cmnd->device->hostdata);
switch (req->wr_status) {
case FW_HOSTERROR:
if (unlikely(!csio_is_hw_ready(hw)))
return;
host_status = DID_ERROR;
CSIO_INC_STATS(scm, n_hosterror);
break;
case FW_SCSI_RSP_ERR:
dma_buf = &req->dma_buf;
fcp_resp = (struct fcp_resp_with_ext *)dma_buf->vaddr;
rsp_info = (struct fcp_resp_rsp_info *)(fcp_resp + 1);
flags = fcp_resp->resp.fr_flags;
scsi_status = fcp_resp->resp.fr_status;
if (flags & FCP_RSP_LEN_VAL) {
rsp_len = be32_to_cpu(fcp_resp->ext.fr_rsp_len);
if ((rsp_len != 0 && rsp_len != 4 && rsp_len != 8) ||
(rsp_info->rsp_code != FCP_TMF_CMPL)) {
host_status = DID_ERROR;
goto out;
}
}
if ((flags & FCP_SNS_LEN_VAL) && fcp_resp->ext.fr_sns_len) {
sns_len = be32_to_cpu(fcp_resp->ext.fr_sns_len);
if (sns_len > SCSI_SENSE_BUFFERSIZE)
sns_len = SCSI_SENSE_BUFFERSIZE;
memcpy(cmnd->sense_buffer,
&rsp_info->_fr_resvd[0] + rsp_len, sns_len);
CSIO_INC_STATS(scm, n_autosense);
}
scsi_set_resid(cmnd, 0);
/* Under run */
if (flags & FCP_RESID_UNDER) {
scsi_set_resid(cmnd,
be32_to_cpu(fcp_resp->ext.fr_resid));
if (!(flags & FCP_SNS_LEN_VAL) &&
(scsi_status == SAM_STAT_GOOD) &&
((scsi_bufflen(cmnd) - scsi_get_resid(cmnd))
< cmnd->underflow))
host_status = DID_ERROR;
} else if (flags & FCP_RESID_OVER)
host_status = DID_ERROR;
CSIO_INC_STATS(scm, n_rsperror);
break;
case FW_SCSI_OVER_FLOW_ERR:
csio_warn(hw,
"Over-flow error,cmnd:0x%x expected len:0x%x"
" resid:0x%x\n", cmnd->cmnd[0],
scsi_bufflen(cmnd), scsi_get_resid(cmnd));
host_status = DID_ERROR;
CSIO_INC_STATS(scm, n_ovflerror);
break;
case FW_SCSI_UNDER_FLOW_ERR:
csio_warn(hw,
"Under-flow error,cmnd:0x%x expected"
" len:0x%x resid:0x%x lun:0x%llx ssn:0x%x\n",
cmnd->cmnd[0], scsi_bufflen(cmnd),
scsi_get_resid(cmnd), cmnd->device->lun,
rn->flowid);
host_status = DID_ERROR;
CSIO_INC_STATS(scm, n_unflerror);
break;
case FW_SCSI_ABORT_REQUESTED:
case FW_SCSI_ABORTED:
case FW_SCSI_CLOSE_REQUESTED:
csio_dbg(hw, "Req %p cmd:%p op:%x %s\n", req, cmnd,
cmnd->cmnd[0],
(req->wr_status == FW_SCSI_CLOSE_REQUESTED) ?
"closed" : "aborted");
/*
* csio_eh_abort_handler checks this value to
* succeed or fail the abort request.
*/
host_status = DID_REQUEUE;
if (req->wr_status == FW_SCSI_CLOSE_REQUESTED)
CSIO_INC_STATS(scm, n_closed);
else
CSIO_INC_STATS(scm, n_aborted);
break;
case FW_SCSI_ABORT_TIMEDOUT:
/* FW timed out the abort itself */
csio_dbg(hw, "FW timed out abort req:%p cmnd:%p status:%x\n",
req, cmnd, req->wr_status);
host_status = DID_ERROR;
CSIO_INC_STATS(scm, n_abrt_timedout);
break;
case FW_RDEV_NOT_READY:
/*
* In firmware, a RDEV can get into this state
* temporarily, before moving into dissapeared/lost
* state. So, the driver should complete the request equivalent
* to device-disappeared!
*/
CSIO_INC_STATS(scm, n_rdev_nr_error);
host_status = DID_ERROR;
break;
case FW_ERR_RDEV_LOST:
CSIO_INC_STATS(scm, n_rdev_lost_error);
host_status = DID_ERROR;
break;
case FW_ERR_RDEV_LOGO:
CSIO_INC_STATS(scm, n_rdev_logo_error);
host_status = DID_ERROR;
break;
case FW_ERR_RDEV_IMPL_LOGO:
host_status = DID_ERROR;
break;
case FW_ERR_LINK_DOWN:
CSIO_INC_STATS(scm, n_link_down_error);
host_status = DID_ERROR;
break;
case FW_FCOE_NO_XCHG:
CSIO_INC_STATS(scm, n_no_xchg_error);
host_status = DID_ERROR;
break;
default:
csio_err(hw, "Unknown SCSI FW WR status:%d req:%p cmnd:%p\n",
req->wr_status, req, cmnd);
CSIO_DB_ASSERT(0);
CSIO_INC_STATS(scm, n_unknown_error);
host_status = DID_ERROR;
break;
}
out:
if (req->nsge > 0) {
scsi_dma_unmap(cmnd);
if (req->dcopy && (host_status == DID_OK))
host_status = csio_scsi_copy_to_sgl(hw, req);
}
cmnd->result = (((host_status) << 16) | scsi_status);
cmnd->scsi_done(cmnd);
/* Wake up waiting threads */
csio_scsi_cmnd(req) = NULL;
complete(&req->cmplobj);
}
/*
* csio_scsi_cbfn - SCSI callback function.
* @hw: HW module.
* @req: IO request.
*
*/
static void
csio_scsi_cbfn(struct csio_hw *hw, struct csio_ioreq *req)
{
struct scsi_cmnd *cmnd = (struct scsi_cmnd *)csio_scsi_cmnd(req);
uint8_t scsi_status = SAM_STAT_GOOD;
uint32_t host_status = DID_OK;
if (likely(req->wr_status == FW_SUCCESS)) {
if (req->nsge > 0) {
scsi_dma_unmap(cmnd);
if (req->dcopy)
host_status = csio_scsi_copy_to_sgl(hw, req);
}
cmnd->result = (((host_status) << 16) | scsi_status);
cmnd->scsi_done(cmnd);
csio_scsi_cmnd(req) = NULL;
CSIO_INC_STATS(csio_hw_to_scsim(hw), n_tot_success);
} else {
/* Error handling */
csio_scsi_err_handler(hw, req);
}
}
/**
* csio_queuecommand - Entry point to kickstart an I/O request.
* @host: The scsi_host pointer.
* @cmnd: The I/O request from ML.
*
* This routine does the following:
* - Checks for HW and Rnode module readiness.
* - Gets a free ioreq structure (which is already initialized
* to uninit during its allocation).
* - Maps SG elements.
* - Initializes ioreq members.
* - Kicks off the SCSI state machine for this IO.
* - Returns busy status on error.
*/
static int
csio_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmnd)
{
struct csio_lnode *ln = shost_priv(host);
struct csio_hw *hw = csio_lnode_to_hw(ln);
struct csio_scsim *scsim = csio_hw_to_scsim(hw);
struct csio_rnode *rn = (struct csio_rnode *)(cmnd->device->hostdata);
struct csio_ioreq *ioreq = NULL;
unsigned long flags;
int nsge = 0;
int rv = SCSI_MLQUEUE_HOST_BUSY, nr;
int retval;
struct csio_scsi_qset *sqset;
struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
sqset = &hw->sqset[ln->portid][blk_mq_rq_cpu(cmnd->request)];
nr = fc_remote_port_chkready(rport);
if (nr) {
cmnd->result = nr;
CSIO_INC_STATS(scsim, n_rn_nr_error);
goto err_done;
}
if (unlikely(!csio_is_hw_ready(hw))) {
cmnd->result = (DID_REQUEUE << 16);
CSIO_INC_STATS(scsim, n_hw_nr_error);
goto err_done;
}
/* Get req->nsge, if there are SG elements to be mapped */
nsge = scsi_dma_map(cmnd);
if (unlikely(nsge < 0)) {
CSIO_INC_STATS(scsim, n_dmamap_error);
goto err;
}
/* Do we support so many mappings? */
if (unlikely(nsge > scsim->max_sge)) {
csio_warn(hw,
"More SGEs than can be supported."
" SGEs: %d, Max SGEs: %d\n", nsge, scsim->max_sge);
CSIO_INC_STATS(scsim, n_unsupp_sge_error);
goto err_dma_unmap;
}
/* Get a free ioreq structure - SM is already set to uninit */
ioreq = csio_get_scsi_ioreq_lock(hw, scsim);
if (!ioreq) {
csio_err(hw, "Out of I/O request elements. Active #:%d\n",
scsim->stats.n_active);
CSIO_INC_STATS(scsim, n_no_req_error);
goto err_dma_unmap;
}
ioreq->nsge = nsge;
ioreq->lnode = ln;
ioreq->rnode = rn;
ioreq->iq_idx = sqset->iq_idx;
ioreq->eq_idx = sqset->eq_idx;
ioreq->wr_status = 0;
ioreq->drv_status = 0;
csio_scsi_cmnd(ioreq) = (void *)cmnd;
ioreq->tmo = 0;
ioreq->datadir = cmnd->sc_data_direction;
if (cmnd->sc_data_direction == DMA_TO_DEVICE) {
CSIO_INC_STATS(ln, n_output_requests);
ln->stats.n_output_bytes += scsi_bufflen(cmnd);
} else if (cmnd->sc_data_direction == DMA_FROM_DEVICE) {
CSIO_INC_STATS(ln, n_input_requests);
ln->stats.n_input_bytes += scsi_bufflen(cmnd);
} else
CSIO_INC_STATS(ln, n_control_requests);
/* Set cbfn */
ioreq->io_cbfn = csio_scsi_cbfn;
/* Needed during abort */
cmnd->host_scribble = (unsigned char *)ioreq;
cmnd->SCp.Message = 0;
/* Kick off SCSI IO SM on the ioreq */
spin_lock_irqsave(&hw->lock, flags);
retval = csio_scsi_start_io(ioreq);
spin_unlock_irqrestore(&hw->lock, flags);
if (retval != 0) {
csio_err(hw, "ioreq: %p couldn't be started, status:%d\n",
ioreq, retval);
CSIO_INC_STATS(scsim, n_busy_error);
goto err_put_req;
}
return 0;
err_put_req:
csio_put_scsi_ioreq_lock(hw, scsim, ioreq);
err_dma_unmap:
if (nsge > 0)
scsi_dma_unmap(cmnd);
err:
return rv;
err_done:
cmnd->scsi_done(cmnd);
return 0;
}
static int
csio_do_abrt_cls(struct csio_hw *hw, struct csio_ioreq *ioreq, bool abort)
{
int rv;
int cpu = smp_processor_id();
struct csio_lnode *ln = ioreq->lnode;
struct csio_scsi_qset *sqset = &hw->sqset[ln->portid][cpu];
ioreq->tmo = CSIO_SCSI_ABRT_TMO_MS;
/*
* Use current processor queue for posting the abort/close, but retain
* the ingress queue ID of the original I/O being aborted/closed - we
* need the abort/close completion to be received on the same queue
* as the original I/O.
*/
ioreq->eq_idx = sqset->eq_idx;
if (abort == SCSI_ABORT)
rv = csio_scsi_abort(ioreq);
else
rv = csio_scsi_close(ioreq);
return rv;
}
static int
csio_eh_abort_handler(struct scsi_cmnd *cmnd)
{
struct csio_ioreq *ioreq;
struct csio_lnode *ln = shost_priv(cmnd->device->host);
struct csio_hw *hw = csio_lnode_to_hw(ln);
struct csio_scsim *scsim = csio_hw_to_scsim(hw);
int ready = 0, ret;
unsigned long tmo = 0;
int rv;
struct csio_rnode *rn = (struct csio_rnode *)(cmnd->device->hostdata);
ret = fc_block_scsi_eh(cmnd);
if (ret)
return ret;
ioreq = (struct csio_ioreq *)cmnd->host_scribble;
if (!ioreq)
return SUCCESS;
if (!rn)
return FAILED;
csio_dbg(hw,
"Request to abort ioreq:%p cmd:%p cdb:%08llx"
" ssni:0x%x lun:%llu iq:0x%x\n",
ioreq, cmnd, *((uint64_t *)cmnd->cmnd), rn->flowid,
cmnd->device->lun, csio_q_physiqid(hw, ioreq->iq_idx));
if (((struct scsi_cmnd *)csio_scsi_cmnd(ioreq)) != cmnd) {
CSIO_INC_STATS(scsim, n_abrt_race_comp);
return SUCCESS;
}
ready = csio_is_lnode_ready(ln);
tmo = CSIO_SCSI_ABRT_TMO_MS;
reinit_completion(&ioreq->cmplobj);
spin_lock_irq(&hw->lock);
rv = csio_do_abrt_cls(hw, ioreq, (ready ? SCSI_ABORT : SCSI_CLOSE));
spin_unlock_irq(&hw->lock);
if (rv != 0) {
if (rv == -EINVAL) {
/* Return success, if abort/close request issued on
* already completed IO
*/
return SUCCESS;
}
if (ready)
CSIO_INC_STATS(scsim, n_abrt_busy_error);
else
CSIO_INC_STATS(scsim, n_cls_busy_error);
goto inval_scmnd;
}
wait_for_completion_timeout(&ioreq->cmplobj, msecs_to_jiffies(tmo));
/* FW didnt respond to abort within our timeout */
if (((struct scsi_cmnd *)csio_scsi_cmnd(ioreq)) == cmnd) {
csio_err(hw, "Abort timed out -- req: %p\n", ioreq);
CSIO_INC_STATS(scsim, n_abrt_timedout);
inval_scmnd:
if (ioreq->nsge > 0)
scsi_dma_unmap(cmnd);
spin_lock_irq(&hw->lock);
csio_scsi_cmnd(ioreq) = NULL;
spin_unlock_irq(&hw->lock);
cmnd->result = (DID_ERROR << 16);
cmnd->scsi_done(cmnd);
return FAILED;
}
/* FW successfully aborted the request */
if (host_byte(cmnd->result) == DID_REQUEUE) {
csio_info(hw,
"Aborted SCSI command to (%d:%llu) tag %u\n",
cmnd->device->id, cmnd->device->lun,
cmnd->request->tag);
return SUCCESS;
} else {
csio_info(hw,
"Failed to abort SCSI command, (%d:%llu) tag %u\n",
cmnd->device->id, cmnd->device->lun,
cmnd->request->tag);
return FAILED;
}
}
/*
* csio_tm_cbfn - TM callback function.
* @hw: HW module.
* @req: IO request.
*
* Cache the result in 'cmnd', since ioreq will be freed soon
* after we return from here, and the waiting thread shouldnt trust
* the ioreq contents.
*/
static void
csio_tm_cbfn(struct csio_hw *hw, struct csio_ioreq *req)
{
struct scsi_cmnd *cmnd = (struct scsi_cmnd *)csio_scsi_cmnd(req);
struct csio_dma_buf *dma_buf;
uint8_t flags = 0;
struct fcp_resp_with_ext *fcp_resp;
struct fcp_resp_rsp_info *rsp_info;
csio_dbg(hw, "req: %p in csio_tm_cbfn status: %d\n",
req, req->wr_status);
/* Cache FW return status */
cmnd->SCp.Status = req->wr_status;
/* Special handling based on FCP response */
/*
* FW returns us this error, if flags were set. FCP4 says
* FCP_RSP_LEN_VAL in flags shall be set for TM completions.
* So if a target were to set this bit, we expect that the
* rsp_code is set to FCP_TMF_CMPL for a successful TM
* completion. Any other rsp_code means TM operation failed.
* If a target were to just ignore setting flags, we treat
* the TM operation as success, and FW returns FW_SUCCESS.
*/
if (req->wr_status == FW_SCSI_RSP_ERR) {
dma_buf = &req->dma_buf;
fcp_resp = (struct fcp_resp_with_ext *)dma_buf->vaddr;
rsp_info = (struct fcp_resp_rsp_info *)(fcp_resp + 1);
flags = fcp_resp->resp.fr_flags;
/* Modify return status if flags indicate success */
if (flags & FCP_RSP_LEN_VAL)
if (rsp_info->rsp_code == FCP_TMF_CMPL)
cmnd->SCp.Status = FW_SUCCESS;
csio_dbg(hw, "TM FCP rsp code: %d\n", rsp_info->rsp_code);
}
/* Wake up the TM handler thread */
csio_scsi_cmnd(req) = NULL;
}
static int
csio_eh_lun_reset_handler(struct scsi_cmnd *cmnd)
{
struct csio_lnode *ln = shost_priv(cmnd->device->host);
struct csio_hw *hw = csio_lnode_to_hw(ln);
struct csio_scsim *scsim = csio_hw_to_scsim(hw);
struct csio_rnode *rn = (struct csio_rnode *)(cmnd->device->hostdata);
struct csio_ioreq *ioreq = NULL;
struct csio_scsi_qset *sqset;
unsigned long flags;
int retval;
int count, ret;
LIST_HEAD(local_q);
struct csio_scsi_level_data sld;
if (!rn)
goto fail;
csio_dbg(hw, "Request to reset LUN:%llu (ssni:0x%x tgtid:%d)\n",
cmnd->device->lun, rn->flowid, rn->scsi_id);
if (!csio_is_lnode_ready(ln)) {
csio_err(hw,
"LUN reset cannot be issued on non-ready"
" local node vnpi:0x%x (LUN:%llu)\n",
ln->vnp_flowid, cmnd->device->lun);
goto fail;
}
/* Lnode is ready, now wait on rport node readiness */
ret = fc_block_scsi_eh(cmnd);
if (ret)
return ret;
/*
* If we have blocked in the previous call, at this point, either the
* remote node has come back online, or device loss timer has fired
* and the remote node is destroyed. Allow the LUN reset only for
* the former case, since LUN reset is a TMF I/O on the wire, and we
* need a valid session to issue it.
*/
if (fc_remote_port_chkready(rn->rport)) {
csio_err(hw,
"LUN reset cannot be issued on non-ready"
" remote node ssni:0x%x (LUN:%llu)\n",
rn->flowid, cmnd->device->lun);
goto fail;
}
/* Get a free ioreq structure - SM is already set to uninit */
ioreq = csio_get_scsi_ioreq_lock(hw, scsim);
if (!ioreq) {
csio_err(hw, "Out of IO request elements. Active # :%d\n",
scsim->stats.n_active);
goto fail;
}
sqset = &hw->sqset[ln->portid][smp_processor_id()];
ioreq->nsge = 0;
ioreq->lnode = ln;
ioreq->rnode = rn;
ioreq->iq_idx = sqset->iq_idx;
ioreq->eq_idx = sqset->eq_idx;
csio_scsi_cmnd(ioreq) = cmnd;
cmnd->host_scribble = (unsigned char *)ioreq;
cmnd->SCp.Status = 0;
cmnd->SCp.Message = FCP_TMF_LUN_RESET;
ioreq->tmo = CSIO_SCSI_LUNRST_TMO_MS / 1000;
/*
* FW times the LUN reset for ioreq->tmo, so we got to wait a little
* longer (10s for now) than that to allow FW to return the timed
* out command.
*/
count = DIV_ROUND_UP((ioreq->tmo + 10) * 1000, CSIO_SCSI_TM_POLL_MS);
/* Set cbfn */
ioreq->io_cbfn = csio_tm_cbfn;
/* Save of the ioreq info for later use */
sld.level = CSIO_LEV_LUN;
sld.lnode = ioreq->lnode;
sld.rnode = ioreq->rnode;
sld.oslun = cmnd->device->lun;
spin_lock_irqsave(&hw->lock, flags);
/* Kick off TM SM on the ioreq */
retval = csio_scsi_start_tm(ioreq);
spin_unlock_irqrestore(&hw->lock, flags);
if (retval != 0) {
csio_err(hw, "Failed to issue LUN reset, req:%p, status:%d\n",
ioreq, retval);
goto fail_ret_ioreq;
}
csio_dbg(hw, "Waiting max %d secs for LUN reset completion\n",
count * (CSIO_SCSI_TM_POLL_MS / 1000));
/* Wait for completion */
while ((((struct scsi_cmnd *)csio_scsi_cmnd(ioreq)) == cmnd)
&& count--)
msleep(CSIO_SCSI_TM_POLL_MS);
/* LUN reset timed-out */
if (((struct scsi_cmnd *)csio_scsi_cmnd(ioreq)) == cmnd) {
csio_err(hw, "LUN reset (%d:%llu) timed out\n",
cmnd->device->id, cmnd->device->lun);
spin_lock_irq(&hw->lock);
csio_scsi_drvcleanup(ioreq);
list_del_init(&ioreq->sm.sm_list);
spin_unlock_irq(&hw->lock);
goto fail_ret_ioreq;
}
/* LUN reset returned, check cached status */
if (cmnd->SCp.Status != FW_SUCCESS) {
csio_err(hw, "LUN reset failed (%d:%llu), status: %d\n",
cmnd->device->id, cmnd->device->lun, cmnd->SCp.Status);
goto fail;
}
/* LUN reset succeeded, Start aborting affected I/Os */
/*
* Since the host guarantees during LUN reset that there
* will not be any more I/Os to that LUN, until the LUN reset
* completes, we gather pending I/Os after the LUN reset.
*/
spin_lock_irq(&hw->lock);
csio_scsi_gather_active_ios(scsim, &sld, &local_q);
retval = csio_scsi_abort_io_q(scsim, &local_q, 30000);
spin_unlock_irq(&hw->lock);
/* Aborts may have timed out */
if (retval != 0) {
csio_err(hw,
"Attempt to abort I/Os during LUN reset of %llu"
" returned %d\n", cmnd->device->lun, retval);
/* Return I/Os back to active_q */
spin_lock_irq(&hw->lock);
list_splice_tail_init(&local_q, &scsim->active_q);
spin_unlock_irq(&hw->lock);
goto fail;
}
CSIO_INC_STATS(rn, n_lun_rst);
csio_info(hw, "LUN reset occurred (%d:%llu)\n",
cmnd->device->id, cmnd->device->lun);
return SUCCESS;
fail_ret_ioreq:
csio_put_scsi_ioreq_lock(hw, scsim, ioreq);
fail:
CSIO_INC_STATS(rn, n_lun_rst_fail);
return FAILED;
}
static int
csio_slave_alloc(struct scsi_device *sdev)
{
struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
if (!rport || fc_remote_port_chkready(rport))
return -ENXIO;
sdev->hostdata = *((struct csio_lnode **)(rport->dd_data));
return 0;
}
static int
csio_slave_configure(struct scsi_device *sdev)
{
scsi_change_queue_depth(sdev, csio_lun_qdepth);
return 0;
}
static void
csio_slave_destroy(struct scsi_device *sdev)
{
sdev->hostdata = NULL;
}
static int
csio_scan_finished(struct Scsi_Host *shost, unsigned long time)
{
struct csio_lnode *ln = shost_priv(shost);
int rv = 1;
spin_lock_irq(shost->host_lock);
if (!ln->hwp || csio_list_deleted(&ln->sm.sm_list))
goto out;
rv = csio_scan_done(ln, jiffies, time, csio_max_scan_tmo * HZ,
csio_delta_scan_tmo * HZ);
out:
spin_unlock_irq(shost->host_lock);
return rv;
}
struct scsi_host_template csio_fcoe_shost_template = {
.module = THIS_MODULE,
.name = CSIO_DRV_DESC,
.proc_name = KBUILD_MODNAME,
.queuecommand = csio_queuecommand,
.eh_timed_out = fc_eh_timed_out,
.eh_abort_handler = csio_eh_abort_handler,
.eh_device_reset_handler = csio_eh_lun_reset_handler,
.slave_alloc = csio_slave_alloc,
.slave_configure = csio_slave_configure,
.slave_destroy = csio_slave_destroy,
.scan_finished = csio_scan_finished,
.this_id = -1,
.sg_tablesize = CSIO_SCSI_MAX_SGE,
.cmd_per_lun = CSIO_MAX_CMD_PER_LUN,
.shost_attrs = csio_fcoe_lport_attrs,
.max_sectors = CSIO_MAX_SECTOR_SIZE,
};
struct scsi_host_template csio_fcoe_shost_vport_template = {
.module = THIS_MODULE,
.name = CSIO_DRV_DESC,
.proc_name = KBUILD_MODNAME,
.queuecommand = csio_queuecommand,
.eh_timed_out = fc_eh_timed_out,
.eh_abort_handler = csio_eh_abort_handler,
.eh_device_reset_handler = csio_eh_lun_reset_handler,
.slave_alloc = csio_slave_alloc,
.slave_configure = csio_slave_configure,
.slave_destroy = csio_slave_destroy,
.scan_finished = csio_scan_finished,
.this_id = -1,
.sg_tablesize = CSIO_SCSI_MAX_SGE,
.cmd_per_lun = CSIO_MAX_CMD_PER_LUN,
.shost_attrs = csio_fcoe_vport_attrs,
.max_sectors = CSIO_MAX_SECTOR_SIZE,
};
/*
* csio_scsi_alloc_ddp_bufs - Allocate buffers for DDP of unaligned SGLs.
* @scm: SCSI Module
* @hw: HW device.
* @buf_size: buffer size
* @num_buf : Number of buffers.
*
* This routine allocates DMA buffers required for SCSI Data xfer, if
* each SGL buffer for a SCSI Read request posted by SCSI midlayer are
* not virtually contiguous.
*/
static int
csio_scsi_alloc_ddp_bufs(struct csio_scsim *scm, struct csio_hw *hw,
int buf_size, int num_buf)
{
int n = 0;
struct list_head *tmp;
struct csio_dma_buf *ddp_desc = NULL;
uint32_t unit_size = 0;
if (!num_buf)
return 0;
if (!buf_size)
return -EINVAL;
INIT_LIST_HEAD(&scm->ddp_freelist);
/* Align buf size to page size */
buf_size = (buf_size + PAGE_SIZE - 1) & PAGE_MASK;
/* Initialize dma descriptors */
for (n = 0; n < num_buf; n++) {
/* Set unit size to request size */
unit_size = buf_size;
ddp_desc = kzalloc(sizeof(struct csio_dma_buf), GFP_KERNEL);
if (!ddp_desc) {
csio_err(hw,
"Failed to allocate ddp descriptors,"
" Num allocated = %d.\n",
scm->stats.n_free_ddp);
goto no_mem;
}
/* Allocate Dma buffers for DDP */
ddp_desc->vaddr = dma_alloc_coherent(&hw->pdev->dev, unit_size,
&ddp_desc->paddr, GFP_KERNEL);
if (!ddp_desc->vaddr) {
csio_err(hw,
"SCSI response DMA buffer (ddp) allocation"
" failed!\n");
kfree(ddp_desc);
goto no_mem;
}
ddp_desc->len = unit_size;
/* Added it to scsi ddp freelist */
list_add_tail(&ddp_desc->list, &scm->ddp_freelist);
CSIO_INC_STATS(scm, n_free_ddp);
}
return 0;
no_mem:
/* release dma descs back to freelist and free dma memory */
list_for_each(tmp, &scm->ddp_freelist) {
ddp_desc = (struct csio_dma_buf *) tmp;
tmp = csio_list_prev(tmp);
dma_free_coherent(&hw->pdev->dev, ddp_desc->len,
ddp_desc->vaddr, ddp_desc->paddr);
list_del_init(&ddp_desc->list);
kfree(ddp_desc);
}
scm->stats.n_free_ddp = 0;
return -ENOMEM;
}
/*
* csio_scsi_free_ddp_bufs - free DDP buffers of unaligned SGLs.
* @scm: SCSI Module
* @hw: HW device.
*
* This routine frees ddp buffers.
*/
static void
csio_scsi_free_ddp_bufs(struct csio_scsim *scm, struct csio_hw *hw)
{
struct list_head *tmp;
struct csio_dma_buf *ddp_desc;
/* release dma descs back to freelist and free dma memory */
list_for_each(tmp, &scm->ddp_freelist) {
ddp_desc = (struct csio_dma_buf *) tmp;
tmp = csio_list_prev(tmp);
dma_free_coherent(&hw->pdev->dev, ddp_desc->len,
ddp_desc->vaddr, ddp_desc->paddr);
list_del_init(&ddp_desc->list);
kfree(ddp_desc);
}
scm->stats.n_free_ddp = 0;
}
/**
* csio_scsim_init - Initialize SCSI Module
* @scm: SCSI Module
* @hw: HW module
*
*/
int
csio_scsim_init(struct csio_scsim *scm, struct csio_hw *hw)
{
int i;
struct csio_ioreq *ioreq;
struct csio_dma_buf *dma_buf;
INIT_LIST_HEAD(&scm->active_q);
scm->hw = hw;
scm->proto_cmd_len = sizeof(struct fcp_cmnd);
scm->proto_rsp_len = CSIO_SCSI_RSP_LEN;
scm->max_sge = CSIO_SCSI_MAX_SGE;
spin_lock_init(&scm->freelist_lock);
/* Pre-allocate ioreqs and initialize them */
INIT_LIST_HEAD(&scm->ioreq_freelist);
for (i = 0; i < csio_scsi_ioreqs; i++) {
ioreq = kzalloc(sizeof(struct csio_ioreq), GFP_KERNEL);
if (!ioreq) {
csio_err(hw,
"I/O request element allocation failed, "
" Num allocated = %d.\n",
scm->stats.n_free_ioreq);
goto free_ioreq;
}
/* Allocate Dma buffers for Response Payload */
dma_buf = &ioreq->dma_buf;
dma_buf->vaddr = dma_pool_alloc(hw->scsi_dma_pool, GFP_KERNEL,
&dma_buf->paddr);
if (!dma_buf->vaddr) {
csio_err(hw,
"SCSI response DMA buffer allocation"
" failed!\n");
kfree(ioreq);
goto free_ioreq;
}
dma_buf->len = scm->proto_rsp_len;
/* Set state to uninit */
csio_init_state(&ioreq->sm, csio_scsis_uninit);
INIT_LIST_HEAD(&ioreq->gen_list);
init_completion(&ioreq->cmplobj);
list_add_tail(&ioreq->sm.sm_list, &scm->ioreq_freelist);
CSIO_INC_STATS(scm, n_free_ioreq);
}
if (csio_scsi_alloc_ddp_bufs(scm, hw, PAGE_SIZE, csio_ddp_descs))
goto free_ioreq;
return 0;
free_ioreq:
/*
* Free up existing allocations, since an error
* from here means we are returning for good
*/
while (!list_empty(&scm->ioreq_freelist)) {
struct csio_sm *tmp;
tmp = list_first_entry(&scm->ioreq_freelist,
struct csio_sm, sm_list);
list_del_init(&tmp->sm_list);
ioreq = (struct csio_ioreq *)tmp;
dma_buf = &ioreq->dma_buf;
dma_pool_free(hw->scsi_dma_pool, dma_buf->vaddr,
dma_buf->paddr);
kfree(ioreq);
}
scm->stats.n_free_ioreq = 0;
return -ENOMEM;
}
/**
* csio_scsim_exit: Uninitialize SCSI Module
* @scm: SCSI Module
*
*/
void
csio_scsim_exit(struct csio_scsim *scm)
{
struct csio_ioreq *ioreq;
struct csio_dma_buf *dma_buf;
while (!list_empty(&scm->ioreq_freelist)) {
struct csio_sm *tmp;
tmp = list_first_entry(&scm->ioreq_freelist,
struct csio_sm, sm_list);
list_del_init(&tmp->sm_list);
ioreq = (struct csio_ioreq *)tmp;
dma_buf = &ioreq->dma_buf;
dma_pool_free(scm->hw->scsi_dma_pool, dma_buf->vaddr,
dma_buf->paddr);
kfree(ioreq);
}
scm->stats.n_free_ioreq = 0;
csio_scsi_free_ddp_bufs(scm, scm->hw);
}
| rperier/linux-rockchip | drivers/scsi/csiostor/csio_scsi.c | C | gpl-2.0 | 68,737 |
tuple = (1, 2)
v = "first is %<ref>s, second is %s" % tuple | asedunov/intellij-community | python/testData/resolve/PercentStringWithRefAsArgument.py | Python | apache-2.0 | 59 |
package com.intellij.openapi.externalSystem.service.internal;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.model.task.*;
import com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager;
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager;
import com.intellij.openapi.project.Project;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* Provides gradle tasks monitoring and management facilities.
* <p/>
* Thread-safe.
*
* @author Denis Zhdanov
* @since 2/8/12 1:52 PM
*/
public class ExternalSystemProcessingManager implements ExternalSystemTaskNotificationListener, Disposable {
/**
* We receive information about the tasks being enqueued to the slave processes which work directly with external systems here.
* However, there is a possible situation when particular task has been sent to execution but remote side has not been responding
* for a while. There at least two possible explanations then:
* <pre>
* <ul>
* <li>the task is still in progress (e.g. great number of libraries is being downloaded);</li>
* <li>remote side has fallen (uncaught exception; manual slave process kill etc);</li>
* </ul>
* </pre>
* We need to distinguish between them, so, we perform 'task pings' if any task is executed too long. Current constant holds
* criteria of 'too long execution'.
*/
private static final long TOO_LONG_EXECUTION_MS = TimeUnit.SECONDS.toMillis(10);
@NotNull private final ConcurrentMap<ExternalSystemTaskId, Long> myTasksInProgress = ContainerUtil.newConcurrentMap();
@NotNull private final ConcurrentMap<ExternalSystemTaskId, ExternalSystemTask> myTasksDetails = ContainerUtil.newConcurrentMap();
@NotNull private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
@NotNull private final ExternalSystemFacadeManager myFacadeManager;
@NotNull private final ExternalSystemProgressNotificationManager myProgressNotificationManager;
public ExternalSystemProcessingManager(@NotNull ExternalSystemFacadeManager facadeManager,
@NotNull ExternalSystemProgressNotificationManager notificationManager)
{
myFacadeManager = facadeManager;
myProgressNotificationManager = notificationManager;
if (ApplicationManager.getApplication().isUnitTestMode()) {
return;
}
notificationManager.addNotificationListener(this);
}
@Override
public void dispose() {
myProgressNotificationManager.removeNotificationListener(this);
myAlarm.cancelAllRequests();
}
/**
* Allows to check if any task of the given type is being executed at the moment.
*
* @param type target task type
* @return <code>true</code> if any task of the given type is being executed at the moment;
* <code>false</code> otherwise
*/
public boolean hasTaskOfTypeInProgress(@NotNull ExternalSystemTaskType type, @NotNull Project project) {
String projectId = ExternalSystemTaskId.getProjectId(project);
for (ExternalSystemTaskId id : myTasksInProgress.keySet()) {
if (type.equals(id.getType()) && projectId.equals(id.getIdeProjectId())) {
return true;
}
}
return false;
}
@Nullable
public ExternalSystemTask findTask(@NotNull ExternalSystemTaskType type,
@NotNull ProjectSystemId projectSystemId,
@NotNull final String externalProjectPath) {
for(ExternalSystemTask task : myTasksDetails.values()) {
if(task instanceof AbstractExternalSystemTask) {
AbstractExternalSystemTask externalSystemTask = (AbstractExternalSystemTask)task;
if(externalSystemTask.getId().getType() == type &&
externalSystemTask.getExternalSystemId().getId().equals(projectSystemId.getId()) &&
externalSystemTask.getExternalProjectPath().equals(externalProjectPath)){
return task;
}
}
}
return null;
}
@NotNull
public List<ExternalSystemTask> findTasksOfState(@NotNull ProjectSystemId projectSystemId,
@NotNull final ExternalSystemTaskState... taskStates) {
List<ExternalSystemTask> result = new SmartList<ExternalSystemTask>();
for (ExternalSystemTask task : myTasksDetails.values()) {
if (task instanceof AbstractExternalSystemTask) {
AbstractExternalSystemTask externalSystemTask = (AbstractExternalSystemTask)task;
if (externalSystemTask.getExternalSystemId().getId().equals(projectSystemId.getId()) &&
ArrayUtil.contains(externalSystemTask.getState(), taskStates)) {
result.add(task);
}
}
}
return result;
}
public void add(@NotNull ExternalSystemTask task) {
myTasksDetails.put(task.getId(), task);
}
public void release(@NotNull ExternalSystemTaskId id) {
myTasksDetails.remove(id);
}
@Override
public void onQueued(@NotNull ExternalSystemTaskId id) {
myTasksInProgress.put(id, System.currentTimeMillis() + TOO_LONG_EXECUTION_MS);
if (myAlarm.getActiveRequestCount() <= 0) {
myAlarm.addRequest(new Runnable() {
@Override
public void run() {
update();
}
}, TOO_LONG_EXECUTION_MS);
}
}
@Override
public void onStart(@NotNull ExternalSystemTaskId id) {
myTasksInProgress.put(id, System.currentTimeMillis() + TOO_LONG_EXECUTION_MS);
}
@Override
public void onStatusChange(@NotNull ExternalSystemTaskNotificationEvent event) {
myTasksInProgress.put(event.getId(), System.currentTimeMillis() + TOO_LONG_EXECUTION_MS);
}
@Override
public void onTaskOutput(@NotNull ExternalSystemTaskId id, @NotNull String text, boolean stdOut) {
myTasksInProgress.put(id, System.currentTimeMillis() + TOO_LONG_EXECUTION_MS);
}
@Override
public void onEnd(@NotNull ExternalSystemTaskId id) {
myTasksInProgress.remove(id);
if (myTasksInProgress.isEmpty()) {
myAlarm.cancelAllRequests();
}
}
@Override
public void onSuccess(@NotNull ExternalSystemTaskId id) {
}
@Override
public void onFailure(@NotNull ExternalSystemTaskId id, @NotNull Exception e) {
}
public void update() {
long delay = TOO_LONG_EXECUTION_MS;
Map<ExternalSystemTaskId, Long> newState = ContainerUtilRt.newHashMap();
Map<ExternalSystemTaskId, Long> currentState = ContainerUtilRt.newHashMap(myTasksInProgress);
if (currentState.isEmpty()) {
return;
}
for (Map.Entry<ExternalSystemTaskId, Long> entry : currentState.entrySet()) {
long diff = System.currentTimeMillis() - entry.getValue();
if (diff > 0) {
delay = Math.min(delay, diff);
newState.put(entry.getKey(), entry.getValue());
}
else {
// Perform explicit check on whether the task is still alive.
if (myFacadeManager.isTaskActive(entry.getKey())) {
newState.put(entry.getKey(), System.currentTimeMillis() + TOO_LONG_EXECUTION_MS);
}
}
}
myTasksInProgress.clear();
myTasksInProgress.putAll(newState);
if (!newState.isEmpty()) {
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
@Override
public void run() {
update();
}
}, delay);
}
}
}
| akosyakov/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemProcessingManager.java | Java | apache-2.0 | 7,952 |
<!DOCTYPE html>
<html>
<head>
<style>
html {
transform: translateZ(0);
}
body {
height: 2000px;
background-image: url('resources/simple_image.png');
background-size: 200px 200px;
background-attachment: fixed;
overflow: hidden; /* hide scrollbar */
}
</style>
</head>
<body>
</body>
</html>
| axinging/chromium-crosswalk | third_party/WebKit/LayoutTests/compositing/fixed-background-composited-html-expected.html | HTML | bsd-3-clause | 403 |
/*
* Sugar Library v1.3.5
*
* Freely distributable and licensed under the MIT-style license.
* Copyright (c) 2012 Andrew Plummer
* http://sugarjs.com/
*
* ---------------------------- */
(function(){
/***
* @package Core
* @description Internal utility and common methods.
***/
// A few optimizations for Google Closure Compiler will save us a couple kb in the release script.
var object = Object, array = Array, regexp = RegExp, date = Date, string = String, number = Number, math = Math, Undefined;
// The global context
var globalContext = typeof global !== 'undefined' ? global : this;
// defineProperty exists in IE8 but will error when trying to define a property on
// native objects. IE8 does not have defineProperies, however, so this check saves a try/catch block.
var definePropertySupport = object.defineProperty && object.defineProperties;
// Class initializers and class helpers
var ClassNames = 'Array,Boolean,Date,Function,Number,String,RegExp'.split(',');
var isArray = buildClassCheck(ClassNames[0]);
var isBoolean = buildClassCheck(ClassNames[1]);
var isDate = buildClassCheck(ClassNames[2]);
var isFunction = buildClassCheck(ClassNames[3]);
var isNumber = buildClassCheck(ClassNames[4]);
var isString = buildClassCheck(ClassNames[5]);
var isRegExp = buildClassCheck(ClassNames[6]);
function buildClassCheck(type) {
return function(obj) {
return className(obj) === '[object '+type+']';
}
}
function className(obj) {
return object.prototype.toString.call(obj);
}
function initializeClasses() {
initializeClass(object);
iterateOverObject(ClassNames, function(i,name) {
initializeClass(globalContext[name]);
});
}
function initializeClass(klass) {
if(klass['SugarMethods']) return;
defineProperty(klass, 'SugarMethods', {});
extend(klass, false, false, {
'restore': function() {
var all = arguments.length === 0, methods = multiArgs(arguments);
iterateOverObject(klass['SugarMethods'], function(name, m) {
if(all || methods.indexOf(name) > -1) {
defineProperty(m.instance ? klass.prototype : klass, name, m.method);
}
});
},
'extend': function(methods, override, instance) {
extend(klass, instance !== false, override, methods);
}
});
}
// Class extending methods
function extend(klass, instance, override, methods) {
var extendee = instance ? klass.prototype : klass, original;
initializeClass(klass);
iterateOverObject(methods, function(name, method) {
original = extendee[name];
if(typeof override === 'function') {
method = wrapNative(extendee[name], method, override);
}
if(override !== false || !extendee[name]) {
defineProperty(extendee, name, method);
}
// If the method is internal to Sugar, then store a reference so it can be restored later.
klass['SugarMethods'][name] = { instance: instance, method: method, original: original };
});
}
function extendSimilar(klass, instance, override, set, fn) {
var methods = {};
set = isString(set) ? set.split(',') : set;
set.forEach(function(name, i) {
fn(methods, name, i);
});
extend(klass, instance, override, methods);
}
function wrapNative(nativeFn, extendedFn, condition) {
return function() {
if(nativeFn && (condition === true || !condition.apply(this, arguments))) {
return nativeFn.apply(this, arguments);
} else {
return extendedFn.apply(this, arguments);
}
}
}
function defineProperty(target, name, method) {
if(definePropertySupport) {
object.defineProperty(target, name, { 'value': method, 'configurable': true, 'enumerable': false, 'writable': true });
} else {
target[name] = method;
}
}
// Argument helpers
function multiArgs(args, fn) {
var result = [], i;
for(i = 0; i < args.length; i++) {
result.push(args[i]);
if(fn) fn.call(args, args[i], i);
}
return result;
}
// General helpers
function isDefined(o) {
return o !== Undefined;
}
function isUndefined(o) {
return o === Undefined;
}
// Object helpers
function isObjectPrimitive(obj) {
// Check for null
return obj && typeof obj === 'object';
}
function isObject(obj) {
// === on the constructor is not safe across iframes
// 'hasOwnProperty' ensures that the object also inherits
// from Object, which is false for DOMElements in IE.
return !!obj && className(obj) === '[object Object]' && 'hasOwnProperty' in obj;
}
function hasOwnProperty(obj, key) {
return object['hasOwnProperty'].call(obj, key);
}
function iterateOverObject(obj, fn) {
var key;
for(key in obj) {
if(!hasOwnProperty(obj, key)) continue;
if(fn.call(obj, key, obj[key]) === false) break;
}
}
function simpleMerge(target, source) {
iterateOverObject(source, function(key) {
target[key] = source[key];
});
return target;
}
// Hash definition
function Hash(obj) {
simpleMerge(this, obj);
};
Hash.prototype.constructor = object;
// Number helpers
function getRange(start, stop, fn, step) {
var arr = [], i = parseInt(start), down = step < 0;
while((!down && i <= stop) || (down && i >= stop)) {
arr.push(i);
if(fn) fn.call(this, i);
i += step || 1;
}
return arr;
}
function round(val, precision, method) {
var fn = math[method || 'round'];
var multiplier = math.pow(10, math.abs(precision || 0));
if(precision < 0) multiplier = 1 / multiplier;
return fn(val * multiplier) / multiplier;
}
function ceil(val, precision) {
return round(val, precision, 'ceil');
}
function floor(val, precision) {
return round(val, precision, 'floor');
}
function padNumber(num, place, sign, base) {
var str = math.abs(num).toString(base || 10);
str = repeatString(place - str.replace(/\.\d+/, '').length, '0') + str;
if(sign || num < 0) {
str = (num < 0 ? '-' : '+') + str;
}
return str;
}
function getOrdinalizedSuffix(num) {
if(num >= 11 && num <= 13) {
return 'th';
} else {
switch(num % 10) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
default: return 'th';
}
}
}
// String helpers
// WhiteSpace/LineTerminator as defined in ES5.1 plus Unicode characters in the Space, Separator category.
function getTrimmableCharacters() {
return '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
}
function repeatString(times, str) {
return array(math.max(0, isDefined(times) ? times : 1) + 1).join(str || '');
}
// RegExp helpers
function getRegExpFlags(reg, add) {
var flags = reg.toString().match(/[^/]*$/)[0];
if(add) {
flags = (flags + add).split('').sort().join('').replace(/([gimy])\1+/g, '$1');
}
return flags;
}
function escapeRegExp(str) {
if(!isString(str)) str = string(str);
return str.replace(/([\\/'*+?|()\[\]{}.^$])/g,'\\$1');
}
// Specialized helpers
// Used by Array#unique and Object.equal
function stringify(thing, stack) {
var type = typeof thing,
thingIsObject,
thingIsArray,
klass, value,
arr, key, i;
// Return quickly if string to save cycles
if(type === 'string') return thing;
klass = object.prototype.toString.call(thing)
thingIsObject = isObject(thing);
thingIsArray = klass === '[object Array]';
if(thing != null && thingIsObject || thingIsArray) {
// This method for checking for cyclic structures was egregiously stolen from
// the ingenious method by @kitcambridge from the Underscore script:
// https://github.com/documentcloud/underscore/issues/240
if(!stack) stack = [];
// Allowing a step into the structure before triggering this
// script to save cycles on standard JSON structures and also to
// try as hard as possible to catch basic properties that may have
// been modified.
if(stack.length > 1) {
i = stack.length;
while (i--) {
if (stack[i] === thing) {
return 'CYC';
}
}
}
stack.push(thing);
value = string(thing.constructor);
arr = thingIsArray ? thing : object.keys(thing).sort();
for(i = 0; i < arr.length; i++) {
key = thingIsArray ? i : arr[i];
value += key + stringify(thing[key], stack);
}
stack.pop();
} else if(1 / thing === -Infinity) {
value = '-0';
} else {
value = string(thing && thing.valueOf ? thing.valueOf() : thing);
}
return type + klass + value;
}
function isEqual(a, b) {
if(objectIsMatchedByValue(a) && objectIsMatchedByValue(b)) {
return stringify(a) === stringify(b);
} else {
return a === b;
}
}
function objectIsMatchedByValue(obj) {
var klass = className(obj);
return klass === '[object Date]' ||
klass === '[object Array]' ||
klass === '[object String]' ||
klass === '[object Number]' ||
klass === '[object RegExp]' ||
klass === '[object Boolean]' ||
klass === '[object Arguments]' ||
isObject(obj);
}
// Used by Array#at and String#at
function entryAtIndex(arr, args, str) {
var result = [], length = arr.length, loop = args[args.length - 1] !== false, r;
multiArgs(args, function(index) {
if(isBoolean(index)) return false;
if(loop) {
index = index % length;
if(index < 0) index = length + index;
}
r = str ? arr.charAt(index) || '' : arr[index];
result.push(r);
});
return result.length < 2 ? result[0] : result;
}
// Object class methods implemented as instance methods
function buildObjectInstanceMethods(set, target) {
extendSimilar(target, true, false, set, function(methods, name) {
methods[name + (name === 'equal' ? 's' : '')] = function() {
return object[name].apply(null, [this].concat(multiArgs(arguments)));
}
});
}
initializeClasses();
/***
* @package ES5
* @description Shim methods that provide ES5 compatible functionality. This package can be excluded if you do not require legacy browser support (IE8 and below).
*
***/
/***
* Object module
*
***/
extend(object, false, false, {
'keys': function(obj) {
var keys = [];
if(!isObjectPrimitive(obj) && !isRegExp(obj) && !isFunction(obj)) {
throw new TypeError('Object required');
}
iterateOverObject(obj, function(key, value) {
keys.push(key);
});
return keys;
}
});
/***
* Array module
*
***/
// ECMA5 methods
function arrayIndexOf(arr, search, fromIndex, increment) {
var length = arr.length,
fromRight = increment == -1,
start = fromRight ? length - 1 : 0,
index = toIntegerWithDefault(fromIndex, start);
if(index < 0) {
index = length + index;
}
if((!fromRight && index < 0) || (fromRight && index >= length)) {
index = start;
}
while((fromRight && index >= 0) || (!fromRight && index < length)) {
if(arr[index] === search) {
return index;
}
index += increment;
}
return -1;
}
function arrayReduce(arr, fn, initialValue, fromRight) {
var length = arr.length, count = 0, defined = isDefined(initialValue), result, index;
checkCallback(fn);
if(length == 0 && !defined) {
throw new TypeError('Reduce called on empty array with no initial value');
} else if(defined) {
result = initialValue;
} else {
result = arr[fromRight ? length - 1 : count];
count++;
}
while(count < length) {
index = fromRight ? length - count - 1 : count;
if(index in arr) {
result = fn(result, arr[index], index, arr);
}
count++;
}
return result;
}
function toIntegerWithDefault(i, d) {
if(isNaN(i)) {
return d;
} else {
return parseInt(i >> 0);
}
}
function checkCallback(fn) {
if(!fn || !fn.call) {
throw new TypeError('Callback is not callable');
}
}
function checkFirstArgumentExists(args) {
if(args.length === 0) {
throw new TypeError('First argument must be defined');
}
}
extend(array, false, false, {
/***
*
* @method Array.isArray(<obj>)
* @returns Boolean
* @short Returns true if <obj> is an Array.
* @extra This method is provided for browsers that don't support it internally.
* @example
*
* Array.isArray(3) -> false
* Array.isArray(true) -> false
* Array.isArray('wasabi') -> false
* Array.isArray([1,2,3]) -> true
*
***/
'isArray': function(obj) {
return isArray(obj);
}
});
extend(array, true, false, {
/***
* @method every(<f>, [scope])
* @returns Boolean
* @short Returns true if all elements in the array match <f>.
* @extra [scope] is the %this% object. %all% is provided an alias. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ ['a','a','a'].every(function(n) {
* return n == 'a';
* });
* ['a','a','a'].every('a') -> true
* [{a:2},{a:2}].every({a:2}) -> true
***/
'every': function(fn, scope) {
var length = this.length, index = 0;
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && !fn.call(scope, this[index], index, this)) {
return false;
}
index++;
}
return true;
},
/***
* @method some(<f>, [scope])
* @returns Boolean
* @short Returns true if any element in the array matches <f>.
* @extra [scope] is the %this% object. %any% is provided as an alias. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ ['a','b','c'].some(function(n) {
* return n == 'a';
* });
+ ['a','b','c'].some(function(n) {
* return n == 'd';
* });
* ['a','b','c'].some('a') -> true
* [{a:2},{b:5}].some({a:2}) -> true
***/
'some': function(fn, scope) {
var length = this.length, index = 0;
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && fn.call(scope, this[index], index, this)) {
return true;
}
index++;
}
return false;
},
/***
* @method map(<map>, [scope])
* @returns Array
* @short Maps the array to another array containing the values that are the result of calling <map> on each element.
* @extra [scope] is the %this% object. In addition to providing this method for browsers that don't support it natively, this enhanced method also directly accepts a string, which is a shortcut for a function that gets that property (or invokes a function) on each element.
* @example
*
+ [1,2,3].map(function(n) {
* return n * 3;
* }); -> [3,6,9]
* ['one','two','three'].map(function(n) {
* return n.length;
* }); -> [3,3,5]
* ['one','two','three'].map('length') -> [3,3,5]
***/
'map': function(fn, scope) {
var length = this.length, index = 0, result = new Array(length);
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this) {
result[index] = fn.call(scope, this[index], index, this);
}
index++;
}
return result;
},
/***
* @method filter(<f>, [scope])
* @returns Array
* @short Returns any elements in the array that match <f>.
* @extra [scope] is the %this% object. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ [1,2,3].filter(function(n) {
* return n > 1;
* });
* [1,2,2,4].filter(2) -> 2
*
***/
'filter': function(fn, scope) {
var length = this.length, index = 0, result = [];
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && fn.call(scope, this[index], index, this)) {
result.push(this[index]);
}
index++;
}
return result;
},
/***
* @method indexOf(<search>, [fromIndex])
* @returns Number
* @short Searches the array and returns the first index where <search> occurs, or -1 if the element is not found.
* @extra [fromIndex] is the index from which to begin the search. This method performs a simple strict equality comparison on <search>. It does not support enhanced functionality such as searching the contents against a regex, callback, or deep comparison of objects. For such functionality, use the %findIndex% method instead.
* @example
*
* [1,2,3].indexOf(3) -> 1
* [1,2,3].indexOf(7) -> -1
*
***/
'indexOf': function(search, fromIndex) {
if(isString(this)) return this.indexOf(search, fromIndex);
return arrayIndexOf(this, search, fromIndex, 1);
},
/***
* @method lastIndexOf(<search>, [fromIndex])
* @returns Number
* @short Searches the array and returns the last index where <search> occurs, or -1 if the element is not found.
* @extra [fromIndex] is the index from which to begin the search. This method performs a simple strict equality comparison on <search>.
* @example
*
* [1,2,1].lastIndexOf(1) -> 2
* [1,2,1].lastIndexOf(7) -> -1
*
***/
'lastIndexOf': function(search, fromIndex) {
if(isString(this)) return this.lastIndexOf(search, fromIndex);
return arrayIndexOf(this, search, fromIndex, -1);
},
/***
* @method forEach([fn], [scope])
* @returns Nothing
* @short Iterates over the array, calling [fn] on each loop.
* @extra This method is only provided for those browsers that do not support it natively. [scope] becomes the %this% object.
* @example
*
* ['a','b','c'].forEach(function(a) {
* // Called 3 times: 'a','b','c'
* });
*
***/
'forEach': function(fn, scope) {
var length = this.length, index = 0;
checkCallback(fn);
while(index < length) {
if(index in this) {
fn.call(scope, this[index], index, this);
}
index++;
}
},
/***
* @method reduce(<fn>, [init])
* @returns Mixed
* @short Reduces the array to a single result.
* @extra If [init] is passed as a starting value, that value will be passed as the first argument to the callback. The second argument will be the first element in the array. From that point, the result of the callback will then be used as the first argument of the next iteration. This is often refered to as "accumulation", and [init] is often called an "accumulator". If [init] is not passed, then <fn> will be called n - 1 times, where n is the length of the array. In this case, on the first iteration only, the first argument will be the first element of the array, and the second argument will be the second. After that callbacks work as normal, using the result of the previous callback as the first argument of the next. This method is only provided for those browsers that do not support it natively.
*
* @example
*
+ [1,2,3,4].reduce(function(a, b) {
* return a - b;
* });
+ [1,2,3,4].reduce(function(a, b) {
* return a - b;
* }, 100);
*
***/
'reduce': function(fn, init) {
return arrayReduce(this, fn, init);
},
/***
* @method reduceRight([fn], [init])
* @returns Mixed
* @short Identical to %Array#reduce%, but operates on the elements in reverse order.
* @extra This method is only provided for those browsers that do not support it natively.
*
*
*
*
* @example
*
+ [1,2,3,4].reduceRight(function(a, b) {
* return a - b;
* });
*
***/
'reduceRight': function(fn, init) {
return arrayReduce(this, fn, init, true);
}
});
/***
* String module
*
***/
function buildTrim() {
var support = getTrimmableCharacters().match(/^\s+$/);
try { string.prototype.trim.call([1]); } catch(e) { support = false; }
extend(string, true, !support, {
/***
* @method trim[Side]()
* @returns String
* @short Removes leading and/or trailing whitespace from the string.
* @extra Whitespace is defined as line breaks, tabs, and any character in the "Space, Separator" Unicode category, conforming to the the ES5 spec. The standard %trim% method is only added when not fully supported natively.
*
* @set
* trim
* trimLeft
* trimRight
*
* @example
*
* ' wasabi '.trim() -> 'wasabi'
* ' wasabi '.trimLeft() -> 'wasabi '
* ' wasabi '.trimRight() -> ' wasabi'
*
***/
'trim': function() {
return this.toString().trimLeft().trimRight();
},
'trimLeft': function() {
return this.replace(regexp('^['+getTrimmableCharacters()+']+'), '');
},
'trimRight': function() {
return this.replace(regexp('['+getTrimmableCharacters()+']+$'), '');
}
});
}
/***
* Function module
*
***/
extend(Function, true, false, {
/***
* @method bind(<scope>, [arg1], ...)
* @returns Function
* @short Binds <scope> as the %this% object for the function when it is called. Also allows currying an unlimited number of parameters.
* @extra "currying" means setting parameters ([arg1], [arg2], etc.) ahead of time so that they are passed when the function is called later. If you pass additional parameters when the function is actually called, they will be added will be added to the end of the curried parameters. This method is provided for browsers that don't support it internally.
* @example
*
+ (function() {
* return this;
* }).bind('woof')(); -> returns 'woof'; function is bound with 'woof' as the this object.
* (function(a) {
* return a;
* }).bind(1, 2)(); -> returns 2; function is bound with 1 as the this object and 2 curried as the first parameter
* (function(a, b) {
* return a + b;
* }).bind(1, 2)(3); -> returns 5; function is bound with 1 as the this object, 2 curied as the first parameter and 3 passed as the second when calling the function
*
***/
'bind': function(scope) {
var fn = this, args = multiArgs(arguments).slice(1), nop, bound;
if(!isFunction(this)) {
throw new TypeError('Function.prototype.bind called on a non-function');
}
bound = function() {
return fn.apply(fn.prototype && this instanceof fn ? this : scope, args.concat(multiArgs(arguments)));
}
bound.prototype = this.prototype;
return bound;
}
});
/***
* Date module
*
***/
/***
* @method toISOString()
* @returns String
* @short Formats the string to ISO8601 format.
* @extra This will always format as UTC time. Provided for browsers that do not support this method.
* @example
*
* Date.create().toISOString() -> ex. 2011-07-05 12:24:55.528Z
*
***
* @method toJSON()
* @returns String
* @short Returns a JSON representation of the date.
* @extra This is effectively an alias for %toISOString%. Will always return the date in UTC time. Provided for browsers that do not support this method.
* @example
*
* Date.create().toJSON() -> ex. 2011-07-05 12:24:55.528Z
*
***/
extend(date, false, false, {
/***
* @method Date.now()
* @returns String
* @short Returns the number of milliseconds since January 1st, 1970 00:00:00 (UTC time).
* @extra Provided for browsers that do not support this method.
* @example
*
* Date.now() -> ex. 1311938296231
*
***/
'now': function() {
return new date().getTime();
}
});
function buildISOString() {
var d = new date(date.UTC(1999, 11, 31)), target = '1999-12-31T00:00:00.000Z';
var support = d.toISOString && d.toISOString() === target;
extendSimilar(date, true, !support, 'toISOString,toJSON', function(methods, name) {
methods[name] = function() {
return padNumber(this.getUTCFullYear(), 4) + '-' +
padNumber(this.getUTCMonth() + 1, 2) + '-' +
padNumber(this.getUTCDate(), 2) + 'T' +
padNumber(this.getUTCHours(), 2) + ':' +
padNumber(this.getUTCMinutes(), 2) + ':' +
padNumber(this.getUTCSeconds(), 2) + '.' +
padNumber(this.getUTCMilliseconds(), 3) + 'Z';
}
});
}
// Initialize
buildTrim();
buildISOString();
/***
* @package Array
* @dependency core
* @description Array manipulation and traversal, "fuzzy matching" against elements, alphanumeric sorting and collation, enumerable methods on Object.
*
***/
function multiMatch(el, match, scope, params) {
var result = true;
if(el === match) {
// Match strictly equal values up front.
return true;
} else if(isRegExp(match) && isString(el)) {
// Match against a regexp
return regexp(match).test(el);
} else if(isFunction(match) && !isFunction(el)) {
// Match against a filtering function
return match.apply(scope, params);
} else if(isObject(match) && isObjectPrimitive(el)) {
// Match against a hash or array.
iterateOverObject(match, function(key, value) {
if(!multiMatch(el[key], match[key], scope, [el[key], el])) {
result = false;
}
});
return result;
} else {
return isEqual(el, match);
}
}
function transformArgument(el, map, context, mapArgs) {
if(isUndefined(map)) {
return el;
} else if(isFunction(map)) {
return map.apply(context, mapArgs || []);
} else if(isFunction(el[map])) {
return el[map].call(el);
} else {
return el[map];
}
}
// Basic array internal methods
function arrayEach(arr, fn, startIndex, loop) {
var length, index, i;
if(startIndex < 0) startIndex = arr.length + startIndex;
i = isNaN(startIndex) ? 0 : startIndex;
length = loop === true ? arr.length + i : arr.length;
while(i < length) {
index = i % arr.length;
if(!(index in arr)) {
return iterateOverSparseArray(arr, fn, i, loop);
} else if(fn.call(arr, arr[index], index, arr) === false) {
break;
}
i++;
}
}
function iterateOverSparseArray(arr, fn, fromIndex, loop) {
var indexes = [], i;
for(i in arr) {
if(isArrayIndex(arr, i) && i >= fromIndex) {
indexes.push(parseInt(i));
}
}
indexes.sort().each(function(index) {
return fn.call(arr, arr[index], index, arr);
});
return arr;
}
function isArrayIndex(arr, i) {
return i in arr && toUInt32(i) == i && i != 0xffffffff;
}
function toUInt32(i) {
return i >>> 0;
}
function arrayFind(arr, f, startIndex, loop, returnIndex) {
var result, index;
arrayEach(arr, function(el, i, arr) {
if(multiMatch(el, f, arr, [el, i, arr])) {
result = el;
index = i;
return false;
}
}, startIndex, loop);
return returnIndex ? index : result;
}
function arrayUnique(arr, map) {
var result = [], o = {}, transformed;
arrayEach(arr, function(el, i) {
transformed = map ? transformArgument(el, map, arr, [el, i, arr]) : el;
if(!checkForElementInHashAndSet(o, transformed)) {
result.push(el);
}
})
return result;
}
function arrayIntersect(arr1, arr2, subtract) {
var result = [], o = {};
arr2.each(function(el) {
checkForElementInHashAndSet(o, el);
});
arr1.each(function(el) {
var stringified = stringify(el),
isReference = !objectIsMatchedByValue(el);
// Add the result to the array if:
// 1. We're subtracting intersections or it doesn't already exist in the result and
// 2. It exists in the compared array and we're adding, or it doesn't exist and we're removing.
if(elementExistsInHash(o, stringified, el, isReference) != subtract) {
discardElementFromHash(o, stringified, el, isReference);
result.push(el);
}
});
return result;
}
function arrayFlatten(arr, level, current) {
level = level || Infinity;
current = current || 0;
var result = [];
arrayEach(arr, function(el) {
if(isArray(el) && current < level) {
result = result.concat(arrayFlatten(el, level, current + 1));
} else {
result.push(el);
}
});
return result;
}
function flatArguments(args) {
var result = [];
multiArgs(args, function(arg) {
result = result.concat(arg);
});
return result;
}
function elementExistsInHash(hash, key, element, isReference) {
var exists = key in hash;
if(isReference) {
if(!hash[key]) {
hash[key] = [];
}
exists = hash[key].indexOf(element) !== -1;
}
return exists;
}
function checkForElementInHashAndSet(hash, element) {
var stringified = stringify(element),
isReference = !objectIsMatchedByValue(element),
exists = elementExistsInHash(hash, stringified, element, isReference);
if(isReference) {
hash[stringified].push(element);
} else {
hash[stringified] = element;
}
return exists;
}
function discardElementFromHash(hash, key, element, isReference) {
var arr, i = 0;
if(isReference) {
arr = hash[key];
while(i < arr.length) {
if(arr[i] === element) {
arr.splice(i, 1);
} else {
i += 1;
}
}
} else {
delete hash[key];
}
}
// Support methods
function getMinOrMax(obj, map, which, all) {
var edge,
result = [],
max = which === 'max',
min = which === 'min',
isArray = Array.isArray(obj);
iterateOverObject(obj, function(key) {
var el = obj[key];
var test = transformArgument(el, map, obj, isArray ? [el, parseInt(key), obj] : []);
if(test === edge) {
result.push(el);
} else if(isUndefined(edge) || (max && test > edge) || (min && test < edge)) {
result = [el];
edge = test;
}
});
if(!isArray) result = arrayFlatten(result, 1);
return all ? result : result[0];
}
// Alphanumeric collation helpers
function collateStrings(a, b) {
var aValue, bValue, aChar, bChar, aEquiv, bEquiv, index = 0, tiebreaker = 0;
a = getCollationReadyString(a);
b = getCollationReadyString(b);
do {
aChar = getCollationCharacter(a, index);
bChar = getCollationCharacter(b, index);
aValue = getCollationValue(aChar);
bValue = getCollationValue(bChar);
if(aValue === -1 || bValue === -1) {
aValue = a.charCodeAt(index) || null;
bValue = b.charCodeAt(index) || null;
}
aEquiv = aChar !== a.charAt(index);
bEquiv = bChar !== b.charAt(index);
if(aEquiv !== bEquiv && tiebreaker === 0) {
tiebreaker = aEquiv - bEquiv;
}
index += 1;
} while(aValue != null && bValue != null && aValue === bValue);
if(aValue === bValue) return tiebreaker;
return aValue < bValue ? -1 : 1;
}
function getCollationReadyString(str) {
if(array[AlphanumericSortIgnoreCase]) {
str = str.toLowerCase();
}
return str.replace(array[AlphanumericSortIgnore], '');
}
function getCollationCharacter(str, index) {
var chr = str.charAt(index), eq = array[AlphanumericSortEquivalents] || {};
return eq[chr] || chr;
}
function getCollationValue(chr) {
var order = array[AlphanumericSortOrder];
if(!chr) {
return null;
} else {
return order.indexOf(chr);
}
}
var AlphanumericSortOrder = 'AlphanumericSortOrder';
var AlphanumericSortIgnore = 'AlphanumericSortIgnore';
var AlphanumericSortIgnoreCase = 'AlphanumericSortIgnoreCase';
var AlphanumericSortEquivalents = 'AlphanumericSortEquivalents';
function buildEnhancements() {
var callbackCheck = function() { var a = arguments; return a.length > 0 && !isFunction(a[0]); };
extendSimilar(array, true, callbackCheck, 'map,every,all,some,any,none,filter', function(methods, name) {
methods[name] = function(f) {
return this[name](function(el, index) {
if(name === 'map') {
return transformArgument(el, f, this, [el, index, this]);
} else {
return multiMatch(el, f, this, [el, index, this]);
}
});
}
});
}
function buildAlphanumericSort() {
var order = 'AÁÀÂÃĄBCĆČÇDĎÐEÉÈĚÊËĘFGĞHıIÍÌİÎÏJKLŁMNŃŇÑOÓÒÔPQRŘSŚŠŞTŤUÚÙŮÛÜVWXYÝZŹŻŽÞÆŒØÕÅÄÖ';
var equiv = 'AÁÀÂÃÄ,CÇ,EÉÈÊË,IÍÌİÎÏ,OÓÒÔÕÖ,Sß,UÚÙÛÜ';
array[AlphanumericSortOrder] = order.split('').map(function(str) {
return str + str.toLowerCase();
}).join('');
var equivalents = {};
arrayEach(equiv.split(','), function(set) {
var equivalent = set.charAt(0);
arrayEach(set.slice(1).split(''), function(chr) {
equivalents[chr] = equivalent;
equivalents[chr.toLowerCase()] = equivalent.toLowerCase();
});
});
array[AlphanumericSortIgnoreCase] = true;
array[AlphanumericSortEquivalents] = equivalents;
}
extend(array, false, false, {
/***
*
* @method Array.create(<obj1>, <obj2>, ...)
* @returns Array
* @short Alternate array constructor.
* @extra This method will create a single array by calling %concat% on all arguments passed. In addition to ensuring that an unknown variable is in a single, flat array (the standard constructor will create nested arrays, this one will not), it is also a useful shorthand to convert a function's arguments object into a standard array.
* @example
*
* Array.create('one', true, 3) -> ['one', true, 3]
* Array.create(['one', true, 3]) -> ['one', true, 3]
+ Array.create(function(n) {
* return arguments;
* }('howdy', 'doody'));
*
***/
'create': function() {
var result = [], tmp;
multiArgs(arguments, function(a) {
if(isObjectPrimitive(a)) {
tmp = array.prototype.slice.call(a);
if(tmp.length > 0) {
a = tmp;
}
}
result = result.concat(a);
});
return result;
}
});
extend(array, true, false, {
/***
* @method find(<f>, [index] = 0, [loop] = false)
* @returns Mixed
* @short Returns the first element that matches <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. Starts at [index], and will continue once from index = 0 if [loop] is true. This method implements @array_matching.
* @example
*
+ [{a:1,b:2},{a:1,b:3},{a:1,b:4}].find(function(n) {
* return n['a'] == 1;
* }); -> {a:1,b:3}
* ['cuba','japan','canada'].find(/^c/, 2) -> 'canada'
*
***/
'find': function(f, index, loop) {
return arrayFind(this, f, index, loop);
},
/***
* @method findAll(<f>, [index] = 0, [loop] = false)
* @returns Array
* @short Returns all elements that match <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. Starts at [index], and will continue once from index = 0 if [loop] is true. This method implements @array_matching.
* @example
*
+ [{a:1,b:2},{a:1,b:3},{a:2,b:4}].findAll(function(n) {
* return n['a'] == 1;
* }); -> [{a:1,b:3},{a:1,b:4}]
* ['cuba','japan','canada'].findAll(/^c/) -> 'cuba','canada'
* ['cuba','japan','canada'].findAll(/^c/, 2) -> 'canada'
*
***/
'findAll': function(f, index, loop) {
var result = [];
arrayEach(this, function(el, i, arr) {
if(multiMatch(el, f, arr, [el, i, arr])) {
result.push(el);
}
}, index, loop);
return result;
},
/***
* @method findIndex(<f>, [startIndex] = 0, [loop] = false)
* @returns Number
* @short Returns the index of the first element that matches <f> or -1 if not found.
* @extra This method has a few notable differences to native %indexOf%. Although <f> will similarly match a primitive such as a string or number, it will also match deep objects and arrays that are not equal by reference (%===%). Additionally, if a function is passed it will be run as a matching function (similar to the behavior of %Array#filter%) rather than attempting to find that function itself by reference in the array. Starts at [index], and will continue once from index = 0 if [loop] is true. This method implements @array_matching.
* @example
*
+ [1,2,3,4].findIndex(3); -> 2
+ [1,2,3,4].findIndex(function(n) {
* return n % 2 == 0;
* }); -> 1
+ ['one','two','three'].findIndex(/th/); -> 2
*
***/
'findIndex': function(f, startIndex, loop) {
var index = arrayFind(this, f, startIndex, loop, true);
return isUndefined(index) ? -1 : index;
},
/***
* @method count(<f>)
* @returns Number
* @short Counts all elements in the array that match <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. This method implements @array_matching.
* @example
*
* [1,2,3,1].count(1) -> 2
* ['a','b','c'].count(/b/) -> 1
+ [{a:1},{b:2}].count(function(n) {
* return n['a'] > 1;
* }); -> 0
*
***/
'count': function(f) {
if(isUndefined(f)) return this.length;
return this.findAll(f).length;
},
/***
* @method removeAt(<start>, [end])
* @returns Array
* @short Removes element at <start>. If [end] is specified, removes the range between <start> and [end]. This method will change the array! If you don't intend the array to be changed use %clone% first.
* @example
*
* ['a','b','c'].removeAt(0) -> ['b','c']
* [1,2,3,4].removeAt(1, 3) -> [1]
*
***/
'removeAt': function(start, end) {
if(isUndefined(start)) return this;
if(isUndefined(end)) end = start;
for(var i = 0; i <= (end - start); i++) {
this.splice(start, 1);
}
return this;
},
/***
* @method include(<el>, [index])
* @returns Array
* @short Adds <el> to the array.
* @extra This is a non-destructive alias for %add%. It will not change the original array.
* @example
*
* [1,2,3,4].include(5) -> [1,2,3,4,5]
* [1,2,3,4].include(8, 1) -> [1,8,2,3,4]
* [1,2,3,4].include([5,6,7]) -> [1,2,3,4,5,6,7]
*
***/
'include': function(el, index) {
return this.clone().add(el, index);
},
/***
* @method exclude([f1], [f2], ...)
* @returns Array
* @short Removes any element in the array that matches [f1], [f2], etc.
* @extra This is a non-destructive alias for %remove%. It will not change the original array. This method implements @array_matching.
* @example
*
* [1,2,3].exclude(3) -> [1,2]
* ['a','b','c'].exclude(/b/) -> ['a','c']
+ [{a:1},{b:2}].exclude(function(n) {
* return n['a'] == 1;
* }); -> [{b:2}]
*
***/
'exclude': function() {
return array.prototype.remove.apply(this.clone(), arguments);
},
/***
* @method clone()
* @returns Array
* @short Clones the array.
* @example
*
* [1,2,3].clone() -> [1,2,3]
*
***/
'clone': function() {
return simpleMerge([], this);
},
/***
* @method unique([map] = null)
* @returns Array
* @short Removes all duplicate elements in the array.
* @extra [map] may be a function mapping the value to be uniqued on or a string acting as a shortcut. This is most commonly used when you have a key that ensures the object's uniqueness, and don't need to check all fields. This method will also correctly operate on arrays of objects.
* @example
*
* [1,2,2,3].unique() -> [1,2,3]
* [{foo:'bar'},{foo:'bar'}].unique() -> [{foo:'bar'}]
+ [{foo:'bar'},{foo:'bar'}].unique(function(obj){
* return obj.foo;
* }); -> [{foo:'bar'}]
* [{foo:'bar'},{foo:'bar'}].unique('foo') -> [{foo:'bar'}]
*
***/
'unique': function(map) {
return arrayUnique(this, map);
},
/***
* @method flatten([limit] = Infinity)
* @returns Array
* @short Returns a flattened, one-dimensional copy of the array.
* @extra You can optionally specify a [limit], which will only flatten that depth.
* @example
*
* [[1], 2, [3]].flatten() -> [1,2,3]
* [['a'],[],'b','c'].flatten() -> ['a','b','c']
*
***/
'flatten': function(limit) {
return arrayFlatten(this, limit);
},
/***
* @method union([a1], [a2], ...)
* @returns Array
* @short Returns an array containing all elements in all arrays with duplicates removed.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].union([5,7,9]) -> [1,3,5,7,9]
* ['a','b'].union(['b','c']) -> ['a','b','c']
*
***/
'union': function() {
return arrayUnique(this.concat(flatArguments(arguments)));
},
/***
* @method intersect([a1], [a2], ...)
* @returns Array
* @short Returns an array containing the elements all arrays have in common.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].intersect([5,7,9]) -> [5]
* ['a','b'].intersect('b','c') -> ['b']
*
***/
'intersect': function() {
return arrayIntersect(this, flatArguments(arguments), false);
},
/***
* @method subtract([a1], [a2], ...)
* @returns Array
* @short Subtracts from the array all elements in [a1], [a2], etc.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].subtract([5,7,9]) -> [1,3]
* [1,3,5].subtract([3],[5]) -> [1]
* ['a','b'].subtract('b','c') -> ['a']
*
***/
'subtract': function(a) {
return arrayIntersect(this, flatArguments(arguments), true);
},
/***
* @method at(<index>, [loop] = true)
* @returns Mixed
* @short Gets the element(s) at a given index.
* @extra When [loop] is true, overshooting the end of the array (or the beginning) will begin counting from the other end. As an alternate syntax, passing multiple indexes will get the elements at those indexes.
* @example
*
* [1,2,3].at(0) -> 1
* [1,2,3].at(2) -> 3
* [1,2,3].at(4) -> 2
* [1,2,3].at(4, false) -> null
* [1,2,3].at(-1) -> 3
* [1,2,3].at(0,1) -> [1,2]
*
***/
'at': function() {
return entryAtIndex(this, arguments);
},
/***
* @method first([num] = 1)
* @returns Mixed
* @short Returns the first element(s) in the array.
* @extra When <num> is passed, returns the first <num> elements in the array.
* @example
*
* [1,2,3].first() -> 1
* [1,2,3].first(2) -> [1,2]
*
***/
'first': function(num) {
if(isUndefined(num)) return this[0];
if(num < 0) num = 0;
return this.slice(0, num);
},
/***
* @method last([num] = 1)
* @returns Mixed
* @short Returns the last element(s) in the array.
* @extra When <num> is passed, returns the last <num> elements in the array.
* @example
*
* [1,2,3].last() -> 3
* [1,2,3].last(2) -> [2,3]
*
***/
'last': function(num) {
if(isUndefined(num)) return this[this.length - 1];
var start = this.length - num < 0 ? 0 : this.length - num;
return this.slice(start);
},
/***
* @method from(<index>)
* @returns Array
* @short Returns a slice of the array from <index>.
* @example
*
* [1,2,3].from(1) -> [2,3]
* [1,2,3].from(2) -> [3]
*
***/
'from': function(num) {
return this.slice(num);
},
/***
* @method to(<index>)
* @returns Array
* @short Returns a slice of the array up to <index>.
* @example
*
* [1,2,3].to(1) -> [1]
* [1,2,3].to(2) -> [1,2]
*
***/
'to': function(num) {
if(isUndefined(num)) num = this.length;
return this.slice(0, num);
},
/***
* @method min([map], [all] = false)
* @returns Mixed
* @short Returns the element in the array with the lowest value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all min values in an array.
* @example
*
* [1,2,3].min() -> 1
* ['fee','fo','fum'].min('length') -> 'fo'
* ['fee','fo','fum'].min('length', true) -> ['fo']
+ ['fee','fo','fum'].min(function(n) {
* return n.length;
* }); -> ['fo']
+ [{a:3,a:2}].min(function(n) {
* return n['a'];
* }); -> [{a:2}]
*
***/
'min': function(map, all) {
return getMinOrMax(this, map, 'min', all);
},
/***
* @method max([map], [all] = false)
* @returns Mixed
* @short Returns the element in the array with the greatest value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all max values in an array.
* @example
*
* [1,2,3].max() -> 3
* ['fee','fo','fum'].max('length') -> 'fee'
* ['fee','fo','fum'].max('length', true) -> ['fee']
+ [{a:3,a:2}].max(function(n) {
* return n['a'];
* }); -> {a:3}
*
***/
'max': function(map, all) {
return getMinOrMax(this, map, 'max', all);
},
/***
* @method least([map])
* @returns Array
* @short Returns the elements in the array with the least commonly occuring value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut.
* @example
*
* [3,2,2].least() -> [3]
* ['fe','fo','fum'].least('length') -> ['fum']
+ [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].least(function(n) {
* return n.age;
* }); -> [{age:35,name:'ken'}]
*
***/
'least': function(map, all) {
return getMinOrMax(this.groupBy.apply(this, [map]), 'length', 'min', all);
},
/***
* @method most([map])
* @returns Array
* @short Returns the elements in the array with the most commonly occuring value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut.
* @example
*
* [3,2,2].most() -> [2]
* ['fe','fo','fum'].most('length') -> ['fe','fo']
+ [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].most(function(n) {
* return n.age;
* }); -> [{age:12,name:'bob'},{age:12,name:'ted'}]
*
***/
'most': function(map, all) {
return getMinOrMax(this.groupBy.apply(this, [map]), 'length', 'max', all);
},
/***
* @method sum([map])
* @returns Number
* @short Sums all values in the array.
* @extra [map] may be a function mapping the value to be summed or a string acting as a shortcut.
* @example
*
* [1,2,2].sum() -> 5
+ [{age:35},{age:12},{age:12}].sum(function(n) {
* return n.age;
* }); -> 59
* [{age:35},{age:12},{age:12}].sum('age') -> 59
*
***/
'sum': function(map) {
var arr = map ? this.map(map) : this;
return arr.length > 0 ? arr.reduce(function(a,b) { return a + b; }) : 0;
},
/***
* @method average([map])
* @returns Number
* @short Averages all values in the array.
* @extra [map] may be a function mapping the value to be averaged or a string acting as a shortcut.
* @example
*
* [1,2,3].average() -> 2
+ [{age:35},{age:11},{age:11}].average(function(n) {
* return n.age;
* }); -> 19
* [{age:35},{age:11},{age:11}].average('age') -> 19
*
***/
'average': function(map) {
var arr = map ? this.map(map) : this;
return arr.length > 0 ? arr.sum() / arr.length : 0;
},
/***
* @method inGroups(<num>, [padding])
* @returns Array
* @short Groups the array into <num> arrays.
* @extra [padding] specifies a value with which to pad the last array so that they are all equal length.
* @example
*
* [1,2,3,4,5,6,7].inGroups(3) -> [ [1,2,3], [4,5,6], [7] ]
* [1,2,3,4,5,6,7].inGroups(3, 'none') -> [ [1,2,3], [4,5,6], [7,'none','none'] ]
*
***/
'inGroups': function(num, padding) {
var pad = arguments.length > 1;
var arr = this;
var result = [];
var divisor = ceil(this.length / num);
getRange(0, num - 1, function(i) {
var index = i * divisor;
var group = arr.slice(index, index + divisor);
if(pad && group.length < divisor) {
getRange(1, divisor - group.length, function() {
group = group.add(padding);
});
}
result.push(group);
});
return result;
},
/***
* @method inGroupsOf(<num>, [padding] = null)
* @returns Array
* @short Groups the array into arrays of <num> elements each.
* @extra [padding] specifies a value with which to pad the last array so that they are all equal length.
* @example
*
* [1,2,3,4,5,6,7].inGroupsOf(4) -> [ [1,2,3,4], [5,6,7] ]
* [1,2,3,4,5,6,7].inGroupsOf(4, 'none') -> [ [1,2,3,4], [5,6,7,'none'] ]
*
***/
'inGroupsOf': function(num, padding) {
var result = [], len = this.length, arr = this, group;
if(len === 0 || num === 0) return arr;
if(isUndefined(num)) num = 1;
if(isUndefined(padding)) padding = null;
getRange(0, ceil(len / num) - 1, function(i) {
group = arr.slice(num * i, num * i + num);
while(group.length < num) {
group.push(padding);
}
result.push(group);
});
return result;
},
/***
* @method isEmpty()
* @returns Boolean
* @short Returns true if the array is empty.
* @extra This is true if the array has a length of zero, or contains only %undefined%, %null%, or %NaN%.
* @example
*
* [].isEmpty() -> true
* [null,undefined].isEmpty() -> true
*
***/
'isEmpty': function() {
return this.compact().length == 0;
},
/***
* @method sortBy(<map>, [desc] = false)
* @returns Array
* @short Sorts the array by <map>.
* @extra <map> may be a function, a string acting as a shortcut, or blank (direct comparison of array values). [desc] will sort the array in descending order. When the field being sorted on is a string, the resulting order will be determined by an internal collation algorithm that is optimized for major Western languages, but can be customized. For more information see @array_sorting.
* @example
*
* ['world','a','new'].sortBy('length') -> ['a','new','world']
* ['world','a','new'].sortBy('length', true) -> ['world','new','a']
+ [{age:72},{age:13},{age:18}].sortBy(function(n) {
* return n.age;
* }); -> [{age:13},{age:18},{age:72}]
*
***/
'sortBy': function(map, desc) {
var arr = this.clone();
arr.sort(function(a, b) {
var aProperty, bProperty, comp;
aProperty = transformArgument(a, map, arr, [a]);
bProperty = transformArgument(b, map, arr, [b]);
if(isString(aProperty) && isString(bProperty)) {
comp = collateStrings(aProperty, bProperty);
} else if(aProperty < bProperty) {
comp = -1;
} else if(aProperty > bProperty) {
comp = 1;
} else {
comp = 0;
}
return comp * (desc ? -1 : 1);
});
return arr;
},
/***
* @method randomize()
* @returns Array
* @short Returns a copy of the array with the elements randomized.
* @extra Uses Fisher-Yates algorithm.
* @example
*
* [1,2,3,4].randomize() -> [?,?,?,?]
*
***/
'randomize': function() {
var a = this.concat();
for(var j, x, i = a.length; i; j = parseInt(math.random() * i), x = a[--i], a[i] = a[j], a[j] = x) {};
return a;
},
/***
* @method zip([arr1], [arr2], ...)
* @returns Array
* @short Merges multiple arrays together.
* @extra This method "zips up" smaller arrays into one large whose elements are "all elements at index 0", "all elements at index 1", etc. Useful when you have associated data that is split over separated arrays. If the arrays passed have more elements than the original array, they will be discarded. If they have fewer elements, the missing elements will filled with %null%.
* @example
*
* [1,2,3].zip([4,5,6]) -> [[1,2], [3,4], [5,6]]
* ['Martin','John'].zip(['Luther','F.'], ['King','Kennedy']) -> [['Martin','Luther','King'], ['John','F.','Kennedy']]
*
***/
'zip': function() {
var args = multiArgs(arguments);
return this.map(function(el, i) {
return [el].concat(args.map(function(k) {
return (i in k) ? k[i] : null;
}));
});
},
/***
* @method sample([num])
* @returns Mixed
* @short Returns a random element from the array.
* @extra If [num] is passed, will return [num] samples from the array.
* @example
*
* [1,2,3,4,5].sample() -> // Random element
* [1,2,3,4,5].sample(3) -> // Array of 3 random elements
*
***/
'sample': function(num) {
var result = [], arr = this.clone(), index;
if(isUndefined(num)) num = 1;
while(result.length < num) {
index = floor(math.random() * (arr.length - 1));
result.push(arr[index]);
arr.removeAt(index);
if(arr.length == 0) break;
}
return arguments.length > 0 ? result : result[0];
},
/***
* @method each(<fn>, [index] = 0, [loop] = false)
* @returns Array
* @short Runs <fn> against each element in the array. Enhanced version of %Array#forEach%.
* @extra Parameters passed to <fn> are identical to %forEach%, ie. the first parameter is the current element, second parameter is the current index, and third parameter is the array itself. If <fn> returns %false% at any time it will break out of the loop. Once %each% finishes, it will return the array. If [index] is passed, <fn> will begin at that index and work its way to the end. If [loop] is true, it will then start over from the beginning of the array and continue until it reaches [index] - 1.
* @example
*
* [1,2,3,4].each(function(n) {
* // Called 4 times: 1, 2, 3, 4
* });
* [1,2,3,4].each(function(n) {
* // Called 4 times: 3, 4, 1, 2
* }, 2, true);
*
***/
'each': function(fn, index, loop) {
arrayEach(this, fn, index, loop);
return this;
},
/***
* @method add(<el>, [index])
* @returns Array
* @short Adds <el> to the array.
* @extra If [index] is specified, it will add at [index], otherwise adds to the end of the array. %add% behaves like %concat% in that if <el> is an array it will be joined, not inserted. This method will change the array! Use %include% for a non-destructive alias. Also, %insert% is provided as an alias that reads better when using an index.
* @example
*
* [1,2,3,4].add(5) -> [1,2,3,4,5]
* [1,2,3,4].add([5,6,7]) -> [1,2,3,4,5,6,7]
* [1,2,3,4].insert(8, 1) -> [1,8,2,3,4]
*
***/
'add': function(el, index) {
if(!isNumber(number(index)) || isNaN(index)) index = this.length;
array.prototype.splice.apply(this, [index, 0].concat(el));
return this;
},
/***
* @method remove([f1], [f2], ...)
* @returns Array
* @short Removes any element in the array that matches [f1], [f2], etc.
* @extra Will match a string, number, array, object, or alternately test against a function or regex. This method will change the array! Use %exclude% for a non-destructive alias. This method implements @array_matching.
* @example
*
* [1,2,3].remove(3) -> [1,2]
* ['a','b','c'].remove(/b/) -> ['a','c']
+ [{a:1},{b:2}].remove(function(n) {
* return n['a'] == 1;
* }); -> [{b:2}]
*
***/
'remove': function() {
var i, arr = this;
multiArgs(arguments, function(f) {
i = 0;
while(i < arr.length) {
if(multiMatch(arr[i], f, arr, [arr[i], i, arr])) {
arr.splice(i, 1);
} else {
i++;
}
}
});
return arr;
},
/***
* @method compact([all] = false)
* @returns Array
* @short Removes all instances of %undefined%, %null%, and %NaN% from the array.
* @extra If [all] is %true%, all "falsy" elements will be removed. This includes empty strings, 0, and false.
* @example
*
* [1,null,2,undefined,3].compact() -> [1,2,3]
* [1,'',2,false,3].compact() -> [1,'',2,false,3]
* [1,'',2,false,3].compact(true) -> [1,2,3]
*
***/
'compact': function(all) {
var result = [];
arrayEach(this, function(el, i) {
if(isArray(el)) {
result.push(el.compact());
} else if(all && el) {
result.push(el);
} else if(!all && el != null && el.valueOf() === el.valueOf()) {
result.push(el);
}
});
return result;
},
/***
* @method groupBy(<map>, [fn])
* @returns Object
* @short Groups the array by <map>.
* @extra Will return an object with keys equal to the grouped values. <map> may be a mapping function, or a string acting as a shortcut. Optionally calls [fn] for each group.
* @example
*
* ['fee','fi','fum'].groupBy('length') -> { 2: ['fi'], 3: ['fee','fum'] }
+ [{age:35,name:'ken'},{age:15,name:'bob'}].groupBy(function(n) {
* return n.age;
* }); -> { 35: [{age:35,name:'ken'}], 15: [{age:15,name:'bob'}] }
*
***/
'groupBy': function(map, fn) {
var arr = this, result = {}, key;
arrayEach(arr, function(el, index) {
key = transformArgument(el, map, arr, [el, index, arr]);
if(!result[key]) result[key] = [];
result[key].push(el);
});
if(fn) {
iterateOverObject(result, fn);
}
return result;
},
/***
* @method none(<f>)
* @returns Boolean
* @short Returns true if none of the elements in the array match <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. This method implements @array_matching.
* @example
*
* [1,2,3].none(5) -> true
* ['a','b','c'].none(/b/) -> false
+ [{a:1},{b:2}].none(function(n) {
* return n['a'] > 1;
* }); -> true
*
***/
'none': function() {
return !this.any.apply(this, arguments);
}
});
// Aliases
extend(array, true, false, {
/***
* @method all()
* @alias every
*
***/
'all': array.prototype.every,
/*** @method any()
* @alias some
*
***/
'any': array.prototype.some,
/***
* @method insert()
* @alias add
*
***/
'insert': array.prototype.add
});
/***
* Object module
* Enumerable methods on objects
*
***/
function keysWithCoercion(obj) {
if(obj && obj.valueOf) {
obj = obj.valueOf();
}
return object.keys(obj);
}
/***
* @method [enumerable](<obj>)
* @returns Boolean
* @short Enumerable methods in the Array package are also available to the Object class. They will perform their normal operations for every property in <obj>.
* @extra In cases where a callback is used, instead of %element, index%, the callback will instead be passed %key, value%. Enumerable methods are also available to extended objects as instance methods.
*
* @set
* map
* any
* all
* none
* count
* find
* findAll
* reduce
* isEmpty
* sum
* average
* min
* max
* least
* most
*
* @example
*
* Object.any({foo:'bar'}, 'bar') -> true
* Object.extended({foo:'bar'}).any('bar') -> true
* Object.isEmpty({}) -> true
+ Object.map({ fred: { age: 52 } }, 'age'); -> { fred: 52 }
*
***/
function buildEnumerableMethods(names, mapping) {
extendSimilar(object, false, false, names, function(methods, name) {
methods[name] = function(obj, arg1, arg2) {
var result;
result = array.prototype[name].call(keysWithCoercion(obj), function(key) {
if(mapping) {
return transformArgument(obj[key], arg1, obj, [key, obj[key], obj]);
} else {
return multiMatch(obj[key], arg1, obj, [key, obj[key], obj]);
}
}, arg2);
if(isArray(result)) {
// The method has returned an array of keys so use this array
// to build up the resulting object in the form we want it in.
result = result.reduce(function(o, key, i) {
o[key] = obj[key];
return o;
}, {});
}
return result;
};
});
buildObjectInstanceMethods(names, Hash);
}
extend(object, false, false, {
'map': function(obj, map) {
return keysWithCoercion(obj).reduce(function(result, key) {
result[key] = transformArgument(obj[key], map, obj, [key, obj[key], obj]);
return result;
}, {});
},
'reduce': function(obj) {
var values = keysWithCoercion(obj).map(function(key) {
return obj[key];
});
return values.reduce.apply(values, multiArgs(arguments).slice(1));
},
/***
* @method size(<obj>)
* @returns Number
* @short Returns the number of properties in <obj>.
* @extra %size% is available as an instance method on extended objects.
* @example
*
* Object.size({ foo: 'bar' }) -> 1
*
***/
'size': function (obj) {
return keysWithCoercion(obj).length;
}
});
buildEnhancements();
buildAlphanumericSort();
buildEnumerableMethods('each,any,all,none,count,find,findAll,isEmpty');
buildEnumerableMethods('sum,average,min,max,least,most', true);
buildObjectInstanceMethods('map,reduce,size', Hash);
/***
* @package Date
* @dependency core
* @description Date parsing and formatting, relative formats like "1 minute ago", Number methods like "daysAgo", localization support with default English locale definition.
*
***/
var English;
var CurrentLocalization;
var TimeFormat = ['ampm','hour','minute','second','ampm','utc','offset_sign','offset_hours','offset_minutes','ampm']
var FloatReg = '\\d{1,2}(?:[,.]\\d+)?';
var RequiredTime = '({t})?\\s*('+FloatReg+')(?:{h}('+FloatReg+')?{m}(?::?('+FloatReg+'){s})?\\s*(?:({t})|(Z)|(?:([+-])(\\d{2,2})(?::?(\\d{2,2}))?)?)?|\\s*({t}))';
var KanjiDigits = '〇一二三四五六七八九十百千万';
var FullWidthDigits = '0123456789';
var AsianDigitMap = {};
var AsianDigitReg;
var DateArgumentUnits;
var DateUnitsReversed;
var CoreDateFormats = [];
var DateOutputFormats = [
{
token: 'f{1,4}|ms|milliseconds',
format: function(d) {
return callDateGet(d, 'Milliseconds');
}
},
{
token: 'ss?|seconds',
format: function(d, len) {
return callDateGet(d, 'Seconds');
}
},
{
token: 'mm?|minutes',
format: function(d, len) {
return callDateGet(d, 'Minutes');
}
},
{
token: 'hh?|hours|12hr',
format: function(d) {
return getShortHour(d);
}
},
{
token: 'HH?|24hr',
format: function(d) {
return callDateGet(d, 'Hours');
}
},
{
token: 'dd?|date|day',
format: function(d) {
return callDateGet(d, 'Date');
}
},
{
token: 'dow|weekday',
word: true,
format: function(d, loc, n, t) {
var dow = callDateGet(d, 'Day');
return loc['weekdays'][dow + (n - 1) * 7];
}
},
{
token: 'MM?',
format: function(d) {
return callDateGet(d, 'Month') + 1;
}
},
{
token: 'mon|month',
word: true,
format: function(d, loc, n, len) {
var month = callDateGet(d, 'Month');
return loc['months'][month + (n - 1) * 12];
}
},
{
token: 'y{2,4}|year',
format: function(d) {
return callDateGet(d, 'FullYear');
}
},
{
token: '[Tt]{1,2}',
format: function(d, loc, n, format) {
if(loc['ampm'].length == 0) return '';
var hours = callDateGet(d, 'Hours');
var str = loc['ampm'][floor(hours / 12)];
if(format.length === 1) str = str.slice(0,1);
if(format.slice(0,1) === 'T') str = str.toUpperCase();
return str;
}
},
{
token: 'z{1,4}|tz|timezone',
text: true,
format: function(d, loc, n, format) {
var tz = d.getUTCOffset();
if(format == 'z' || format == 'zz') {
tz = tz.replace(/(\d{2})(\d{2})/, function(f,h,m) {
return padNumber(h, format.length);
});
}
return tz;
}
},
{
token: 'iso(tz|timezone)',
format: function(d) {
return d.getUTCOffset(true);
}
},
{
token: 'ord',
format: function(d) {
var date = callDateGet(d, 'Date');
return date + getOrdinalizedSuffix(date);
}
}
];
var DateUnits = [
{
unit: 'year',
method: 'FullYear',
ambiguous: true,
multiplier: function(d) {
var adjust = d ? (d.isLeapYear() ? 1 : 0) : 0.25;
return (365 + adjust) * 24 * 60 * 60 * 1000;
}
},
{
unit: 'month',
method: 'Month',
ambiguous: true,
multiplier: function(d, ms) {
var days = 30.4375, inMonth;
if(d) {
inMonth = d.daysInMonth();
if(ms <= inMonth.days()) {
days = inMonth;
}
}
return days * 24 * 60 * 60 * 1000;
}
},
{
unit: 'week',
method: 'Week',
multiplier: function() {
return 7 * 24 * 60 * 60 * 1000;
}
},
{
unit: 'day',
method: 'Date',
ambiguous: true,
multiplier: function() {
return 24 * 60 * 60 * 1000;
}
},
{
unit: 'hour',
method: 'Hours',
multiplier: function() {
return 60 * 60 * 1000;
}
},
{
unit: 'minute',
method: 'Minutes',
multiplier: function() {
return 60 * 1000;
}
},
{
unit: 'second',
method: 'Seconds',
multiplier: function() {
return 1000;
}
},
{
unit: 'millisecond',
method: 'Milliseconds',
multiplier: function() {
return 1;
}
}
];
// Date Localization
var Localizations = {};
// Localization object
function Localization(l) {
simpleMerge(this, l);
this.compiledFormats = CoreDateFormats.concat();
}
Localization.prototype = {
getMonth: function(n) {
if(isNumber(n)) {
return n - 1;
} else {
return this['months'].indexOf(n) % 12;
}
},
getWeekday: function(n) {
return this['weekdays'].indexOf(n) % 7;
},
getNumber: function(n) {
var i;
if(isNumber(n)) {
return n;
} else if(n && (i = this['numbers'].indexOf(n)) !== -1) {
return (i + 1) % 10;
} else {
return 1;
}
},
getNumericDate: function(n) {
var self = this;
return n.replace(regexp(this['num'], 'g'), function(d) {
var num = self.getNumber(d);
return num || '';
});
},
getEnglishUnit: function(n) {
return English['units'][this['units'].indexOf(n) % 8];
},
getRelativeFormat: function(adu) {
return this.convertAdjustedToFormat(adu, adu[2] > 0 ? 'future' : 'past');
},
getDuration: function(ms) {
return this.convertAdjustedToFormat(getAdjustedUnit(ms), 'duration');
},
hasVariant: function(code) {
code = code || this.code;
return code === 'en' || code === 'en-US' ? true : this['variant'];
},
matchAM: function(str) {
return str === this['ampm'][0];
},
matchPM: function(str) {
return str && str === this['ampm'][1];
},
convertAdjustedToFormat: function(adu, mode) {
var sign, unit, mult,
num = adu[0],
u = adu[1],
ms = adu[2],
format = this[mode] || this['relative'];
if(isFunction(format)) {
return format.call(this, num, u, ms, mode);
}
mult = this['plural'] && num > 1 ? 1 : 0;
unit = this['units'][mult * 8 + u] || this['units'][u];
if(this['capitalizeUnit']) unit = simpleCapitalize(unit);
sign = this['modifiers'].filter(function(m) { return m.name == 'sign' && m.value == (ms > 0 ? 1 : -1); })[0];
return format.replace(/\{(.*?)\}/g, function(full, match) {
switch(match) {
case 'num': return num;
case 'unit': return unit;
case 'sign': return sign.src;
}
});
},
getFormats: function() {
return this.cachedFormat ? [this.cachedFormat].concat(this.compiledFormats) : this.compiledFormats;
},
addFormat: function(src, allowsTime, match, variant, iso) {
var to = match || [], loc = this, time, timeMarkers, lastIsNumeral;
src = src.replace(/\s+/g, '[-,. ]*');
src = src.replace(/\{([^,]+?)\}/g, function(all, k) {
var value, arr, result,
opt = k.match(/\?$/),
nc = k.match(/^(\d+)\??$/),
slice = k.match(/(\d)(?:-(\d))?/),
key = k.replace(/[^a-z]+$/, '');
if(nc) {
value = loc['tokens'][nc[1]];
} else if(loc[key]) {
value = loc[key];
} else if(loc[key + 's']) {
value = loc[key + 's'];
if(slice) {
// Can't use filter here as Prototype hijacks the method and doesn't
// pass an index, so use a simple loop instead!
arr = [];
value.forEach(function(m, i) {
var mod = i % (loc['units'] ? 8 : value.length);
if(mod >= slice[1] && mod <= (slice[2] || slice[1])) {
arr.push(m);
}
});
value = arr;
}
value = arrayToAlternates(value);
}
if(nc) {
result = '(?:' + value + ')';
} else {
if(!match) {
to.push(key);
}
result = '(' + value + ')';
}
if(opt) {
result += '?';
}
return result;
});
if(allowsTime) {
time = prepareTime(RequiredTime, loc, iso);
timeMarkers = ['t','[\\s\\u3000]'].concat(loc['timeMarker']);
lastIsNumeral = src.match(/\\d\{\d,\d\}\)+\??$/);
addDateInputFormat(loc, '(?:' + time + ')[,\\s\\u3000]+?' + src, TimeFormat.concat(to), variant);
addDateInputFormat(loc, src + '(?:[,\\s]*(?:' + timeMarkers.join('|') + (lastIsNumeral ? '+' : '*') +')' + time + ')?', to.concat(TimeFormat), variant);
} else {
addDateInputFormat(loc, src, to, variant);
}
}
};
// Localization helpers
function getLocalization(localeCode, fallback) {
var loc;
if(!isString(localeCode)) localeCode = '';
loc = Localizations[localeCode] || Localizations[localeCode.slice(0,2)];
if(fallback === false && !loc) {
throw new Error('Invalid locale.');
}
return loc || CurrentLocalization;
}
function setLocalization(localeCode, set) {
var loc, canAbbreviate;
function initializeField(name) {
var val = loc[name];
if(isString(val)) {
loc[name] = val.split(',');
} else if(!val) {
loc[name] = [];
}
}
function eachAlternate(str, fn) {
str = str.split('+').map(function(split) {
return split.replace(/(.+):(.+)$/, function(full, base, suffixes) {
return suffixes.split('|').map(function(suffix) {
return base + suffix;
}).join('|');
});
}).join('|');
return str.split('|').forEach(fn);
}
function setArray(name, abbreviate, multiple) {
var arr = [];
loc[name].forEach(function(full, i) {
if(abbreviate) {
full += '+' + full.slice(0,3);
}
eachAlternate(full, function(day, j) {
arr[j * multiple + i] = day.toLowerCase();
});
});
loc[name] = arr;
}
function getDigit(start, stop, allowNumbers) {
var str = '\\d{' + start + ',' + stop + '}';
if(allowNumbers) str += '|(?:' + arrayToAlternates(loc['numbers']) + ')+';
return str;
}
function getNum() {
var arr = ['\\d+'].concat(loc['articles']);
if(loc['numbers']) arr = arr.concat(loc['numbers']);
return arrayToAlternates(arr);
}
function setModifiers() {
var arr = [];
loc.modifiersByName = {};
loc['modifiers'].forEach(function(modifier) {
var name = modifier.name;
eachAlternate(modifier.src, function(t) {
var locEntry = loc[name];
loc.modifiersByName[t] = modifier;
arr.push({ name: name, src: t, value: modifier.value });
loc[name] = locEntry ? locEntry + '|' + t : t;
});
});
loc['day'] += '|' + arrayToAlternates(loc['weekdays']);
loc['modifiers'] = arr;
}
// Initialize the locale
loc = new Localization(set);
initializeField('modifiers');
'months,weekdays,units,numbers,articles,tokens,timeMarker,ampm,timeSuffixes,dateParse,timeParse'.split(',').forEach(initializeField);
canAbbreviate = !loc['monthSuffix'];
setArray('months', canAbbreviate, 12);
setArray('weekdays', canAbbreviate, 7);
setArray('units', false, 8);
setArray('numbers', false, 10);
loc['code'] = localeCode;
loc['date'] = getDigit(1,2, loc['digitDate']);
loc['year'] = getDigit(4,4);
loc['num'] = getNum();
setModifiers();
if(loc['monthSuffix']) {
loc['month'] = getDigit(1,2);
loc['months'] = getRange(1, 12).map(function(n) { return n + loc['monthSuffix']; });
}
loc['full_month'] = getDigit(1,2) + '|' + arrayToAlternates(loc['months']);
// The order of these formats is very important. Order is reversed so formats that come
// later will take precedence over formats that come before. This generally means that
// more specific formats should come later, however, the {year} format should come before
// {day}, as 2011 needs to be parsed as a year (2011) and not date (20) + hours (11)
// If the locale has time suffixes then add a time only format for that locale
// that is separate from the core English-based one.
if(loc['timeSuffixes'].length > 0) {
loc.addFormat(prepareTime(RequiredTime, loc), false, TimeFormat)
}
loc.addFormat('{day}', true);
loc.addFormat('{month}' + (loc['monthSuffix'] || ''));
loc.addFormat('{year}' + (loc['yearSuffix'] || ''));
loc['timeParse'].forEach(function(src) {
loc.addFormat(src, true);
});
loc['dateParse'].forEach(function(src) {
loc.addFormat(src);
});
return Localizations[localeCode] = loc;
}
// General helpers
function addDateInputFormat(locale, format, match, variant) {
locale.compiledFormats.unshift({
variant: variant,
locale: locale,
reg: regexp('^' + format + '$', 'i'),
to: match
});
}
function simpleCapitalize(str) {
return str.slice(0,1).toUpperCase() + str.slice(1);
}
function arrayToAlternates(arr) {
return arr.filter(function(el) {
return !!el;
}).join('|');
}
// Date argument helpers
function collectDateArguments(args, allowDuration) {
var obj, arr;
if(isObject(args[0])) {
return args;
} else if (isNumber(args[0]) && !isNumber(args[1])) {
return [args[0]];
} else if (isString(args[0]) && allowDuration) {
return [getDateParamsFromString(args[0]), args[1]];
}
obj = {};
DateArgumentUnits.forEach(function(u,i) {
obj[u.unit] = args[i];
});
return [obj];
}
function getDateParamsFromString(str, num) {
var params = {};
match = str.match(/^(\d+)?\s?(\w+?)s?$/i);
if(match) {
if(isUndefined(num)) {
num = parseInt(match[1]) || 1;
}
params[match[2].toLowerCase()] = num;
}
return params;
}
// Date parsing helpers
function getFormatMatch(match, arr) {
var obj = {}, value, num;
arr.forEach(function(key, i) {
value = match[i + 1];
if(isUndefined(value) || value === '') return;
if(key === 'year') obj.yearAsString = value;
num = parseFloat(value.replace(/,/, '.'));
obj[key] = !isNaN(num) ? num : value.toLowerCase();
});
return obj;
}
function cleanDateInput(str) {
str = str.trim().replace(/^(just )?now|\.+$/i, '');
return convertAsianDigits(str);
}
function convertAsianDigits(str) {
return str.replace(AsianDigitReg, function(full, disallowed, match) {
var sum = 0, place = 1, lastWasHolder, lastHolder;
if(disallowed) return full;
match.split('').reverse().forEach(function(letter) {
var value = AsianDigitMap[letter], holder = value > 9;
if(holder) {
if(lastWasHolder) sum += place;
place *= value / (lastHolder || 1);
lastHolder = value;
} else {
if(lastWasHolder === false) {
place *= 10;
}
sum += place * value;
}
lastWasHolder = holder;
});
if(lastWasHolder) sum += place;
return sum;
});
}
function getExtendedDate(f, localeCode, prefer, forceUTC) {
var d = new date(), relative = false, baseLocalization, loc, format, set, unit, weekday, num, tmp, after;
d.utc(forceUTC);
if(isDate(f)) {
d = new date(f.getTime());
} else if(isNumber(f)) {
d = new date(f);
} else if(isObject(f)) {
d.set(f, true);
set = f;
} else if(isString(f)) {
// The act of getting the localization will pre-initialize
// if it is missing and add the required formats.
baseLocalization = getLocalization(localeCode);
// Clean the input and convert Kanji based numerals if they exist.
f = cleanDateInput(f);
if(baseLocalization) {
iterateOverObject(baseLocalization.getFormats(), function(i, dif) {
var match = f.match(dif.reg);
if(match) {
format = dif;
loc = format.locale;
set = getFormatMatch(match, format.to, loc);
if(set['utc']) {
d.utc();
}
loc.cachedFormat = format;
if(set.timestamp) {
set = set.timestamp;
return false;
}
// If there's a variant (crazy Endian American format), swap the month and day.
if(format.variant && !isString(set['month']) && (isString(set['date']) || baseLocalization.hasVariant(localeCode))) {
tmp = set['month'];
set['month'] = set['date'];
set['date'] = tmp;
}
// If the year is 2 digits then get the implied century.
if(set['year'] && set.yearAsString.length === 2) {
set['year'] = getYearFromAbbreviation(set['year']);
}
// Set the month which may be localized.
if(set['month']) {
set['month'] = loc.getMonth(set['month']);
if(set['shift'] && !set['unit']) set['unit'] = loc['units'][7];
}
// If there is both a weekday and a date, the date takes precedence.
if(set['weekday'] && set['date']) {
delete set['weekday'];
// Otherwise set a localized weekday.
} else if(set['weekday']) {
set['weekday'] = loc.getWeekday(set['weekday']);
if(set['shift'] && !set['unit']) set['unit'] = loc['units'][5];
}
// Relative day localizations such as "today" and "tomorrow".
if(set['day'] && (tmp = loc.modifiersByName[set['day']])) {
set['day'] = tmp.value;
d.reset();
relative = true;
// If the day is a weekday, then set that instead.
} else if(set['day'] && (weekday = loc.getWeekday(set['day'])) > -1) {
delete set['day'];
if(set['num'] && set['month']) {
// If we have "the 2nd tuesday of June", set the day to the beginning of the month, then
// look ahead to set the weekday after all other properties have been set. The weekday needs
// to be set after the actual set because it requires overriding the "prefer" argument which
// could unintentionally send the year into the future, past, etc.
after = function() {
var w = d.getWeekday();
d.setWeekday((7 * (set['num'] - 1)) + (w > weekday ? weekday + 7 : weekday));
}
set['day'] = 1;
} else {
set['weekday'] = weekday;
}
}
if(set['date'] && !isNumber(set['date'])) {
set['date'] = loc.getNumericDate(set['date']);
}
// If the time is 1pm-11pm advance the time by 12 hours.
if(loc.matchPM(set['ampm']) && set['hour'] < 12) {
set['hour'] += 12;
} else if(loc.matchAM(set['ampm']) && set['hour'] === 12) {
set['hour'] = 0;
}
// Adjust for timezone offset
if('offset_hours' in set || 'offset_minutes' in set) {
d.utc();
set['offset_minutes'] = set['offset_minutes'] || 0;
set['offset_minutes'] += set['offset_hours'] * 60;
if(set['offset_sign'] === '-') {
set['offset_minutes'] *= -1;
}
set['minute'] -= set['offset_minutes'];
}
// Date has a unit like "days", "months", etc. are all relative to the current date.
if(set['unit']) {
relative = true;
num = loc.getNumber(set['num']);
unit = loc.getEnglishUnit(set['unit']);
// Shift and unit, ie "next month", "last week", etc.
if(set['shift'] || set['edge']) {
num *= (tmp = loc.modifiersByName[set['shift']]) ? tmp.value : 0;
// Relative month and static date: "the 15th of last month"
if(unit === 'month' && isDefined(set['date'])) {
d.set({ 'day': set['date'] }, true);
delete set['date'];
}
// Relative year and static month/date: "June 15th of last year"
if(unit === 'year' && isDefined(set['month'])) {
d.set({ 'month': set['month'], 'day': set['date'] }, true);
delete set['month'];
delete set['date'];
}
}
// Unit and sign, ie "months ago", "weeks from now", etc.
if(set['sign'] && (tmp = loc.modifiersByName[set['sign']])) {
num *= tmp.value;
}
// Units can be with non-relative dates, set here. ie "the day after monday"
if(isDefined(set['weekday'])) {
d.set({'weekday': set['weekday'] }, true);
delete set['weekday'];
}
// Finally shift the unit.
set[unit] = (set[unit] || 0) + num;
}
if(set['year_sign'] === '-') {
set['year'] *= -1;
}
DateUnitsReversed.slice(1,4).forEach(function(u, i) {
var value = set[u.unit], fraction = value % 1;
if(fraction) {
set[DateUnitsReversed[i].unit] = round(fraction * (u.unit === 'second' ? 1000 : 60));
set[u.unit] = floor(value);
}
});
return false;
}
});
}
if(!format) {
// The Date constructor does something tricky like checking the number
// of arguments so simply passing in undefined won't work.
d = f ? new date(f) : new date();
} else if(relative) {
d.advance(set);
} else {
if(d._utc) {
// UTC times can traverse into other days or even months,
// so preemtively reset the time here to prevent this.
d.reset();
}
updateDate(d, set, true, false, prefer);
}
// If there is an "edge" it needs to be set after the
// other fields are set. ie "the end of February"
if(set && set['edge']) {
tmp = loc.modifiersByName[set['edge']];
iterateOverObject(DateUnitsReversed.slice(4), function(i, u) {
if(isDefined(set[u.unit])) {
unit = u.unit;
return false;
}
});
if(unit === 'year') set.specificity = 'month';
else if(unit === 'month' || unit === 'week') set.specificity = 'day';
d[(tmp.value < 0 ? 'endOf' : 'beginningOf') + simpleCapitalize(unit)]();
// This value of -2 is arbitrary but it's a nice clean way to hook into this system.
if(tmp.value === -2) d.reset();
}
if(after) {
after();
}
}
d.utc(false);
return {
date: d,
set: set
}
}
// If the year is two digits, add the most appropriate century prefix.
function getYearFromAbbreviation(year) {
return round(callDateGet(new date(), 'FullYear') / 100) * 100 - round(year / 100) * 100 + year;
}
function getShortHour(d) {
var hours = callDateGet(d, 'Hours');
return hours === 0 ? 12 : hours - (floor(hours / 13) * 12);
}
// weeksSince won't work here as the result needs to be floored, not rounded.
function getWeekNumber(date) {
date = date.clone();
var dow = callDateGet(date, 'Day') || 7;
date.addDays(4 - dow).reset();
return 1 + floor(date.daysSince(date.clone().beginningOfYear()) / 7);
}
function getAdjustedUnit(ms) {
var next, ams = math.abs(ms), value = ams, unit = 0;
DateUnitsReversed.slice(1).forEach(function(u, i) {
next = floor(round(ams / u.multiplier() * 10) / 10);
if(next >= 1) {
value = next;
unit = i + 1;
}
});
return [value, unit, ms];
}
// Date formatting helpers
function formatDate(date, format, relative, localeCode) {
var adu, loc = getLocalization(localeCode), caps = regexp(/^[A-Z]/), value, shortcut;
if(!date.isValid()) {
return 'Invalid Date';
} else if(Date[format]) {
format = Date[format];
} else if(isFunction(format)) {
adu = getAdjustedUnit(date.millisecondsFromNow());
format = format.apply(date, adu.concat(loc));
}
if(!format && relative) {
adu = adu || getAdjustedUnit(date.millisecondsFromNow());
// Adjust up if time is in ms, as this doesn't
// look very good for a standard relative date.
if(adu[1] === 0) {
adu[1] = 1;
adu[0] = 1;
}
return loc.getRelativeFormat(adu);
}
format = format || 'long';
format = loc[format] || format;
DateOutputFormats.forEach(function(dof) {
format = format.replace(regexp('\\{('+dof.token+')(\\d)?\\}', dof.word ? 'i' : ''), function(m,t,d) {
var val = dof.format(date, loc, d || 1, t), l = t.length, one = t.match(/^(.)\1+$/);
if(dof.word) {
if(l === 3) val = val.slice(0,3);
if(one || t.match(caps)) val = simpleCapitalize(val);
} else if(one && !dof.text) {
val = (isNumber(val) ? padNumber(val, l) : val.toString()).slice(-l);
}
return val;
});
});
return format;
}
// Date comparison helpers
function compareDate(d, find, buffer, forceUTC) {
var p = getExtendedDate(find, null, null, forceUTC), accuracy = 0, loBuffer = 0, hiBuffer = 0, override, capitalized;
if(buffer > 0) {
loBuffer = hiBuffer = buffer;
override = true;
}
if(!p.date.isValid()) return false;
if(p.set && p.set.specificity) {
DateUnits.forEach(function(u, i) {
if(u.unit === p.set.specificity) {
accuracy = u.multiplier(p.date, d - p.date) - 1;
}
});
capitalized = simpleCapitalize(p.set.specificity);
if(p.set['edge'] || p.set['shift']) {
p.date['beginningOf' + capitalized]();
}
if(p.set.specificity === 'month') {
max = p.date.clone()['endOf' + capitalized]().getTime();
}
if(!override && p.set['sign'] && p.set.specificity != 'millisecond') {
// If the time is relative, there can occasionally be an disparity between the relative date
// and "now", which it is being compared to, so set an extra buffer to account for this.
loBuffer = 50;
hiBuffer = -50;
}
}
var t = d.getTime();
var min = p.date.getTime();
var max = max || (min + accuracy);
return t >= (min - loBuffer) && t <= (max + hiBuffer);
}
function updateDate(d, params, reset, advance, prefer) {
var weekday, specificityIndex;
function getParam(key) {
return isDefined(params[key]) ? params[key] : params[key + 's'];
}
function paramExists(key) {
return isDefined(getParam(key));
}
function uniqueParamExists(key, isDay) {
return paramExists(key) || (isDay && paramExists('weekday'));
}
function canDisambiguate() {
var now = new date;
return (prefer === -1 && d > now) || (prefer === 1 && d < now);
}
if(isNumber(params) && advance) {
// If param is a number and we're advancing, the number is presumed to be milliseconds.
params = { 'milliseconds': params };
} else if(isNumber(params)) {
// Otherwise just set the timestamp and return.
d.setTime(params);
return d;
}
// "date" can also be passed for the day
if(params['date']) params['day'] = params['date'];
// Reset any unit lower than the least specific unit set. Do not do this for weeks
// or for years. This needs to be performed before the acutal setting of the date
// because the order needs to be reversed in order to get the lowest specificity,
// also because higher order units can be overwritten by lower order units, such
// as setting hour: 3, minute: 345, etc.
iterateOverObject(DateUnitsReversed, function(i,u) {
var isDay = u.unit === 'day';
if(uniqueParamExists(u.unit, isDay)) {
params.specificity = u.unit;
specificityIndex = +i;
return false;
} else if(reset && u.unit !== 'week' && (!isDay || !paramExists('week'))) {
// Days are relative to months, not weeks, so don't reset if a week exists.
callDateSet(d, u.method, (isDay ? 1 : 0));
}
});
// Now actually set or advance the date in order, higher units first.
DateUnits.forEach(function(u,i) {
var unit = u.unit, method = u.method, higherUnit = DateUnits[i - 1], value;
value = getParam(unit)
if(isUndefined(value)) return;
if(advance) {
if(unit === 'week') {
value = (params['day'] || 0) + (value * 7);
method = 'Date';
}
value = (value * advance) + callDateGet(d, method);
} else if(unit === 'month' && paramExists('day')) {
// When setting the month, there is a chance that we will traverse into a new month.
// This happens in DST shifts, for example June 1st DST jumping to January 1st
// (non-DST) will have a shift of -1:00 which will traverse into the previous year.
// Prevent this by proactively setting the day when we know it will be set again anyway.
// It can also happen when there are not enough days in the target month. This second
// situation is identical to checkMonthTraversal below, however when we are advancing
// we want to reset the date to "the last date in the target month". In the case of
// DST shifts, however, we want to avoid the "edges" of months as that is where this
// unintended traversal can happen. This is the reason for the different handling of
// two similar but slightly different situations.
//
// TL;DR This method avoids the edges of a month IF not advancing and the date is going
// to be set anyway, while checkMonthTraversal resets the date to the last day if advancing.
//
callDateSet(d, 'Date', 15);
}
callDateSet(d, method, value);
if(advance && unit === 'month') {
checkMonthTraversal(d, value);
}
});
// If a weekday is included in the params, set it ahead of time and set the params
// to reflect the updated date so that resetting works properly.
if(!advance && !paramExists('day') && paramExists('weekday')) {
var weekday = getParam('weekday'), isAhead, futurePreferred;
d.setWeekday(weekday);
}
if(canDisambiguate()) {
iterateOverObject(DateUnitsReversed.slice(specificityIndex + 1), function(i,u) {
var ambiguous = u.ambiguous || (u.unit === 'week' && paramExists('weekday'));
if(ambiguous && !uniqueParamExists(u.unit, u.unit === 'day')) {
d[u.addMethod](prefer);
return false;
}
});
}
return d;
}
function callDateGet(d, method) {
return d['get' + (d._utc ? 'UTC' : '') + method]();
}
function callDateSet(d, method, value) {
return d['set' + (d._utc ? 'UTC' : '') + method](value);
}
// The ISO format allows times strung together without a demarcating ":", so make sure
// that these markers are now optional.
function prepareTime(format, loc, iso) {
var timeSuffixMapping = {'h':0,'m':1,'s':2}, add;
loc = loc || English;
return format.replace(/{([a-z])}/g, function(full, token) {
var separators = [],
isHours = token === 'h',
tokenIsRequired = isHours && !iso;
if(token === 't') {
return loc['ampm'].join('|');
} else {
if(isHours) {
separators.push(':');
}
if(add = loc['timeSuffixes'][timeSuffixMapping[token]]) {
separators.push(add + '\\s*');
}
return separators.length === 0 ? '' : '(?:' + separators.join('|') + ')' + (tokenIsRequired ? '' : '?');
}
});
}
// If the month is being set, then we don't want to accidentally
// traverse into a new month just because the target month doesn't have enough
// days. In other words, "5 months ago" from July 30th is still February, even
// though there is no February 30th, so it will of necessity be February 28th
// (or 29th in the case of a leap year).
function checkMonthTraversal(date, targetMonth) {
if(targetMonth < 0) targetMonth += 12;
if(targetMonth % 12 != callDateGet(date, 'Month')) {
callDateSet(date, 'Date', 0);
}
}
function createDate(args, prefer, forceUTC) {
var f, localeCode;
if(isNumber(args[1])) {
// If the second argument is a number, then we have an enumerated constructor type as in "new Date(2003, 2, 12);"
f = collectDateArguments(args)[0];
} else {
f = args[0];
localeCode = args[1];
}
return getExtendedDate(f, localeCode, prefer, forceUTC).date;
}
function buildDateUnits() {
DateUnitsReversed = DateUnits.concat().reverse();
DateArgumentUnits = DateUnits.concat();
DateArgumentUnits.splice(2,1);
}
/***
* @method [units]Since([d], [locale] = currentLocale)
* @returns Number
* @short Returns the time since [d] in the appropriate unit.
* @extra [d] will accept a date object, timestamp, or text format. If not specified, [d] is assumed to be now. [locale] can be passed to specify the locale that the date is in. %[unit]Ago% is provided as an alias to make this more readable when [d] is assumed to be the current date. For more see @date_format.
*
* @set
* millisecondsSince
* secondsSince
* minutesSince
* hoursSince
* daysSince
* weeksSince
* monthsSince
* yearsSince
*
* @example
*
* Date.create().millisecondsSince('1 hour ago') -> 3,600,000
* Date.create().daysSince('1 week ago') -> 7
* Date.create().yearsSince('15 years ago') -> 15
* Date.create('15 years ago').yearsAgo() -> 15
*
***
* @method [units]Ago()
* @returns Number
* @short Returns the time ago in the appropriate unit.
*
* @set
* millisecondsAgo
* secondsAgo
* minutesAgo
* hoursAgo
* daysAgo
* weeksAgo
* monthsAgo
* yearsAgo
*
* @example
*
* Date.create('last year').millisecondsAgo() -> 3,600,000
* Date.create('last year').daysAgo() -> 7
* Date.create('last year').yearsAgo() -> 15
*
***
* @method [units]Until([d], [locale] = currentLocale)
* @returns Number
* @short Returns the time until [d] in the appropriate unit.
* @extra [d] will accept a date object, timestamp, or text format. If not specified, [d] is assumed to be now. [locale] can be passed to specify the locale that the date is in. %[unit]FromNow% is provided as an alias to make this more readable when [d] is assumed to be the current date. For more see @date_format.
*
* @set
* millisecondsUntil
* secondsUntil
* minutesUntil
* hoursUntil
* daysUntil
* weeksUntil
* monthsUntil
* yearsUntil
*
* @example
*
* Date.create().millisecondsUntil('1 hour from now') -> 3,600,000
* Date.create().daysUntil('1 week from now') -> 7
* Date.create().yearsUntil('15 years from now') -> 15
* Date.create('15 years from now').yearsFromNow() -> 15
*
***
* @method [units]FromNow()
* @returns Number
* @short Returns the time from now in the appropriate unit.
*
* @set
* millisecondsFromNow
* secondsFromNow
* minutesFromNow
* hoursFromNow
* daysFromNow
* weeksFromNow
* monthsFromNow
* yearsFromNow
*
* @example
*
* Date.create('next year').millisecondsFromNow() -> 3,600,000
* Date.create('next year').daysFromNow() -> 7
* Date.create('next year').yearsFromNow() -> 15
*
***
* @method add[Units](<num>, [reset] = false)
* @returns Date
* @short Adds <num> of the unit to the date. If [reset] is true, all lower units will be reset.
* @extra Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Don't use %addMonths% if you need precision.
*
* @set
* addMilliseconds
* addSeconds
* addMinutes
* addHours
* addDays
* addWeeks
* addMonths
* addYears
*
* @example
*
* Date.create().addMilliseconds(5) -> current time + 5 milliseconds
* Date.create().addDays(5) -> current time + 5 days
* Date.create().addYears(5) -> current time + 5 years
*
***
* @method isLast[Unit]()
* @returns Boolean
* @short Returns true if the date is last week/month/year.
*
* @set
* isLastWeek
* isLastMonth
* isLastYear
*
* @example
*
* Date.create('yesterday').isLastWeek() -> true or false?
* Date.create('yesterday').isLastMonth() -> probably not...
* Date.create('yesterday').isLastYear() -> even less likely...
*
***
* @method isThis[Unit]()
* @returns Boolean
* @short Returns true if the date is this week/month/year.
*
* @set
* isThisWeek
* isThisMonth
* isThisYear
*
* @example
*
* Date.create('tomorrow').isThisWeek() -> true or false?
* Date.create('tomorrow').isThisMonth() -> probably...
* Date.create('tomorrow').isThisYear() -> signs point to yes...
*
***
* @method isNext[Unit]()
* @returns Boolean
* @short Returns true if the date is next week/month/year.
*
* @set
* isNextWeek
* isNextMonth
* isNextYear
*
* @example
*
* Date.create('tomorrow').isNextWeek() -> true or false?
* Date.create('tomorrow').isNextMonth() -> probably not...
* Date.create('tomorrow').isNextYear() -> even less likely...
*
***
* @method beginningOf[Unit]()
* @returns Date
* @short Sets the date to the beginning of the appropriate unit.
*
* @set
* beginningOfDay
* beginningOfWeek
* beginningOfMonth
* beginningOfYear
*
* @example
*
* Date.create().beginningOfDay() -> the beginning of today (resets the time)
* Date.create().beginningOfWeek() -> the beginning of the week
* Date.create().beginningOfMonth() -> the beginning of the month
* Date.create().beginningOfYear() -> the beginning of the year
*
***
* @method endOf[Unit]()
* @returns Date
* @short Sets the date to the end of the appropriate unit.
*
* @set
* endOfDay
* endOfWeek
* endOfMonth
* endOfYear
*
* @example
*
* Date.create().endOfDay() -> the end of today (sets the time to 23:59:59.999)
* Date.create().endOfWeek() -> the end of the week
* Date.create().endOfMonth() -> the end of the month
* Date.create().endOfYear() -> the end of the year
*
***/
function buildDateMethods() {
extendSimilar(date, true, false, DateUnits, function(methods, u, i) {
var unit = u.unit, caps = simpleCapitalize(unit), multiplier = u.multiplier(), since, until;
u.addMethod = 'add' + caps + 's';
since = function(f, localeCode) {
return round((this.getTime() - date.create(f, localeCode).getTime()) / multiplier);
};
until = function(f, localeCode) {
return round((date.create(f, localeCode).getTime() - this.getTime()) / multiplier);
};
methods[unit+'sAgo'] = until;
methods[unit+'sUntil'] = until;
methods[unit+'sSince'] = since;
methods[unit+'sFromNow'] = since;
methods[u.addMethod] = function(num, reset) {
var set = {};
set[unit] = num;
return this.advance(set, reset);
};
buildNumberToDateAlias(u, multiplier);
if(i < 3) {
['Last','This','Next'].forEach(function(shift) {
methods['is' + shift + caps] = function() {
return this.is(shift + ' ' + unit);
};
});
}
if(i < 4) {
methods['beginningOf' + caps] = function() {
var set = {};
switch(unit) {
case 'year': set['year'] = callDateGet(this, 'FullYear'); break;
case 'month': set['month'] = callDateGet(this, 'Month'); break;
case 'day': set['day'] = callDateGet(this, 'Date'); break;
case 'week': set['weekday'] = 0; break;
}
return this.set(set, true);
};
methods['endOf' + caps] = function() {
var set = { 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 999 };
switch(unit) {
case 'year': set['month'] = 11; set['day'] = 31; break;
case 'month': set['day'] = this.daysInMonth(); break;
case 'week': set['weekday'] = 6; break;
}
return this.set(set, true);
};
}
});
}
function buildCoreInputFormats() {
English.addFormat('([+-])?(\\d{4,4})[-.]?{full_month}[-.]?(\\d{1,2})?', true, ['year_sign','year','month','date'], false, true);
English.addFormat('(\\d{1,2})[-.\\/]{full_month}(?:[-.\\/](\\d{2,4}))?', true, ['date','month','year'], true);
English.addFormat('{full_month}[-.](\\d{4,4})', false, ['month','year']);
English.addFormat('\\/Date\\((\\d+(?:\\+\\d{4,4})?)\\)\\/', false, ['timestamp'])
English.addFormat(prepareTime(RequiredTime, English), false, TimeFormat)
// When a new locale is initialized it will have the CoreDateFormats initialized by default.
// From there, adding new formats will push them in front of the previous ones, so the core
// formats will be the last to be reached. However, the core formats themselves have English
// months in them, which means that English needs to first be initialized and creates a race
// condition. I'm getting around this here by adding these generalized formats in the order
// specific -> general, which will mean they will be added to the English localization in
// general -> specific order, then chopping them off the front and reversing to get the correct
// order. Note that there are 7 formats as 2 have times which adds a front and a back format.
CoreDateFormats = English.compiledFormats.slice(0,7).reverse();
English.compiledFormats = English.compiledFormats.slice(7).concat(CoreDateFormats);
}
function buildDateOutputShortcuts() {
extendSimilar(date, true, false, 'short,long,full', function(methods, name) {
methods[name] = function(localeCode) {
return formatDate(this, name, false, localeCode);
}
});
}
function buildAsianDigits() {
KanjiDigits.split('').forEach(function(digit, value) {
var holder;
if(value > 9) {
value = math.pow(10, value - 9);
}
AsianDigitMap[digit] = value;
});
FullWidthDigits.split('').forEach(function(digit, value) {
AsianDigitMap[digit] = value;
});
// Kanji numerals may also be included in phrases which are text-based rather
// than actual numbers such as Chinese weekdays (上周三), and "the day before
// yesterday" (一昨日) in Japanese, so don't match these.
AsianDigitReg = regexp('([期週周])?([' + KanjiDigits + FullWidthDigits + ']+)(?!昨)', 'g');
}
/***
* @method is[Day]()
* @returns Boolean
* @short Returns true if the date falls on that day.
* @extra Also available: %isYesterday%, %isToday%, %isTomorrow%, %isWeekday%, and %isWeekend%.
*
* @set
* isToday
* isYesterday
* isTomorrow
* isWeekday
* isWeekend
* isSunday
* isMonday
* isTuesday
* isWednesday
* isThursday
* isFriday
* isSaturday
*
* @example
*
* Date.create('tomorrow').isToday() -> false
* Date.create('thursday').isTomorrow() -> ?
* Date.create('yesterday').isWednesday() -> ?
* Date.create('today').isWeekend() -> ?
*
***
* @method isFuture()
* @returns Boolean
* @short Returns true if the date is in the future.
* @example
*
* Date.create('next week').isFuture() -> true
* Date.create('last week').isFuture() -> false
*
***
* @method isPast()
* @returns Boolean
* @short Returns true if the date is in the past.
* @example
*
* Date.create('last week').isPast() -> true
* Date.create('next week').isPast() -> false
*
***/
function buildRelativeAliases() {
var special = 'today,yesterday,tomorrow,weekday,weekend,future,past'.split(',');
var weekdays = English['weekdays'].slice(0,7);
var months = English['months'].slice(0,12);
extendSimilar(date, true, false, special.concat(weekdays).concat(months), function(methods, name) {
methods['is'+ simpleCapitalize(name)] = function(utc) {
return this.is(name, 0, utc);
};
});
}
function buildUTCAliases() {
date.extend({
'utc': {
'create': function() {
return createDate(arguments, 0, true);
},
'past': function() {
return createDate(arguments, -1, true);
},
'future': function() {
return createDate(arguments, 1, true);
}
}
}, false, false);
}
function setDateProperties() {
date.extend({
'RFC1123': '{Dow}, {dd} {Mon} {yyyy} {HH}:{mm}:{ss} {tz}',
'RFC1036': '{Weekday}, {dd}-{Mon}-{yy} {HH}:{mm}:{ss} {tz}',
'ISO8601_DATE': '{yyyy}-{MM}-{dd}',
'ISO8601_DATETIME': '{yyyy}-{MM}-{dd}T{HH}:{mm}:{ss}.{fff}{isotz}'
}, false, false);
}
date.extend({
/***
* @method Date.create(<d>, [locale] = currentLocale)
* @returns Date
* @short Alternate Date constructor which understands many different text formats, a timestamp, or another date.
* @extra If no argument is given, date is assumed to be now. %Date.create% additionally can accept enumerated parameters as with the standard date constructor. [locale] can be passed to specify the locale that the date is in. When unspecified, the current locale (default is English) is assumed. UTC-based dates can be created through the %utc% object. For more see @date_format.
* @set
* Date.utc.create
*
* @example
*
* Date.create('July') -> July of this year
* Date.create('1776') -> 1776
* Date.create('today') -> today
* Date.create('wednesday') -> This wednesday
* Date.create('next friday') -> Next friday
* Date.create('July 4, 1776') -> July 4, 1776
* Date.create(-446806800000) -> November 5, 1955
* Date.create(1776, 6, 4) -> July 4, 1776
* Date.create('1776年07月04日', 'ja') -> July 4, 1776
* Date.utc.create('July 4, 1776', 'en') -> July 4, 1776
*
***/
'create': function() {
return createDate(arguments);
},
/***
* @method Date.past(<d>, [locale] = currentLocale)
* @returns Date
* @short Alternate form of %Date.create% with any ambiguity assumed to be the past.
* @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" depending on context. Note that dates explicitly in the future ("next Sunday") will remain in the future. This method simply provides a hint when ambiguity exists. UTC-based dates can be created through the %utc% object. For more, see @date_format.
* @set
* Date.utc.past
* @example
*
* Date.past('July') -> July of this year or last depending on the current month
* Date.past('Wednesday') -> This wednesday or last depending on the current weekday
*
***/
'past': function() {
return createDate(arguments, -1);
},
/***
* @method Date.future(<d>, [locale] = currentLocale)
* @returns Date
* @short Alternate form of %Date.create% with any ambiguity assumed to be the future.
* @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" depending on context. Note that dates explicitly in the past ("last Sunday") will remain in the past. This method simply provides a hint when ambiguity exists. UTC-based dates can be created through the %utc% object. For more, see @date_format.
* @set
* Date.utc.future
*
* @example
*
* Date.future('July') -> July of this year or next depending on the current month
* Date.future('Wednesday') -> This wednesday or next depending on the current weekday
*
***/
'future': function() {
return createDate(arguments, 1);
},
/***
* @method Date.addLocale(<code>, <set>)
* @returns Locale
* @short Adds a locale <set> to the locales understood by Sugar.
* @extra For more see @date_format.
*
***/
'addLocale': function(localeCode, set) {
return setLocalization(localeCode, set);
},
/***
* @method Date.setLocale(<code>)
* @returns Locale
* @short Sets the current locale to be used with dates.
* @extra Sugar has support for 13 locales that are available through the "Date Locales" package. In addition you can define a new locale with %Date.addLocale%. For more see @date_format.
*
***/
'setLocale': function(localeCode, set) {
var loc = getLocalization(localeCode, false);
CurrentLocalization = loc;
// The code is allowed to be more specific than the codes which are required:
// i.e. zh-CN or en-US. Currently this only affects US date variants such as 8/10/2000.
if(localeCode && localeCode != loc['code']) {
loc['code'] = localeCode;
}
return loc;
},
/***
* @method Date.getLocale([code] = current)
* @returns Locale
* @short Gets the locale for the given code, or the current locale.
* @extra The resulting locale object can be manipulated to provide more control over date localizations. For more about locales, see @date_format.
*
***/
'getLocale': function(localeCode) {
return !localeCode ? CurrentLocalization : getLocalization(localeCode, false);
},
/**
* @method Date.addFormat(<format>, <match>, [code] = null)
* @returns Nothing
* @short Manually adds a new date input format.
* @extra This method allows fine grained control for alternate formats. <format> is a string that can have regex tokens inside. <match> is an array of the tokens that each regex capturing group will map to, for example %year%, %date%, etc. For more, see @date_format.
*
**/
'addFormat': function(format, match, localeCode) {
addDateInputFormat(getLocalization(localeCode), format, match);
}
}, false, false);
date.extend({
/***
* @method set(<set>, [reset] = false)
* @returns Date
* @short Sets the date object.
* @extra This method can accept multiple formats including a single number as a timestamp, an object, or enumerated parameters (as with the Date constructor). If [reset] is %true%, any units more specific than those passed will be reset.
*
* @example
*
* new Date().set({ year: 2011, month: 11, day: 31 }) -> December 31, 2011
* new Date().set(2011, 11, 31) -> December 31, 2011
* new Date().set(86400000) -> 1 day after Jan 1, 1970
* new Date().set({ year: 2004, month: 6 }, true) -> June 1, 2004, 00:00:00.000
*
***/
'set': function() {
var args = collectDateArguments(arguments);
return updateDate(this, args[0], args[1])
},
/***
* @method setWeekday()
* @returns Nothing
* @short Sets the weekday of the date.
*
* @example
*
* d = new Date(); d.setWeekday(1); d; -> Monday of this week
* d = new Date(); d.setWeekday(6); d; -> Saturday of this week
*
***/
'setWeekday': function(dow) {
if(isUndefined(dow)) return;
return callDateSet(this, 'Date', callDateGet(this, 'Date') + dow - callDateGet(this, 'Day'));
},
/***
* @method setWeek()
* @returns Nothing
* @short Sets the week (of the year).
*
* @example
*
* d = new Date(); d.setWeek(15); d; -> 15th week of the year
*
***/
'setWeek': function(week) {
if(isUndefined(week)) return;
var date = callDateGet(this, 'Date');
callDateSet(this, 'Month', 0);
callDateSet(this, 'Date', (week * 7) + 1);
return this.getTime();
},
/***
* @method getWeek()
* @returns Number
* @short Gets the date's week (of the year).
* @extra If %utc% is set on the date, the week will be according to UTC time.
*
* @example
*
* new Date().getWeek() -> today's week of the year
*
***/
'getWeek': function() {
return getWeekNumber(this);
},
/***
* @method getUTCOffset([iso])
* @returns String
* @short Returns a string representation of the offset from UTC time. If [iso] is true the offset will be in ISO8601 format.
* @example
*
* new Date().getUTCOffset() -> "+0900"
* new Date().getUTCOffset(true) -> "+09:00"
*
***/
'getUTCOffset': function(iso) {
var offset = this._utc ? 0 : this.getTimezoneOffset();
var colon = iso === true ? ':' : '';
if(!offset && iso) return 'Z';
return padNumber(round(-offset / 60), 2, true) + colon + padNumber(offset % 60, 2);
},
/***
* @method utc([on] = true)
* @returns Date
* @short Sets the internal utc flag for the date. When on, UTC-based methods will be called internally.
* @extra For more see @date_format.
* @example
*
* new Date().utc(true)
* new Date().utc(false)
*
***/
'utc': function(set) {
this._utc = set === true || arguments.length === 0;
return this;
},
/***
* @method isUTC()
* @returns Boolean
* @short Returns true if the date has no timezone offset.
* @extra This will also return true for a date that has had %toUTC% called on it. This is intended to help approximate shifting timezones which is not possible in client-side Javascript. Note that the native method %getTimezoneOffset% will always report the same thing, even if %isUTC% becomes true.
* @example
*
* new Date().isUTC() -> true or false?
* new Date().toUTC().isUTC() -> true
*
***/
'isUTC': function() {
return !!this._utc || this.getTimezoneOffset() === 0;
},
/***
* @method advance(<set>, [reset] = false)
* @returns Date
* @short Sets the date forward.
* @extra This method can accept multiple formats including an object, a string in the format %3 days%, a single number as milliseconds, or enumerated parameters (as with the Date constructor). If [reset] is %true%, any units more specific than those passed will be reset. For more see @date_format.
* @example
*
* new Date().advance({ year: 2 }) -> 2 years in the future
* new Date().advance('2 days') -> 2 days in the future
* new Date().advance(0, 2, 3) -> 2 months 3 days in the future
* new Date().advance(86400000) -> 1 day in the future
*
***/
'advance': function() {
var args = collectDateArguments(arguments, true);
return updateDate(this, args[0], args[1], 1);
},
/***
* @method rewind(<set>, [reset] = false)
* @returns Date
* @short Sets the date back.
* @extra This method can accept multiple formats including a single number as a timestamp, an object, or enumerated parameters (as with the Date constructor). If [reset] is %true%, any units more specific than those passed will be reset. For more see @date_format.
* @example
*
* new Date().rewind({ year: 2 }) -> 2 years in the past
* new Date().rewind(0, 2, 3) -> 2 months 3 days in the past
* new Date().rewind(86400000) -> 1 day in the past
*
***/
'rewind': function() {
var args = collectDateArguments(arguments, true);
return updateDate(this, args[0], args[1], -1);
},
/***
* @method isValid()
* @returns Boolean
* @short Returns true if the date is valid.
* @example
*
* new Date().isValid() -> true
* new Date('flexor').isValid() -> false
*
***/
'isValid': function() {
return !isNaN(this.getTime());
},
/***
* @method isAfter(<d>, [margin] = 0)
* @returns Boolean
* @short Returns true if the date is after the <d>.
* @extra [margin] is to allow extra margin of error (in ms). <d> will accept a date object, timestamp, or text format. If not specified, <d> is assumed to be now. See @date_format for more.
* @example
*
* new Date().isAfter('tomorrow') -> false
* new Date().isAfter('yesterday') -> true
*
***/
'isAfter': function(d, margin, utc) {
return this.getTime() > date.create(d).getTime() - (margin || 0);
},
/***
* @method isBefore(<d>, [margin] = 0)
* @returns Boolean
* @short Returns true if the date is before <d>.
* @extra [margin] is to allow extra margin of error (in ms). <d> will accept a date object, timestamp, or text format. If not specified, <d> is assumed to be now. See @date_format for more.
* @example
*
* new Date().isBefore('tomorrow') -> true
* new Date().isBefore('yesterday') -> false
*
***/
'isBefore': function(d, margin) {
return this.getTime() < date.create(d).getTime() + (margin || 0);
},
/***
* @method isBetween(<d1>, <d2>, [margin] = 0)
* @returns Boolean
* @short Returns true if the date falls between <d1> and <d2>.
* @extra [margin] is to allow extra margin of error (in ms). <d1> and <d2> will accept a date object, timestamp, or text format. If not specified, they are assumed to be now. See @date_format for more.
* @example
*
* new Date().isBetween('yesterday', 'tomorrow') -> true
* new Date().isBetween('last year', '2 years ago') -> false
*
***/
'isBetween': function(d1, d2, margin) {
var t = this.getTime();
var t1 = date.create(d1).getTime();
var t2 = date.create(d2).getTime();
var lo = math.min(t1, t2);
var hi = math.max(t1, t2);
margin = margin || 0;
return (lo - margin < t) && (hi + margin > t);
},
/***
* @method isLeapYear()
* @returns Boolean
* @short Returns true if the date is a leap year.
* @example
*
* Date.create('2000').isLeapYear() -> true
*
***/
'isLeapYear': function() {
var year = callDateGet(this, 'FullYear');
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
},
/***
* @method daysInMonth()
* @returns Number
* @short Returns the number of days in the date's month.
* @example
*
* Date.create('May').daysInMonth() -> 31
* Date.create('February, 2000').daysInMonth() -> 29
*
***/
'daysInMonth': function() {
return 32 - callDateGet(new date(callDateGet(this, 'FullYear'), callDateGet(this, 'Month'), 32), 'Date');
},
/***
* @method format(<format>, [locale] = currentLocale)
* @returns String
* @short Formats and outputs the date.
* @extra <format> can be a number of pre-determined formats or a string of tokens. Locale-specific formats are %short%, %long%, and %full% which have their own aliases and can be called with %date.short()%, etc. If <format> is not specified the %long% format is assumed. [locale] specifies a locale code to use (if not specified the current locale is used). See @date_format for more details.
*
* @set
* short
* long
* full
*
* @example
*
* Date.create().format() -> ex. July 4, 2003
* Date.create().format('{Weekday} {d} {Month}, {yyyy}') -> ex. Monday July 4, 2003
* Date.create().format('{hh}:{mm}') -> ex. 15:57
* Date.create().format('{12hr}:{mm}{tt}') -> ex. 3:57pm
* Date.create().format(Date.ISO8601_DATETIME) -> ex. 2011-07-05 12:24:55.528Z
* Date.create('last week').format('short', 'ja') -> ex. 先週
* Date.create('yesterday').format(function(value,unit,ms,loc) {
* // value = 1, unit = 3, ms = -86400000, loc = [current locale object]
* }); -> ex. 1 day ago
*
***/
'format': function(f, localeCode) {
return formatDate(this, f, false, localeCode);
},
/***
* @method relative([fn], [locale] = currentLocale)
* @returns String
* @short Returns a relative date string offset to the current time.
* @extra [fn] can be passed to provide for more granular control over the resulting string. [fn] is passed 4 arguments: the adjusted value, unit, offset in milliseconds, and a localization object. As an alternate syntax, [locale] can also be passed as the first (and only) parameter. For more, see @date_format.
* @example
*
* Date.create('90 seconds ago').relative() -> 1 minute ago
* Date.create('January').relative() -> ex. 5 months ago
* Date.create('January').relative('ja') -> 3ヶ月前
* Date.create('120 minutes ago').relative(function(val,unit,ms,loc) {
* // value = 2, unit = 3, ms = -7200, loc = [current locale object]
* }); -> ex. 5 months ago
*
***/
'relative': function(f, localeCode) {
if(isString(f)) {
localeCode = f;
f = null;
}
return formatDate(this, f, true, localeCode);
},
/***
* @method is(<d>, [margin] = 0)
* @returns Boolean
* @short Returns true if the date is <d>.
* @extra <d> will accept a date object, timestamp, or text format. %is% additionally understands more generalized expressions like month/weekday names, 'today', etc, and compares to the precision implied in <d>. [margin] allows an extra margin of error in milliseconds. For more, see @date_format.
* @example
*
* Date.create().is('July') -> true or false?
* Date.create().is('1776') -> false
* Date.create().is('today') -> true
* Date.create().is('weekday') -> true or false?
* Date.create().is('July 4, 1776') -> false
* Date.create().is(-6106093200000) -> false
* Date.create().is(new Date(1776, 6, 4)) -> false
*
***/
'is': function(d, margin, utc) {
var tmp, comp;
if(!this.isValid()) return;
if(isString(d)) {
d = d.trim().toLowerCase();
comp = this.clone().utc(utc);
switch(true) {
case d === 'future': return this.getTime() > new date().getTime();
case d === 'past': return this.getTime() < new date().getTime();
case d === 'weekday': return callDateGet(comp, 'Day') > 0 && callDateGet(comp, 'Day') < 6;
case d === 'weekend': return callDateGet(comp, 'Day') === 0 || callDateGet(comp, 'Day') === 6;
case (tmp = English['weekdays'].indexOf(d) % 7) > -1: return callDateGet(comp, 'Day') === tmp;
case (tmp = English['months'].indexOf(d) % 12) > -1: return callDateGet(comp, 'Month') === tmp;
}
}
return compareDate(this, d, margin, utc);
},
/***
* @method reset([unit] = 'hours')
* @returns Date
* @short Resets the unit passed and all smaller units. Default is "hours", effectively resetting the time.
* @example
*
* Date.create().reset('day') -> Beginning of today
* Date.create().reset('month') -> 1st of the month
*
***/
'reset': function(unit) {
var params = {}, recognized;
unit = unit || 'hours';
if(unit === 'date') unit = 'days';
recognized = DateUnits.some(function(u) {
return unit === u.unit || unit === u.unit + 's';
});
params[unit] = unit.match(/^days?/) ? 1 : 0;
return recognized ? this.set(params, true) : this;
},
/***
* @method clone()
* @returns Date
* @short Clones the date.
* @example
*
* Date.create().clone() -> Copy of now
*
***/
'clone': function() {
var d = new date(this.getTime());
d._utc = this._utc;
return d;
}
});
// Instance aliases
date.extend({
/***
* @method iso()
* @alias toISOString
*
***/
'iso': function() {
return this.toISOString();
},
/***
* @method getWeekday()
* @returns Number
* @short Alias for %getDay%.
* @set
* getUTCWeekday
*
* @example
*
+ Date.create().getWeekday(); -> (ex.) 3
+ Date.create().getUTCWeekday(); -> (ex.) 3
*
***/
'getWeekday': date.prototype.getDay,
'getUTCWeekday': date.prototype.getUTCDay
});
/***
* Number module
*
***/
/***
* @method [unit]()
* @returns Number
* @short Takes the number as a corresponding unit of time and converts to milliseconds.
* @extra Method names can be both singular and plural. Note that as "a month" is ambiguous as a unit of time, %months% will be equivalent to 30.4375 days, the average number in a month. Be careful using %months% if you need exact precision.
*
* @set
* millisecond
* milliseconds
* second
* seconds
* minute
* minutes
* hour
* hours
* day
* days
* week
* weeks
* month
* months
* year
* years
*
* @example
*
* (5).milliseconds() -> 5
* (10).hours() -> 36000000
* (1).day() -> 86400000
*
***
* @method [unit]Before([d], [locale] = currentLocale)
* @returns Date
* @short Returns a date that is <n> units before [d], where <n> is the number.
* @extra [d] will accept a date object, timestamp, or text format. Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Be careful using %monthsBefore% if you need exact precision. See @date_format for more.
*
* @set
* millisecondBefore
* millisecondsBefore
* secondBefore
* secondsBefore
* minuteBefore
* minutesBefore
* hourBefore
* hoursBefore
* dayBefore
* daysBefore
* weekBefore
* weeksBefore
* monthBefore
* monthsBefore
* yearBefore
* yearsBefore
*
* @example
*
* (5).daysBefore('tuesday') -> 5 days before tuesday of this week
* (1).yearBefore('January 23, 1997') -> January 23, 1996
*
***
* @method [unit]Ago()
* @returns Date
* @short Returns a date that is <n> units ago.
* @extra Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Be careful using %monthsAgo% if you need exact precision.
*
* @set
* millisecondAgo
* millisecondsAgo
* secondAgo
* secondsAgo
* minuteAgo
* minutesAgo
* hourAgo
* hoursAgo
* dayAgo
* daysAgo
* weekAgo
* weeksAgo
* monthAgo
* monthsAgo
* yearAgo
* yearsAgo
*
* @example
*
* (5).weeksAgo() -> 5 weeks ago
* (1).yearAgo() -> January 23, 1996
*
***
* @method [unit]After([d], [locale] = currentLocale)
* @returns Date
* @short Returns a date <n> units after [d], where <n> is the number.
* @extra [d] will accept a date object, timestamp, or text format. Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Be careful using %monthsAfter% if you need exact precision. See @date_format for more.
*
* @set
* millisecondAfter
* millisecondsAfter
* secondAfter
* secondsAfter
* minuteAfter
* minutesAfter
* hourAfter
* hoursAfter
* dayAfter
* daysAfter
* weekAfter
* weeksAfter
* monthAfter
* monthsAfter
* yearAfter
* yearsAfter
*
* @example
*
* (5).daysAfter('tuesday') -> 5 days after tuesday of this week
* (1).yearAfter('January 23, 1997') -> January 23, 1998
*
***
* @method [unit]FromNow()
* @returns Date
* @short Returns a date <n> units from now.
* @extra Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Be careful using %monthsFromNow% if you need exact precision.
*
* @set
* millisecondFromNow
* millisecondsFromNow
* secondFromNow
* secondsFromNow
* minuteFromNow
* minutesFromNow
* hourFromNow
* hoursFromNow
* dayFromNow
* daysFromNow
* weekFromNow
* weeksFromNow
* monthFromNow
* monthsFromNow
* yearFromNow
* yearsFromNow
*
* @example
*
* (5).weeksFromNow() -> 5 weeks ago
* (1).yearFromNow() -> January 23, 1998
*
***/
function buildNumberToDateAlias(u, multiplier) {
var unit = u.unit, methods = {};
function base() { return round(this * multiplier); }
function after() { return createDate(arguments)[u.addMethod](this); }
function before() { return createDate(arguments)[u.addMethod](-this); }
methods[unit] = base;
methods[unit + 's'] = base;
methods[unit + 'Before'] = before;
methods[unit + 'sBefore'] = before;
methods[unit + 'Ago'] = before;
methods[unit + 'sAgo'] = before;
methods[unit + 'After'] = after;
methods[unit + 'sAfter'] = after;
methods[unit + 'FromNow'] = after;
methods[unit + 'sFromNow'] = after;
number.extend(methods);
}
number.extend({
/***
* @method duration([locale] = currentLocale)
* @returns String
* @short Takes the number as milliseconds and returns a unit-adjusted localized string.
* @extra This method is the same as %Date#relative% without the localized equivalent of "from now" or "ago". [locale] can be passed as the first (and only) parameter. Note that this method is only available when the dates package is included.
* @example
*
* (500).duration() -> '500 milliseconds'
* (1200).duration() -> '1 second'
* (75).minutes().duration() -> '1 hour'
* (75).minutes().duration('es') -> '1 hora'
*
***/
'duration': function(localeCode) {
return getLocalization(localeCode).getDuration(this);
}
});
English = CurrentLocalization = date.addLocale('en', {
'plural': true,
'timeMarker': 'at',
'ampm': 'am,pm',
'months': 'January,February,March,April,May,June,July,August,September,October,November,December',
'weekdays': 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday',
'units': 'millisecond:|s,second:|s,minute:|s,hour:|s,day:|s,week:|s,month:|s,year:|s',
'numbers': 'one,two,three,four,five,six,seven,eight,nine,ten',
'articles': 'a,an,the',
'tokens': 'the,st|nd|rd|th,of',
'short': '{Month} {d}, {yyyy}',
'long': '{Month} {d}, {yyyy} {h}:{mm}{tt}',
'full': '{Weekday} {Month} {d}, {yyyy} {h}:{mm}:{ss}{tt}',
'past': '{num} {unit} {sign}',
'future': '{num} {unit} {sign}',
'duration': '{num} {unit}',
'modifiers': [
{ 'name': 'day', 'src': 'yesterday', 'value': -1 },
{ 'name': 'day', 'src': 'today', 'value': 0 },
{ 'name': 'day', 'src': 'tomorrow', 'value': 1 },
{ 'name': 'sign', 'src': 'ago|before', 'value': -1 },
{ 'name': 'sign', 'src': 'from now|after|from|in|later', 'value': 1 },
{ 'name': 'edge', 'src': 'last day', 'value': -2 },
{ 'name': 'edge', 'src': 'end', 'value': -1 },
{ 'name': 'edge', 'src': 'first day|beginning', 'value': 1 },
{ 'name': 'shift', 'src': 'last', 'value': -1 },
{ 'name': 'shift', 'src': 'the|this', 'value': 0 },
{ 'name': 'shift', 'src': 'next', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{month} {year}',
'{shift} {unit=5-7}',
'{0?} {date}{1}',
'{0?} {edge} of {shift?} {unit=4-7?}{month?}{year?}'
],
'timeParse': [
'{0} {num}{1} {day} of {month} {year?}',
'{weekday?} {month} {date}{1?} {year?}',
'{date} {month} {year}',
'{shift} {weekday}',
'{shift} week {weekday}',
'{weekday} {2?} {shift} week',
'{num} {unit=4-5} {sign} {day}',
'{0?} {date}{1} of {month}',
'{0?}{month?} {date?}{1?} of {shift} {unit=6-7}'
]
});
buildDateUnits();
buildDateMethods();
buildCoreInputFormats();
buildDateOutputShortcuts();
buildAsianDigits();
buildRelativeAliases();
buildUTCAliases();
setDateProperties();
/***
* @package DateRange
* @dependency date
* @description Date Ranges define a range of time. They can enumerate over specific points within that range, and be manipulated and compared.
*
***/
var DateRange = function(start, end) {
this.start = date.create(start);
this.end = date.create(end);
};
// 'toString' doesn't appear in a for..in loop in IE even though
// hasOwnProperty reports true, so extend() can't be used here.
// Also tried simply setting the prototype = {} up front for all
// methods but GCC very oddly started dropping properties in the
// object randomly (maybe because of the global scope?) hence
// the need for the split logic here.
DateRange.prototype.toString = function() {
/***
* @method toString()
* @returns String
* @short Returns a string representation of the DateRange.
* @example
*
* Date.range('2003', '2005').toString() -> January 1, 2003..January 1, 2005
*
***/
return this.isValid() ? this.start.full() + '..' + this.end.full() : 'Invalid DateRange';
};
extend(DateRange, true, false, {
/***
* @method isValid()
* @returns Boolean
* @short Returns true if the DateRange is valid, false otherwise.
* @example
*
* Date.range('2003', '2005').isValid() -> true
* Date.range('2005', '2003').isValid() -> false
*
***/
'isValid': function() {
return this.start < this.end;
},
/***
* @method duration()
* @returns Number
* @short Return the duration of the DateRange in milliseconds.
* @example
*
* Date.range('2003', '2005').duration() -> 94694400000
*
***/
'duration': function() {
return this.isValid() ? this.end.getTime() - this.start.getTime() : NaN;
},
/***
* @method contains(<d>)
* @returns Boolean
* @short Returns true if <d> is contained inside the DateRange. <d> may be a date or another DateRange.
* @example
*
* Date.range('2003', '2005').contains(Date.create('2004')) -> true
*
***/
'contains': function(obj) {
var self = this, arr = obj.start && obj.end ? [obj.start, obj.end] : [obj];
return arr.every(function(d) {
return d >= self.start && d <= self.end;
});
},
/***
* @method every(<increment>, [fn])
* @returns Array
* @short Iterates through the DateRange for every <increment>, calling [fn] if it is passed. Returns an array of each increment visited.
* @extra When <increment> is a number, increments will be to the exact millisecond. <increment> can also be a string in the format %{number} {unit}s%, in which case it will increment in the unit specified. Note that a discrepancy exists in the case of months, as %(2).months()% is an approximation. Stepping through the actual months by passing %"2 months"% is usually preferable in this case.
* @example
*
* Date.range('2003-01', '2003-03').every("2 months") -> [...]
*
***/
'every': function(increment, fn) {
var current = this.start.clone(), result = [], index = 0, params, isDay;
if(isString(increment)) {
current.advance(getDateParamsFromString(increment, 0), true);
params = getDateParamsFromString(increment);
isDay = increment.toLowerCase() === 'day';
} else {
params = { 'milliseconds': increment };
}
while(current <= this.end) {
result.push(current);
if(fn) fn(current, index);
if(isDay && callDateGet(current, 'Hours') === 23) {
// When DST traversal happens at 00:00 hours, the time is effectively
// pushed back to 23:00, meaning 1) 00:00 for that day does not exist,
// and 2) there is no difference between 23:00 and 00:00, as you are
// "jumping" around in time. Hours here will be reset before the date
// is advanced and the date will never in fact advance, so set the hours
// directly ahead to the next day to avoid this problem.
current = current.clone();
callDateSet(current, 'Hours', 48);
} else {
current = current.clone().advance(params, true);
}
index++;
}
return result;
},
/***
* @method union(<range>)
* @returns DateRange
* @short Returns a new DateRange with the earliest starting point as its start, and the latest ending point as its end. If the two ranges do not intersect this will effectively remove the "gap" between them.
* @example
*
* Date.range('2003=01', '2005-01').union(Date.range('2004-01', '2006-01')) -> Jan 1, 2003..Jan 1, 2006
*
***/
'union': function(range) {
return new DateRange(
this.start < range.start ? this.start : range.start,
this.end > range.end ? this.end : range.end
);
},
/***
* @method intersect(<range>)
* @returns DateRange
* @short Returns a new DateRange with the latest starting point as its start, and the earliest ending point as its end. If the two ranges do not intersect this will effectively produce an invalid range.
* @example
*
* Date.range('2003-01', '2005-01').intersect(Date.range('2004-01', '2006-01')) -> Jan 1, 2004..Jan 1, 2005
*
***/
'intersect': function(range) {
return new DateRange(
this.start > range.start ? this.start : range.start,
this.end < range.end ? this.end : range.end
);
}
});
/***
* @method each[Unit]([fn])
* @returns Date
* @short Increments through the date range for each [unit], calling [fn] if it is passed. Returns an array of each increment visited.
*
* @set
* eachMillisecond
* eachSecond
* eachMinute
* eachHour
* eachDay
* eachWeek
* eachMonth
* eachYear
*
* @example
*
* Date.range('2003-01', '2003-02').eachMonth() -> [...]
* Date.range('2003-01-15', '2003-01-16').eachDay() -> [...]
*
***/
extendSimilar(DateRange, true, false, 'Millisecond,Second,Minute,Hour,Day,Week,Month,Year', function(methods, name) {
methods['each' + name] = function(fn) { return this.every(name, fn); }
});
/***
* Date module
***/
extend(date, false, false, {
/***
* @method Date.range([start], [end])
* @returns DateRange
* @short Creates a new date range.
* @extra If either [start] or [end] are null, they will default to the current date.
*
***/
'range': function(start, end) {
return new DateRange(start, end);
}
});
/***
* @package Function
* @dependency core
* @description Lazy, throttled, and memoized functions, delayed functions and handling of timers, argument currying.
*
***/
function setDelay(fn, ms, after, scope, args) {
var index;
if(!fn.timers) fn.timers = [];
if(!isNumber(ms)) ms = 0;
fn.timers.push(setTimeout(function(){
fn.timers.splice(index, 1);
after.apply(scope, args || []);
}, ms));
index = fn.timers.length;
}
extend(Function, true, false, {
/***
* @method lazy([ms] = 1, [limit] = Infinity)
* @returns Function
* @short Creates a lazy function that, when called repeatedly, will queue execution and wait [ms] milliseconds to execute again.
* @extra Lazy functions will always execute as many times as they are called up to [limit], after which point subsequent calls will be ignored (if it is set to a finite number). Compare this to %throttle%, which will execute only once per [ms] milliseconds. %lazy% is useful when you need to be sure that every call to a function is executed, but in a non-blocking manner. Calling %cancel% on a lazy function will clear the entire queue. Note that [ms] can also be a fraction.
* @example
*
* (function() {
* // Executes immediately.
* }).lazy()();
* (3).times(function() {
* // Executes 3 times, with each execution 20ms later than the last.
* }.lazy(20));
* (100).times(function() {
* // Executes 50 times, with each execution 20ms later than the last.
* }.lazy(20, 50));
*
***/
'lazy': function(ms, limit) {
var fn = this, queue = [], lock = false, execute, rounded, perExecution;
ms = ms || 1;
limit = limit || Infinity;
rounded = ceil(ms);
perExecution = round(rounded / ms);
execute = function() {
if(lock || queue.length == 0) return;
var max = math.max(queue.length - perExecution, 0);
while(queue.length > max) {
// Getting uber-meta here...
Function.prototype.apply.apply(fn, queue.shift());
}
setDelay(lazy, rounded, function() {
lock = false;
execute();
});
lock = true;
}
function lazy() {
// The first call is immediate, so having 1 in the queue
// implies two calls have already taken place.
if(lock && queue.length > limit - 2) return;
queue.push([this, arguments]);
execute();
}
return lazy;
},
/***
* @method delay([ms] = 0, [arg1], ...)
* @returns Function
* @short Executes the function after <ms> milliseconds.
* @extra Returns a reference to itself. %delay% is also a way to execute non-blocking operations that will wait until the CPU is free. Delayed functions can be canceled using the %cancel% method. Can also curry arguments passed in after <ms>.
* @example
*
* (function(arg1) {
* // called 1s later
* }).delay(1000, 'arg1');
*
***/
'delay': function(ms) {
var fn = this;
var args = multiArgs(arguments).slice(1);
setDelay(fn, ms, fn, fn, args);
return fn;
},
/***
* @method throttle(<ms>)
* @returns Function
* @short Creates a "throttled" version of the function that will only be executed once per <ms> milliseconds.
* @extra This is functionally equivalent to calling %lazy% with a [limit] of %1%. %throttle% is appropriate when you want to make sure a function is only executed at most once for a given duration. Compare this to %lazy%, which will queue rapid calls and execute them later.
* @example
*
* (3).times(function() {
* // called only once. will wait 50ms until it responds again
* }.throttle(50));
*
***/
'throttle': function(ms) {
return this.lazy(ms, 1);
},
/***
* @method debounce(<ms>)
* @returns Function
* @short Creates a "debounced" function that postpones its execution until after <ms> milliseconds have passed.
* @extra This method is useful to execute a function after things have "settled down". A good example of this is when a user tabs quickly through form fields, execution of a heavy operation should happen after a few milliseconds when they have "settled" on a field.
* @example
*
* var fn = (function(arg1) {
* // called once 50ms later
* }).debounce(50); fn() fn() fn();
*
***/
'debounce': function(ms) {
var fn = this;
function debounced() {
debounced.cancel();
setDelay(debounced, ms, fn, this, arguments);
};
return debounced;
},
/***
* @method cancel()
* @returns Function
* @short Cancels a delayed function scheduled to be run.
* @extra %delay%, %lazy%, %throttle%, and %debounce% can all set delays.
* @example
*
* (function() {
* alert('hay'); // Never called
* }).delay(500).cancel();
*
***/
'cancel': function() {
if(isArray(this.timers)) {
while(this.timers.length > 0) {
clearTimeout(this.timers.shift());
}
}
return this;
},
/***
* @method after([num] = 1)
* @returns Function
* @short Creates a function that will execute after [num] calls.
* @extra %after% is useful for running a final callback after a series of asynchronous operations, when the order in which the operations will complete is unknown.
* @example
*
* var fn = (function() {
* // Will be executed once only
* }).after(3); fn(); fn(); fn();
*
***/
'after': function(num) {
var fn = this, counter = 0, storedArguments = [];
if(!isNumber(num)) {
num = 1;
} else if(num === 0) {
fn.call();
return fn;
}
return function() {
var ret;
storedArguments.push(multiArgs(arguments));
counter++;
if(counter == num) {
ret = fn.call(this, storedArguments);
counter = 0;
storedArguments = [];
return ret;
}
}
},
/***
* @method once()
* @returns Function
* @short Creates a function that will execute only once and store the result.
* @extra %once% is useful for creating functions that will cache the result of an expensive operation and use it on subsequent calls. Also it can be useful for creating initialization functions that only need to be run once.
* @example
*
* var fn = (function() {
* // Will be executed once only
* }).once(); fn(); fn(); fn();
*
***/
'once': function() {
var fn = this;
return function() {
return hasOwnProperty(fn, 'memo') ? fn['memo'] : fn['memo'] = fn.apply(this, arguments);
}
},
/***
* @method fill(<arg1>, <arg2>, ...)
* @returns Function
* @short Returns a new version of the function which when called will have some of its arguments pre-emptively filled in, also known as "currying".
* @extra Arguments passed to a "filled" function are generally appended to the curried arguments. However, if %undefined% is passed as any of the arguments to %fill%, it will be replaced, when the "filled" function is executed. This allows currying of arguments even when they occur toward the end of an argument list (the example demonstrates this much more clearly).
* @example
*
* var delayOneSecond = setTimeout.fill(undefined, 1000);
* delayOneSecond(function() {
* // Will be executed 1s later
* });
*
***/
'fill': function() {
var fn = this, curried = multiArgs(arguments);
return function() {
var args = multiArgs(arguments);
curried.forEach(function(arg, index) {
if(arg != null || index >= args.length) args.splice(index, 0, arg);
});
return fn.apply(this, args);
}
}
});
/***
* @package Number
* @dependency core
* @description Number formatting, rounding (with precision), and ranges. Aliases to Math methods.
*
***/
function abbreviateNumber(num, roundTo, str, mid, limit, bytes) {
var fixed = num.toFixed(20),
decimalPlace = fixed.search(/\./),
numeralPlace = fixed.search(/[1-9]/),
significant = decimalPlace - numeralPlace,
unit, i, divisor;
if(significant > 0) {
significant -= 1;
}
i = math.max(math.min((significant / 3).floor(), limit === false ? str.length : limit), -mid);
unit = str.charAt(i + mid - 1);
if(significant < -9) {
i = -3;
roundTo = significant.abs() - 9;
unit = str.slice(0,1);
}
divisor = bytes ? (2).pow(10 * i) : (10).pow(i * 3);
return (num / divisor).round(roundTo || 0).format() + unit.trim();
}
extend(number, false, false, {
/***
* @method Number.random([n1], [n2])
* @returns Number
* @short Returns a random integer between [n1] and [n2].
* @extra If only 1 number is passed, the other will be 0. If none are passed, the number will be either 0 or 1.
* @example
*
* Number.random(50, 100) -> ex. 85
* Number.random(50) -> ex. 27
* Number.random() -> ex. 0
*
***/
'random': function(n1, n2) {
var min, max;
if(arguments.length == 1) n2 = n1, n1 = 0;
min = math.min(n1 || 0, isUndefined(n2) ? 1 : n2);
max = math.max(n1 || 0, isUndefined(n2) ? 1 : n2) + 1;
return floor((math.random() * (max - min)) + min);
}
});
extend(number, true, false, {
/***
* @method log(<base> = Math.E)
* @returns Number
* @short Returns the logarithm of the number with base <base>, or natural logarithm of the number if <base> is undefined.
* @example
*
* (64).log(2) -> 6
* (9).log(3) -> 2
* (5).log() -> 1.6094379124341003
*
***/
'log': function(base) {
return math.log(this) / (base ? math.log(base) : 1);
},
/***
* @method abbr([precision] = 0)
* @returns String
* @short Returns an abbreviated form of the number.
* @extra [precision] will round to the given precision.
* @example
*
* (1000).abbr() -> "1k"
* (1000000).abbr() -> "1m"
* (1280).abbr(1) -> "1.3k"
*
***/
'abbr': function(precision) {
return abbreviateNumber(this, precision, 'kmbt', 0, 4);
},
/***
* @method metric([precision] = 0, [limit] = 1)
* @returns String
* @short Returns the number as a string in metric notation.
* @extra [precision] will round to the given precision. Both very large numbers and very small numbers are supported. [limit] is the upper limit for the units. The default is %1%, which is "kilo". If [limit] is %false%, the upper limit will be "exa". The lower limit is "nano", and cannot be changed.
* @example
*
* (1000).metric() -> "1k"
* (1000000).metric() -> "1,000k"
* (1000000).metric(0, false) -> "1M"
* (1249).metric(2) + 'g' -> "1.25kg"
* (0.025).metric() + 'm' -> "25mm"
*
***/
'metric': function(precision, limit) {
return abbreviateNumber(this, precision, 'nμm kMGTPE', 4, isUndefined(limit) ? 1 : limit);
},
/***
* @method bytes([precision] = 0, [limit] = 4)
* @returns String
* @short Returns an abbreviated form of the number, considered to be "Bytes".
* @extra [precision] will round to the given precision. [limit] is the upper limit for the units. The default is %4%, which is "terabytes" (TB). If [limit] is %false%, the upper limit will be "exa".
* @example
*
* (1000).bytes() -> "1kB"
* (1000).bytes(2) -> "0.98kB"
* ((10).pow(20)).bytes() -> "90,949,470TB"
* ((10).pow(20)).bytes(0, false) -> "87EB"
*
***/
'bytes': function(precision, limit) {
return abbreviateNumber(this, precision, 'kMGTPE', 0, isUndefined(limit) ? 4 : limit, true) + 'B';
},
/***
* @method isInteger()
* @returns Boolean
* @short Returns true if the number has no trailing decimal.
* @example
*
* (420).isInteger() -> true
* (4.5).isInteger() -> false
*
***/
'isInteger': function() {
return this % 1 == 0;
},
/***
* @method isOdd()
* @returns Boolean
* @short Returns true if the number is odd.
* @example
*
* (3).isOdd() -> true
* (18).isOdd() -> false
*
***/
'isOdd': function() {
return !this.isMultipleOf(2);
},
/***
* @method isEven()
* @returns Boolean
* @short Returns true if the number is even.
* @example
*
* (6).isEven() -> true
* (17).isEven() -> false
*
***/
'isEven': function() {
return this.isMultipleOf(2);
},
/***
* @method isMultipleOf(<num>)
* @returns Boolean
* @short Returns true if the number is a multiple of <num>.
* @example
*
* (6).isMultipleOf(2) -> true
* (17).isMultipleOf(2) -> false
* (32).isMultipleOf(4) -> true
* (34).isMultipleOf(4) -> false
*
***/
'isMultipleOf': function(num) {
return this % num === 0;
},
/***
* @method format([place] = 0, [thousands] = ',', [decimal] = '.')
* @returns String
* @short Formats the number to a readable string.
* @extra If [place] is %undefined%, will automatically determine the place. [thousands] is the character used for the thousands separator. [decimal] is the character used for the decimal point.
* @example
*
* (56782).format() -> '56,782'
* (56782).format(2) -> '56,782.00'
* (4388.43).format(2, ' ') -> '4 388.43'
* (4388.43).format(2, '.', ',') -> '4.388,43'
*
***/
'format': function(place, thousands, decimal) {
var str, split, method, after, r = /(\d+)(\d{3})/;
if(string(thousands).match(/\d/)) throw new TypeError('Thousands separator cannot contain numbers.');
str = isNumber(place) ? round(this, place || 0).toFixed(math.max(place, 0)) : this.toString();
thousands = thousands || ',';
decimal = decimal || '.';
split = str.split('.');
str = split[0];
after = split[1] || '';
while (str.match(r)) {
str = str.replace(r, '$1' + thousands + '$2');
}
if(after.length > 0) {
str += decimal + repeatString((place || 0) - after.length, '0') + after;
}
return str;
},
/***
* @method hex([pad] = 1)
* @returns String
* @short Converts the number to hexidecimal.
* @extra [pad] will pad the resulting string to that many places.
* @example
*
* (255).hex() -> 'ff';
* (255).hex(4) -> '00ff';
* (23654).hex() -> '5c66';
*
***/
'hex': function(pad) {
return this.pad(pad || 1, false, 16);
},
/***
* @method upto(<num>, [fn], [step] = 1)
* @returns Array
* @short Returns an array containing numbers from the number up to <num>.
* @extra Optionally calls [fn] callback for each number in that array. [step] allows multiples greater than 1.
* @example
*
* (2).upto(6) -> [2, 3, 4, 5, 6]
* (2).upto(6, function(n) {
* // This function is called 5 times receiving n as the value.
* });
* (2).upto(8, null, 2) -> [2, 4, 6, 8]
*
***/
'upto': function(num, fn, step) {
return getRange(this, num, fn, step || 1);
},
/***
* @method downto(<num>, [fn], [step] = 1)
* @returns Array
* @short Returns an array containing numbers from the number down to <num>.
* @extra Optionally calls [fn] callback for each number in that array. [step] allows multiples greater than 1.
* @example
*
* (8).downto(3) -> [8, 7, 6, 5, 4, 3]
* (8).downto(3, function(n) {
* // This function is called 6 times receiving n as the value.
* });
* (8).downto(2, null, 2) -> [8, 6, 4, 2]
*
***/
'downto': function(num, fn, step) {
return getRange(this, num, fn, -(step || 1));
},
/***
* @method times(<fn>)
* @returns Number
* @short Calls <fn> a number of times equivalent to the number.
* @example
*
* (8).times(function(i) {
* // This function is called 8 times.
* });
*
***/
'times': function(fn) {
if(fn) {
for(var i = 0; i < this; i++) {
fn.call(this, i);
}
}
return this.toNumber();
},
/***
* @method chr()
* @returns String
* @short Returns a string at the code point of the number.
* @example
*
* (65).chr() -> "A"
* (75).chr() -> "K"
*
***/
'chr': function() {
return string.fromCharCode(this);
},
/***
* @method pad(<place> = 0, [sign] = false, [base] = 10)
* @returns String
* @short Pads a number with "0" to <place>.
* @extra [sign] allows you to force the sign as well (+05, etc). [base] can change the base for numeral conversion.
* @example
*
* (5).pad(2) -> '05'
* (-5).pad(4) -> '-0005'
* (82).pad(3, true) -> '+082'
*
***/
'pad': function(place, sign, base) {
return padNumber(this, place, sign, base);
},
/***
* @method ordinalize()
* @returns String
* @short Returns an ordinalized (English) string, i.e. "1st", "2nd", etc.
* @example
*
* (1).ordinalize() -> '1st';
* (2).ordinalize() -> '2nd';
* (8).ordinalize() -> '8th';
*
***/
'ordinalize': function() {
var suffix, num = this.abs(), last = parseInt(num.toString().slice(-2));
return this + getOrdinalizedSuffix(last);
},
/***
* @method toNumber()
* @returns Number
* @short Returns a number. This is mostly for compatibility reasons.
* @example
*
* (420).toNumber() -> 420
*
***/
'toNumber': function() {
return parseFloat(this, 10);
}
});
/***
* @method round(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.round% that also allows a <precision>.
*
* @example
*
* (3.241).round() -> 3
* (-3.841).round() -> -4
* (3.241).round(2) -> 3.24
* (3748).round(-2) -> 3800
*
***
* @method ceil(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.ceil% that also allows a <precision>.
*
* @example
*
* (3.241).ceil() -> 4
* (-3.241).ceil() -> -3
* (3.241).ceil(2) -> 3.25
* (3748).ceil(-2) -> 3800
*
***
* @method floor(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.floor% that also allows a <precision>.
*
* @example
*
* (3.241).floor() -> 3
* (-3.841).floor() -> -4
* (3.241).floor(2) -> 3.24
* (3748).floor(-2) -> 3700
*
***
* @method [math]()
* @returns Number
* @short Math related functions are mapped as shortcuts to numbers and are identical. Note that %Number#log% provides some special defaults.
*
* @set
* abs
* sin
* asin
* cos
* acos
* tan
* atan
* sqrt
* exp
* pow
*
* @example
*
* (3).pow(3) -> 27
* (-3).abs() -> 3
* (1024).sqrt() -> 32
*
***/
function buildNumber() {
extendSimilar(number, true, false, 'round,floor,ceil', function(methods, name) {
methods[name] = function(precision) {
return round(this, precision, name);
}
});
extendSimilar(number, true, false, 'abs,pow,sin,asin,cos,acos,tan,atan,exp,pow,sqrt', function(methods, name) {
methods[name] = function(a, b) {
return math[name](this, a, b);
}
});
}
buildNumber();
/***
* @package Object
* @dependency core
* @description Object manipulation, type checking (isNumber, isString, ...), extended objects with hash-like methods available as instance methods.
*
* Much thanks to kangax for his informative aricle about how problems with instanceof and constructor
* http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
*
***/
var ObjectTypeMethods = 'isObject,isNaN'.split(',');
var ObjectHashMethods = 'keys,values,each,merge,clone,equal,watch,tap,has'.split(',');
function setParamsObject(obj, param, value, deep) {
var reg = /^(.+?)(\[.*\])$/, paramIsArray, match, allKeys, key;
if(deep !== false && (match = param.match(reg))) {
key = match[1];
allKeys = match[2].replace(/^\[|\]$/g, '').split('][');
allKeys.forEach(function(k) {
paramIsArray = !k || k.match(/^\d+$/);
if(!key && isArray(obj)) key = obj.length;
if(!obj[key]) {
obj[key] = paramIsArray ? [] : {};
}
obj = obj[key];
key = k;
});
if(!key && paramIsArray) key = obj.length.toString();
setParamsObject(obj, key, value);
} else if(value.match(/^[\d.]+$/)) {
obj[param] = parseFloat(value);
} else if(value === 'true') {
obj[param] = true;
} else if(value === 'false') {
obj[param] = false;
} else {
obj[param] = value;
}
}
/***
* @method Object.is[Type](<obj>)
* @returns Boolean
* @short Returns true if <obj> is an object of that type.
* @extra %isObject% will return false on anything that is not an object literal, including instances of inherited classes. Note also that %isNaN% will ONLY return true if the object IS %NaN%. It does not mean the same as browser native %isNaN%, which returns true for anything that is "not a number".
*
* @set
* isArray
* isObject
* isBoolean
* isDate
* isFunction
* isNaN
* isNumber
* isString
* isRegExp
*
* @example
*
* Object.isArray([1,2,3]) -> true
* Object.isDate(3) -> false
* Object.isRegExp(/wasabi/) -> true
* Object.isObject({ broken:'wear' }) -> true
*
***/
function buildTypeMethods() {
extendSimilar(object, false, false, ClassNames, function(methods, name) {
var method = 'is' + name;
ObjectTypeMethods.push(method);
methods[method] = function(obj) {
return className(obj) === '[object '+name+']';
}
});
}
function buildObjectExtend() {
extend(object, false, function(){ return arguments.length === 0; }, {
'extend': function() {
buildObjectInstanceMethods(ObjectTypeMethods.concat(ObjectHashMethods), object);
}
});
}
extend(object, false, true, {
/***
* @method watch(<obj>, <prop>, <fn>)
* @returns Nothing
* @short Watches a property of <obj> and runs <fn> when it changes.
* @extra <fn> is passed three arguments: the property <prop>, the old value, and the new value. The return value of [fn] will be set as the new value. This method is useful for things such as validating or cleaning the value when it is set. Warning: this method WILL NOT work in browsers that don't support %Object.defineProperty%. This notably includes IE 8 and below, and Opera. This is the only method in Sugar that is not fully compatible with all browsers. %watch% is available as an instance method on extended objects.
* @example
*
* Object.watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) {
* // Will be run when the property 'foo' is set on the object.
* });
* Object.extended().watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) {
* // Will be run when the property 'foo' is set on the object.
* });
*
***/
'watch': function(obj, prop, fn) {
if(!definePropertySupport) return;
var value = obj[prop];
object.defineProperty(obj, prop, {
'enumerable' : true,
'configurable': true,
'get': function() {
return value;
},
'set': function(to) {
value = fn.call(obj, prop, value, to);
}
});
}
});
extend(object, false, function(arg1, arg2) { return isFunction(arg2); }, {
/***
* @method keys(<obj>, [fn])
* @returns Array
* @short Returns an array containing the keys in <obj>. Optionally calls [fn] for each key.
* @extra This method is provided for browsers that don't support it natively, and additionally is enhanced to accept the callback [fn]. Returned keys are in no particular order. %keys% is available as an instance method on extended objects.
* @example
*
* Object.keys({ broken: 'wear' }) -> ['broken']
* Object.keys({ broken: 'wear' }, function(key, value) {
* // Called once for each key.
* });
* Object.extended({ broken: 'wear' }).keys() -> ['broken']
*
***/
'keys': function(obj, fn) {
var keys = object.keys(obj);
keys.forEach(function(key) {
fn.call(obj, key, obj[key]);
});
return keys;
}
});
extend(object, false, false, {
'isObject': function(obj) {
return isObject(obj);
},
'isNaN': function(obj) {
// This is only true of NaN
return isNumber(obj) && obj.valueOf() !== obj.valueOf();
},
/***
* @method equal(<a>, <b>)
* @returns Boolean
* @short Returns true if <a> and <b> are equal.
* @extra %equal% in Sugar is "egal", meaning the values are equal if they are "not observably distinguishable". Note that on extended objects the name is %equals% for readability.
* @example
*
* Object.equal({a:2}, {a:2}) -> true
* Object.equal({a:2}, {a:3}) -> false
* Object.extended({a:2}).equals({a:3}) -> false
*
***/
'equal': function(a, b) {
return isEqual(a, b);
},
/***
* @method Object.extended(<obj> = {})
* @returns Extended object
* @short Creates a new object, equivalent to %new Object()% or %{}%, but with extended methods.
* @extra See extended objects for more.
* @example
*
* Object.extended()
* Object.extended({ happy:true, pappy:false }).keys() -> ['happy','pappy']
* Object.extended({ happy:true, pappy:false }).values() -> [true, false]
*
***/
'extended': function(obj) {
return new Hash(obj);
},
/***
* @method merge(<target>, <source>, [deep] = false, [resolve] = true)
* @returns Merged object
* @short Merges all the properties of <source> into <target>.
* @extra Merges are shallow unless [deep] is %true%. Properties of <source> will win in the case of conflicts, unless [resolve] is %false%. [resolve] can also be a function that resolves the conflict. In this case it will be passed 3 arguments, %key%, %targetVal%, and %sourceVal%, with the context set to <source>. This will allow you to solve conflict any way you want, ie. adding two numbers together, etc. %merge% is available as an instance method on extended objects.
* @example
*
* Object.merge({a:1},{b:2}) -> { a:1, b:2 }
* Object.merge({a:1},{a:2}, false, false) -> { a:1 }
+ Object.merge({a:1},{a:2}, false, function(key, a, b) {
* return a + b;
* }); -> { a:3 }
* Object.extended({a:1}).merge({b:2}) -> { a:1, b:2 }
*
***/
'merge': function(target, source, deep, resolve) {
var key, val;
// Strings cannot be reliably merged thanks to
// their properties not being enumerable in < IE8.
if(target && typeof source != 'string') {
for(key in source) {
if(!hasOwnProperty(source, key) || !target) continue;
val = source[key];
// Conflict!
if(isDefined(target[key])) {
// Do not merge.
if(resolve === false) {
continue;
}
// Use the result of the callback as the result.
if(isFunction(resolve)) {
val = resolve.call(source, key, target[key], source[key])
}
}
// Deep merging.
if(deep === true && val && isObjectPrimitive(val)) {
if(isDate(val)) {
val = new date(val.getTime());
} else if(isRegExp(val)) {
val = new regexp(val.source, getRegExpFlags(val));
} else {
if(!target[key]) target[key] = array.isArray(val) ? [] : {};
object.merge(target[key], source[key], deep, resolve);
continue;
}
}
target[key] = val;
}
}
return target;
},
/***
* @method values(<obj>, [fn])
* @returns Array
* @short Returns an array containing the values in <obj>. Optionally calls [fn] for each value.
* @extra Returned values are in no particular order. %values% is available as an instance method on extended objects.
* @example
*
* Object.values({ broken: 'wear' }) -> ['wear']
* Object.values({ broken: 'wear' }, function(value) {
* // Called once for each value.
* });
* Object.extended({ broken: 'wear' }).values() -> ['wear']
*
***/
'values': function(obj, fn) {
var values = [];
iterateOverObject(obj, function(k,v) {
values.push(v);
if(fn) fn.call(obj,v);
});
return values;
},
/***
* @method clone(<obj> = {}, [deep] = false)
* @returns Cloned object
* @short Creates a clone (copy) of <obj>.
* @extra Default is a shallow clone, unless [deep] is true. %clone% is available as an instance method on extended objects.
* @example
*
* Object.clone({foo:'bar'}) -> { foo: 'bar' }
* Object.clone() -> {}
* Object.extended({foo:'bar'}).clone() -> { foo: 'bar' }
*
***/
'clone': function(obj, deep) {
if(!isObjectPrimitive(obj)) return obj;
if(array.isArray(obj)) return obj.concat();
var target = obj instanceof Hash ? new Hash() : {};
return object.merge(target, obj, deep);
},
/***
* @method Object.fromQueryString(<str>, [deep] = true)
* @returns Object
* @short Converts the query string of a URL into an object.
* @extra If [deep] is %false%, conversion will only accept shallow params (ie. no object or arrays with %[]% syntax) as these are not universally supported.
* @example
*
* Object.fromQueryString('foo=bar&broken=wear') -> { foo: 'bar', broken: 'wear' }
* Object.fromQueryString('foo[]=1&foo[]=2') -> { foo: [1,2] }
*
***/
'fromQueryString': function(str, deep) {
var result = object.extended(), split;
str = str && str.toString ? str.toString() : '';
str.replace(/^.*?\?/, '').split('&').forEach(function(p) {
var split = p.split('=');
if(split.length !== 2) return;
setParamsObject(result, split[0], decodeURIComponent(split[1]), deep);
});
return result;
},
/***
* @method tap(<obj>, <fn>)
* @returns Object
* @short Runs <fn> and returns <obj>.
* @extra A string can also be used as a shortcut to a method. This method is used to run an intermediary function in the middle of method chaining. As a standalone method on the Object class it doesn't have too much use. The power of %tap% comes when using extended objects or modifying the Object prototype with Object.extend().
* @example
*
* Object.extend();
* [2,4,6].map(Math.exp).tap(function(){ arr.pop(); }).map(Math.round); -> [7,55]
* [2,4,6].map(Math.exp).tap('pop').map(Math.round); -> [7,55]
*
***/
'tap': function(obj, arg) {
var fn = arg;
if(!isFunction(arg)) {
fn = function() {
if(arg) obj[arg]();
}
}
fn.call(obj, obj);
return obj;
},
/***
* @method has(<obj>, <key>)
* @returns Boolean
* @short Checks if <obj> has <key> using hasOwnProperty from Object.prototype.
* @extra This method is considered safer than %Object#hasOwnProperty% when using objects as hashes. See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ for more.
* @example
*
* Object.has({ foo: 'bar' }, 'foo') -> true
* Object.has({ foo: 'bar' }, 'baz') -> false
* Object.has({ hasOwnProperty: true }, 'foo') -> false
*
***/
'has': function (obj, key) {
return hasOwnProperty(obj, key);
}
});
buildTypeMethods();
buildObjectExtend();
buildObjectInstanceMethods(ObjectHashMethods, Hash);
/***
* @package RegExp
* @dependency core
* @description Escaping regexes and manipulating their flags.
*
* Note here that methods on the RegExp class like .exec and .test will fail in the current version of SpiderMonkey being
* used by CouchDB when using shorthand regex notation like /foo/. This is the reason for the intermixed use of shorthand
* and compiled regexes here. If you're using JS in CouchDB, it is safer to ALWAYS compile your regexes from a string.
*
***/
function uniqueRegExpFlags(flags) {
return flags.split('').sort().join('').replace(/([gimy])\1+/g, '$1');
}
extend(regexp, false, false, {
/***
* @method RegExp.escape(<str> = '')
* @returns String
* @short Escapes all RegExp tokens in a string.
* @example
*
* RegExp.escape('really?') -> 'really\?'
* RegExp.escape('yes.') -> 'yes\.'
* RegExp.escape('(not really)') -> '\(not really\)'
*
***/
'escape': function(str) {
return escapeRegExp(str);
}
});
extend(regexp, true, false, {
/***
* @method getFlags()
* @returns String
* @short Returns the flags of the regex as a string.
* @example
*
* /texty/gim.getFlags('testy') -> 'gim'
*
***/
'getFlags': function() {
return getRegExpFlags(this);
},
/***
* @method setFlags(<flags>)
* @returns RegExp
* @short Sets the flags on a regex and retuns a copy.
* @example
*
* /texty/.setFlags('gim') -> now has global, ignoreCase, and multiline set
*
***/
'setFlags': function(flags) {
return regexp(this.source, flags);
},
/***
* @method addFlag(<flag>)
* @returns RegExp
* @short Adds <flag> to the regex.
* @example
*
* /texty/.addFlag('g') -> now has global flag set
*
***/
'addFlag': function(flag) {
return this.setFlags(getRegExpFlags(this, flag));
},
/***
* @method removeFlag(<flag>)
* @returns RegExp
* @short Removes <flag> from the regex.
* @example
*
* /texty/g.removeFlag('g') -> now has global flag removed
*
***/
'removeFlag': function(flag) {
return this.setFlags(getRegExpFlags(this).replace(flag, ''));
}
});
/***
* @package String
* @dependency core
* @description String manupulation, escaping, encoding, truncation, and:conversion.
*
***/
function getAcronym(word) {
var inflector = string.Inflector;
var word = inflector && inflector.acronyms[word];
if(isString(word)) {
return word;
}
}
function padString(str, p, left, right) {
var padding = string(p);
if(padding != p) {
padding = '';
}
if(!isNumber(left)) left = 1;
if(!isNumber(right)) right = 1;
return padding.repeat(left) + str + padding.repeat(right);
}
function chr(num) {
return string.fromCharCode(num);
}
var btoa, atob;
function buildBase64(key) {
if(this.btoa) {
btoa = this.btoa;
atob = this.atob;
return;
}
var base64reg = /[^A-Za-z0-9\+\/\=]/g;
btoa = function(str) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = str.charCodeAt(i++);
chr2 = str.charCodeAt(i++);
chr3 = str.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + key.charAt(enc1) + key.charAt(enc2) + key.charAt(enc3) + key.charAt(enc4);
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < str.length);
return output;
}
atob = function(input) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
if(input.match(base64reg)) {
throw new Error('String contains invalid base64 characters');
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
do {
enc1 = key.indexOf(input.charAt(i++));
enc2 = key.indexOf(input.charAt(i++));
enc3 = key.indexOf(input.charAt(i++));
enc4 = key.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + chr(chr1);
if (enc3 != 64) {
output = output + chr(chr2);
}
if (enc4 != 64) {
output = output + chr(chr3);
}
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < input.length);
return output;
}
}
extend(string, true, false, {
/***
* @method escapeRegExp()
* @returns String
* @short Escapes all RegExp tokens in the string.
* @example
*
* 'really?'.escapeRegExp() -> 'really\?'
* 'yes.'.escapeRegExp() -> 'yes\.'
* '(not really)'.escapeRegExp() -> '\(not really\)'
*
***/
'escapeRegExp': function() {
return escapeRegExp(this);
},
/***
* @method escapeURL([param] = false)
* @returns String
* @short Escapes characters in a string to make a valid URL.
* @extra If [param] is true, it will also escape valid URL characters for use as a URL parameter.
* @example
*
* 'http://foo.com/"bar"'.escapeURL() -> 'http://foo.com/%22bar%22'
* 'http://foo.com/"bar"'.escapeURL(true) -> 'http%3A%2F%2Ffoo.com%2F%22bar%22'
*
***/
'escapeURL': function(param) {
return param ? encodeURIComponent(this) : encodeURI(this);
},
/***
* @method unescapeURL([partial] = false)
* @returns String
* @short Restores escaped characters in a URL escaped string.
* @extra If [partial] is true, it will only unescape non-valid URL characters. [partial] is included here for completeness, but should very rarely be needed.
* @example
*
* 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL() -> 'http://foo.com/the bar'
* 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL(true) -> 'http%3A%2F%2Ffoo.com%2Fthe bar'
*
***/
'unescapeURL': function(param) {
return param ? decodeURI(this) : decodeURIComponent(this);
},
/***
* @method escapeHTML()
* @returns String
* @short Converts HTML characters to their entity equivalents.
* @example
*
* '<p>some text</p>'.escapeHTML() -> '<p>some text</p>'
* 'one & two'.escapeHTML() -> 'one & two'
*
***/
'escapeHTML': function() {
return this.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
},
/***
* @method unescapeHTML([partial] = false)
* @returns String
* @short Restores escaped HTML characters.
* @example
*
* '<p>some text</p>'.unescapeHTML() -> '<p>some text</p>'
* 'one & two'.unescapeHTML() -> 'one & two'
*
***/
'unescapeHTML': function() {
return this.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
},
/***
* @method encodeBase64()
* @returns String
* @short Encodes the string into base64 encoding.
* @extra This method wraps the browser native %btoa% when available, and uses a custom implementation when not available.
* @example
*
* 'gonna get encoded!'.encodeBase64() -> 'Z29ubmEgZ2V0IGVuY29kZWQh'
* 'http://twitter.com/'.encodeBase64() -> 'aHR0cDovL3R3aXR0ZXIuY29tLw=='
*
***/
'encodeBase64': function() {
return btoa(this);
},
/***
* @method decodeBase64()
* @returns String
* @short Decodes the string from base64 encoding.
* @extra This method wraps the browser native %atob% when available, and uses a custom implementation when not available.
* @example
*
* 'aHR0cDovL3R3aXR0ZXIuY29tLw=='.decodeBase64() -> 'http://twitter.com/'
* 'anVzdCBnb3QgZGVjb2RlZA=='.decodeBase64() -> 'just got decoded!'
*
***/
'decodeBase64': function() {
return atob(this);
},
/***
* @method each([search] = single character, [fn])
* @returns Array
* @short Runs callback [fn] against each occurence of [search].
* @extra Returns an array of matches. [search] may be either a string or regex, and defaults to every character in the string.
* @example
*
* 'jumpy'.each() -> ['j','u','m','p','y']
* 'jumpy'.each(/[r-z]/) -> ['u','y']
* 'jumpy'.each(/[r-z]/, function(m) {
* // Called twice: "u", "y"
* });
*
***/
'each': function(search, fn) {
var match, i;
if(isFunction(search)) {
fn = search;
search = /[\s\S]/g;
} else if(!search) {
search = /[\s\S]/g
} else if(isString(search)) {
search = regexp(escapeRegExp(search), 'gi');
} else if(isRegExp(search)) {
search = regexp(search.source, getRegExpFlags(search, 'g'));
}
match = this.match(search) || [];
if(fn) {
for(i = 0; i < match.length; i++) {
match[i] = fn.call(this, match[i], i, match) || match[i];
}
}
return match;
},
/***
* @method shift(<n>)
* @returns Array
* @short Shifts each character in the string <n> places in the character map.
* @example
*
* 'a'.shift(1) -> 'b'
* 'ク'.shift(1) -> 'グ'
*
***/
'shift': function(n) {
var result = '';
n = n || 0;
this.codes(function(c) {
result += chr(c + n);
});
return result;
},
/***
* @method codes([fn])
* @returns Array
* @short Runs callback [fn] against each character code in the string. Returns an array of character codes.
* @example
*
* 'jumpy'.codes() -> [106,117,109,112,121]
* 'jumpy'.codes(function(c) {
* // Called 5 times: 106, 117, 109, 112, 121
* });
*
***/
'codes': function(fn) {
var codes = [];
for(var i=0; i<this.length; i++) {
var code = this.charCodeAt(i);
codes.push(code);
if(fn) fn.call(this, code, i);
}
return codes;
},
/***
* @method chars([fn])
* @returns Array
* @short Runs callback [fn] against each character in the string. Returns an array of characters.
* @example
*
* 'jumpy'.chars() -> ['j','u','m','p','y']
* 'jumpy'.chars(function(c) {
* // Called 5 times: "j","u","m","p","y"
* });
*
***/
'chars': function(fn) {
return this.each(fn);
},
/***
* @method words([fn])
* @returns Array
* @short Runs callback [fn] against each word in the string. Returns an array of words.
* @extra A "word" here is defined as any sequence of non-whitespace characters.
* @example
*
* 'broken wear'.words() -> ['broken','wear']
* 'broken wear'.words(function(w) {
* // Called twice: "broken", "wear"
* });
*
***/
'words': function(fn) {
return this.trim().each(/\S+/g, fn);
},
/***
* @method lines([fn])
* @returns Array
* @short Runs callback [fn] against each line in the string. Returns an array of lines.
* @example
*
* 'broken wear\nand\njumpy jump'.lines() -> ['broken wear','and','jumpy jump']
* 'broken wear\nand\njumpy jump'.lines(function(l) {
* // Called three times: "broken wear", "and", "jumpy jump"
* });
*
***/
'lines': function(fn) {
return this.trim().each(/^.*$/gm, fn);
},
/***
* @method paragraphs([fn])
* @returns Array
* @short Runs callback [fn] against each paragraph in the string. Returns an array of paragraphs.
* @extra A paragraph here is defined as a block of text bounded by two or more line breaks.
* @example
*
* 'Once upon a time.\n\nIn the land of oz...'.paragraphs() -> ['Once upon a time.','In the land of oz...']
* 'Once upon a time.\n\nIn the land of oz...'.paragraphs(function(p) {
* // Called twice: "Once upon a time.", "In teh land of oz..."
* });
*
***/
'paragraphs': function(fn) {
var paragraphs = this.trim().split(/[\r\n]{2,}/);
paragraphs = paragraphs.map(function(p) {
if(fn) var s = fn.call(p);
return s ? s : p;
});
return paragraphs;
},
/***
* @method startsWith(<find>, [case] = true)
* @returns Boolean
* @short Returns true if the string starts with <find>.
* @extra <find> may be either a string or regex. Case sensitive if [case] is true.
* @example
*
* 'hello'.startsWith('hell') -> true
* 'hello'.startsWith(/[a-h]/) -> true
* 'hello'.startsWith('HELL') -> false
* 'hello'.startsWith('HELL', false) -> true
*
***/
'startsWith': function(reg, c) {
if(isUndefined(c)) c = true;
var source = isRegExp(reg) ? reg.source.replace('^', '') : escapeRegExp(reg);
return regexp('^' + source, c ? '' : 'i').test(this);
},
/***
* @method endsWith(<find>, [case] = true)
* @returns Boolean
* @short Returns true if the string ends with <find>.
* @extra <find> may be either a string or regex. Case sensitive if [case] is true.
* @example
*
* 'jumpy'.endsWith('py') -> true
* 'jumpy'.endsWith(/[q-z]/) -> true
* 'jumpy'.endsWith('MPY') -> false
* 'jumpy'.endsWith('MPY', false) -> true
*
***/
'endsWith': function(reg, c) {
if(isUndefined(c)) c = true;
var source = isRegExp(reg) ? reg.source.replace('$', '') : escapeRegExp(reg);
return regexp(source + '$', c ? '' : 'i').test(this);
},
/***
* @method isBlank()
* @returns Boolean
* @short Returns true if the string has a length of 0 or contains only whitespace.
* @example
*
* ''.isBlank() -> true
* ' '.isBlank() -> true
* 'noway'.isBlank() -> false
*
***/
'isBlank': function() {
return this.trim().length === 0;
},
/***
* @method has(<find>)
* @returns Boolean
* @short Returns true if the string matches <find>.
* @extra <find> may be a string or regex.
* @example
*
* 'jumpy'.has('py') -> true
* 'broken'.has(/[a-n]/) -> true
* 'broken'.has(/[s-z]/) -> false
*
***/
'has': function(find) {
return this.search(isRegExp(find) ? find : escapeRegExp(find)) !== -1;
},
/***
* @method add(<str>, [index] = length)
* @returns String
* @short Adds <str> at [index]. Negative values are also allowed.
* @extra %insert% is provided as an alias, and is generally more readable when using an index.
* @example
*
* 'schfifty'.add(' five') -> schfifty five
* 'dopamine'.insert('e', 3) -> dopeamine
* 'spelling eror'.insert('r', -3) -> spelling error
*
***/
'add': function(str, index) {
index = isUndefined(index) ? this.length : index;
return this.slice(0, index) + str + this.slice(index);
},
/***
* @method remove(<f>)
* @returns String
* @short Removes any part of the string that matches <f>.
* @extra <f> can be a string or a regex.
* @example
*
* 'schfifty five'.remove('f') -> 'schity ive'
* 'schfifty five'.remove(/[a-f]/g) -> 'shity iv'
*
***/
'remove': function(f) {
return this.replace(f, '');
},
/***
* @method reverse()
* @returns String
* @short Reverses the string.
* @example
*
* 'jumpy'.reverse() -> 'ypmuj'
* 'lucky charms'.reverse() -> 'smrahc ykcul'
*
***/
'reverse': function() {
return this.split('').reverse().join('');
},
/***
* @method compact()
* @returns String
* @short Compacts all white space in the string to a single space and trims the ends.
* @example
*
* 'too \n much \n space'.compact() -> 'too much space'
* 'enough \n '.compact() -> 'enought'
*
***/
'compact': function() {
return this.trim().replace(/([\r\n\s ])+/g, function(match, whitespace){
return whitespace === ' ' ? whitespace : ' ';
});
},
/***
* @method at(<index>, [loop] = true)
* @returns String or Array
* @short Gets the character(s) at a given index.
* @extra When [loop] is true, overshooting the end of the string (or the beginning) will begin counting from the other end. As an alternate syntax, passing multiple indexes will get the characters at those indexes.
* @example
*
* 'jumpy'.at(0) -> 'j'
* 'jumpy'.at(2) -> 'm'
* 'jumpy'.at(5) -> 'j'
* 'jumpy'.at(5, false) -> ''
* 'jumpy'.at(-1) -> 'y'
* 'lucky charms'.at(2,4,6,8) -> ['u','k','y',c']
*
***/
'at': function() {
return entryAtIndex(this, arguments, true);
},
/***
* @method from([index] = 0)
* @returns String
* @short Returns a section of the string starting from [index].
* @example
*
* 'lucky charms'.from() -> 'lucky charms'
* 'lucky charms'.from(7) -> 'harms'
*
***/
'from': function(num) {
return this.slice(num);
},
/***
* @method to([index] = end)
* @returns String
* @short Returns a section of the string ending at [index].
* @example
*
* 'lucky charms'.to() -> 'lucky charms'
* 'lucky charms'.to(7) -> 'lucky ch'
*
***/
'to': function(num) {
if(isUndefined(num)) num = this.length;
return this.slice(0, num);
},
/***
* @method dasherize()
* @returns String
* @short Converts underscores and camel casing to hypens.
* @example
*
* 'a_farewell_to_arms'.dasherize() -> 'a-farewell-to-arms'
* 'capsLock'.dasherize() -> 'caps-lock'
*
***/
'dasherize': function() {
return this.underscore().replace(/_/g, '-');
},
/***
* @method underscore()
* @returns String
* @short Converts hyphens and camel casing to underscores.
* @example
*
* 'a-farewell-to-arms'.underscore() -> 'a_farewell_to_arms'
* 'capsLock'.underscore() -> 'caps_lock'
*
***/
'underscore': function() {
return this
.replace(/[-\s]+/g, '_')
.replace(string.Inflector && string.Inflector.acronymRegExp, function(acronym, index) {
return (index > 0 ? '_' : '') + acronym.toLowerCase();
})
.replace(/([A-Z\d]+)([A-Z][a-z])/g,'$1_$2')
.replace(/([a-z\d])([A-Z])/g,'$1_$2')
.toLowerCase();
},
/***
* @method camelize([first] = true)
* @returns String
* @short Converts underscores and hyphens to camel case. If [first] is true the first letter will also be capitalized.
* @extra If the Inflections package is included acryonyms can also be defined that will be used when camelizing.
* @example
*
* 'caps_lock'.camelize() -> 'CapsLock'
* 'moz-border-radius'.camelize() -> 'MozBorderRadius'
* 'moz-border-radius'.camelize(false) -> 'mozBorderRadius'
*
***/
'camelize': function(first) {
return this.underscore().replace(/(^|_)([^_]+)/g, function(match, pre, word, index) {
var acronym = getAcronym(word), capitalize = first !== false || index > 0;
if(acronym) return capitalize ? acronym : acronym.toLowerCase();
return capitalize ? word.capitalize() : word;
});
},
/***
* @method spacify()
* @returns String
* @short Converts camel case, underscores, and hyphens to a properly spaced string.
* @example
*
* 'camelCase'.spacify() -> 'camel case'
* 'an-ugly-string'.spacify() -> 'an ugly string'
* 'oh-no_youDid-not'.spacify().capitalize(true) -> 'something else'
*
***/
'spacify': function() {
return this.underscore().replace(/_/g, ' ');
},
/***
* @method stripTags([tag1], [tag2], ...)
* @returns String
* @short Strips all HTML tags from the string.
* @extra Tags to strip may be enumerated in the parameters, otherwise will strip all.
* @example
*
* '<p>just <b>some</b> text</p>'.stripTags() -> 'just some text'
* '<p>just <b>some</b> text</p>'.stripTags('p') -> 'just <b>some</b> text'
*
***/
'stripTags': function() {
var str = this, args = arguments.length > 0 ? arguments : [''];
multiArgs(args, function(tag) {
str = str.replace(regexp('<\/?' + escapeRegExp(tag) + '[^<>]*>', 'gi'), '');
});
return str;
},
/***
* @method removeTags([tag1], [tag2], ...)
* @returns String
* @short Removes all HTML tags and their contents from the string.
* @extra Tags to remove may be enumerated in the parameters, otherwise will remove all.
* @example
*
* '<p>just <b>some</b> text</p>'.removeTags() -> ''
* '<p>just <b>some</b> text</p>'.removeTags('b') -> '<p>just text</p>'
*
***/
'removeTags': function() {
var str = this, args = arguments.length > 0 ? arguments : ['\\S+'];
multiArgs(args, function(t) {
var reg = regexp('<(' + t + ')[^<>]*(?:\\/>|>.*?<\\/\\1>)', 'gi');
str = str.replace(reg, '');
});
return str;
},
/***
* @method truncate(<length>, [split] = true, [from] = 'right', [ellipsis] = '...')
* @returns Object
* @short Truncates a string.
* @extra If [split] is %false%, will not split words up, and instead discard the word where the truncation occurred. [from] can also be %"middle"% or %"left"%.
* @example
*
* 'just sittin on the dock of the bay'.truncate(20) -> 'just sittin on the do...'
* 'just sittin on the dock of the bay'.truncate(20, false) -> 'just sittin on the...'
* 'just sittin on the dock of the bay'.truncate(20, true, 'middle') -> 'just sitt...of the bay'
* 'just sittin on the dock of the bay'.truncate(20, true, 'left') -> '...the dock of the bay'
*
***/
'truncate': function(length, split, from, ellipsis) {
var pos,
prepend = '',
append = '',
str = this.toString(),
chars = '[' + getTrimmableCharacters() + ']+',
space = '[^' + getTrimmableCharacters() + ']*',
reg = regexp(chars + space + '$');
ellipsis = isUndefined(ellipsis) ? '...' : string(ellipsis);
if(str.length <= length) {
return str;
}
switch(from) {
case 'left':
pos = str.length - length;
prepend = ellipsis;
str = str.slice(pos);
reg = regexp('^' + space + chars);
break;
case 'middle':
pos = floor(length / 2);
append = ellipsis + str.slice(str.length - pos).trimLeft();
str = str.slice(0, pos);
break;
default:
pos = length;
append = ellipsis;
str = str.slice(0, pos);
}
if(split === false && this.slice(pos, pos + 1).match(/\S/)) {
str = str.remove(reg);
}
return prepend + str + append;
},
/***
* @method pad[Side](<padding> = '', [num] = 1)
* @returns String
* @short Pads either/both sides of the string.
* @extra [num] is the number of characters on each side, and [padding] is the character to pad with.
*
* @set
* pad
* padLeft
* padRight
*
* @example
*
* 'wasabi'.pad('-') -> '-wasabi-'
* 'wasabi'.pad('-', 2) -> '--wasabi--'
* 'wasabi'.padLeft('-', 2) -> '--wasabi'
* 'wasabi'.padRight('-', 2) -> 'wasabi--'
*
***/
'pad': function(padding, num) {
return repeatString(num, padding) + this + repeatString(num, padding);
},
'padLeft': function(padding, num) {
return repeatString(num, padding) + this;
},
'padRight': function(padding, num) {
return this + repeatString(num, padding);
},
/***
* @method first([n] = 1)
* @returns String
* @short Returns the first [n] characters of the string.
* @example
*
* 'lucky charms'.first() -> 'l'
* 'lucky charms'.first(3) -> 'luc'
*
***/
'first': function(num) {
if(isUndefined(num)) num = 1;
return this.substr(0, num);
},
/***
* @method last([n] = 1)
* @returns String
* @short Returns the last [n] characters of the string.
* @example
*
* 'lucky charms'.last() -> 's'
* 'lucky charms'.last(3) -> 'rms'
*
***/
'last': function(num) {
if(isUndefined(num)) num = 1;
var start = this.length - num < 0 ? 0 : this.length - num;
return this.substr(start);
},
/***
* @method repeat([num] = 0)
* @returns String
* @short Returns the string repeated [num] times.
* @example
*
* 'jumpy'.repeat(2) -> 'jumpyjumpy'
* 'a'.repeat(5) -> 'aaaaa'
*
***/
'repeat': function(num) {
var str = '', i = 0;
if(isNumber(num) && num > 0) {
while(i < num) {
str += this;
i++;
}
}
return str;
},
/***
* @method toNumber([base] = 10)
* @returns Number
* @short Converts the string into a number.
* @extra Any value with a "." fill be converted to a floating point value, otherwise an integer.
* @example
*
* '153'.toNumber() -> 153
* '12,000'.toNumber() -> 12000
* '10px'.toNumber() -> 10
* 'ff'.toNumber(16) -> 255
*
***/
'toNumber': function(base) {
var str = this.replace(/,/g, '');
return str.match(/\./) ? parseFloat(str) : parseInt(str, base || 10);
},
/***
* @method capitalize([all] = false)
* @returns String
* @short Capitalizes the first character in the string.
* @extra If [all] is true, all words in the string will be capitalized.
* @example
*
* 'hello'.capitalize() -> 'Hello'
* 'hello kitty'.capitalize() -> 'Hello kitty'
* 'hello kitty'.capitalize(true) -> 'Hello Kitty'
*
*
***/
'capitalize': function(all) {
var lastResponded;
return this.toLowerCase().replace(all ? /[\s\S]/g : /^\S/, function(lower) {
var upper = lower.toUpperCase(), result;
result = lastResponded ? lower : upper;
lastResponded = upper !== lower;
return result;
});
},
/***
* @method assign(<obj1>, <obj2>, ...)
* @returns String
* @short Assigns variables to tokens in a string.
* @extra If an object is passed, it's properties can be assigned using the object's keys. If a non-object (string, number, etc.) is passed it can be accessed by the argument number beginning with 1 (as with regex tokens). Multiple objects can be passed and will be merged together (original objects are unaffected).
* @example
*
* 'Welcome, Mr. {name}.'.assign({ name: 'Franklin' }) -> 'Welcome, Mr. Franklin.'
* 'You are {1} years old today.'.assign(14) -> 'You are 14 years old today.'
* '{n} and {r}'.assign({ n: 'Cheech' }, { r: 'Chong' }) -> 'Cheech and Chong'
*
***/
'assign': function() {
var assign = {};
multiArgs(arguments, function(a, i) {
if(isObject(a)) {
simpleMerge(assign, a);
} else {
assign[i + 1] = a;
}
});
return this.replace(/\{([^{]+?)\}/g, function(m, key) {
return hasOwnProperty(assign, key) ? assign[key] : m;
});
},
/***
* @method namespace([init] = global)
* @returns Mixed
* @short Finds the namespace or property indicated by the string.
* @extra [init] can be passed to provide a starting context, otherwise the global context will be used. If any level returns a falsy value, that will be the final result.
* @example
*
* 'Path.To.Namespace'.namespace() -> Path.To.Namespace
* '$.fn'.namespace() -> $.fn
*
***/
'namespace': function(context) {
context = context || globalContext;
iterateOverObject(this.split('.'), function(i,s) {
return !!(context = context[s]);
});
return context;
}
});
// Aliases
extend(string, true, false, {
/***
* @method insert()
* @alias add
*
***/
'insert': string.prototype.add
});
buildBase64('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=');
/***
*
* @package Inflections
* @dependency string
* @description Pluralization similar to ActiveSupport including uncountable words and acronyms. Humanized and URL-friendly strings.
*
***/
/***
* String module
*
***/
var plurals = [],
singulars = [],
uncountables = [],
humans = [],
acronyms = {},
Downcased,
Inflector;
function removeFromArray(arr, find) {
var index = arr.indexOf(find);
if(index > -1) {
arr.splice(index, 1);
}
}
function removeFromUncountablesAndAddTo(arr, rule, replacement) {
if(isString(rule)) {
removeFromArray(uncountables, rule);
}
removeFromArray(uncountables, replacement);
arr.unshift({ rule: rule, replacement: replacement })
}
function paramMatchesType(param, type) {
return param == type || param == 'all' || !param;
}
function isUncountable(word) {
return uncountables.some(function(uncountable) {
return new regexp('\\b' + uncountable + '$', 'i').test(word);
});
}
function inflect(word, pluralize) {
word = isString(word) ? word.toString() : '';
if(word.isBlank() || isUncountable(word)) {
return word;
} else {
return runReplacements(word, pluralize ? plurals : singulars);
}
}
function runReplacements(word, table) {
iterateOverObject(table, function(i, inflection) {
if(word.match(inflection.rule)) {
word = word.replace(inflection.rule, inflection.replacement);
return false;
}
});
return word;
}
function capitalize(word) {
return word.replace(/^\W*[a-z]/, function(w){
return w.toUpperCase();
});
}
Inflector = {
/*
* Specifies a new acronym. An acronym must be specified as it will appear in a camelized string. An underscore
* string that contains the acronym will retain the acronym when passed to %camelize%, %humanize%, or %titleize%.
* A camelized string that contains the acronym will maintain the acronym when titleized or humanized, and will
* convert the acronym into a non-delimited single lowercase word when passed to String#underscore.
*
* Examples:
* String.Inflector.acronym('HTML')
* 'html'.titleize() -> 'HTML'
* 'html'.camelize() -> 'HTML'
* 'MyHTML'.underscore() -> 'my_html'
*
* The acronym, however, must occur as a delimited unit and not be part of another word for conversions to recognize it:
*
* String.Inflector.acronym('HTTP')
* 'my_http_delimited'.camelize() -> 'MyHTTPDelimited'
* 'https'.camelize() -> 'Https', not 'HTTPs'
* 'HTTPS'.underscore() -> 'http_s', not 'https'
*
* String.Inflector.acronym('HTTPS')
* 'https'.camelize() -> 'HTTPS'
* 'HTTPS'.underscore() -> 'https'
*
* Note: Acronyms that are passed to %pluralize% will no longer be recognized, since the acronym will not occur as
* a delimited unit in the pluralized result. To work around this, you must specify the pluralized form as an
* acronym as well:
*
* String.Inflector.acronym('API')
* 'api'.pluralize().camelize() -> 'Apis'
*
* String.Inflector.acronym('APIs')
* 'api'.pluralize().camelize() -> 'APIs'
*
* %acronym% may be used to specify any word that contains an acronym or otherwise needs to maintain a non-standard
* capitalization. The only restriction is that the word must begin with a capital letter.
*
* Examples:
* String.Inflector.acronym('RESTful')
* 'RESTful'.underscore() -> 'restful'
* 'RESTfulController'.underscore() -> 'restful_controller'
* 'RESTfulController'.titleize() -> 'RESTful Controller'
* 'restful'.camelize() -> 'RESTful'
* 'restful_controller'.camelize() -> 'RESTfulController'
*
* String.Inflector.acronym('McDonald')
* 'McDonald'.underscore() -> 'mcdonald'
* 'mcdonald'.camelize() -> 'McDonald'
*/
'acronym': function(word) {
acronyms[word.toLowerCase()] = word;
var all = object.keys(acronyms).map(function(key) {
return acronyms[key];
});
Inflector.acronymRegExp = regexp(all.join('|'), 'g');
},
/*
* Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression.
* The replacement should always be a string that may include references to the matched data from the rule.
*/
'plural': function(rule, replacement) {
removeFromUncountablesAndAddTo(plurals, rule, replacement);
},
/*
* Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression.
* The replacement should always be a string that may include references to the matched data from the rule.
*/
'singular': function(rule, replacement) {
removeFromUncountablesAndAddTo(singulars, rule, replacement);
},
/*
* Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used
* for strings, not regular expressions. You simply pass the irregular in singular and plural form.
*
* Examples:
* String.Inflector.irregular('octopus', 'octopi')
* String.Inflector.irregular('person', 'people')
*/
'irregular': function(singular, plural) {
var singularFirst = singular.first(),
singularRest = singular.from(1),
pluralFirst = plural.first(),
pluralRest = plural.from(1),
pluralFirstUpper = pluralFirst.toUpperCase(),
pluralFirstLower = pluralFirst.toLowerCase(),
singularFirstUpper = singularFirst.toUpperCase(),
singularFirstLower = singularFirst.toLowerCase();
removeFromArray(uncountables, singular);
removeFromArray(uncountables, plural);
if(singularFirstUpper == pluralFirstUpper) {
Inflector.plural(new regexp('({1}){2}$'.assign(singularFirst, singularRest), 'i'), '$1' + pluralRest);
Inflector.plural(new regexp('({1}){2}$'.assign(pluralFirst, pluralRest), 'i'), '$1' + pluralRest);
Inflector.singular(new regexp('({1}){2}$'.assign(pluralFirst, pluralRest), 'i'), '$1' + singularRest);
} else {
Inflector.plural(new regexp('{1}{2}$'.assign(singularFirstUpper, singularRest)), pluralFirstUpper + pluralRest);
Inflector.plural(new regexp('{1}{2}$'.assign(singularFirstLower, singularRest)), pluralFirstLower + pluralRest);
Inflector.plural(new regexp('{1}{2}$'.assign(pluralFirstUpper, pluralRest)), pluralFirstUpper + pluralRest);
Inflector.plural(new regexp('{1}{2}$'.assign(pluralFirstLower, pluralRest)), pluralFirstLower + pluralRest);
Inflector.singular(new regexp('{1}{2}$'.assign(pluralFirstUpper, pluralRest)), singularFirstUpper + singularRest);
Inflector.singular(new regexp('{1}{2}$'.assign(pluralFirstLower, pluralRest)), singularFirstLower + singularRest);
}
},
/*
* Add uncountable words that shouldn't be attempted inflected.
*
* Examples:
* String.Inflector.uncountable('money')
* String.Inflector.uncountable('money', 'information')
* String.Inflector.uncountable(['money', 'information', 'rice'])
*/
'uncountable': function(first) {
var add = array.isArray(first) ? first : multiArgs(arguments);
uncountables = uncountables.concat(add);
},
/*
* Specifies a humanized form of a string by a regular expression rule or by a string mapping.
* When using a regular expression based replacement, the normal humanize formatting is called after the replacement.
* When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name')
*
* Examples:
* String.Inflector.human(/_cnt$/i, '_count')
* String.Inflector.human('legacy_col_person_name', 'Name')
*/
'human': function(rule, replacement) {
humans.unshift({ rule: rule, replacement: replacement })
},
/*
* Clears the loaded inflections within a given scope (default is 'all').
* Options are: 'all', 'plurals', 'singulars', 'uncountables', 'humans'.
*
* Examples:
* String.Inflector.clear('all')
* String.Inflector.clear('plurals')
*/
'clear': function(type) {
if(paramMatchesType(type, 'singulars')) singulars = [];
if(paramMatchesType(type, 'plurals')) plurals = [];
if(paramMatchesType(type, 'uncountables')) uncountables = [];
if(paramMatchesType(type, 'humans')) humans = [];
if(paramMatchesType(type, 'acronyms')) acronyms = {};
}
};
Downcased = [
'and', 'or', 'nor', 'a', 'an', 'the', 'so', 'but', 'to', 'of', 'at',
'by', 'from', 'into', 'on', 'onto', 'off', 'out', 'in', 'over',
'with', 'for'
];
Inflector.plural(/$/, 's');
Inflector.plural(/s$/gi, 's');
Inflector.plural(/(ax|test)is$/gi, '$1es');
Inflector.plural(/(octop|vir|fung|foc|radi|alumn)(i|us)$/gi, '$1i');
Inflector.plural(/(census|alias|status)$/gi, '$1es');
Inflector.plural(/(bu)s$/gi, '$1ses');
Inflector.plural(/(buffal|tomat)o$/gi, '$1oes');
Inflector.plural(/([ti])um$/gi, '$1a');
Inflector.plural(/([ti])a$/gi, '$1a');
Inflector.plural(/sis$/gi, 'ses');
Inflector.plural(/f+e?$/gi, 'ves');
Inflector.plural(/(cuff|roof)$/gi, '$1s');
Inflector.plural(/([ht]ive)$/gi, '$1s');
Inflector.plural(/([^aeiouy]o)$/gi, '$1es');
Inflector.plural(/([^aeiouy]|qu)y$/gi, '$1ies');
Inflector.plural(/(x|ch|ss|sh)$/gi, '$1es');
Inflector.plural(/(matr|vert|ind)(?:ix|ex)$/gi, '$1ices');
Inflector.plural(/([ml])ouse$/gi, '$1ice');
Inflector.plural(/([ml])ice$/gi, '$1ice');
Inflector.plural(/^(ox)$/gi, '$1en');
Inflector.plural(/^(oxen)$/gi, '$1');
Inflector.plural(/(quiz)$/gi, '$1zes');
Inflector.plural(/(phot|cant|hom|zer|pian|portic|pr|quart|kimon)o$/gi, '$1os');
Inflector.plural(/(craft)$/gi, '$1');
Inflector.plural(/([ft])[eo]{2}(th?)$/gi, '$1ee$2');
Inflector.singular(/s$/gi, '');
Inflector.singular(/([pst][aiu]s)$/gi, '$1');
Inflector.singular(/([aeiouy])ss$/gi, '$1ss');
Inflector.singular(/(n)ews$/gi, '$1ews');
Inflector.singular(/([ti])a$/gi, '$1um');
Inflector.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/gi, '$1$2sis');
Inflector.singular(/(^analy)ses$/gi, '$1sis');
Inflector.singular(/(i)(f|ves)$/i, '$1fe');
Inflector.singular(/([aeolr]f?)(f|ves)$/i, '$1f');
Inflector.singular(/([ht]ive)s$/gi, '$1');
Inflector.singular(/([^aeiouy]|qu)ies$/gi, '$1y');
Inflector.singular(/(s)eries$/gi, '$1eries');
Inflector.singular(/(m)ovies$/gi, '$1ovie');
Inflector.singular(/(x|ch|ss|sh)es$/gi, '$1');
Inflector.singular(/([ml])(ous|ic)e$/gi, '$1ouse');
Inflector.singular(/(bus)(es)?$/gi, '$1');
Inflector.singular(/(o)es$/gi, '$1');
Inflector.singular(/(shoe)s?$/gi, '$1');
Inflector.singular(/(cris|ax|test)[ie]s$/gi, '$1is');
Inflector.singular(/(octop|vir|fung|foc|radi|alumn)(i|us)$/gi, '$1us');
Inflector.singular(/(census|alias|status)(es)?$/gi, '$1');
Inflector.singular(/^(ox)(en)?/gi, '$1');
Inflector.singular(/(vert|ind)(ex|ices)$/gi, '$1ex');
Inflector.singular(/(matr)(ix|ices)$/gi, '$1ix');
Inflector.singular(/(quiz)(zes)?$/gi, '$1');
Inflector.singular(/(database)s?$/gi, '$1');
Inflector.singular(/ee(th?)$/gi, 'oo$1');
Inflector.irregular('person', 'people');
Inflector.irregular('man', 'men');
Inflector.irregular('child', 'children');
Inflector.irregular('sex', 'sexes');
Inflector.irregular('move', 'moves');
Inflector.irregular('save', 'saves');
Inflector.irregular('save', 'saves');
Inflector.irregular('cow', 'kine');
Inflector.irregular('goose', 'geese');
Inflector.irregular('zombie', 'zombies');
Inflector.uncountable('equipment,information,rice,money,species,series,fish,sheep,jeans'.split(','));
extend(string, true, false, {
/***
* @method pluralize()
* @returns String
* @short Returns the plural form of the word in the string.
* @example
*
* 'post'.pluralize() -> 'posts'
* 'octopus'.pluralize() -> 'octopi'
* 'sheep'.pluralize() -> 'sheep'
* 'words'.pluralize() -> 'words'
* 'CamelOctopus'.pluralize() -> 'CamelOctopi'
*
***/
'pluralize': function() {
return inflect(this, true);
},
/***
* @method singularize()
* @returns String
* @short The reverse of String#pluralize. Returns the singular form of a word in a string.
* @example
*
* 'posts'.singularize() -> 'post'
* 'octopi'.singularize() -> 'octopus'
* 'sheep'.singularize() -> 'sheep'
* 'word'.singularize() -> 'word'
* 'CamelOctopi'.singularize() -> 'CamelOctopus'
*
***/
'singularize': function() {
return inflect(this, false);
},
/***
* @method humanize()
* @returns String
* @short Creates a human readable string.
* @extra Capitalizes the first word and turns underscores into spaces and strips a trailing '_id', if any. Like String#titleize, this is meant for creating pretty output.
* @example
*
* 'employee_salary'.humanize() -> 'Employee salary'
* 'author_id'.humanize() -> 'Author'
*
***/
'humanize': function() {
var str = runReplacements(this, humans);
str = str.replace(/_id$/g, '');
str = str.replace(/(_)?([a-z\d]*)/gi, function(match, _, word){
return (_ ? ' ' : '') + (acronyms[word] || word.toLowerCase());
});
return capitalize(str);
},
/***
* @method titleize()
* @returns String
* @short Creates a title version of the string.
* @extra Capitalizes all the words and replaces some characters in the string to create a nicer looking title. String#titleize is meant for creating pretty output.
* @example
*
* 'man from the boondocks'.titleize() -> 'Man from the Boondocks'
* 'x-men: the last stand'.titleize() -> 'X Men: The Last Stand'
* 'TheManWithoutAPast'.titleize() -> 'The Man Without a Past'
* 'raiders_of_the_lost_ark'.titleize() -> 'Raiders of the Lost Ark'
*
***/
'titleize': function() {
var fullStopPunctuation = /[.:;!]$/, hasPunctuation, lastHadPunctuation, isFirstOrLast;
return this.spacify().humanize().words(function(word, index, words) {
hasPunctuation = fullStopPunctuation.test(word);
isFirstOrLast = index == 0 || index == words.length - 1 || hasPunctuation || lastHadPunctuation;
lastHadPunctuation = hasPunctuation;
if(isFirstOrLast || Downcased.indexOf(word) === -1) {
return capitalize(word);
} else {
return word;
}
}).join(' ');
},
/***
* @method parameterize()
* @returns String
* @short Replaces special characters in a string so that it may be used as part of a pretty URL.
* @example
*
* 'hell, no!'.parameterize() -> 'hell-no'
*
***/
'parameterize': function(separator) {
var str = this;
if(separator === undefined) separator = '-';
if(str.normalize) {
str = str.normalize();
}
str = str.replace(/[^a-z0-9\-_]+/gi, separator)
if(separator) {
str = str.replace(new regexp('^{sep}+|{sep}+$|({sep}){sep}+'.assign({ 'sep': escapeRegExp(separator) }), 'g'), '$1');
}
return encodeURI(str.toLowerCase());
}
});
string.Inflector = Inflector;
string.Inflector.acronyms = acronyms;
/***
*
* @package Language
* @dependency string
* @description Normalizing accented characters, character width conversion, Hiragana and Katakana conversions.
*
***/
/***
* String module
*
***/
var NormalizeMap,
NormalizeReg = '',
NormalizeSource;
/***
* @method has[Script]()
* @returns Boolean
* @short Returns true if the string contains any characters in that script.
*
* @set
* hasArabic
* hasCyrillic
* hasGreek
* hasHangul
* hasHan
* hasKanji
* hasHebrew
* hasHiragana
* hasKana
* hasKatakana
* hasLatin
* hasThai
* hasDevanagari
*
* @example
*
* 'أتكلم'.hasArabic() -> true
* 'визит'.hasCyrillic() -> true
* '잘 먹겠습니다!'.hasHangul() -> true
* 'ミックスです'.hasKatakana() -> true
* "l'année".hasLatin() -> true
*
***
* @method is[Script]()
* @returns Boolean
* @short Returns true if the string contains only characters in that script. Whitespace is ignored.
*
* @set
* isArabic
* isCyrillic
* isGreek
* isHangul
* isHan
* isKanji
* isHebrew
* isHiragana
* isKana
* isKatakana
* isKatakana
* isThai
* isDevanagari
*
* @example
*
* 'أتكلم'.isArabic() -> true
* 'визит'.isCyrillic() -> true
* '잘 먹겠습니다!'.isHangul() -> true
* 'ミックスです'.isKatakana() -> false
* "l'année".isLatin() -> true
*
***/
var unicodeScripts = [
{ names: ['Arabic'], source: '\u0600-\u06FF' },
{ names: ['Cyrillic'], source: '\u0400-\u04FF' },
{ names: ['Devanagari'], source: '\u0900-\u097F' },
{ names: ['Greek'], source: '\u0370-\u03FF' },
{ names: ['Hangul'], source: '\uAC00-\uD7AF\u1100-\u11FF' },
{ names: ['Han','Kanji'], source: '\u4E00-\u9FFF\uF900-\uFAFF' },
{ names: ['Hebrew'], source: '\u0590-\u05FF' },
{ names: ['Hiragana'], source: '\u3040-\u309F\u30FB-\u30FC' },
{ names: ['Kana'], source: '\u3040-\u30FF\uFF61-\uFF9F' },
{ names: ['Katakana'], source: '\u30A0-\u30FF\uFF61-\uFF9F' },
{ names: ['Latin'], source: '\u0001-\u007F\u0080-\u00FF\u0100-\u017F\u0180-\u024F' },
{ names: ['Thai'], source: '\u0E00-\u0E7F' }
];
function buildUnicodeScripts() {
unicodeScripts.forEach(function(s) {
var is = regexp('^['+s.source+'\\s]+$');
var has = regexp('['+s.source+']');
s.names.forEach(function(name) {
defineProperty(string.prototype, 'is' + name, function() { return is.test(this.trim()); });
defineProperty(string.prototype, 'has' + name, function() { return has.test(this); });
});
});
}
// Support for converting character widths and katakana to hiragana.
var widthConversionRanges = [
{ type: 'a', shift: 65248, start: 65, end: 90 },
{ type: 'a', shift: 65248, start: 97, end: 122 },
{ type: 'n', shift: 65248, start: 48, end: 57 },
{ type: 'p', shift: 65248, start: 33, end: 47 },
{ type: 'p', shift: 65248, start: 58, end: 64 },
{ type: 'p', shift: 65248, start: 91, end: 96 },
{ type: 'p', shift: 65248, start: 123, end: 126 }
];
var WidthConversionTable;
var allHankaku = /[\u0020-\u00A5]|[\uFF61-\uFF9F][゙゚]?/g;
var allZenkaku = /[\u3000-\u301C]|[\u301A-\u30FC]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g;
var hankakuPunctuation = '。、「」¥¢£';
var zenkakuPunctuation = '。、「」¥¢£';
var voicedKatakana = /[カキクケコサシスセソタチツテトハヒフヘホ]/;
var semiVoicedKatakana = /[ハヒフヘホヲ]/;
var hankakuKatakana = 'アイウエオァィゥェォカキクケコサシスセソタチツッテトナニヌネノハヒフヘホマミムメモヤャユュヨョラリルレロワヲンー・';
var zenkakuKatakana = 'アイウエオァィゥェォカキクケコサシスセソタチツッテトナニヌネノハヒフヘホマミムメモヤャユュヨョラリルレロワヲンー・';
function convertCharacterWidth(str, args, reg, type) {
if(!WidthConversionTable) {
buildWidthConversionTables();
}
var mode = multiArgs(args).join(''), table = WidthConversionTable[type];
mode = mode.replace(/all/, '').replace(/(\w)lphabet|umbers?|atakana|paces?|unctuation/g, '$1');
return str.replace(reg, function(c) {
if(table[c] && (!mode || mode.has(table[c].type))) {
return table[c].to;
} else {
return c;
}
});
}
function buildWidthConversionTables() {
var hankaku;
WidthConversionTable = {
'zenkaku': {},
'hankaku': {}
};
widthConversionRanges.forEach(function(r) {
getRange(r.start, r.end, function(n) {
setWidthConversion(r.type, chr(n), chr(n + r.shift));
});
});
zenkakuKatakana.each(function(c, i) {
hankaku = hankakuKatakana.charAt(i);
setWidthConversion('k', hankaku, c);
if(c.match(voicedKatakana)) {
setWidthConversion('k', hankaku + '゙', c.shift(1));
}
if(c.match(semiVoicedKatakana)) {
setWidthConversion('k', hankaku + '゚', c.shift(2));
}
});
zenkakuPunctuation.each(function(c, i) {
setWidthConversion('p', hankakuPunctuation.charAt(i), c);
});
setWidthConversion('k', 'ヴ', 'ヴ');
setWidthConversion('k', 'ヺ', 'ヺ');
setWidthConversion('s', ' ', ' ');
}
function setWidthConversion(type, half, full) {
WidthConversionTable['zenkaku'][half] = { type: type, to: full };
WidthConversionTable['hankaku'][full] = { type: type, to: half };
}
function buildNormalizeMap() {
NormalizeMap = {};
iterateOverObject(NormalizeSource, function(normalized, str) {
str.split('').forEach(function(character) {
NormalizeMap[character] = normalized;
});
NormalizeReg += str;
});
NormalizeReg = regexp('[' + NormalizeReg + ']', 'g');
}
NormalizeSource = {
'A': 'AⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ',
'B': 'BⒷBḂḄḆɃƂƁ',
'C': 'CⒸCĆĈĊČÇḈƇȻꜾ',
'D': 'DⒹDḊĎḌḐḒḎĐƋƊƉꝹ',
'E': 'EⒺEÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎ',
'F': 'FⒻFḞƑꝻ',
'G': 'GⒼGǴĜḠĞĠǦĢǤƓꞠꝽꝾ',
'H': 'HⒽHĤḢḦȞḤḨḪĦⱧⱵꞍ',
'I': 'IⒾIÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ',
'J': 'JⒿJĴɈ',
'K': 'KⓀKḰǨḲĶḴƘⱩꝀꝂꝄꞢ',
'L': 'LⓁLĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ',
'M': 'MⓂMḾṀṂⱮƜ',
'N': 'NⓃNǸŃÑṄŇṆŅṊṈȠƝꞐꞤ',
'O': 'OⓄOÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ',
'P': 'PⓅPṔṖƤⱣꝐꝒꝔ',
'Q': 'QⓆQꝖꝘɊ',
'R': 'RⓇRŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ',
'S': 'SⓈSẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ',
'T': 'TⓉTṪŤṬȚŢṰṮŦƬƮȾꞆ',
'U': 'UⓊUÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ',
'V': 'VⓋVṼṾƲꝞɅ',
'W': 'WⓌWẀẂŴẆẄẈⱲ',
'X': 'XⓍXẊẌ',
'Y': 'YⓎYỲÝŶỸȲẎŸỶỴƳɎỾ',
'Z': 'ZⓏZŹẐŻŽẒẔƵȤⱿⱫꝢ',
'a': 'aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐ',
'b': 'bⓑbḃḅḇƀƃɓ',
'c': 'cⓒcćĉċčçḉƈȼꜿↄ',
'd': 'dⓓdḋďḍḑḓḏđƌɖɗꝺ',
'e': 'eⓔeèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇɛǝ',
'f': 'fⓕfḟƒꝼ',
'g': 'gⓖgǵĝḡğġǧģǥɠꞡᵹꝿ',
'h': 'hⓗhĥḣḧȟḥḩḫẖħⱨⱶɥ',
'i': 'iⓘiìíîĩīĭïḯỉǐȉȋịįḭɨı',
'j': 'jⓙjĵǰɉ',
'k': 'kⓚkḱǩḳķḵƙⱪꝁꝃꝅꞣ',
'l': 'lⓛlŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇ',
'm': 'mⓜmḿṁṃɱɯ',
'n': 'nⓝnǹńñṅňṇņṋṉƞɲʼnꞑꞥ',
'o': 'oⓞoòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿɔꝋꝍɵ',
'p': 'pⓟpṕṗƥᵽꝑꝓꝕ',
'q': 'qⓠqɋꝗꝙ',
'r': 'rⓡrŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ',
's': 'sⓢsśṥŝṡšṧṣṩșşȿꞩꞅẛ',
't': 'tⓣtṫẗťṭțţṱṯŧƭʈⱦꞇ',
'u': 'uⓤuùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ',
'v': 'vⓥvṽṿʋꝟʌ',
'w': 'wⓦwẁẃŵẇẅẘẉⱳ',
'x': 'xⓧxẋẍ',
'y': 'yⓨyỳýŷỹȳẏÿỷẙỵƴɏỿ',
'z': 'zⓩzźẑżžẓẕƶȥɀⱬꝣ',
'AA': 'Ꜳ',
'AE': 'ÆǼǢ',
'AO': 'Ꜵ',
'AU': 'Ꜷ',
'AV': 'ꜸꜺ',
'AY': 'Ꜽ',
'DZ': 'DZDŽ',
'Dz': 'DzDž',
'LJ': 'LJ',
'Lj': 'Lj',
'NJ': 'NJ',
'Nj': 'Nj',
'OI': 'Ƣ',
'OO': 'Ꝏ',
'OU': 'Ȣ',
'TZ': 'Ꜩ',
'VY': 'Ꝡ',
'aa': 'ꜳ',
'ae': 'æǽǣ',
'ao': 'ꜵ',
'au': 'ꜷ',
'av': 'ꜹꜻ',
'ay': 'ꜽ',
'dz': 'dzdž',
'hv': 'ƕ',
'lj': 'lj',
'nj': 'nj',
'oi': 'ƣ',
'ou': 'ȣ',
'oo': 'ꝏ',
'ss': 'ß',
'tz': 'ꜩ',
'vy': 'ꝡ'
};
extend(string, true, false, {
/***
* @method normalize()
* @returns String
* @short Returns the string with accented and non-standard Latin-based characters converted into ASCII approximate equivalents.
* @example
*
* 'á'.normalize() -> 'a'
* 'Ménage à trois'.normalize() -> 'Menage a trois'
* 'Volkswagen'.normalize() -> 'Volkswagen'
* 'FULLWIDTH'.normalize() -> 'FULLWIDTH'
*
***/
'normalize': function() {
if(!NormalizeMap) {
buildNormalizeMap();
}
return this.replace(NormalizeReg, function(character) {
return NormalizeMap[character];
});
},
/***
* @method hankaku([mode] = 'all')
* @returns String
* @short Converts full-width characters (zenkaku) to half-width (hankaku).
* @extra [mode] accepts any combination of "a" (alphabet), "n" (numbers), "k" (katakana), "s" (spaces), "p" (punctuation), or "all".
* @example
*
* 'タロウ YAMADAです!'.hankaku() -> 'タロウ YAMADAです!'
* 'タロウ YAMADAです!'.hankaku('a') -> 'タロウ YAMADAです!'
* 'タロウ YAMADAです!'.hankaku('alphabet') -> 'タロウ YAMADAです!'
* 'タロウです! 25歳です!'.hankaku('katakana', 'numbers') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.hankaku('k', 'n') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.hankaku('kn') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.hankaku('sp') -> 'タロウです! 25歳です!'
*
***/
'hankaku': function() {
return convertCharacterWidth(this, arguments, allZenkaku, 'hankaku');
},
/***
* @method zenkaku([mode] = 'all')
* @returns String
* @short Converts half-width characters (hankaku) to full-width (zenkaku).
* @extra [mode] accepts any combination of "a" (alphabet), "n" (numbers), "k" (katakana), "s" (spaces), "p" (punctuation), or "all".
* @example
*
* 'タロウ YAMADAです!'.zenkaku() -> 'タロウ YAMADAです!'
* 'タロウ YAMADAです!'.zenkaku('a') -> 'タロウ YAMADAです!'
* 'タロウ YAMADAです!'.zenkaku('alphabet') -> 'タロウ YAMADAです!'
* 'タロウです! 25歳です!'.zenkaku('katakana', 'numbers') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.zenkaku('k', 'n') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.zenkaku('kn') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.zenkaku('sp') -> 'タロウです! 25歳です!'
*
***/
'zenkaku': function() {
return convertCharacterWidth(this, arguments, allHankaku, 'zenkaku');
},
/***
* @method hiragana([all] = true)
* @returns String
* @short Converts katakana into hiragana.
* @extra If [all] is false, only full-width katakana will be converted.
* @example
*
* 'カタカナ'.hiragana() -> 'かたかな'
* 'コンニチハ'.hiragana() -> 'こんにちは'
* 'カタカナ'.hiragana() -> 'かたかな'
* 'カタカナ'.hiragana(false) -> 'カタカナ'
*
***/
'hiragana': function(all) {
var str = this;
if(all !== false) {
str = str.zenkaku('k');
}
return str.replace(/[\u30A1-\u30F6]/g, function(c) {
return c.shift(-96);
});
},
/***
* @method katakana()
* @returns String
* @short Converts hiragana into katakana.
* @example
*
* 'かたかな'.katakana() -> 'カタカナ'
* 'こんにちは'.katakana() -> 'コンニチハ'
*
***/
'katakana': function() {
return this.replace(/[\u3041-\u3096]/g, function(c) {
return c.shift(96);
});
}
});
buildUnicodeScripts();
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('da');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('da', {
'plural': true,
'months': 'januar,februar,marts,april,maj,juni,juli,august,september,oktober,november,december',
'weekdays': 'søndag|sondag,mandag,tirsdag,onsdag,torsdag,fredag,lørdag|lordag',
'units': 'millisekund:|er,sekund:|er,minut:|ter,tim:e|er,dag:|e,ug:e|er|en,måned:|er|en+maaned:|er|en,år:||et+aar:||et',
'numbers': 'en|et,to,tre,fire,fem,seks,syv,otte,ni,ti',
'tokens': 'den,for',
'articles': 'den',
'short':'d. {d}. {month} {yyyy}',
'long': 'den {d}. {month} {yyyy} {H}:{mm}',
'full': '{Weekday} den {d}. {month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'forgårs|i forgårs|forgaars|i forgaars', 'value': -2 },
{ 'name': 'day', 'src': 'i går|igår|i gaar|igaar', 'value': -1 },
{ 'name': 'day', 'src': 'i dag|idag', 'value': 0 },
{ 'name': 'day', 'src': 'i morgen|imorgen', 'value': 1 },
{ 'name': 'day', 'src': 'over morgon|overmorgen|i over morgen|i overmorgen|iovermorgen', 'value': 2 },
{ 'name': 'sign', 'src': 'siden', 'value': -1 },
{ 'name': 'sign', 'src': 'om', 'value': 1 },
{ 'name': 'shift', 'src': 'i sidste|sidste', 'value': -1 },
{ 'name': 'shift', 'src': 'denne', 'value': 0 },
{ 'name': 'shift', 'src': 'næste|naeste', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{1?} {num} {unit} {sign}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{0?} {weekday?} {date?} {month} {year}',
'{date} {month}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('de');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('de', {
'plural': true,
'capitalizeUnit': true,
'months': 'Januar,Februar,März|Marz,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember',
'weekdays': 'Sonntag,Montag,Dienstag,Mittwoch,Donnerstag,Freitag,Samstag',
'units': 'Millisekunde:|n,Sekunde:|n,Minute:|n,Stunde:|n,Tag:|en,Woche:|n,Monat:|en,Jahr:|en',
'numbers': 'ein:|e|er|en|em,zwei,drei,vier,fuenf,sechs,sieben,acht,neun,zehn',
'tokens': 'der',
'short':'{d}. {Month} {yyyy}',
'long': '{d}. {Month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d}. {Month} {yyyy} {H}:{mm}:{ss}',
'past': '{sign} {num} {unit}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'timeMarker': 'um',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'vorgestern', 'value': -2 },
{ 'name': 'day', 'src': 'gestern', 'value': -1 },
{ 'name': 'day', 'src': 'heute', 'value': 0 },
{ 'name': 'day', 'src': 'morgen', 'value': 1 },
{ 'name': 'day', 'src': 'übermorgen|ubermorgen|uebermorgen', 'value': 2 },
{ 'name': 'sign', 'src': 'vor:|her', 'value': -1 },
{ 'name': 'sign', 'src': 'in', 'value': 1 },
{ 'name': 'shift', 'src': 'letzte:|r|n|s', 'value': -1 },
{ 'name': 'shift', 'src': 'nächste:|r|n|s+nachste:|r|n|s+naechste:|r|n|s+kommende:n|r', 'value': 1 }
],
'dateParse': [
'{sign} {num} {unit}',
'{num} {unit} {sign}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{weekday?} {date?} {month} {year?}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('es');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('es', {
'plural': true,
'months': 'enero,febrero,marzo,abril,mayo,junio,julio,agosto,septiembre,octubre,noviembre,diciembre',
'weekdays': 'domingo,lunes,martes,miércoles|miercoles,jueves,viernes,sábado|sabado',
'units': 'milisegundo:|s,segundo:|s,minuto:|s,hora:|s,día|días|dia|dias,semana:|s,mes:|es,año|años|ano|anos',
'numbers': 'uno,dos,tres,cuatro,cinco,seis,siete,ocho,nueve,diez',
'tokens': 'el,de',
'short':'{d} {month} {yyyy}',
'long': '{d} {month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d} {month} {yyyy} {H}:{mm}:{ss}',
'past': '{sign} {num} {unit}',
'future': '{num} {unit} {sign}',
'duration': '{num} {unit}',
'timeMarker': 'a las',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'anteayer', 'value': -2 },
{ 'name': 'day', 'src': 'ayer', 'value': -1 },
{ 'name': 'day', 'src': 'hoy', 'value': 0 },
{ 'name': 'day', 'src': 'mañana|manana', 'value': 1 },
{ 'name': 'sign', 'src': 'hace', 'value': -1 },
{ 'name': 'sign', 'src': 'de ahora', 'value': 1 },
{ 'name': 'shift', 'src': 'pasad:o|a', 'value': -1 },
{ 'name': 'shift', 'src': 'próximo|próxima|proximo|proxima', 'value': 1 }
],
'dateParse': [
'{sign} {num} {unit}',
'{num} {unit} {sign}',
'{0?} {unit=5-7} {shift}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{shift} {weekday}',
'{weekday} {shift}',
'{date?} {1?} {month} {1?} {year?}'
]
});
Date.addLocale('fi', {
'plural': true,
'timeMarker': 'kello',
'ampm': ',',
'months': 'tammikuu,helmikuu,maaliskuu,huhtikuu,toukokuu,kesäkuu,heinäkuu,elokuu,syyskuu,lokakuu,marraskuu,joulukuu',
'weekdays': 'sunnuntai,maanantai,tiistai,keskiviikko,torstai,perjantai,lauantai',
'units': 'millisekun:ti|tia|teja|tina|nin,sekun:ti|tia|teja|tina|nin,minuut:ti|tia|teja|tina|in,tun:ti|tia|teja|tina|nin,päiv:ä|ää|iä|änä|än,viik:ko|koa|koja|on|kona,kuukau:si|sia|tta|den|tena,vuo:si|sia|tta|den|tena',
'numbers': 'yksi|ensimmäinen,kaksi|toinen,kolm:e|as,neljä:s,vii:si|des,kuu:si|des,seitsemä:n|s,kahdeksa:n|s,yhdeksä:n|s,kymmene:n|s',
'articles': '',
'optionals': '',
'short': '{d}. {month}ta {yyyy}',
'long': '{d}. {month}ta {yyyy} kello {H}.{mm}',
'full': '{Weekday}na {d}. {month}ta {yyyy} kello {H}.{mm}',
'relative': function(num, unit, ms, format) {
var units = this['units'];
function numberWithUnit(mult) {
return (num === 1 ? '' : num + ' ') + units[(8 * mult) + unit];
}
switch(format) {
case 'duration': return numberWithUnit(0);
case 'past': return numberWithUnit(num > 1 ? 1 : 0) + ' sitten';
case 'future': return numberWithUnit(4) + ' päästä';
}
},
'modifiers': [
{ 'name': 'day', 'src': 'toissa päivänä|toissa päiväistä', 'value': -2 },
{ 'name': 'day', 'src': 'eilen|eilistä', 'value': -1 },
{ 'name': 'day', 'src': 'tänään', 'value': 0 },
{ 'name': 'day', 'src': 'huomenna|huomista', 'value': 1 },
{ 'name': 'day', 'src': 'ylihuomenna|ylihuomista', 'value': 2 },
{ 'name': 'sign', 'src': 'sitten|aiemmin', 'value': -1 },
{ 'name': 'sign', 'src': 'päästä|kuluttua|myöhemmin', 'value': 1 },
{ 'name': 'edge', 'src': 'viimeinen|viimeisenä', 'value': -2 },
{ 'name': 'edge', 'src': 'lopussa', 'value': -1 },
{ 'name': 'edge', 'src': 'ensimmäinen|ensimmäisenä', 'value': 1 },
{ 'name': 'shift', 'src': 'edellinen|edellisenä|edeltävä|edeltävänä|viime|toissa', 'value': -1 },
{ 'name': 'shift', 'src': 'tänä|tämän', 'value': 0 },
{ 'name': 'shift', 'src': 'seuraava|seuraavana|tuleva|tulevana|ensi', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{num} {unit=4-5} {sign} {day}',
'{month} {year}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{0} {num}{1} {day} of {month} {year?}',
'{weekday?} {month} {date}{1} {year?}',
'{date} {month} {year}',
'{shift} {weekday}',
'{shift} week {weekday}',
'{weekday} {2} {shift} week',
'{0} {date}{1} of {month}',
'{0}{month?} {date?}{1} of {shift} {unit=6-7}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('fr');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('fr', {
'plural': true,
'months': 'janvier,février|fevrier,mars,avril,mai,juin,juillet,août,septembre,octobre,novembre,décembre|decembre',
'weekdays': 'dimanche,lundi,mardi,mercredi,jeudi,vendredi,samedi',
'units': 'milliseconde:|s,seconde:|s,minute:|s,heure:|s,jour:|s,semaine:|s,mois,an:|s|née|nee',
'numbers': 'un:|e,deux,trois,quatre,cinq,six,sept,huit,neuf,dix',
'tokens': ["l'|la|le"],
'short':'{d} {month} {yyyy}',
'long': '{d} {month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d} {month} {yyyy} {H}:{mm}:{ss}',
'past': '{sign} {num} {unit}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'timeMarker': 'à',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'hier', 'value': -1 },
{ 'name': 'day', 'src': "aujourd'hui", 'value': 0 },
{ 'name': 'day', 'src': 'demain', 'value': 1 },
{ 'name': 'sign', 'src': 'il y a', 'value': -1 },
{ 'name': 'sign', 'src': "dans|d'ici", 'value': 1 },
{ 'name': 'shift', 'src': 'derni:èr|er|ère|ere', 'value': -1 },
{ 'name': 'shift', 'src': 'prochain:|e', 'value': 1 }
],
'dateParse': [
'{sign} {num} {unit}',
'{sign} {num} {unit}',
'{0?} {unit=5-7} {shift}'
],
'timeParse': [
'{0?} {date?} {month} {year?}',
'{0?} {weekday} {shift}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('it');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('it', {
'plural': true,
'months': 'Gennaio,Febbraio,Marzo,Aprile,Maggio,Giugno,Luglio,Agosto,Settembre,Ottobre,Novembre,Dicembre',
'weekdays': 'Domenica,Luned:ì|i,Marted:ì|i,Mercoled:ì|i,Gioved:ì|i,Venerd:ì|i,Sabato',
'units': 'millisecond:o|i,second:o|i,minut:o|i,or:a|e,giorn:o|i,settiman:a|e,mes:e|i,ann:o|i',
'numbers': "un:|a|o|',due,tre,quattro,cinque,sei,sette,otto,nove,dieci",
'tokens': "l'|la|il",
'short':'{d} {Month} {yyyy}',
'long': '{d} {Month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d} {Month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{num} {unit} {sign}',
'duration': '{num} {unit}',
'timeMarker': 'alle',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'ieri', 'value': -1 },
{ 'name': 'day', 'src': 'oggi', 'value': 0 },
{ 'name': 'day', 'src': 'domani', 'value': 1 },
{ 'name': 'day', 'src': 'dopodomani', 'value': 2 },
{ 'name': 'sign', 'src': 'fa', 'value': -1 },
{ 'name': 'sign', 'src': 'da adesso', 'value': 1 },
{ 'name': 'shift', 'src': 'scors:o|a', 'value': -1 },
{ 'name': 'shift', 'src': 'prossim:o|a', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{0?} {unit=5-7} {shift}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{weekday?} {date?} {month} {year?}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('ja');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('ja', {
'monthSuffix': '月',
'weekdays': '日曜日,月曜日,火曜日,水曜日,木曜日,金曜日,土曜日',
'units': 'ミリ秒,秒,分,時間,日,週間|週,ヶ月|ヵ月|月,年',
'short': '{yyyy}年{M}月{d}日',
'long': '{yyyy}年{M}月{d}日 {H}時{mm}分',
'full': '{yyyy}年{M}月{d}日 {Weekday} {H}時{mm}分{ss}秒',
'past': '{num}{unit}{sign}',
'future': '{num}{unit}{sign}',
'duration': '{num}{unit}',
'timeSuffixes': '時,分,秒',
'ampm': '午前,午後',
'modifiers': [
{ 'name': 'day', 'src': '一昨日', 'value': -2 },
{ 'name': 'day', 'src': '昨日', 'value': -1 },
{ 'name': 'day', 'src': '今日', 'value': 0 },
{ 'name': 'day', 'src': '明日', 'value': 1 },
{ 'name': 'day', 'src': '明後日', 'value': 2 },
{ 'name': 'sign', 'src': '前', 'value': -1 },
{ 'name': 'sign', 'src': '後', 'value': 1 },
{ 'name': 'shift', 'src': '去|先', 'value': -1 },
{ 'name': 'shift', 'src': '来', 'value': 1 }
],
'dateParse': [
'{num}{unit}{sign}'
],
'timeParse': [
'{shift}{unit=5-7}{weekday?}',
'{year}年{month?}月?{date?}日?',
'{month}月{date?}日?',
'{date}日'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('ko');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('ko', {
'digitDate': true,
'monthSuffix': '월',
'weekdays': '일요일,월요일,화요일,수요일,목요일,금요일,토요일',
'units': '밀리초,초,분,시간,일,주,개월|달,년',
'numbers': '일|한,이,삼,사,오,육,칠,팔,구,십',
'short': '{yyyy}년{M}월{d}일',
'long': '{yyyy}년{M}월{d}일 {H}시{mm}분',
'full': '{yyyy}년{M}월{d}일 {Weekday} {H}시{mm}분{ss}초',
'past': '{num}{unit} {sign}',
'future': '{num}{unit} {sign}',
'duration': '{num}{unit}',
'timeSuffixes': '시,분,초',
'ampm': '오전,오후',
'modifiers': [
{ 'name': 'day', 'src': '그저께', 'value': -2 },
{ 'name': 'day', 'src': '어제', 'value': -1 },
{ 'name': 'day', 'src': '오늘', 'value': 0 },
{ 'name': 'day', 'src': '내일', 'value': 1 },
{ 'name': 'day', 'src': '모레', 'value': 2 },
{ 'name': 'sign', 'src': '전', 'value': -1 },
{ 'name': 'sign', 'src': '후', 'value': 1 },
{ 'name': 'shift', 'src': '지난|작', 'value': -1 },
{ 'name': 'shift', 'src': '이번', 'value': 0 },
{ 'name': 'shift', 'src': '다음|내', 'value': 1 }
],
'dateParse': [
'{num}{unit} {sign}',
'{shift?} {unit=5-7}'
],
'timeParse': [
'{shift} {unit=5?} {weekday}',
'{year}년{month?}월?{date?}일?',
'{month}월{date?}일?',
'{date}일'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('nl');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('nl', {
'plural': true,
'months': 'januari,februari,maart,april,mei,juni,juli,augustus,september,oktober,november,december',
'weekdays': 'zondag|zo,maandag|ma,dinsdag|di,woensdag|woe|wo,donderdag|do,vrijdag|vrij|vr,zaterdag|za',
'units': 'milliseconde:|n,seconde:|n,minu:ut|ten,uur,dag:|en,we:ek|ken,maand:|en,jaar',
'numbers': 'een,twee,drie,vier,vijf,zes,zeven,acht,negen',
'tokens': '',
'short':'{d} {Month} {yyyy}',
'long': '{d} {Month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d} {Month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{num} {unit} {sign}',
'duration': '{num} {unit}',
'timeMarker': "'s|om",
'modifiers': [
{ 'name': 'day', 'src': 'gisteren', 'value': -1 },
{ 'name': 'day', 'src': 'vandaag', 'value': 0 },
{ 'name': 'day', 'src': 'morgen', 'value': 1 },
{ 'name': 'day', 'src': 'overmorgen', 'value': 2 },
{ 'name': 'sign', 'src': 'geleden', 'value': -1 },
{ 'name': 'sign', 'src': 'vanaf nu', 'value': 1 },
{ 'name': 'shift', 'src': 'laatste|vorige|afgelopen', 'value': -1 },
{ 'name': 'shift', 'src': 'volgend:|e', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{0?} {unit=5-7} {shift}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{weekday?} {date?} {month} {year?}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('pl');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.optionals. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('pl', {
'plural': true,
'months': 'Styczeń|Stycznia,Luty|Lutego,Marzec|Marca,Kwiecień|Kwietnia,Maj|Maja,Czerwiec|Czerwca,Lipiec|Lipca,Sierpień|Sierpnia,Wrzesień|Września,Październik|Października,Listopad|Listopada,Grudzień|Grudnia',
'weekdays': 'Niedziela|Niedzielę,Poniedziałek,Wtorek,Środ:a|ę,Czwartek,Piątek,Sobota|Sobotę',
'units': 'milisekund:a|y|,sekund:a|y|,minut:a|y|,godzin:a|y|,dzień|dni,tydzień|tygodnie|tygodni,miesiące|miesiące|miesięcy,rok|lata|lat',
'numbers': 'jeden|jedną,dwa|dwie,trzy,cztery,pięć,sześć,siedem,osiem,dziewięć,dziesięć',
'optionals': 'w|we,roku',
'short': '{d} {Month} {yyyy}',
'long': '{d} {Month} {yyyy} {H}:{mm}',
'full' : '{Weekday}, {d} {Month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'timeMarker':'o',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'przedwczoraj', 'value': -2 },
{ 'name': 'day', 'src': 'wczoraj', 'value': -1 },
{ 'name': 'day', 'src': 'dzisiaj|dziś', 'value': 0 },
{ 'name': 'day', 'src': 'jutro', 'value': 1 },
{ 'name': 'day', 'src': 'pojutrze', 'value': 2 },
{ 'name': 'sign', 'src': 'temu|przed', 'value': -1 },
{ 'name': 'sign', 'src': 'za', 'value': 1 },
{ 'name': 'shift', 'src': 'zeszły|zeszła|ostatni|ostatnia', 'value': -1 },
{ 'name': 'shift', 'src': 'następny|następna|następnego|przyszły|przyszła|przyszłego', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{month} {year}',
'{shift} {unit=5-7}',
'{0} {shift?} {weekday}'
],
'timeParse': [
'{date} {month} {year?} {1}',
'{0} {shift?} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('pt');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('pt', {
'plural': true,
'months': 'janeiro,fevereiro,março,abril,maio,junho,julho,agosto,setembro,outubro,novembro,dezembro',
'weekdays': 'domingo,segunda-feira,terça-feira,quarta-feira,quinta-feira,sexta-feira,sábado|sabado',
'units': 'milisegundo:|s,segundo:|s,minuto:|s,hora:|s,dia:|s,semana:|s,mês|mêses|mes|meses,ano:|s',
'numbers': 'um,dois,três|tres,quatro,cinco,seis,sete,oito,nove,dez,uma,duas',
'tokens': 'a,de',
'short':'{d} de {month} de {yyyy}',
'long': '{d} de {month} de {yyyy} {H}:{mm}',
'full': '{Weekday}, {d} de {month} de {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'timeMarker': 'às',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'anteontem', 'value': -2 },
{ 'name': 'day', 'src': 'ontem', 'value': -1 },
{ 'name': 'day', 'src': 'hoje', 'value': 0 },
{ 'name': 'day', 'src': 'amanh:ã|a', 'value': 1 },
{ 'name': 'sign', 'src': 'atrás|atras|há|ha', 'value': -1 },
{ 'name': 'sign', 'src': 'daqui a', 'value': 1 },
{ 'name': 'shift', 'src': 'passad:o|a', 'value': -1 },
{ 'name': 'shift', 'src': 'próximo|próxima|proximo|proxima', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{0?} {unit=5-7} {shift}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{date?} {1?} {month} {1?} {year?}',
'{0?} {shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('ru');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('ru', {
'months': 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь',
'weekdays': 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота',
'units': 'миллисекунд:а|у|ы|,секунд:а|у|ы|,минут:а|у|ы|,час:||а|ов,день|день|дня|дней,недел:я|ю|и|ь|е,месяц:||а|ев|е,год|год|года|лет|году',
'numbers': 'од:ин|ну,дв:а|е,три,четыре,пять,шесть,семь,восемь,девять,десять',
'tokens': 'в|на,года',
'short':'{d} {month} {yyyy} года',
'long': '{d} {month} {yyyy} года {H}:{mm}',
'full': '{Weekday} {d} {month} {yyyy} года {H}:{mm}:{ss}',
'relative': function(num, unit, ms, format) {
var numberWithUnit, last = num.toString().slice(-1);
switch(true) {
case num >= 11 && num <= 15: mult = 3; break;
case last == 1: mult = 1; break;
case last >= 2 && last <= 4: mult = 2; break;
default: mult = 3;
}
numberWithUnit = num + ' ' + this['units'][(mult * 8) + unit];
switch(format) {
case 'duration': return numberWithUnit;
case 'past': return numberWithUnit + ' назад';
case 'future': return 'через ' + numberWithUnit;
}
},
'timeMarker': 'в',
'ampm': ' утра, вечера',
'modifiers': [
{ 'name': 'day', 'src': 'позавчера', 'value': -2 },
{ 'name': 'day', 'src': 'вчера', 'value': -1 },
{ 'name': 'day', 'src': 'сегодня', 'value': 0 },
{ 'name': 'day', 'src': 'завтра', 'value': 1 },
{ 'name': 'day', 'src': 'послезавтра', 'value': 2 },
{ 'name': 'sign', 'src': 'назад', 'value': -1 },
{ 'name': 'sign', 'src': 'через', 'value': 1 },
{ 'name': 'shift', 'src': 'прошл:ый|ой|ом', 'value': -1 },
{ 'name': 'shift', 'src': 'следующ:ий|ей|ем', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{month} {year}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{date} {month} {year?} {1?}',
'{0?} {shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('sv');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('sv', {
'plural': true,
'months': 'januari,februari,mars,april,maj,juni,juli,augusti,september,oktober,november,december',
'weekdays': 'söndag|sondag,måndag:|en+mandag:|en,tisdag,onsdag,torsdag,fredag,lördag|lordag',
'units': 'millisekund:|er,sekund:|er,minut:|er,timm:e|ar,dag:|ar,veck:a|or|an,månad:|er|en+manad:|er|en,år:||et+ar:||et',
'numbers': 'en|ett,två|tva,tre,fyra,fem,sex,sju,åtta|atta,nio,tio',
'tokens': 'den,för|for',
'articles': 'den',
'short':'den {d} {month} {yyyy}',
'long': 'den {d} {month} {yyyy} {H}:{mm}',
'full': '{Weekday} den {d} {month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'förrgår|i förrgår|iförrgår|forrgar|i forrgar|iforrgar', 'value': -2 },
{ 'name': 'day', 'src': 'går|i går|igår|gar|i gar|igar', 'value': -1 },
{ 'name': 'day', 'src': 'dag|i dag|idag', 'value': 0 },
{ 'name': 'day', 'src': 'morgon|i morgon|imorgon', 'value': 1 },
{ 'name': 'day', 'src': 'över morgon|övermorgon|i över morgon|i övermorgon|iövermorgon|over morgon|overmorgon|i over morgon|i overmorgon|iovermorgon', 'value': 2 },
{ 'name': 'sign', 'src': 'sedan|sen', 'value': -1 },
{ 'name': 'sign', 'src': 'om', 'value': 1 },
{ 'name': 'shift', 'src': 'i förra|förra|i forra|forra', 'value': -1 },
{ 'name': 'shift', 'src': 'denna', 'value': 0 },
{ 'name': 'shift', 'src': 'nästa|nasta', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{1?} {num} {unit} {sign}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{0?} {weekday?} {date?} {month} {year}',
'{date} {month}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('zh-CN');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('zh-CN', {
'variant': true,
'monthSuffix': '月',
'weekdays': '星期日|周日,星期一|周一,星期二|周二,星期三|周三,星期四|周四,星期五|周五,星期六|周六',
'units': '毫秒,秒钟,分钟,小时,天,个星期|周,个月,年',
'tokens': '日|号',
'short':'{yyyy}年{M}月{d}日',
'long': '{yyyy}年{M}月{d}日 {tt}{h}:{mm}',
'full': '{yyyy}年{M}月{d}日 {weekday} {tt}{h}:{mm}:{ss}',
'past': '{num}{unit}{sign}',
'future': '{num}{unit}{sign}',
'duration': '{num}{unit}',
'timeSuffixes': '点|时,分钟?,秒',
'ampm': '上午,下午',
'modifiers': [
{ 'name': 'day', 'src': '前天', 'value': -2 },
{ 'name': 'day', 'src': '昨天', 'value': -1 },
{ 'name': 'day', 'src': '今天', 'value': 0 },
{ 'name': 'day', 'src': '明天', 'value': 1 },
{ 'name': 'day', 'src': '后天', 'value': 2 },
{ 'name': 'sign', 'src': '前', 'value': -1 },
{ 'name': 'sign', 'src': '后', 'value': 1 },
{ 'name': 'shift', 'src': '上|去', 'value': -1 },
{ 'name': 'shift', 'src': '这', 'value': 0 },
{ 'name': 'shift', 'src': '下|明', 'value': 1 }
],
'dateParse': [
'{num}{unit}{sign}',
'{shift}{unit=5-7}'
],
'timeParse': [
'{shift}{weekday}',
'{year}年{month?}月?{date?}{0?}',
'{month}月{date?}{0?}',
'{date}[日号]'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('zh-TW');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
//'zh-TW': '1;月;年;;星期日|週日,星期一|週一,星期二|週二,星期三|週三,星期四|週四,星期五|週五,星期六|週六;毫秒,秒鐘,分鐘,小時,天,個星期|週,個月,年;;;日|號;;上午,下午;點|時,分鐘?,秒;{num}{unit}{sign},{shift}{unit=5-7};{shift}{weekday},{year}年{month?}月?{date?}{0},{month}月{date?}{0},{date}{0};{yyyy}年{M}月{d}日 {Weekday};{tt}{h}:{mm}:{ss};前天,昨天,今天,明天,後天;,前,,後;,上|去,這,下|明',
Date.addLocale('zh-TW', {
'monthSuffix': '月',
'weekdays': '星期日|週日,星期一|週一,星期二|週二,星期三|週三,星期四|週四,星期五|週五,星期六|週六',
'units': '毫秒,秒鐘,分鐘,小時,天,個星期|週,個月,年',
'tokens': '日|號',
'short':'{yyyy}年{M}月{d}日',
'long': '{yyyy}年{M}月{d}日 {tt}{h}:{mm}',
'full': '{yyyy}年{M}月{d}日 {Weekday} {tt}{h}:{mm}:{ss}',
'past': '{num}{unit}{sign}',
'future': '{num}{unit}{sign}',
'duration': '{num}{unit}',
'timeSuffixes': '點|時,分鐘?,秒',
'ampm': '上午,下午',
'modifiers': [
{ 'name': 'day', 'src': '前天', 'value': -2 },
{ 'name': 'day', 'src': '昨天', 'value': -1 },
{ 'name': 'day', 'src': '今天', 'value': 0 },
{ 'name': 'day', 'src': '明天', 'value': 1 },
{ 'name': 'day', 'src': '後天', 'value': 2 },
{ 'name': 'sign', 'src': '前', 'value': -1 },
{ 'name': 'sign', 'src': '後', 'value': 1 },
{ 'name': 'shift', 'src': '上|去', 'value': -1 },
{ 'name': 'shift', 'src': '這', 'value': 0 },
{ 'name': 'shift', 'src': '下|明', 'value': 1 }
],
'dateParse': [
'{num}{unit}{sign}',
'{shift}{unit=5-7}'
],
'timeParse': [
'{shift}{weekday}',
'{year}年{month?}月?{date?}{0?}',
'{month}月{date?}{0?}',
'{date}[日號]'
]
});
})(); | sunnywz/weather | node_modules/sugar/release/1.3.5/sugar-1.3.5-full.development.js | JavaScript | mit | 286,482 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\CoreBundle\Settings;
use Sylius\Bundle\SettingsBundle\Schema\SchemaInterface;
use Sylius\Bundle\SettingsBundle\Schema\SettingsBuilderInterface;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Security settings schema.
*
* @author Paweł Jędrzejewski <[email protected]>
*/
class SecuritySettingsSchema implements SchemaInterface
{
/**
* {@inheritdoc}
*/
public function buildSettings(SettingsBuilderInterface $builder)
{
$builder
->setDefaults(array(
'enabled' => false,
))
->setAllowedTypes(array(
'enabled' => array('bool'),
))
;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder)
{
$builder
->add('enabled', 'checkbox', array(
'label' => 'sylius.form.settings.security.enabled',
))
;
}
}
| wwojcik/Sylius | src/Sylius/Bundle/CoreBundle/Settings/SecuritySettingsSchema.php | PHP | mit | 1,184 |
from .base import ScriptDirectory, Script # noqa
__all__ = ['ScriptDirectory', 'Script']
| pcu4dros/pandora-core | workspace/lib/python3.5/site-packages/alembic/script/__init__.py | Python | mit | 91 |
/******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called LICENSE.GPL.
*
* Contact Information:
* Intel Linux Wireless <[email protected]>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2005 - 2011 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#ifndef __iwl_core_h__
#define __iwl_core_h__
#include "iwl-dev.h"
/************************
* forward declarations *
************************/
struct iwl_host_cmd;
struct iwl_cmd;
#define IWLWIFI_VERSION "in-tree:"
#define DRV_COPYRIGHT "Copyright(c) 2003-2011 Intel Corporation"
#define DRV_AUTHOR "<[email protected]>"
#define IWL_PCI_DEVICE(dev, subdev, cfg) \
.vendor = PCI_VENDOR_ID_INTEL, .device = (dev), \
.subvendor = PCI_ANY_ID, .subdevice = (subdev), \
.driver_data = (kernel_ulong_t)&(cfg)
#define TIME_UNIT 1024
#define IWL_SKU_G 0x1
#define IWL_SKU_A 0x2
#define IWL_SKU_N 0x8
#define IWL_CMD(x) case x: return #x
struct iwl_hcmd_ops {
int (*commit_rxon)(struct iwl_priv *priv, struct iwl_rxon_context *ctx);
void (*set_rxon_chain)(struct iwl_priv *priv,
struct iwl_rxon_context *ctx);
int (*set_tx_ant)(struct iwl_priv *priv, u8 valid_tx_ant);
void (*send_bt_config)(struct iwl_priv *priv);
int (*set_pan_params)(struct iwl_priv *priv);
};
struct iwl_hcmd_utils_ops {
u16 (*build_addsta_hcmd)(const struct iwl_addsta_cmd *cmd, u8 *data);
void (*gain_computation)(struct iwl_priv *priv,
u32 *average_noise,
u16 min_average_noise_antennat_i,
u32 min_average_noise,
u8 default_chain);
void (*chain_noise_reset)(struct iwl_priv *priv);
void (*tx_cmd_protection)(struct iwl_priv *priv,
struct ieee80211_tx_info *info,
__le16 fc, __le32 *tx_flags);
int (*calc_rssi)(struct iwl_priv *priv,
struct iwl_rx_phy_res *rx_resp);
int (*request_scan)(struct iwl_priv *priv, struct ieee80211_vif *vif);
void (*post_scan)(struct iwl_priv *priv);
};
struct iwl_apm_ops {
int (*init)(struct iwl_priv *priv);
void (*config)(struct iwl_priv *priv);
};
struct iwl_temp_ops {
void (*temperature)(struct iwl_priv *priv);
};
struct iwl_lib_ops {
/* set hw dependent parameters */
int (*set_hw_params)(struct iwl_priv *priv);
/* setup Rx handler */
void (*rx_handler_setup)(struct iwl_priv *priv);
/* setup deferred work */
void (*setup_deferred_work)(struct iwl_priv *priv);
/* cancel deferred work */
void (*cancel_deferred_work)(struct iwl_priv *priv);
/* check validity of rtc data address */
int (*is_valid_rtc_data_addr)(u32 addr);
int (*set_channel_switch)(struct iwl_priv *priv,
struct ieee80211_channel_switch *ch_switch);
/* power management */
struct iwl_apm_ops apm_ops;
/* power */
int (*send_tx_power) (struct iwl_priv *priv);
void (*update_chain_flags)(struct iwl_priv *priv);
/* eeprom operations (as defined in iwl-eeprom.h) */
struct iwl_eeprom_ops eeprom_ops;
/* temperature */
struct iwl_temp_ops temp_ops;
int (*txfifo_flush)(struct iwl_priv *priv, u16 flush_control);
void (*dev_txfifo_flush)(struct iwl_priv *priv, u16 flush_control);
};
/* NIC specific ops */
struct iwl_nic_ops {
void (*additional_nic_config)(struct iwl_priv *priv);
};
struct iwl_ops {
const struct iwl_lib_ops *lib;
const struct iwl_hcmd_ops *hcmd;
const struct iwl_hcmd_utils_ops *utils;
const struct iwl_nic_ops *nic;
};
struct iwl_mod_params {
int sw_crypto; /* def: 0 = using hardware encryption */
int num_of_queues; /* def: HW dependent */
int disable_11n; /* def: 0 = 11n capabilities enabled */
int amsdu_size_8K; /* def: 1 = enable 8K amsdu size */
int antenna; /* def: 0 = both antennas (use diversity) */
int restart_fw; /* def: 1 = restart firmware */
bool plcp_check; /* def: true = enable plcp health check */
bool ack_check; /* def: false = disable ack health check */
};
/*
* @max_ll_items: max number of OTP blocks
* @shadow_ram_support: shadow support for OTP memory
* @led_compensation: compensate on the led on/off time per HW according
* to the deviation to achieve the desired led frequency.
* The detail algorithm is described in iwl-led.c
* @chain_noise_num_beacons: number of beacons used to compute chain noise
* @adv_thermal_throttle: support advance thermal throttle
* @support_ct_kill_exit: support ct kill exit condition
* @support_wimax_coexist: support wimax/wifi co-exist
* @plcp_delta_threshold: plcp error rate threshold used to trigger
* radio tuning when there is a high receiving plcp error rate
* @chain_noise_scale: default chain noise scale used for gain computation
* @wd_timeout: TX queues watchdog timeout
* @temperature_kelvin: temperature report by uCode in kelvin
* @max_event_log_size: size of event log buffer size for ucode event logging
* @shadow_reg_enable: HW shadhow register bit
*/
struct iwl_base_params {
int eeprom_size;
int num_of_queues; /* def: HW dependent */
int num_of_ampdu_queues;/* def: HW dependent */
/* for iwl_apm_init() */
u32 pll_cfg_val;
const u16 max_ll_items;
const bool shadow_ram_support;
u16 led_compensation;
int chain_noise_num_beacons;
bool adv_thermal_throttle;
bool support_ct_kill_exit;
const bool support_wimax_coexist;
u8 plcp_delta_threshold;
s32 chain_noise_scale;
unsigned int wd_timeout;
bool temperature_kelvin;
u32 max_event_log_size;
const bool shadow_reg_enable;
};
/*
* @advanced_bt_coexist: support advanced bt coexist
* @bt_init_traffic_load: specify initial bt traffic load
* @bt_prio_boost: default bt priority boost value
* @agg_time_limit: maximum number of uSec in aggregation
* @ampdu_factor: Maximum A-MPDU length factor
* @ampdu_density: Minimum A-MPDU spacing
* @bt_sco_disable: uCode should not response to BT in SCO/ESCO mode
*/
struct iwl_bt_params {
bool advanced_bt_coexist;
u8 bt_init_traffic_load;
u8 bt_prio_boost;
u16 agg_time_limit;
u8 ampdu_factor;
u8 ampdu_density;
bool bt_sco_disable;
bool bt_session_2;
};
/*
* @use_rts_for_aggregation: use rts/cts protection for HT traffic
*/
struct iwl_ht_params {
const bool ht_greenfield_support; /* if used set to true */
bool use_rts_for_aggregation;
};
/**
* struct iwl_cfg
* @fw_name_pre: Firmware filename prefix. The api version and extension
* (.ucode) will be added to filename before loading from disk. The
* filename is constructed as fw_name_pre<api>.ucode.
* @ucode_api_max: Highest version of uCode API supported by driver.
* @ucode_api_min: Lowest version of uCode API supported by driver.
* @pa_type: used by 6000 series only to identify the type of Power Amplifier
* @need_dc_calib: need to perform init dc calibration
* @need_temp_offset_calib: need to perform temperature offset calibration
* @scan_antennas: available antenna for scan operation
* @led_mode: 0=blinking, 1=On(RF On)/Off(RF Off)
* @adv_pm: advance power management
* @rx_with_siso_diversity: 1x1 device with rx antenna diversity
* @internal_wimax_coex: internal wifi/wimax combo device
* @iq_invert: I/Q inversion
* @disable_otp_refresh: disable OTP refresh current limit
*
* We enable the driver to be backward compatible wrt API version. The
* driver specifies which APIs it supports (with @ucode_api_max being the
* highest and @ucode_api_min the lowest). Firmware will only be loaded if
* it has a supported API version. The firmware's API version will be
* stored in @iwl_priv, enabling the driver to make runtime changes based
* on firmware version used.
*
* For example,
* if (IWL_UCODE_API(priv->ucode_ver) >= 2) {
* Driver interacts with Firmware API version >= 2.
* } else {
* Driver interacts with Firmware API version 1.
* }
*
* The ideal usage of this infrastructure is to treat a new ucode API
* release as a new hardware revision. That is, through utilizing the
* iwl_hcmd_utils_ops etc. we accommodate different command structures
* and flows between hardware versions (4965/5000) as well as their API
* versions.
*
*/
struct iwl_cfg {
/* params specific to an individual device within a device family */
const char *name;
const char *fw_name_pre;
const unsigned int ucode_api_max;
const unsigned int ucode_api_min;
u8 valid_tx_ant;
u8 valid_rx_ant;
unsigned int sku;
u16 eeprom_ver;
u16 eeprom_calib_ver;
const struct iwl_ops *ops;
/* params not likely to change within a device family */
struct iwl_base_params *base_params;
/* params likely to change within a device family */
struct iwl_ht_params *ht_params;
struct iwl_bt_params *bt_params;
enum iwl_pa_type pa_type; /* if used set to IWL_PA_SYSTEM */
const bool need_dc_calib; /* if used set to true */
const bool need_temp_offset_calib; /* if used set to true */
u8 scan_rx_antennas[IEEE80211_NUM_BANDS];
enum iwl_led_mode led_mode;
const bool adv_pm;
const bool rx_with_siso_diversity;
const bool internal_wimax_coex;
const bool iq_invert;
const bool disable_otp_refresh;
};
/***************************
* L i b *
***************************/
int iwl_mac_conf_tx(struct ieee80211_hw *hw, u16 queue,
const struct ieee80211_tx_queue_params *params);
int iwl_mac_tx_last_beacon(struct ieee80211_hw *hw);
void iwl_set_rxon_hwcrypto(struct iwl_priv *priv, struct iwl_rxon_context *ctx,
int hw_decrypt);
int iwl_check_rxon_cmd(struct iwl_priv *priv, struct iwl_rxon_context *ctx);
int iwl_full_rxon_required(struct iwl_priv *priv, struct iwl_rxon_context *ctx);
int iwl_set_rxon_channel(struct iwl_priv *priv, struct ieee80211_channel *ch,
struct iwl_rxon_context *ctx);
void iwl_set_flags_for_band(struct iwl_priv *priv,
struct iwl_rxon_context *ctx,
enum ieee80211_band band,
struct ieee80211_vif *vif);
u8 iwl_get_single_channel_number(struct iwl_priv *priv,
enum ieee80211_band band);
void iwl_set_rxon_ht(struct iwl_priv *priv, struct iwl_ht_config *ht_conf);
bool iwl_is_ht40_tx_allowed(struct iwl_priv *priv,
struct iwl_rxon_context *ctx,
struct ieee80211_sta_ht_cap *ht_cap);
void iwl_connection_init_rx_config(struct iwl_priv *priv,
struct iwl_rxon_context *ctx);
void iwl_set_rate(struct iwl_priv *priv);
void iwl_irq_handle_error(struct iwl_priv *priv);
int iwl_mac_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif);
void iwl_mac_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif);
int iwl_mac_change_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum nl80211_iftype newtype, bool newp2p);
int iwl_alloc_txq_mem(struct iwl_priv *priv);
void iwl_free_txq_mem(struct iwl_priv *priv);
#ifdef CONFIG_IWLWIFI_DEBUGFS
int iwl_alloc_traffic_mem(struct iwl_priv *priv);
void iwl_free_traffic_mem(struct iwl_priv *priv);
void iwl_reset_traffic_log(struct iwl_priv *priv);
void iwl_dbg_log_tx_data_frame(struct iwl_priv *priv,
u16 length, struct ieee80211_hdr *header);
void iwl_dbg_log_rx_data_frame(struct iwl_priv *priv,
u16 length, struct ieee80211_hdr *header);
const char *get_mgmt_string(int cmd);
const char *get_ctrl_string(int cmd);
void iwl_clear_traffic_stats(struct iwl_priv *priv);
void iwl_update_stats(struct iwl_priv *priv, bool is_tx, __le16 fc,
u16 len);
#else
static inline int iwl_alloc_traffic_mem(struct iwl_priv *priv)
{
return 0;
}
static inline void iwl_free_traffic_mem(struct iwl_priv *priv)
{
}
static inline void iwl_reset_traffic_log(struct iwl_priv *priv)
{
}
static inline void iwl_dbg_log_tx_data_frame(struct iwl_priv *priv,
u16 length, struct ieee80211_hdr *header)
{
}
static inline void iwl_dbg_log_rx_data_frame(struct iwl_priv *priv,
u16 length, struct ieee80211_hdr *header)
{
}
static inline void iwl_update_stats(struct iwl_priv *priv, bool is_tx,
__le16 fc, u16 len)
{
}
#endif
/*****************************************************
* RX
******************************************************/
void iwl_cmd_queue_free(struct iwl_priv *priv);
void iwl_cmd_queue_unmap(struct iwl_priv *priv);
int iwl_rx_queue_alloc(struct iwl_priv *priv);
void iwl_rx_queue_update_write_ptr(struct iwl_priv *priv,
struct iwl_rx_queue *q);
int iwl_rx_queue_space(const struct iwl_rx_queue *q);
void iwl_tx_cmd_complete(struct iwl_priv *priv, struct iwl_rx_mem_buffer *rxb);
void iwl_chswitch_done(struct iwl_priv *priv, bool is_success);
/* TX helpers */
/*****************************************************
* TX
******************************************************/
void iwl_txq_update_write_ptr(struct iwl_priv *priv, struct iwl_tx_queue *txq);
int iwl_tx_queue_init(struct iwl_priv *priv, struct iwl_tx_queue *txq,
int slots_num, u32 txq_id);
void iwl_tx_queue_reset(struct iwl_priv *priv, struct iwl_tx_queue *txq,
int slots_num, u32 txq_id);
void iwl_tx_queue_free(struct iwl_priv *priv, int txq_id);
void iwl_tx_queue_unmap(struct iwl_priv *priv, int txq_id);
void iwl_setup_watchdog(struct iwl_priv *priv);
/*****************************************************
* TX power
****************************************************/
int iwl_set_tx_power(struct iwl_priv *priv, s8 tx_power, bool force);
/*******************************************************************************
* Rate
******************************************************************************/
u8 iwl_rate_get_lowest_plcp(struct iwl_priv *priv,
struct iwl_rxon_context *ctx);
/*******************************************************************************
* Scanning
******************************************************************************/
void iwl_init_scan_params(struct iwl_priv *priv);
int iwl_scan_cancel(struct iwl_priv *priv);
int iwl_scan_cancel_timeout(struct iwl_priv *priv, unsigned long ms);
void iwl_force_scan_end(struct iwl_priv *priv);
int iwl_mac_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct cfg80211_scan_request *req);
void iwl_internal_short_hw_scan(struct iwl_priv *priv);
int iwl_force_reset(struct iwl_priv *priv, int mode, bool external);
u16 iwl_fill_probe_req(struct iwl_priv *priv, struct ieee80211_mgmt *frame,
const u8 *ta, const u8 *ie, int ie_len, int left);
void iwl_setup_rx_scan_handlers(struct iwl_priv *priv);
u16 iwl_get_active_dwell_time(struct iwl_priv *priv,
enum ieee80211_band band,
u8 n_probes);
u16 iwl_get_passive_dwell_time(struct iwl_priv *priv,
enum ieee80211_band band,
struct ieee80211_vif *vif);
void iwl_setup_scan_deferred_work(struct iwl_priv *priv);
void iwl_cancel_scan_deferred_work(struct iwl_priv *priv);
int __must_check iwl_scan_initiate(struct iwl_priv *priv,
struct ieee80211_vif *vif,
enum iwl_scan_type scan_type,
enum ieee80211_band band);
/* For faster active scanning, scan will move to the next channel if fewer than
* PLCP_QUIET_THRESH packets are heard on this channel within
* ACTIVE_QUIET_TIME after sending probe request. This shortens the dwell
* time if it's a quiet channel (nothing responded to our probe, and there's
* no other traffic).
* Disable "quiet" feature by setting PLCP_QUIET_THRESH to 0. */
#define IWL_ACTIVE_QUIET_TIME cpu_to_le16(10) /* msec */
#define IWL_PLCP_QUIET_THRESH cpu_to_le16(1) /* packets */
#define IWL_SCAN_CHECK_WATCHDOG (HZ * 7)
/*****************************************************
* S e n d i n g H o s t C o m m a n d s *
*****************************************************/
const char *get_cmd_string(u8 cmd);
int __must_check iwl_send_cmd_sync(struct iwl_priv *priv,
struct iwl_host_cmd *cmd);
int iwl_send_cmd(struct iwl_priv *priv, struct iwl_host_cmd *cmd);
int __must_check iwl_send_cmd_pdu(struct iwl_priv *priv, u8 id,
u16 len, const void *data);
int iwl_send_cmd_pdu_async(struct iwl_priv *priv, u8 id, u16 len,
const void *data,
void (*callback)(struct iwl_priv *priv,
struct iwl_device_cmd *cmd,
struct iwl_rx_packet *pkt));
int iwl_enqueue_hcmd(struct iwl_priv *priv, struct iwl_host_cmd *cmd);
/*****************************************************
* PCI *
*****************************************************/
static inline u16 iwl_pcie_link_ctl(struct iwl_priv *priv)
{
int pos;
u16 pci_lnk_ctl;
pos = pci_find_capability(priv->pci_dev, PCI_CAP_ID_EXP);
pci_read_config_word(priv->pci_dev, pos + PCI_EXP_LNKCTL, &pci_lnk_ctl);
return pci_lnk_ctl;
}
void iwl_bg_watchdog(unsigned long data);
u32 iwl_usecs_to_beacons(struct iwl_priv *priv, u32 usec, u32 beacon_interval);
__le32 iwl_add_beacon_time(struct iwl_priv *priv, u32 base,
u32 addon, u32 beacon_interval);
#ifdef CONFIG_PM
int iwl_pci_suspend(struct device *device);
int iwl_pci_resume(struct device *device);
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,29))
int iwl_pci_suspend_compat(struct pci_dev *pdev, pm_message_t state);
int iwl_pci_resume_compat(struct pci_dev *pdev);
#else
extern const struct dev_pm_ops iwl_pm_ops;
#endif
#define IWL_PM_OPS (&iwl_pm_ops)
#else /* !CONFIG_PM */
#define IWL_PM_OPS NULL
#endif /* !CONFIG_PM */
/*****************************************************
* Error Handling Debugging
******************************************************/
void iwl_dump_nic_error_log(struct iwl_priv *priv);
int iwl_dump_nic_event_log(struct iwl_priv *priv,
bool full_log, char **buf, bool display);
void iwl_dump_csr(struct iwl_priv *priv);
int iwl_dump_fh(struct iwl_priv *priv, char **buf, bool display);
#ifdef CONFIG_IWLWIFI_DEBUG
void iwl_print_rx_config_cmd(struct iwl_priv *priv,
struct iwl_rxon_context *ctx);
#else
static inline void iwl_print_rx_config_cmd(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
}
#endif
void iwl_clear_isr_stats(struct iwl_priv *priv);
/*****************************************************
* GEOS
******************************************************/
int iwlcore_init_geos(struct iwl_priv *priv);
void iwlcore_free_geos(struct iwl_priv *priv);
/*************** DRIVER STATUS FUNCTIONS *****/
#define STATUS_HCMD_ACTIVE 0 /* host command in progress */
/* 1 is unused (used to be STATUS_HCMD_SYNC_ACTIVE) */
#define STATUS_INT_ENABLED 2
#define STATUS_RF_KILL_HW 3
#define STATUS_CT_KILL 4
#define STATUS_INIT 5
#define STATUS_ALIVE 6
#define STATUS_READY 7
#define STATUS_TEMPERATURE 8
#define STATUS_GEO_CONFIGURED 9
#define STATUS_EXIT_PENDING 10
#define STATUS_STATISTICS 12
#define STATUS_SCANNING 13
#define STATUS_SCAN_ABORTING 14
#define STATUS_SCAN_HW 15
#define STATUS_POWER_PMI 16
#define STATUS_FW_ERROR 17
#define STATUS_DEVICE_ENABLED 18
#define STATUS_CHANNEL_SWITCH_PENDING 19
static inline int iwl_is_ready(struct iwl_priv *priv)
{
/* The adapter is 'ready' if READY and GEO_CONFIGURED bits are
* set but EXIT_PENDING is not */
return test_bit(STATUS_READY, &priv->status) &&
test_bit(STATUS_GEO_CONFIGURED, &priv->status) &&
!test_bit(STATUS_EXIT_PENDING, &priv->status);
}
static inline int iwl_is_alive(struct iwl_priv *priv)
{
return test_bit(STATUS_ALIVE, &priv->status);
}
static inline int iwl_is_init(struct iwl_priv *priv)
{
return test_bit(STATUS_INIT, &priv->status);
}
static inline int iwl_is_rfkill_hw(struct iwl_priv *priv)
{
return test_bit(STATUS_RF_KILL_HW, &priv->status);
}
static inline int iwl_is_rfkill(struct iwl_priv *priv)
{
return iwl_is_rfkill_hw(priv);
}
static inline int iwl_is_ctkill(struct iwl_priv *priv)
{
return test_bit(STATUS_CT_KILL, &priv->status);
}
static inline int iwl_is_ready_rf(struct iwl_priv *priv)
{
if (iwl_is_rfkill(priv))
return 0;
return iwl_is_ready(priv);
}
extern void iwl_send_bt_config(struct iwl_priv *priv);
extern int iwl_send_statistics_request(struct iwl_priv *priv,
u8 flags, bool clear);
void iwl_apm_stop(struct iwl_priv *priv);
int iwl_apm_init(struct iwl_priv *priv);
int iwl_send_rxon_timing(struct iwl_priv *priv, struct iwl_rxon_context *ctx);
static inline int iwlcore_commit_rxon(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
return priv->cfg->ops->hcmd->commit_rxon(priv, ctx);
}
static inline const struct ieee80211_supported_band *iwl_get_hw_mode(
struct iwl_priv *priv, enum ieee80211_band band)
{
return priv->hw->wiphy->bands[band];
}
static inline bool iwl_advanced_bt_coexist(struct iwl_priv *priv)
{
return priv->cfg->bt_params &&
priv->cfg->bt_params->advanced_bt_coexist;
}
extern bool bt_coex_active;
extern bool bt_siso_mode;
void iwlagn_fw_error(struct iwl_priv *priv, bool ondemand);
#endif /* __iwl_core_h__ */
| leftrepo/Owl-Kernel-for-Xperia-Sola | net/compat-wireless/drivers/net/wireless/iwlwifi/iwl-core.h | C | gpl-2.0 | 23,102 |
/* Disassembler code for CRIS.
Copyright 2000, 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc.
Contributed by Axis Communications AB, Lund, Sweden.
Written by Hans-Peter Nilsson.
This file is part of the GNU binutils and GDB, the GNU debugger.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
#include "dis-asm.h"
//#include "sysdep.h"
#include "target-cris/opcode-cris.h"
//#include "libiberty.h"
void *qemu_malloc(size_t len); /* can't include qemu-common.h here */
#define FALSE 0
#define TRUE 1
#define CONST_STRNEQ(STR1,STR2) (strncmp ((STR1), (STR2), sizeof (STR2) - 1) == 0)
/* cris-opc.c -- Table of opcodes for the CRIS processor.
Copyright 2000, 2001, 2004 Free Software Foundation, Inc.
Contributed by Axis Communications AB, Lund, Sweden.
Originally written for GAS 1.38.1 by Mikael Asker.
Reorganized by Hans-Peter Nilsson.
This file is part of GAS, GDB and the GNU binutils.
GAS, GDB, and GNU binutils is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2, or (at your
option) any later version.
GAS, GDB, and GNU binutils are distributed in the hope that they will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */
#ifndef NULL
#define NULL (0)
#endif
/* This table isn't used for CRISv32 and the size of immediate operands. */
const struct cris_spec_reg
cris_spec_regs[] =
{
{"bz", 0, 1, cris_ver_v32p, NULL},
{"p0", 0, 1, 0, NULL},
{"vr", 1, 1, 0, NULL},
{"p1", 1, 1, 0, NULL},
{"pid", 2, 1, cris_ver_v32p, NULL},
{"p2", 2, 1, cris_ver_v32p, NULL},
{"p2", 2, 1, cris_ver_warning, NULL},
{"srs", 3, 1, cris_ver_v32p, NULL},
{"p3", 3, 1, cris_ver_v32p, NULL},
{"p3", 3, 1, cris_ver_warning, NULL},
{"wz", 4, 2, cris_ver_v32p, NULL},
{"p4", 4, 2, 0, NULL},
{"ccr", 5, 2, cris_ver_v0_10, NULL},
{"exs", 5, 4, cris_ver_v32p, NULL},
{"p5", 5, 2, cris_ver_v0_10, NULL},
{"p5", 5, 4, cris_ver_v32p, NULL},
{"dcr0",6, 2, cris_ver_v0_3, NULL},
{"eda", 6, 4, cris_ver_v32p, NULL},
{"p6", 6, 2, cris_ver_v0_3, NULL},
{"p6", 6, 4, cris_ver_v32p, NULL},
{"dcr1/mof", 7, 4, cris_ver_v10p,
"Register `dcr1/mof' with ambiguous size specified. Guessing 4 bytes"},
{"dcr1/mof", 7, 2, cris_ver_v0_3,
"Register `dcr1/mof' with ambiguous size specified. Guessing 2 bytes"},
{"mof", 7, 4, cris_ver_v10p, NULL},
{"dcr1",7, 2, cris_ver_v0_3, NULL},
{"p7", 7, 4, cris_ver_v10p, NULL},
{"p7", 7, 2, cris_ver_v0_3, NULL},
{"dz", 8, 4, cris_ver_v32p, NULL},
{"p8", 8, 4, 0, NULL},
{"ibr", 9, 4, cris_ver_v0_10, NULL},
{"ebp", 9, 4, cris_ver_v32p, NULL},
{"p9", 9, 4, 0, NULL},
{"irp", 10, 4, cris_ver_v0_10, NULL},
{"erp", 10, 4, cris_ver_v32p, NULL},
{"p10", 10, 4, 0, NULL},
{"srp", 11, 4, 0, NULL},
{"p11", 11, 4, 0, NULL},
/* For disassembly use only. Accept at assembly with a warning. */
{"bar/dtp0", 12, 4, cris_ver_warning,
"Ambiguous register `bar/dtp0' specified"},
{"nrp", 12, 4, cris_ver_v32p, NULL},
{"bar", 12, 4, cris_ver_v8_10, NULL},
{"dtp0",12, 4, cris_ver_v0_3, NULL},
{"p12", 12, 4, 0, NULL},
/* For disassembly use only. Accept at assembly with a warning. */
{"dccr/dtp1",13, 4, cris_ver_warning,
"Ambiguous register `dccr/dtp1' specified"},
{"ccs", 13, 4, cris_ver_v32p, NULL},
{"dccr",13, 4, cris_ver_v8_10, NULL},
{"dtp1",13, 4, cris_ver_v0_3, NULL},
{"p13", 13, 4, 0, NULL},
{"brp", 14, 4, cris_ver_v3_10, NULL},
{"usp", 14, 4, cris_ver_v32p, NULL},
{"p14", 14, 4, cris_ver_v3p, NULL},
{"usp", 15, 4, cris_ver_v10, NULL},
{"spc", 15, 4, cris_ver_v32p, NULL},
{"p15", 15, 4, cris_ver_v10p, NULL},
{NULL, 0, 0, cris_ver_version_all, NULL}
};
/* Add version specifiers to this table when necessary.
The (now) regular coding of register names suggests a simpler
implementation. */
const struct cris_support_reg cris_support_regs[] =
{
{"s0", 0},
{"s1", 1},
{"s2", 2},
{"s3", 3},
{"s4", 4},
{"s5", 5},
{"s6", 6},
{"s7", 7},
{"s8", 8},
{"s9", 9},
{"s10", 10},
{"s11", 11},
{"s12", 12},
{"s13", 13},
{"s14", 14},
{"s15", 15},
{NULL, 0}
};
/* All CRIS opcodes are 16 bits.
- The match component is a mask saying which bits must match a
particular opcode in order for an instruction to be an instance
of that opcode.
- The args component is a string containing characters symbolically
matching the operands of an instruction. Used for both assembly
and disassembly.
Operand-matching characters:
[ ] , space
Verbatim.
A The string "ACR" (case-insensitive).
B Not really an operand. It causes a "BDAP -size,SP" prefix to be
output for the PUSH alias-instructions and recognizes a push-
prefix at disassembly. This letter isn't recognized for v32.
Must be followed by a R or P letter.
! Non-match pattern, will not match if there's a prefix insn.
b Non-matching operand, used for branches with 16-bit
displacement. Only recognized by the disassembler.
c 5-bit unsigned immediate in bits <4:0>.
C 4-bit unsigned immediate in bits <3:0>.
d At assembly, optionally (as in put other cases before this one)
".d" or ".D" at the start of the operands, followed by one space
character. At disassembly, nothing.
D General register in bits <15:12> and <3:0>.
f List of flags in bits <15:12> and <3:0>.
i 6-bit signed immediate in bits <5:0>.
I 6-bit unsigned immediate in bits <5:0>.
M Size modifier (B, W or D) for CLEAR instructions.
m Size modifier (B, W or D) in bits <5:4>
N A 32-bit dword, like in the difference between s and y.
This has no effect on bits in the opcode. Can also be expressed
as "[pc+]" in input.
n As N, but PC-relative (to the start of the instruction).
o [-128..127] word offset in bits <7:1> and <0>. Used by 8-bit
branch instructions.
O [-128..127] offset in bits <7:0>. Also matches a comma and a
general register after the expression, in bits <15:12>. Used
only for the BDAP prefix insn (in v32 the ADDOQ insn; same opcode).
P Special register in bits <15:12>.
p Indicates that the insn is a prefix insn. Must be first
character.
Q As O, but don't relax; force an 8-bit offset.
R General register in bits <15:12>.
r General register in bits <3:0>.
S Source operand in bit <10> and a prefix; a 3-operand prefix
without side-effect.
s Source operand in bits <10> and <3:0>, optionally with a
side-effect prefix, except [pc] (the name, not R15 as in ACR)
isn't allowed for v32 and higher.
T Support register in bits <15:12>.
u 4-bit (PC-relative) unsigned immediate word offset in bits <3:0>.
U Relaxes to either u or n, instruction is assumed LAPCQ or LAPC.
Not recognized at disassembly.
x Register-dot-modifier, for example "r5.w" in bits <15:12> and <5:4>.
y Like 's' but do not allow an integer at assembly.
Y The difference s-y; only an integer is allowed.
z Size modifier (B or W) in bit <4>. */
/* Please note the order of the opcodes in this table is significant.
The assembler requires that all instances of the same mnemonic must
be consecutive. If they aren't, the assembler might not recognize
them, or may indicate an internal error.
The disassembler should not normally care about the order of the
opcodes, but will prefer an earlier alternative if the "match-score"
(see cris-dis.c) is computed as equal.
It should not be significant for proper execution that this table is
in alphabetical order, but please follow that convention for an easy
overview. */
const struct cris_opcode
cris_opcodes[] =
{
{"abs", 0x06B0, 0x0940, "r,R", 0, SIZE_NONE, 0,
cris_abs_op},
{"add", 0x0600, 0x09c0, "m r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
{"add", 0x0A00, 0x01c0, "m s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"add", 0x0A00, 0x01c0, "m S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"add", 0x0a00, 0x05c0, "m S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_add_sub_cmp_and_or_op},
{"add", 0x0A00, 0x01c0, "m s,R", 0, SIZE_FIELD,
cris_ver_v32p,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"addc", 0x0570, 0x0A80, "r,R", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_not_implemented_op},
{"addc", 0x09A0, 0x0250, "s,R", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_not_implemented_op},
{"addi", 0x0540, 0x0A80, "x,r,A", 0, SIZE_NONE,
cris_ver_v32p,
cris_addi_op},
{"addi", 0x0500, 0x0Ac0, "x,r", 0, SIZE_NONE, 0,
cris_addi_op},
/* This collates after "addo", but we want to disassemble as "addoq",
not "addo". */
{"addoq", 0x0100, 0x0E00, "Q,A", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"addo", 0x0940, 0x0280, "m s,R,A", 0, SIZE_FIELD_SIGNED,
cris_ver_v32p,
cris_not_implemented_op},
/* This must be located after the insn above, lest we misinterpret
"addo.b -1,r0,acr" as "addo .b-1,r0,acr". FIXME: Sounds like a
parser bug. */
{"addo", 0x0100, 0x0E00, "O,A", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"addq", 0x0200, 0x0Dc0, "I,R", 0, SIZE_NONE, 0,
cris_quick_mode_add_sub_op},
{"adds", 0x0420, 0x0Bc0, "z r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
/* FIXME: SIZE_FIELD_SIGNED and all necessary changes. */
{"adds", 0x0820, 0x03c0, "z s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"adds", 0x0820, 0x03c0, "z S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"adds", 0x0820, 0x07c0, "z S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_add_sub_cmp_and_or_op},
{"addu", 0x0400, 0x0be0, "z r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
/* FIXME: SIZE_FIELD_UNSIGNED and all necessary changes. */
{"addu", 0x0800, 0x03e0, "z s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"addu", 0x0800, 0x03e0, "z S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"addu", 0x0800, 0x07e0, "z S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_add_sub_cmp_and_or_op},
{"and", 0x0700, 0x08C0, "m r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
{"and", 0x0B00, 0x00C0, "m s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"and", 0x0B00, 0x00C0, "m S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"and", 0x0B00, 0x04C0, "m S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_add_sub_cmp_and_or_op},
{"andq", 0x0300, 0x0CC0, "i,R", 0, SIZE_NONE, 0,
cris_quick_mode_and_cmp_move_or_op},
{"asr", 0x0780, 0x0840, "m r,R", 0, SIZE_NONE, 0,
cris_asr_op},
{"asrq", 0x03a0, 0x0c40, "c,R", 0, SIZE_NONE, 0,
cris_asrq_op},
{"ax", 0x15B0, 0xEA4F, "", 0, SIZE_NONE, 0,
cris_ax_ei_setf_op},
/* FIXME: Should use branch #defines. */
{"b", 0x0dff, 0x0200, "b", 1, SIZE_NONE, 0,
cris_sixteen_bit_offset_branch_op},
{"ba",
BA_QUICK_OPCODE,
0x0F00+(0xF-CC_A)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
/* Needs to come after the usual "ba o", which might be relaxed to
this one. */
{"ba", BA_DWORD_OPCODE,
0xffff & (~BA_DWORD_OPCODE), "n", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_none_reg_mode_jump_op},
{"bas", 0x0EBF, 0x0140, "n,P", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_none_reg_mode_jump_op},
{"basc", 0x0EFF, 0x0100, "n,P", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_none_reg_mode_jump_op},
{"bcc",
BRANCH_QUICK_OPCODE+CC_CC*0x1000,
0x0f00+(0xF-CC_CC)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bcs",
BRANCH_QUICK_OPCODE+CC_CS*0x1000,
0x0f00+(0xF-CC_CS)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bdap",
BDAP_INDIR_OPCODE, BDAP_INDIR_Z_BITS, "pm s,R", 0, SIZE_FIELD_SIGNED,
cris_ver_v0_10,
cris_bdap_prefix},
{"bdap",
BDAP_QUICK_OPCODE, BDAP_QUICK_Z_BITS, "pO", 0, SIZE_NONE,
cris_ver_v0_10,
cris_quick_mode_bdap_prefix},
{"beq",
BRANCH_QUICK_OPCODE+CC_EQ*0x1000,
0x0f00+(0xF-CC_EQ)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
/* This is deliberately put before "bext" to trump it, even though not
in alphabetical order, since we don't do excluding version checks
for v0..v10. */
{"bwf",
BRANCH_QUICK_OPCODE+CC_EXT*0x1000,
0x0f00+(0xF-CC_EXT)*0x1000, "o", 1, SIZE_NONE,
cris_ver_v10,
cris_eight_bit_offset_branch_op},
{"bext",
BRANCH_QUICK_OPCODE+CC_EXT*0x1000,
0x0f00+(0xF-CC_EXT)*0x1000, "o", 1, SIZE_NONE,
cris_ver_v0_3,
cris_eight_bit_offset_branch_op},
{"bge",
BRANCH_QUICK_OPCODE+CC_GE*0x1000,
0x0f00+(0xF-CC_GE)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bgt",
BRANCH_QUICK_OPCODE+CC_GT*0x1000,
0x0f00+(0xF-CC_GT)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bhi",
BRANCH_QUICK_OPCODE+CC_HI*0x1000,
0x0f00+(0xF-CC_HI)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bhs",
BRANCH_QUICK_OPCODE+CC_HS*0x1000,
0x0f00+(0xF-CC_HS)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"biap", BIAP_OPCODE, BIAP_Z_BITS, "pm r,R", 0, SIZE_NONE,
cris_ver_v0_10,
cris_biap_prefix},
{"ble",
BRANCH_QUICK_OPCODE+CC_LE*0x1000,
0x0f00+(0xF-CC_LE)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"blo",
BRANCH_QUICK_OPCODE+CC_LO*0x1000,
0x0f00+(0xF-CC_LO)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bls",
BRANCH_QUICK_OPCODE+CC_LS*0x1000,
0x0f00+(0xF-CC_LS)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"blt",
BRANCH_QUICK_OPCODE+CC_LT*0x1000,
0x0f00+(0xF-CC_LT)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bmi",
BRANCH_QUICK_OPCODE+CC_MI*0x1000,
0x0f00+(0xF-CC_MI)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bmod", 0x0ab0, 0x0140, "s,R", 0, SIZE_FIX_32,
cris_ver_sim_v0_10,
cris_not_implemented_op},
{"bmod", 0x0ab0, 0x0140, "S,D", 0, SIZE_NONE,
cris_ver_sim_v0_10,
cris_not_implemented_op},
{"bmod", 0x0ab0, 0x0540, "S,R,r", 0, SIZE_NONE,
cris_ver_sim_v0_10,
cris_not_implemented_op},
{"bne",
BRANCH_QUICK_OPCODE+CC_NE*0x1000,
0x0f00+(0xF-CC_NE)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bound", 0x05c0, 0x0A00, "m r,R", 0, SIZE_NONE, 0,
cris_two_operand_bound_op},
/* FIXME: SIZE_FIELD_UNSIGNED and all necessary changes. */
{"bound", 0x09c0, 0x0200, "m s,R", 0, SIZE_FIELD,
cris_ver_v0_10,
cris_two_operand_bound_op},
/* FIXME: SIZE_FIELD_UNSIGNED and all necessary changes. */
{"bound", 0x0dcf, 0x0200, "m Y,R", 0, SIZE_FIELD, 0,
cris_two_operand_bound_op},
{"bound", 0x09c0, 0x0200, "m S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_two_operand_bound_op},
{"bound", 0x09c0, 0x0600, "m S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_bound_op},
{"bpl",
BRANCH_QUICK_OPCODE+CC_PL*0x1000,
0x0f00+(0xF-CC_PL)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"break", 0xe930, 0x16c0, "C", 0, SIZE_NONE,
cris_ver_v3p,
cris_break_op},
{"bsb",
BRANCH_QUICK_OPCODE+CC_EXT*0x1000,
0x0f00+(0xF-CC_EXT)*0x1000, "o", 1, SIZE_NONE,
cris_ver_v32p,
cris_eight_bit_offset_branch_op},
{"bsr", 0xBEBF, 0x4140, "n", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_none_reg_mode_jump_op},
{"bsrc", 0xBEFF, 0x4100, "n", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_none_reg_mode_jump_op},
{"bstore", 0x0af0, 0x0100, "s,R", 0, SIZE_FIX_32,
cris_ver_warning,
cris_not_implemented_op},
{"bstore", 0x0af0, 0x0100, "S,D", 0, SIZE_NONE,
cris_ver_warning,
cris_not_implemented_op},
{"bstore", 0x0af0, 0x0500, "S,R,r", 0, SIZE_NONE,
cris_ver_warning,
cris_not_implemented_op},
{"btst", 0x04F0, 0x0B00, "r,R", 0, SIZE_NONE, 0,
cris_btst_nop_op},
{"btstq", 0x0380, 0x0C60, "c,R", 0, SIZE_NONE, 0,
cris_btst_nop_op},
{"bvc",
BRANCH_QUICK_OPCODE+CC_VC*0x1000,
0x0f00+(0xF-CC_VC)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"bvs",
BRANCH_QUICK_OPCODE+CC_VS*0x1000,
0x0f00+(0xF-CC_VS)*0x1000, "o", 1, SIZE_NONE, 0,
cris_eight_bit_offset_branch_op},
{"clear", 0x0670, 0x3980, "M r", 0, SIZE_NONE, 0,
cris_reg_mode_clear_op},
{"clear", 0x0A70, 0x3180, "M y", 0, SIZE_NONE, 0,
cris_none_reg_mode_clear_test_op},
{"clear", 0x0A70, 0x3180, "M S", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_clear_test_op},
{"clearf", 0x05F0, 0x0A00, "f", 0, SIZE_NONE, 0,
cris_clearf_di_op},
{"cmp", 0x06C0, 0x0900, "m r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
{"cmp", 0x0Ac0, 0x0100, "m s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"cmp", 0x0Ac0, 0x0100, "m S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"cmpq", 0x02C0, 0x0D00, "i,R", 0, SIZE_NONE, 0,
cris_quick_mode_and_cmp_move_or_op},
/* FIXME: SIZE_FIELD_SIGNED and all necessary changes. */
{"cmps", 0x08e0, 0x0300, "z s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"cmps", 0x08e0, 0x0300, "z S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
/* FIXME: SIZE_FIELD_UNSIGNED and all necessary changes. */
{"cmpu", 0x08c0, 0x0320, "z s,R" , 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"cmpu", 0x08c0, 0x0320, "z S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"di", 0x25F0, 0xDA0F, "", 0, SIZE_NONE, 0,
cris_clearf_di_op},
{"dip", DIP_OPCODE, DIP_Z_BITS, "ps", 0, SIZE_FIX_32,
cris_ver_v0_10,
cris_dip_prefix},
{"div", 0x0980, 0x0640, "m R,r", 0, SIZE_FIELD, 0,
cris_not_implemented_op},
{"dstep", 0x06f0, 0x0900, "r,R", 0, SIZE_NONE, 0,
cris_dstep_logshift_mstep_neg_not_op},
{"ei", 0x25B0, 0xDA4F, "", 0, SIZE_NONE, 0,
cris_ax_ei_setf_op},
{"fidxd", 0x0ab0, 0xf540, "[r]", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"fidxi", 0x0d30, 0xF2C0, "[r]", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"ftagd", 0x1AB0, 0xE540, "[r]", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"ftagi", 0x1D30, 0xE2C0, "[r]", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"halt", 0xF930, 0x06CF, "", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"jas", 0x09B0, 0x0640, "r,P", 0, SIZE_NONE,
cris_ver_v32p,
cris_reg_mode_jump_op},
{"jas", 0x0DBF, 0x0240, "N,P", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_reg_mode_jump_op},
{"jasc", 0x0B30, 0x04C0, "r,P", 0, SIZE_NONE,
cris_ver_v32p,
cris_reg_mode_jump_op},
{"jasc", 0x0F3F, 0x00C0, "N,P", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_reg_mode_jump_op},
{"jbrc", 0x69b0, 0x9640, "r", 0, SIZE_NONE,
cris_ver_v8_10,
cris_reg_mode_jump_op},
{"jbrc", 0x6930, 0x92c0, "s", 0, SIZE_FIX_32,
cris_ver_v8_10,
cris_none_reg_mode_jump_op},
{"jbrc", 0x6930, 0x92c0, "S", 0, SIZE_NONE,
cris_ver_v8_10,
cris_none_reg_mode_jump_op},
{"jir", 0xA9b0, 0x5640, "r", 0, SIZE_NONE,
cris_ver_v8_10,
cris_reg_mode_jump_op},
{"jir", 0xA930, 0x52c0, "s", 0, SIZE_FIX_32,
cris_ver_v8_10,
cris_none_reg_mode_jump_op},
{"jir", 0xA930, 0x52c0, "S", 0, SIZE_NONE,
cris_ver_v8_10,
cris_none_reg_mode_jump_op},
{"jirc", 0x29b0, 0xd640, "r", 0, SIZE_NONE,
cris_ver_v8_10,
cris_reg_mode_jump_op},
{"jirc", 0x2930, 0xd2c0, "s", 0, SIZE_FIX_32,
cris_ver_v8_10,
cris_none_reg_mode_jump_op},
{"jirc", 0x2930, 0xd2c0, "S", 0, SIZE_NONE,
cris_ver_v8_10,
cris_none_reg_mode_jump_op},
{"jsr", 0xB9b0, 0x4640, "r", 0, SIZE_NONE, 0,
cris_reg_mode_jump_op},
{"jsr", 0xB930, 0x42c0, "s", 0, SIZE_FIX_32,
cris_ver_v0_10,
cris_none_reg_mode_jump_op},
{"jsr", 0xBDBF, 0x4240, "N", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_none_reg_mode_jump_op},
{"jsr", 0xB930, 0x42c0, "S", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_jump_op},
{"jsrc", 0x39b0, 0xc640, "r", 0, SIZE_NONE,
cris_ver_v8_10,
cris_reg_mode_jump_op},
{"jsrc", 0x3930, 0xc2c0, "s", 0, SIZE_FIX_32,
cris_ver_v8_10,
cris_none_reg_mode_jump_op},
{"jsrc", 0x3930, 0xc2c0, "S", 0, SIZE_NONE,
cris_ver_v8_10,
cris_none_reg_mode_jump_op},
{"jsrc", 0xBB30, 0x44C0, "r", 0, SIZE_NONE,
cris_ver_v32p,
cris_reg_mode_jump_op},
{"jsrc", 0xBF3F, 0x40C0, "N", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_reg_mode_jump_op},
{"jump", 0x09b0, 0xF640, "r", 0, SIZE_NONE, 0,
cris_reg_mode_jump_op},
{"jump",
JUMP_INDIR_OPCODE, JUMP_INDIR_Z_BITS, "s", 0, SIZE_FIX_32,
cris_ver_v0_10,
cris_none_reg_mode_jump_op},
{"jump",
JUMP_INDIR_OPCODE, JUMP_INDIR_Z_BITS, "S", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_jump_op},
{"jump", 0x09F0, 0x060F, "P", 0, SIZE_NONE,
cris_ver_v32p,
cris_none_reg_mode_jump_op},
{"jump",
JUMP_PC_INCR_OPCODE_V32,
(0xffff & ~JUMP_PC_INCR_OPCODE_V32), "N", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_none_reg_mode_jump_op},
{"jmpu", 0x8930, 0x72c0, "s", 0, SIZE_FIX_32,
cris_ver_v10,
cris_none_reg_mode_jump_op},
{"jmpu", 0x8930, 0x72c0, "S", 0, SIZE_NONE,
cris_ver_v10,
cris_none_reg_mode_jump_op},
{"lapc", 0x0970, 0x0680, "U,R", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"lapc", 0x0D7F, 0x0280, "dn,R", 0, SIZE_FIX_32,
cris_ver_v32p,
cris_not_implemented_op},
{"lapcq", 0x0970, 0x0680, "u,R", 0, SIZE_NONE,
cris_ver_v32p,
cris_addi_op},
{"lsl", 0x04C0, 0x0B00, "m r,R", 0, SIZE_NONE, 0,
cris_dstep_logshift_mstep_neg_not_op},
{"lslq", 0x03c0, 0x0C20, "c,R", 0, SIZE_NONE, 0,
cris_dstep_logshift_mstep_neg_not_op},
{"lsr", 0x07C0, 0x0800, "m r,R", 0, SIZE_NONE, 0,
cris_dstep_logshift_mstep_neg_not_op},
{"lsrq", 0x03e0, 0x0C00, "c,R", 0, SIZE_NONE, 0,
cris_dstep_logshift_mstep_neg_not_op},
{"lz", 0x0730, 0x08C0, "r,R", 0, SIZE_NONE,
cris_ver_v3p,
cris_not_implemented_op},
{"mcp", 0x07f0, 0x0800, "P,r", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"move", 0x0640, 0x0980, "m r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
{"move", 0x0A40, 0x0180, "m s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"move", 0x0A40, 0x0180, "m S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"move", 0x0630, 0x09c0, "r,P", 0, SIZE_NONE, 0,
cris_move_to_preg_op},
{"move", 0x0670, 0x0980, "P,r", 0, SIZE_NONE, 0,
cris_reg_mode_move_from_preg_op},
{"move", 0x0BC0, 0x0000, "m R,y", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"move", 0x0BC0, 0x0000, "m D,S", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"move",
MOVE_M_TO_PREG_OPCODE, MOVE_M_TO_PREG_ZBITS,
"s,P", 0, SIZE_SPEC_REG, 0,
cris_move_to_preg_op},
{"move", 0x0A30, 0x01c0, "S,P", 0, SIZE_NONE,
cris_ver_v0_10,
cris_move_to_preg_op},
{"move", 0x0A70, 0x0180, "P,y", 0, SIZE_SPEC_REG, 0,
cris_none_reg_mode_move_from_preg_op},
{"move", 0x0A70, 0x0180, "P,S", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_move_from_preg_op},
{"move", 0x0B70, 0x0480, "r,T", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"move", 0x0F70, 0x0080, "T,r", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"movem", 0x0BF0, 0x0000, "R,y", 0, SIZE_FIX_32, 0,
cris_move_reg_to_mem_movem_op},
{"movem", 0x0BF0, 0x0000, "D,S", 0, SIZE_NONE,
cris_ver_v0_10,
cris_move_reg_to_mem_movem_op},
{"movem", 0x0BB0, 0x0040, "s,R", 0, SIZE_FIX_32, 0,
cris_move_mem_to_reg_movem_op},
{"movem", 0x0BB0, 0x0040, "S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_move_mem_to_reg_movem_op},
{"moveq", 0x0240, 0x0D80, "i,R", 0, SIZE_NONE, 0,
cris_quick_mode_and_cmp_move_or_op},
{"movs", 0x0460, 0x0B80, "z r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
/* FIXME: SIZE_FIELD_SIGNED and all necessary changes. */
{"movs", 0x0860, 0x0380, "z s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"movs", 0x0860, 0x0380, "z S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"movu", 0x0440, 0x0Ba0, "z r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
/* FIXME: SIZE_FIELD_UNSIGNED and all necessary changes. */
{"movu", 0x0840, 0x03a0, "z s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"movu", 0x0840, 0x03a0, "z S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"mstep", 0x07f0, 0x0800, "r,R", 0, SIZE_NONE,
cris_ver_v0_10,
cris_dstep_logshift_mstep_neg_not_op},
{"muls", 0x0d00, 0x02c0, "m r,R", 0, SIZE_NONE,
cris_ver_v10p,
cris_muls_op},
{"mulu", 0x0900, 0x06c0, "m r,R", 0, SIZE_NONE,
cris_ver_v10p,
cris_mulu_op},
{"neg", 0x0580, 0x0A40, "m r,R", 0, SIZE_NONE, 0,
cris_dstep_logshift_mstep_neg_not_op},
{"nop", NOP_OPCODE, NOP_Z_BITS, "", 0, SIZE_NONE,
cris_ver_v0_10,
cris_btst_nop_op},
{"nop", NOP_OPCODE_V32, NOP_Z_BITS_V32, "", 0, SIZE_NONE,
cris_ver_v32p,
cris_btst_nop_op},
{"not", 0x8770, 0x7880, "r", 0, SIZE_NONE, 0,
cris_dstep_logshift_mstep_neg_not_op},
{"or", 0x0740, 0x0880, "m r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
{"or", 0x0B40, 0x0080, "m s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"or", 0x0B40, 0x0080, "m S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"or", 0x0B40, 0x0480, "m S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_add_sub_cmp_and_or_op},
{"orq", 0x0340, 0x0C80, "i,R", 0, SIZE_NONE, 0,
cris_quick_mode_and_cmp_move_or_op},
{"pop", 0x0E6E, 0x0191, "!R", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"pop", 0x0e3e, 0x01c1, "!P", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_move_from_preg_op},
{"push", 0x0FEE, 0x0011, "BR", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"push", 0x0E7E, 0x0181, "BP", 0, SIZE_NONE,
cris_ver_v0_10,
cris_move_to_preg_op},
{"rbf", 0x3b30, 0xc0c0, "y", 0, SIZE_NONE,
cris_ver_v10,
cris_not_implemented_op},
{"rbf", 0x3b30, 0xc0c0, "S", 0, SIZE_NONE,
cris_ver_v10,
cris_not_implemented_op},
{"rfe", 0x2930, 0xD6CF, "", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"rfg", 0x4930, 0xB6CF, "", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"rfn", 0x5930, 0xA6CF, "", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
{"ret", 0xB67F, 0x4980, "", 1, SIZE_NONE,
cris_ver_v0_10,
cris_reg_mode_move_from_preg_op},
{"ret", 0xB9F0, 0x460F, "", 1, SIZE_NONE,
cris_ver_v32p,
cris_reg_mode_move_from_preg_op},
{"retb", 0xe67f, 0x1980, "", 1, SIZE_NONE,
cris_ver_v0_10,
cris_reg_mode_move_from_preg_op},
{"rete", 0xA9F0, 0x560F, "", 1, SIZE_NONE,
cris_ver_v32p,
cris_reg_mode_move_from_preg_op},
{"reti", 0xA67F, 0x5980, "", 1, SIZE_NONE,
cris_ver_v0_10,
cris_reg_mode_move_from_preg_op},
{"retn", 0xC9F0, 0x360F, "", 1, SIZE_NONE,
cris_ver_v32p,
cris_reg_mode_move_from_preg_op},
{"sbfs", 0x3b70, 0xc080, "y", 0, SIZE_NONE,
cris_ver_v10,
cris_not_implemented_op},
{"sbfs", 0x3b70, 0xc080, "S", 0, SIZE_NONE,
cris_ver_v10,
cris_not_implemented_op},
{"sa",
0x0530+CC_A*0x1000,
0x0AC0+(0xf-CC_A)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"ssb",
0x0530+CC_EXT*0x1000,
0x0AC0+(0xf-CC_EXT)*0x1000, "r", 0, SIZE_NONE,
cris_ver_v32p,
cris_scc_op},
{"scc",
0x0530+CC_CC*0x1000,
0x0AC0+(0xf-CC_CC)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"scs",
0x0530+CC_CS*0x1000,
0x0AC0+(0xf-CC_CS)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"seq",
0x0530+CC_EQ*0x1000,
0x0AC0+(0xf-CC_EQ)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"setf", 0x05b0, 0x0A40, "f", 0, SIZE_NONE, 0,
cris_ax_ei_setf_op},
{"sfe", 0x3930, 0xC6CF, "", 0, SIZE_NONE,
cris_ver_v32p,
cris_not_implemented_op},
/* Need to have "swf" in front of "sext" so it is the one displayed in
disassembly. */
{"swf",
0x0530+CC_EXT*0x1000,
0x0AC0+(0xf-CC_EXT)*0x1000, "r", 0, SIZE_NONE,
cris_ver_v10,
cris_scc_op},
{"sext",
0x0530+CC_EXT*0x1000,
0x0AC0+(0xf-CC_EXT)*0x1000, "r", 0, SIZE_NONE,
cris_ver_v0_3,
cris_scc_op},
{"sge",
0x0530+CC_GE*0x1000,
0x0AC0+(0xf-CC_GE)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"sgt",
0x0530+CC_GT*0x1000,
0x0AC0+(0xf-CC_GT)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"shi",
0x0530+CC_HI*0x1000,
0x0AC0+(0xf-CC_HI)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"shs",
0x0530+CC_HS*0x1000,
0x0AC0+(0xf-CC_HS)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"sle",
0x0530+CC_LE*0x1000,
0x0AC0+(0xf-CC_LE)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"slo",
0x0530+CC_LO*0x1000,
0x0AC0+(0xf-CC_LO)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"sls",
0x0530+CC_LS*0x1000,
0x0AC0+(0xf-CC_LS)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"slt",
0x0530+CC_LT*0x1000,
0x0AC0+(0xf-CC_LT)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"smi",
0x0530+CC_MI*0x1000,
0x0AC0+(0xf-CC_MI)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"sne",
0x0530+CC_NE*0x1000,
0x0AC0+(0xf-CC_NE)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"spl",
0x0530+CC_PL*0x1000,
0x0AC0+(0xf-CC_PL)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"sub", 0x0680, 0x0940, "m r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
{"sub", 0x0a80, 0x0140, "m s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"sub", 0x0a80, 0x0140, "m S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"sub", 0x0a80, 0x0540, "m S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_add_sub_cmp_and_or_op},
{"subq", 0x0280, 0x0d40, "I,R", 0, SIZE_NONE, 0,
cris_quick_mode_add_sub_op},
{"subs", 0x04a0, 0x0b40, "z r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
/* FIXME: SIZE_FIELD_SIGNED and all necessary changes. */
{"subs", 0x08a0, 0x0340, "z s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"subs", 0x08a0, 0x0340, "z S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"subs", 0x08a0, 0x0740, "z S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_add_sub_cmp_and_or_op},
{"subu", 0x0480, 0x0b60, "z r,R", 0, SIZE_NONE, 0,
cris_reg_mode_add_sub_cmp_and_or_move_op},
/* FIXME: SIZE_FIELD_UNSIGNED and all necessary changes. */
{"subu", 0x0880, 0x0360, "z s,R", 0, SIZE_FIELD, 0,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"subu", 0x0880, 0x0360, "z S,D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_add_sub_cmp_and_or_move_op},
{"subu", 0x0880, 0x0760, "z S,R,r", 0, SIZE_NONE,
cris_ver_v0_10,
cris_three_operand_add_sub_cmp_and_or_op},
{"svc",
0x0530+CC_VC*0x1000,
0x0AC0+(0xf-CC_VC)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
{"svs",
0x0530+CC_VS*0x1000,
0x0AC0+(0xf-CC_VS)*0x1000, "r", 0, SIZE_NONE, 0,
cris_scc_op},
/* The insn "swapn" is the same as "not" and will be disassembled as
such, but the swap* family of mnmonics are generally v8-and-higher
only, so count it in. */
{"swapn", 0x8770, 0x7880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapw", 0x4770, 0xb880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapnw", 0xc770, 0x3880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapb", 0x2770, 0xd880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapnb", 0xA770, 0x5880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapwb", 0x6770, 0x9880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapnwb", 0xE770, 0x1880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapr", 0x1770, 0xe880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapnr", 0x9770, 0x6880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapwr", 0x5770, 0xa880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapnwr", 0xd770, 0x2880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapbr", 0x3770, 0xc880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapnbr", 0xb770, 0x4880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapwbr", 0x7770, 0x8880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"swapnwbr", 0xf770, 0x0880, "r", 0, SIZE_NONE,
cris_ver_v8p,
cris_not_implemented_op},
{"test", 0x0640, 0x0980, "m D", 0, SIZE_NONE,
cris_ver_v0_10,
cris_reg_mode_test_op},
{"test", 0x0b80, 0xf040, "m y", 0, SIZE_FIELD, 0,
cris_none_reg_mode_clear_test_op},
{"test", 0x0b80, 0xf040, "m S", 0, SIZE_NONE,
cris_ver_v0_10,
cris_none_reg_mode_clear_test_op},
{"xor", 0x07B0, 0x0840, "r,R", 0, SIZE_NONE, 0,
cris_xor_op},
{NULL, 0, 0, NULL, 0, 0, 0, cris_not_implemented_op}
};
/* Condition-names, indexed by the CC_* numbers as found in cris.h. */
const char * const
cris_cc_strings[] =
{
"hs",
"lo",
"ne",
"eq",
"vc",
"vs",
"pl",
"mi",
"ls",
"hi",
"ge",
"lt",
"gt",
"le",
"a",
/* This is a placeholder. In v0, this would be "ext". In v32, this
is "sb". See cris_conds15. */
"wf"
};
/* Different names and semantics for condition 1111 (0xf). */
const struct cris_cond15 cris_cond15s[] =
{
/* FIXME: In what version did condition "ext" disappear? */
{"ext", cris_ver_v0_3},
{"wf", cris_ver_v10},
{"sb", cris_ver_v32p},
{NULL, 0}
};
/*
* Local variables:
* eval: (c-set-style "gnu")
* indent-tabs-mode: t
* End:
*/
/* No instruction will be disassembled longer than this. In theory, and
in silicon, address prefixes can be cascaded. In practice, cascading
is not used by GCC, and not supported by the assembler. */
#ifndef MAX_BYTES_PER_CRIS_INSN
#define MAX_BYTES_PER_CRIS_INSN 8
#endif
/* Whether or not to decode prefixes, folding it into the following
instruction. FIXME: Make this optional later. */
#ifndef PARSE_PREFIX
#define PARSE_PREFIX 1
#endif
/* Sometimes we prefix all registers with this character. */
#define REGISTER_PREFIX_CHAR '$'
/* Whether or not to trace the following sequence:
sub* X,r%d
bound* Y,r%d
adds.w [pc+r%d.w],pc
This is the assembly form of a switch-statement in C.
The "sub is optional. If there is none, then X will be zero.
X is the value of the first case,
Y is the number of cases (including default).
This results in case offsets printed on the form:
case N: -> case_address
where N is an estimation on the corresponding 'case' operand in C,
and case_address is where execution of that case continues after the
sequence presented above.
The old style of output was to print the offsets as instructions,
which made it hard to follow "case"-constructs in the disassembly,
and caused a lot of annoying warnings about undefined instructions.
FIXME: Make this optional later. */
#ifndef TRACE_CASE
#define TRACE_CASE (disdata->trace_case)
#endif
enum cris_disass_family
{ cris_dis_v0_v10, cris_dis_common_v10_v32, cris_dis_v32 };
/* Stored in the disasm_info->private_data member. */
struct cris_disasm_data
{
/* Whether to print something less confusing if we find something
matching a switch-construct. */
bfd_boolean trace_case;
/* Whether this code is flagged as crisv32. FIXME: Should be an enum
that includes "compatible". */
enum cris_disass_family distype;
};
/* Value of first element in switch. */
static long case_offset = 0;
/* How many more case-offsets to print. */
static long case_offset_counter = 0;
/* Number of case offsets. */
static long no_of_case_offsets = 0;
/* Candidate for next case_offset. */
static long last_immediate = 0;
static int cris_constraint
(const char *, unsigned, unsigned, struct cris_disasm_data *);
/* Parse disassembler options and store state in info. FIXME: For the
time being, we abuse static variables. */
static bfd_boolean
cris_parse_disassembler_options (disassemble_info *info,
enum cris_disass_family distype)
{
struct cris_disasm_data *disdata;
info->private_data = calloc (1, sizeof (struct cris_disasm_data));
disdata = (struct cris_disasm_data *) info->private_data;
if (disdata == NULL)
return FALSE;
/* Default true. */
disdata->trace_case
= (info->disassembler_options == NULL
|| (strcmp (info->disassembler_options, "nocase") != 0));
disdata->distype = distype;
return TRUE;
}
static const struct cris_spec_reg *
spec_reg_info (unsigned int sreg, enum cris_disass_family distype)
{
int i;
for (i = 0; cris_spec_regs[i].name != NULL; i++)
{
if (cris_spec_regs[i].number == sreg)
{
if (distype == cris_dis_v32)
switch (cris_spec_regs[i].applicable_version)
{
case cris_ver_warning:
case cris_ver_version_all:
case cris_ver_v3p:
case cris_ver_v8p:
case cris_ver_v10p:
case cris_ver_v32p:
/* No ambiguous sizes or register names with CRISv32. */
if (cris_spec_regs[i].warning == NULL)
return &cris_spec_regs[i];
default:
;
}
else if (cris_spec_regs[i].applicable_version != cris_ver_v32p)
return &cris_spec_regs[i];
}
}
return NULL;
}
/* Return the number of bits in the argument. */
static int
number_of_bits (unsigned int val)
{
int bits;
for (bits = 0; val != 0; val &= val - 1)
bits++;
return bits;
}
/* Get an entry in the opcode-table. */
static const struct cris_opcode *
get_opcode_entry (unsigned int insn,
unsigned int prefix_insn,
struct cris_disasm_data *disdata)
{
/* For non-prefixed insns, we keep a table of pointers, indexed by the
insn code. Each entry is initialized when found to be NULL. */
static const struct cris_opcode **opc_table = NULL;
const struct cris_opcode *max_matchedp = NULL;
const struct cris_opcode **prefix_opc_table = NULL;
/* We hold a table for each prefix that need to be handled differently. */
static const struct cris_opcode **dip_prefixes = NULL;
static const struct cris_opcode **bdapq_m1_prefixes = NULL;
static const struct cris_opcode **bdapq_m2_prefixes = NULL;
static const struct cris_opcode **bdapq_m4_prefixes = NULL;
static const struct cris_opcode **rest_prefixes = NULL;
/* Allocate and clear the opcode-table. */
if (opc_table == NULL)
{
opc_table = qemu_malloc (65536 * sizeof (opc_table[0]));
memset (opc_table, 0, 65536 * sizeof (const struct cris_opcode *));
dip_prefixes
= qemu_malloc (65536 * sizeof (const struct cris_opcode **));
memset (dip_prefixes, 0, 65536 * sizeof (dip_prefixes[0]));
bdapq_m1_prefixes
= qemu_malloc (65536 * sizeof (const struct cris_opcode **));
memset (bdapq_m1_prefixes, 0, 65536 * sizeof (bdapq_m1_prefixes[0]));
bdapq_m2_prefixes
= qemu_malloc (65536 * sizeof (const struct cris_opcode **));
memset (bdapq_m2_prefixes, 0, 65536 * sizeof (bdapq_m2_prefixes[0]));
bdapq_m4_prefixes
= qemu_malloc (65536 * sizeof (const struct cris_opcode **));
memset (bdapq_m4_prefixes, 0, 65536 * sizeof (bdapq_m4_prefixes[0]));
rest_prefixes
= qemu_malloc (65536 * sizeof (const struct cris_opcode **));
memset (rest_prefixes, 0, 65536 * sizeof (rest_prefixes[0]));
}
/* Get the right table if this is a prefix.
This code is connected to cris_constraints in that it knows what
prefixes play a role in recognition of patterns; the necessary
state is reflected by which table is used. If constraints
involving match or non-match of prefix insns are changed, then this
probably needs changing too. */
if (prefix_insn != NO_CRIS_PREFIX)
{
const struct cris_opcode *popcodep
= (opc_table[prefix_insn] != NULL
? opc_table[prefix_insn]
: get_opcode_entry (prefix_insn, NO_CRIS_PREFIX, disdata));
if (popcodep == NULL)
return NULL;
if (popcodep->match == BDAP_QUICK_OPCODE)
{
/* Since some offsets are recognized with "push" macros, we
have to have different tables for them. */
int offset = (prefix_insn & 255);
if (offset > 127)
offset -= 256;
switch (offset)
{
case -4:
prefix_opc_table = bdapq_m4_prefixes;
break;
case -2:
prefix_opc_table = bdapq_m2_prefixes;
break;
case -1:
prefix_opc_table = bdapq_m1_prefixes;
break;
default:
prefix_opc_table = rest_prefixes;
break;
}
}
else if (popcodep->match == DIP_OPCODE)
/* We don't allow postincrement when the prefix is DIP, so use a
different table for DIP. */
prefix_opc_table = dip_prefixes;
else
prefix_opc_table = rest_prefixes;
}
if (prefix_insn != NO_CRIS_PREFIX
&& prefix_opc_table[insn] != NULL)
max_matchedp = prefix_opc_table[insn];
else if (prefix_insn == NO_CRIS_PREFIX && opc_table[insn] != NULL)
max_matchedp = opc_table[insn];
else
{
const struct cris_opcode *opcodep;
int max_level_of_match = -1;
for (opcodep = cris_opcodes;
opcodep->name != NULL;
opcodep++)
{
int level_of_match;
if (disdata->distype == cris_dis_v32)
{
switch (opcodep->applicable_version)
{
case cris_ver_version_all:
break;
case cris_ver_v0_3:
case cris_ver_v0_10:
case cris_ver_v3_10:
case cris_ver_sim_v0_10:
case cris_ver_v8_10:
case cris_ver_v10:
case cris_ver_warning:
continue;
case cris_ver_v3p:
case cris_ver_v8p:
case cris_ver_v10p:
case cris_ver_v32p:
break;
case cris_ver_v8:
abort ();
default:
abort ();
}
}
else
{
switch (opcodep->applicable_version)
{
case cris_ver_version_all:
case cris_ver_v0_3:
case cris_ver_v3p:
case cris_ver_v0_10:
case cris_ver_v8p:
case cris_ver_v8_10:
case cris_ver_v10:
case cris_ver_sim_v0_10:
case cris_ver_v10p:
case cris_ver_warning:
break;
case cris_ver_v32p:
continue;
case cris_ver_v8:
abort ();
default:
abort ();
}
}
/* We give a double lead for bits matching the template in
cris_opcodes. Not even, because then "move p8,r10" would
be given 2 bits lead over "clear.d r10". When there's a
tie, the first entry in the table wins. This is
deliberate, to avoid a more complicated recognition
formula. */
if ((opcodep->match & insn) == opcodep->match
&& (opcodep->lose & insn) == 0
&& ((level_of_match
= cris_constraint (opcodep->args,
insn,
prefix_insn,
disdata))
>= 0)
&& ((level_of_match
+= 2 * number_of_bits (opcodep->match
| opcodep->lose))
> max_level_of_match))
{
max_matchedp = opcodep;
max_level_of_match = level_of_match;
/* If there was a full match, never mind looking
further. */
if (level_of_match >= 2 * 16)
break;
}
}
/* Fill in the new entry.
If there are changes to the opcode-table involving prefixes, and
disassembly then does not work correctly, try removing the
else-clause below that fills in the prefix-table. If that
helps, you need to change the prefix_opc_table setting above, or
something related. */
if (prefix_insn == NO_CRIS_PREFIX)
opc_table[insn] = max_matchedp;
else
prefix_opc_table[insn] = max_matchedp;
}
return max_matchedp;
}
/* Return -1 if the constraints of a bitwise-matched instruction say
that there is no match. Otherwise return a nonnegative number
indicating the confidence in the match (higher is better). */
static int
cris_constraint (const char *cs,
unsigned int insn,
unsigned int prefix_insn,
struct cris_disasm_data *disdata)
{
int retval = 0;
int tmp;
int prefix_ok = 0;
const char *s;
for (s = cs; *s; s++)
switch (*s)
{
case '!':
/* Do not recognize "pop" if there's a prefix and then only for
v0..v10. */
if (prefix_insn != NO_CRIS_PREFIX
|| disdata->distype != cris_dis_v0_v10)
return -1;
break;
case 'U':
/* Not recognized at disassembly. */
return -1;
case 'M':
/* Size modifier for "clear", i.e. special register 0, 4 or 8.
Check that it is one of them. Only special register 12 could
be mismatched, but checking for matches is more logical than
checking for mismatches when there are only a few cases. */
tmp = ((insn >> 12) & 0xf);
if (tmp != 0 && tmp != 4 && tmp != 8)
return -1;
break;
case 'm':
if ((insn & 0x30) == 0x30)
return -1;
break;
case 'S':
/* A prefix operand without side-effect. */
if (prefix_insn != NO_CRIS_PREFIX && (insn & 0x400) == 0)
{
prefix_ok = 1;
break;
}
else
return -1;
case 's':
case 'y':
case 'Y':
/* If this is a prefixed insn with postincrement (side-effect),
the prefix must not be DIP. */
if (prefix_insn != NO_CRIS_PREFIX)
{
if (insn & 0x400)
{
const struct cris_opcode *prefix_opcodep
= get_opcode_entry (prefix_insn, NO_CRIS_PREFIX, disdata);
if (prefix_opcodep->match == DIP_OPCODE)
return -1;
}
prefix_ok = 1;
}
break;
case 'B':
/* If we don't fall through, then the prefix is ok. */
prefix_ok = 1;
/* A "push" prefix. Check for valid "push" size.
In case of special register, it may be != 4. */
if (prefix_insn != NO_CRIS_PREFIX)
{
/* Match the prefix insn to BDAPQ. */
const struct cris_opcode *prefix_opcodep
= get_opcode_entry (prefix_insn, NO_CRIS_PREFIX, disdata);
if (prefix_opcodep->match == BDAP_QUICK_OPCODE)
{
int pushsize = (prefix_insn & 255);
if (pushsize > 127)
pushsize -= 256;
if (s[1] == 'P')
{
unsigned int spec_reg = (insn >> 12) & 15;
const struct cris_spec_reg *sregp
= spec_reg_info (spec_reg, disdata->distype);
/* For a special-register, the "prefix size" must
match the size of the register. */
if (sregp && sregp->reg_size == (unsigned int) -pushsize)
break;
}
else if (s[1] == 'R')
{
if ((insn & 0x30) == 0x20 && pushsize == -4)
break;
}
/* FIXME: Should abort here; next constraint letter
*must* be 'P' or 'R'. */
}
}
return -1;
case 'D':
retval = (((insn >> 12) & 15) == (insn & 15));
if (!retval)
return -1;
else
retval += 4;
break;
case 'P':
{
const struct cris_spec_reg *sregp
= spec_reg_info ((insn >> 12) & 15, disdata->distype);
/* Since we match four bits, we will give a value of 4-1 = 3
in a match. If there is a corresponding exact match of a
special register in another pattern, it will get a value of
4, which will be higher. This should be correct in that an
exact pattern would match better than a general pattern.
Note that there is a reason for not returning zero; the
pattern for "clear" is partly matched in the bit-pattern
(the two lower bits must be zero), while the bit-pattern
for a move from a special register is matched in the
register constraint. */
if (sregp != NULL)
{
retval += 3;
break;
}
else
return -1;
}
}
if (prefix_insn != NO_CRIS_PREFIX && ! prefix_ok)
return -1;
return retval;
}
/* Format number as hex with a leading "0x" into outbuffer. */
static char *
format_hex (unsigned long number,
char *outbuffer,
struct cris_disasm_data *disdata)
{
/* Truncate negative numbers on >32-bit hosts. */
number &= 0xffffffff;
sprintf (outbuffer, "0x%lx", number);
/* Save this value for the "case" support. */
if (TRACE_CASE)
last_immediate = number;
return outbuffer + strlen (outbuffer);
}
/* Format number as decimal into outbuffer. Parameter signedp says
whether the number should be formatted as signed (!= 0) or
unsigned (== 0). */
static char *
format_dec (long number, char *outbuffer, int signedp)
{
last_immediate = number;
sprintf (outbuffer, signedp ? "%ld" : "%lu", number);
return outbuffer + strlen (outbuffer);
}
/* Format the name of the general register regno into outbuffer. */
static char *
format_reg (struct cris_disasm_data *disdata,
int regno,
char *outbuffer_start,
bfd_boolean with_reg_prefix)
{
char *outbuffer = outbuffer_start;
if (with_reg_prefix)
*outbuffer++ = REGISTER_PREFIX_CHAR;
switch (regno)
{
case 15:
/* For v32, there is no context in which we output PC. */
if (disdata->distype == cris_dis_v32)
strcpy (outbuffer, "acr");
else
strcpy (outbuffer, "pc");
break;
case 14:
strcpy (outbuffer, "sp");
break;
default:
sprintf (outbuffer, "r%d", regno);
break;
}
return outbuffer_start + strlen (outbuffer_start);
}
/* Format the name of a support register into outbuffer. */
static char *
format_sup_reg (unsigned int regno,
char *outbuffer_start,
bfd_boolean with_reg_prefix)
{
char *outbuffer = outbuffer_start;
int i;
if (with_reg_prefix)
*outbuffer++ = REGISTER_PREFIX_CHAR;
for (i = 0; cris_support_regs[i].name != NULL; i++)
if (cris_support_regs[i].number == regno)
{
sprintf (outbuffer, "%s", cris_support_regs[i].name);
return outbuffer_start + strlen (outbuffer_start);
}
/* There's supposed to be register names covering all numbers, though
some may be generic names. */
sprintf (outbuffer, "format_sup_reg-BUG");
return outbuffer_start + strlen (outbuffer_start);
}
/* Return the length of an instruction. */
static unsigned
bytes_to_skip (unsigned int insn,
const struct cris_opcode *matchedp,
enum cris_disass_family distype,
const struct cris_opcode *prefix_matchedp)
{
/* Each insn is a word plus "immediate" operands. */
unsigned to_skip = 2;
const char *template = matchedp->args;
const char *s;
for (s = template; *s; s++)
if ((*s == 's' || *s == 'N' || *s == 'Y')
&& (insn & 0x400) && (insn & 15) == 15
&& prefix_matchedp == NULL)
{
/* Immediate via [pc+], so we have to check the size of the
operand. */
int mode_size = 1 << ((insn >> 4) & (*template == 'z' ? 1 : 3));
if (matchedp->imm_oprnd_size == SIZE_FIX_32)
to_skip += 4;
else if (matchedp->imm_oprnd_size == SIZE_SPEC_REG)
{
const struct cris_spec_reg *sregp
= spec_reg_info ((insn >> 12) & 15, distype);
/* FIXME: Improve error handling; should have been caught
earlier. */
if (sregp == NULL)
return 2;
/* PC is incremented by two, not one, for a byte. Except on
CRISv32, where constants are always DWORD-size for
special registers. */
to_skip +=
distype == cris_dis_v32 ? 4 : (sregp->reg_size + 1) & ~1;
}
else
to_skip += (mode_size + 1) & ~1;
}
else if (*s == 'n')
to_skip += 4;
else if (*s == 'b')
to_skip += 2;
return to_skip;
}
/* Print condition code flags. */
static char *
print_flags (struct cris_disasm_data *disdata, unsigned int insn, char *cp)
{
/* Use the v8 (Etrax 100) flag definitions for disassembly.
The differences with v0 (Etrax 1..4) vs. Svinto are:
v0 'd' <=> v8 'm'
v0 'e' <=> v8 'b'.
FIXME: Emit v0..v3 flag names somehow. */
static const char v8_fnames[] = "cvznxibm";
static const char v32_fnames[] = "cvznxiup";
const char *fnames
= disdata->distype == cris_dis_v32 ? v32_fnames : v8_fnames;
unsigned char flagbits = (((insn >> 8) & 0xf0) | (insn & 15));
int i;
for (i = 0; i < 8; i++)
if (flagbits & (1 << i))
*cp++ = fnames[i];
return cp;
}
/* Print out an insn with its operands, and update the info->insn_type
fields. The prefix_opcodep and the rest hold a prefix insn that is
supposed to be output as an address mode. */
static void
print_with_operands (const struct cris_opcode *opcodep,
unsigned int insn,
unsigned char *buffer,
bfd_vma addr,
disassemble_info *info,
/* If a prefix insn was before this insn (and is supposed
to be output as an address), here is a description of
it. */
const struct cris_opcode *prefix_opcodep,
unsigned int prefix_insn,
unsigned char *prefix_buffer,
bfd_boolean with_reg_prefix)
{
/* Get a buffer of somewhat reasonable size where we store
intermediate parts of the insn. */
char temp[sizeof (".d [$r13=$r12-2147483648],$r10") * 2];
char *tp = temp;
static const char mode_char[] = "bwd?";
const char *s;
const char *cs;
struct cris_disasm_data *disdata
= (struct cris_disasm_data *) info->private_data;
/* Print out the name first thing we do. */
(*info->fprintf_func) (info->stream, "%s", opcodep->name);
cs = opcodep->args;
s = cs;
/* Ignore any prefix indicator. */
if (*s == 'p')
s++;
if (*s == 'm' || *s == 'M' || *s == 'z')
{
*tp++ = '.';
/* Get the size-letter. */
*tp++ = *s == 'M'
? (insn & 0x8000 ? 'd'
: insn & 0x4000 ? 'w' : 'b')
: mode_char[(insn >> 4) & (*s == 'z' ? 1 : 3)];
/* Ignore the size and the space character that follows. */
s += 2;
}
/* Add a space if this isn't a long-branch, because for those will add
the condition part of the name later. */
if (opcodep->match != (BRANCH_PC_LOW + BRANCH_INCR_HIGH * 256))
*tp++ = ' ';
/* Fill in the insn-type if deducible from the name (and there's no
better way). */
if (opcodep->name[0] == 'j')
{
if (CONST_STRNEQ (opcodep->name, "jsr"))
/* It's "jsr" or "jsrc". */
info->insn_type = dis_jsr;
else
/* Any other jump-type insn is considered a branch. */
info->insn_type = dis_branch;
}
/* We might know some more fields right now. */
info->branch_delay_insns = opcodep->delayed;
/* Handle operands. */
for (; *s; s++)
{
switch (*s)
{
case 'T':
tp = format_sup_reg ((insn >> 12) & 15, tp, with_reg_prefix);
break;
case 'A':
if (with_reg_prefix)
*tp++ = REGISTER_PREFIX_CHAR;
*tp++ = 'a';
*tp++ = 'c';
*tp++ = 'r';
break;
case '[':
case ']':
case ',':
*tp++ = *s;
break;
case '!':
/* Ignore at this point; used at earlier stages to avoid
recognition if there's a prefix at something that in other
ways looks like a "pop". */
break;
case 'd':
/* Ignore. This is an optional ".d " on the large one of
relaxable insns. */
break;
case 'B':
/* This was the prefix that made this a "push". We've already
handled it by recognizing it, so signal that the prefix is
handled by setting it to NULL. */
prefix_opcodep = NULL;
break;
case 'D':
case 'r':
tp = format_reg (disdata, insn & 15, tp, with_reg_prefix);
break;
case 'R':
tp = format_reg (disdata, (insn >> 12) & 15, tp, with_reg_prefix);
break;
case 'n':
{
/* Like N but pc-relative to the start of the insn. */
unsigned long number
= (buffer[2] + buffer[3] * 256 + buffer[4] * 65536
+ buffer[5] * 0x1000000 + addr);
/* Finish off and output previous formatted bytes. */
*tp = 0;
if (temp[0])
(*info->fprintf_func) (info->stream, "%s", temp);
tp = temp;
(*info->print_address_func) ((bfd_vma) number, info);
}
break;
case 'u':
{
/* Like n but the offset is bits <3:0> in the instruction. */
unsigned long number = (buffer[0] & 0xf) * 2 + addr;
/* Finish off and output previous formatted bytes. */
*tp = 0;
if (temp[0])
(*info->fprintf_func) (info->stream, "%s", temp);
tp = temp;
(*info->print_address_func) ((bfd_vma) number, info);
}
break;
case 'N':
case 'y':
case 'Y':
case 'S':
case 's':
/* Any "normal" memory operand. */
if ((insn & 0x400) && (insn & 15) == 15 && prefix_opcodep == NULL)
{
/* We're looking at [pc+], i.e. we need to output an immediate
number, where the size can depend on different things. */
long number;
int signedp
= ((*cs == 'z' && (insn & 0x20))
|| opcodep->match == BDAP_QUICK_OPCODE);
int nbytes;
if (opcodep->imm_oprnd_size == SIZE_FIX_32)
nbytes = 4;
else if (opcodep->imm_oprnd_size == SIZE_SPEC_REG)
{
const struct cris_spec_reg *sregp
= spec_reg_info ((insn >> 12) & 15, disdata->distype);
/* A NULL return should have been as a non-match earlier,
so catch it as an internal error in the error-case
below. */
if (sregp == NULL)
/* Whatever non-valid size. */
nbytes = 42;
else
/* PC is always incremented by a multiple of two.
For CRISv32, immediates are always 4 bytes for
special registers. */
nbytes = disdata->distype == cris_dis_v32
? 4 : (sregp->reg_size + 1) & ~1;
}
else
{
int mode_size = 1 << ((insn >> 4) & (*cs == 'z' ? 1 : 3));
if (mode_size == 1)
nbytes = 2;
else
nbytes = mode_size;
}
switch (nbytes)
{
case 1:
number = buffer[2];
if (signedp && number > 127)
number -= 256;
break;
case 2:
number = buffer[2] + buffer[3] * 256;
if (signedp && number > 32767)
number -= 65536;
break;
case 4:
number
= buffer[2] + buffer[3] * 256 + buffer[4] * 65536
+ buffer[5] * 0x1000000;
break;
default:
strcpy (tp, "bug");
tp += 3;
number = 42;
}
if ((*cs == 'z' && (insn & 0x20))
|| (opcodep->match == BDAP_QUICK_OPCODE
&& (nbytes <= 2 || buffer[1 + nbytes] == 0)))
tp = format_dec (number, tp, signedp);
else
{
unsigned int highbyte = (number >> 24) & 0xff;
/* Either output this as an address or as a number. If it's
a dword with the same high-byte as the address of the
insn, assume it's an address, and also if it's a non-zero
non-0xff high-byte. If this is a jsr or a jump, then
it's definitely an address. */
if (nbytes == 4
&& (highbyte == ((addr >> 24) & 0xff)
|| (highbyte != 0 && highbyte != 0xff)
|| info->insn_type == dis_branch
|| info->insn_type == dis_jsr))
{
/* Finish off and output previous formatted bytes. */
*tp = 0;
tp = temp;
if (temp[0])
(*info->fprintf_func) (info->stream, "%s", temp);
(*info->print_address_func) ((bfd_vma) number, info);
info->target = number;
}
else
tp = format_hex (number, tp, disdata);
}
}
else
{
/* Not an immediate number. Then this is a (possibly
prefixed) memory operand. */
if (info->insn_type != dis_nonbranch)
{
int mode_size
= 1 << ((insn >> 4)
& (opcodep->args[0] == 'z' ? 1 : 3));
int size;
info->insn_type = dis_dref;
info->flags |= CRIS_DIS_FLAG_MEMREF;
if (opcodep->imm_oprnd_size == SIZE_FIX_32)
size = 4;
else if (opcodep->imm_oprnd_size == SIZE_SPEC_REG)
{
const struct cris_spec_reg *sregp
= spec_reg_info ((insn >> 12) & 15, disdata->distype);
/* FIXME: Improve error handling; should have been caught
earlier. */
if (sregp == NULL)
size = 4;
else
size = sregp->reg_size;
}
else
size = mode_size;
info->data_size = size;
}
*tp++ = '[';
if (prefix_opcodep
/* We don't match dip with a postincremented field
as a side-effect address mode. */
&& ((insn & 0x400) == 0
|| prefix_opcodep->match != DIP_OPCODE))
{
if (insn & 0x400)
{
tp = format_reg (disdata, insn & 15, tp, with_reg_prefix);
*tp++ = '=';
}
/* We mainly ignore the prefix format string when the
address-mode syntax is output. */
switch (prefix_opcodep->match)
{
case DIP_OPCODE:
/* It's [r], [r+] or [pc+]. */
if ((prefix_insn & 0x400) && (prefix_insn & 15) == 15)
{
/* It's [pc+]. This cannot possibly be anything
but an address. */
unsigned long number
= prefix_buffer[2] + prefix_buffer[3] * 256
+ prefix_buffer[4] * 65536
+ prefix_buffer[5] * 0x1000000;
info->target = (bfd_vma) number;
/* Finish off and output previous formatted
data. */
*tp = 0;
tp = temp;
if (temp[0])
(*info->fprintf_func) (info->stream, "%s", temp);
(*info->print_address_func) ((bfd_vma) number, info);
}
else
{
/* For a memref in an address, we use target2.
In this case, target is zero. */
info->flags
|= (CRIS_DIS_FLAG_MEM_TARGET2_IS_REG
| CRIS_DIS_FLAG_MEM_TARGET2_MEM);
info->target2 = prefix_insn & 15;
*tp++ = '[';
tp = format_reg (disdata, prefix_insn & 15, tp,
with_reg_prefix);
if (prefix_insn & 0x400)
*tp++ = '+';
*tp++ = ']';
}
break;
case BDAP_QUICK_OPCODE:
{
int number;
number = prefix_buffer[0];
if (number > 127)
number -= 256;
/* Output "reg+num" or, if num < 0, "reg-num". */
tp = format_reg (disdata, (prefix_insn >> 12) & 15, tp,
with_reg_prefix);
if (number >= 0)
*tp++ = '+';
tp = format_dec (number, tp, 1);
info->flags |= CRIS_DIS_FLAG_MEM_TARGET_IS_REG;
info->target = (prefix_insn >> 12) & 15;
info->target2 = (bfd_vma) number;
break;
}
case BIAP_OPCODE:
/* Output "r+R.m". */
tp = format_reg (disdata, prefix_insn & 15, tp,
with_reg_prefix);
*tp++ = '+';
tp = format_reg (disdata, (prefix_insn >> 12) & 15, tp,
with_reg_prefix);
*tp++ = '.';
*tp++ = mode_char[(prefix_insn >> 4) & 3];
info->flags
|= (CRIS_DIS_FLAG_MEM_TARGET2_IS_REG
| CRIS_DIS_FLAG_MEM_TARGET_IS_REG
| ((prefix_insn & 0x8000)
? CRIS_DIS_FLAG_MEM_TARGET2_MULT4
: ((prefix_insn & 0x8000)
? CRIS_DIS_FLAG_MEM_TARGET2_MULT2 : 0)));
/* Is it the casejump? It's a "adds.w [pc+r%d.w],pc". */
if (insn == 0xf83f && (prefix_insn & ~0xf000) == 0x55f)
/* Then start interpreting data as offsets. */
case_offset_counter = no_of_case_offsets;
break;
case BDAP_INDIR_OPCODE:
/* Output "r+s.m", or, if "s" is [pc+], "r+s" or
"r-s". */
tp = format_reg (disdata, (prefix_insn >> 12) & 15, tp,
with_reg_prefix);
if ((prefix_insn & 0x400) && (prefix_insn & 15) == 15)
{
long number;
unsigned int nbytes;
/* It's a value. Get its size. */
int mode_size = 1 << ((prefix_insn >> 4) & 3);
if (mode_size == 1)
nbytes = 2;
else
nbytes = mode_size;
switch (nbytes)
{
case 1:
number = prefix_buffer[2];
if (number > 127)
number -= 256;
break;
case 2:
number = prefix_buffer[2] + prefix_buffer[3] * 256;
if (number > 32767)
number -= 65536;
break;
case 4:
number
= prefix_buffer[2] + prefix_buffer[3] * 256
+ prefix_buffer[4] * 65536
+ prefix_buffer[5] * 0x1000000;
break;
default:
strcpy (tp, "bug");
tp += 3;
number = 42;
}
info->flags |= CRIS_DIS_FLAG_MEM_TARGET_IS_REG;
info->target2 = (bfd_vma) number;
/* If the size is dword, then assume it's an
address. */
if (nbytes == 4)
{
/* Finish off and output previous formatted
bytes. */
*tp++ = '+';
*tp = 0;
tp = temp;
(*info->fprintf_func) (info->stream, "%s", temp);
(*info->print_address_func) ((bfd_vma) number, info);
}
else
{
if (number >= 0)
*tp++ = '+';
tp = format_dec (number, tp, 1);
}
}
else
{
/* Output "r+[R].m" or "r+[R+].m". */
*tp++ = '+';
*tp++ = '[';
tp = format_reg (disdata, prefix_insn & 15, tp,
with_reg_prefix);
if (prefix_insn & 0x400)
*tp++ = '+';
*tp++ = ']';
*tp++ = '.';
*tp++ = mode_char[(prefix_insn >> 4) & 3];
info->flags
|= (CRIS_DIS_FLAG_MEM_TARGET2_IS_REG
| CRIS_DIS_FLAG_MEM_TARGET2_MEM
| CRIS_DIS_FLAG_MEM_TARGET_IS_REG
| (((prefix_insn >> 4) == 2)
? 0
: (((prefix_insn >> 4) & 3) == 1
? CRIS_DIS_FLAG_MEM_TARGET2_MEM_WORD
: CRIS_DIS_FLAG_MEM_TARGET2_MEM_BYTE)));
}
break;
default:
(*info->fprintf_func) (info->stream, "?prefix-bug");
}
/* To mark that the prefix is used, reset it. */
prefix_opcodep = NULL;
}
else
{
tp = format_reg (disdata, insn & 15, tp, with_reg_prefix);
info->flags |= CRIS_DIS_FLAG_MEM_TARGET_IS_REG;
info->target = insn & 15;
if (insn & 0x400)
*tp++ = '+';
}
*tp++ = ']';
}
break;
case 'x':
tp = format_reg (disdata, (insn >> 12) & 15, tp, with_reg_prefix);
*tp++ = '.';
*tp++ = mode_char[(insn >> 4) & 3];
break;
case 'I':
tp = format_dec (insn & 63, tp, 0);
break;
case 'b':
{
int where = buffer[2] + buffer[3] * 256;
if (where > 32767)
where -= 65536;
where += addr + ((disdata->distype == cris_dis_v32) ? 0 : 4);
if (insn == BA_PC_INCR_OPCODE)
info->insn_type = dis_branch;
else
info->insn_type = dis_condbranch;
info->target = (bfd_vma) where;
*tp = 0;
tp = temp;
(*info->fprintf_func) (info->stream, "%s%s ",
temp, cris_cc_strings[insn >> 12]);
(*info->print_address_func) ((bfd_vma) where, info);
}
break;
case 'c':
tp = format_dec (insn & 31, tp, 0);
break;
case 'C':
tp = format_dec (insn & 15, tp, 0);
break;
case 'o':
{
long offset = insn & 0xfe;
bfd_vma target;
if (insn & 1)
offset |= ~0xff;
if (opcodep->match == BA_QUICK_OPCODE)
info->insn_type = dis_branch;
else
info->insn_type = dis_condbranch;
target = addr + ((disdata->distype == cris_dis_v32) ? 0 : 2) + offset;
info->target = target;
*tp = 0;
tp = temp;
(*info->fprintf_func) (info->stream, "%s", temp);
(*info->print_address_func) (target, info);
}
break;
case 'Q':
case 'O':
{
long number = buffer[0];
if (number > 127)
number = number - 256;
tp = format_dec (number, tp, 1);
*tp++ = ',';
tp = format_reg (disdata, (insn >> 12) & 15, tp, with_reg_prefix);
}
break;
case 'f':
tp = print_flags (disdata, insn, tp);
break;
case 'i':
tp = format_dec ((insn & 32) ? (insn & 31) | ~31L : insn & 31, tp, 1);
break;
case 'P':
{
const struct cris_spec_reg *sregp
= spec_reg_info ((insn >> 12) & 15, disdata->distype);
if (sregp->name == NULL)
/* Should have been caught as a non-match eariler. */
*tp++ = '?';
else
{
if (with_reg_prefix)
*tp++ = REGISTER_PREFIX_CHAR;
strcpy (tp, sregp->name);
tp += strlen (tp);
}
}
break;
default:
strcpy (tp, "???");
tp += 3;
}
}
*tp = 0;
if (prefix_opcodep)
(*info->fprintf_func) (info->stream, " (OOPS unused prefix \"%s: %s\")",
prefix_opcodep->name, prefix_opcodep->args);
(*info->fprintf_func) (info->stream, "%s", temp);
/* Get info for matching case-tables, if we don't have any active.
We assume that the last constant seen is used; either in the insn
itself or in a "move.d const,rN, sub.d rN,rM"-like sequence. */
if (TRACE_CASE && case_offset_counter == 0)
{
if (CONST_STRNEQ (opcodep->name, "sub"))
case_offset = last_immediate;
/* It could also be an "add", if there are negative case-values. */
else if (CONST_STRNEQ (opcodep->name, "add"))
/* The first case is the negated operand to the add. */
case_offset = -last_immediate;
/* A bound insn will tell us the number of cases. */
else if (CONST_STRNEQ (opcodep->name, "bound"))
no_of_case_offsets = last_immediate + 1;
/* A jump or jsr or branch breaks the chain of insns for a
case-table, so assume default first-case again. */
else if (info->insn_type == dis_jsr
|| info->insn_type == dis_branch
|| info->insn_type == dis_condbranch)
case_offset = 0;
}
}
/* Print the CRIS instruction at address memaddr on stream. Returns
length of the instruction, in bytes. Prefix register names with `$' if
WITH_REG_PREFIX. */
static int
print_insn_cris_generic (bfd_vma memaddr,
disassemble_info *info,
bfd_boolean with_reg_prefix)
{
int nbytes;
unsigned int insn;
const struct cris_opcode *matchedp;
int advance = 0;
struct cris_disasm_data *disdata
= (struct cris_disasm_data *) info->private_data;
/* No instruction will be disassembled as longer than this number of
bytes; stacked prefixes will not be expanded. */
unsigned char buffer[MAX_BYTES_PER_CRIS_INSN];
unsigned char *bufp;
int status = 0;
bfd_vma addr;
/* There will be an "out of range" error after the last instruction.
Reading pairs of bytes in decreasing number, we hope that we will get
at least the amount that we will consume.
If we can't get any data, or we do not get enough data, we print
the error message. */
nbytes = info->buffer_length;
if (nbytes > MAX_BYTES_PER_CRIS_INSN)
nbytes = MAX_BYTES_PER_CRIS_INSN;
status = (*info->read_memory_func) (memaddr, buffer, nbytes, info);
/* If we did not get all we asked for, then clear the rest.
Hopefully this makes a reproducible result in case of errors. */
if (nbytes != MAX_BYTES_PER_CRIS_INSN)
memset (buffer + nbytes, 0, MAX_BYTES_PER_CRIS_INSN - nbytes);
addr = memaddr;
bufp = buffer;
/* Set some defaults for the insn info. */
info->insn_info_valid = 1;
info->branch_delay_insns = 0;
info->data_size = 0;
info->insn_type = dis_nonbranch;
info->flags = 0;
info->target = 0;
info->target2 = 0;
/* If we got any data, disassemble it. */
if (nbytes != 0)
{
matchedp = NULL;
insn = bufp[0] + bufp[1] * 256;
/* If we're in a case-table, don't disassemble the offsets. */
if (TRACE_CASE && case_offset_counter != 0)
{
info->insn_type = dis_noninsn;
advance += 2;
/* If to print data as offsets, then shortcut here. */
(*info->fprintf_func) (info->stream, "case %ld%s: -> ",
case_offset + no_of_case_offsets
- case_offset_counter,
case_offset_counter == 1 ? "/default" :
"");
(*info->print_address_func) ((bfd_vma)
((short) (insn)
+ (long) (addr
- (no_of_case_offsets
- case_offset_counter)
* 2)), info);
case_offset_counter--;
/* The default case start (without a "sub" or "add") must be
zero. */
if (case_offset_counter == 0)
case_offset = 0;
}
else if (insn == 0)
{
/* We're often called to disassemble zeroes. While this is a
valid "bcc .+2" insn, it is also useless enough and enough
of a nuiscance that we will just output "bcc .+2" for it
and signal it as a noninsn. */
(*info->fprintf_func) (info->stream,
disdata->distype == cris_dis_v32
? "bcc ." : "bcc .+2");
info->insn_type = dis_noninsn;
advance += 2;
}
else
{
const struct cris_opcode *prefix_opcodep = NULL;
unsigned char *prefix_buffer = bufp;
unsigned int prefix_insn = insn;
int prefix_size = 0;
matchedp = get_opcode_entry (insn, NO_CRIS_PREFIX, disdata);
/* Check if we're supposed to write out prefixes as address
modes and if this was a prefix. */
if (matchedp != NULL && PARSE_PREFIX && matchedp->args[0] == 'p')
{
/* If it's a prefix, put it into the prefix vars and get the
main insn. */
prefix_size = bytes_to_skip (prefix_insn, matchedp,
disdata->distype, NULL);
prefix_opcodep = matchedp;
insn = bufp[prefix_size] + bufp[prefix_size + 1] * 256;
matchedp = get_opcode_entry (insn, prefix_insn, disdata);
if (matchedp != NULL)
{
addr += prefix_size;
bufp += prefix_size;
advance += prefix_size;
}
else
{
/* The "main" insn wasn't valid, at least not when
prefixed. Put back things enough to output the
prefix insn only, as a normal insn. */
matchedp = prefix_opcodep;
insn = prefix_insn;
prefix_opcodep = NULL;
}
}
if (matchedp == NULL)
{
(*info->fprintf_func) (info->stream, "??0x%x", insn);
advance += 2;
info->insn_type = dis_noninsn;
}
else
{
advance
+= bytes_to_skip (insn, matchedp, disdata->distype,
prefix_opcodep);
/* The info_type and assorted fields will be set according
to the operands. */
print_with_operands (matchedp, insn, bufp, addr, info,
prefix_opcodep, prefix_insn,
prefix_buffer, with_reg_prefix);
}
}
}
else
info->insn_type = dis_noninsn;
/* If we read less than MAX_BYTES_PER_CRIS_INSN, i.e. we got an error
status when reading that much, and the insn decoding indicated a
length exceeding what we read, there is an error. */
if (status != 0 && (nbytes == 0 || advance > nbytes))
{
(*info->memory_error_func) (status, memaddr, info);
return -1;
}
/* Max supported insn size with one folded prefix insn. */
info->bytes_per_line = MAX_BYTES_PER_CRIS_INSN;
/* I would like to set this to a fixed value larger than the actual
number of bytes to print in order to avoid spaces between bytes,
but objdump.c (2.9.1) does not like that, so we print 16-bit
chunks, which is the next choice. */
info->bytes_per_chunk = 2;
/* Printing bytes in order of increasing addresses makes sense,
especially on a little-endian target.
This is completely the opposite of what you think; setting this to
BFD_ENDIAN_LITTLE will print bytes in order N..0 rather than the 0..N
we want. */
info->display_endian = BFD_ENDIAN_BIG;
return advance;
}
/* Disassemble, prefixing register names with `$'. CRIS v0..v10. */
#if 0
static int
print_insn_cris_with_register_prefix (bfd_vma vma,
disassemble_info *info)
{
if (info->private_data == NULL
&& !cris_parse_disassembler_options (info, cris_dis_v0_v10))
return -1;
return print_insn_cris_generic (vma, info, TRUE);
}
#endif
/* Disassemble, prefixing register names with `$'. CRIS v32. */
static int
print_insn_crisv32_with_register_prefix (bfd_vma vma,
disassemble_info *info)
{
if (info->private_data == NULL
&& !cris_parse_disassembler_options (info, cris_dis_v32))
return -1;
return print_insn_cris_generic (vma, info, TRUE);
}
#if 0
/* Disassemble, prefixing register names with `$'.
Common v10 and v32 subset. */
static int
print_insn_crisv10_v32_with_register_prefix (bfd_vma vma,
disassemble_info *info)
{
if (info->private_data == NULL
&& !cris_parse_disassembler_options (info, cris_dis_common_v10_v32))
return -1;
return print_insn_cris_generic (vma, info, TRUE);
}
/* Disassemble, no prefixes on register names. CRIS v0..v10. */
static int
print_insn_cris_without_register_prefix (bfd_vma vma,
disassemble_info *info)
{
if (info->private_data == NULL
&& !cris_parse_disassembler_options (info, cris_dis_v0_v10))
return -1;
return print_insn_cris_generic (vma, info, FALSE);
}
/* Disassemble, no prefixes on register names. CRIS v32. */
static int
print_insn_crisv32_without_register_prefix (bfd_vma vma,
disassemble_info *info)
{
if (info->private_data == NULL
&& !cris_parse_disassembler_options (info, cris_dis_v32))
return -1;
return print_insn_cris_generic (vma, info, FALSE);
}
/* Disassemble, no prefixes on register names.
Common v10 and v32 subset. */
static int
print_insn_crisv10_v32_without_register_prefix (bfd_vma vma,
disassemble_info *info)
{
if (info->private_data == NULL
&& !cris_parse_disassembler_options (info, cris_dis_common_v10_v32))
return -1;
return print_insn_cris_generic (vma, info, FALSE);
}
#endif
int
print_insn_crisv32 (bfd_vma vma,
disassemble_info *info)
{
return print_insn_crisv32_with_register_prefix(vma, info);
}
/* Return a disassembler-function that prints registers with a `$' prefix,
or one that prints registers without a prefix.
FIXME: We should improve the solution to avoid the multitude of
functions seen above. */
#if 0
disassembler_ftype
cris_get_disassembler (bfd *abfd)
{
/* If there's no bfd in sight, we return what is valid as input in all
contexts if fed back to the assembler: disassembly *with* register
prefix. Unfortunately this will be totally wrong for v32. */
if (abfd == NULL)
return print_insn_cris_with_register_prefix;
if (bfd_get_symbol_leading_char (abfd) == 0)
{
if (bfd_get_mach (abfd) == bfd_mach_cris_v32)
return print_insn_crisv32_with_register_prefix;
if (bfd_get_mach (abfd) == bfd_mach_cris_v10_v32)
return print_insn_crisv10_v32_with_register_prefix;
/* We default to v10. This may be specifically specified in the
bfd mach, but is also the default setting. */
return print_insn_cris_with_register_prefix;
}
if (bfd_get_mach (abfd) == bfd_mach_cris_v32)
return print_insn_crisv32_without_register_prefix;
if (bfd_get_mach (abfd) == bfd_mach_cris_v10_v32)
return print_insn_crisv10_v32_without_register_prefix;
return print_insn_cris_without_register_prefix;
}
#endif
/* Local variables:
eval: (c-set-style "gnu")
indent-tabs-mode: t
End: */
| Aaron0927/xen-4.2.1 | tools/qemu-xen-traditional/cris-dis.c | C | gpl-2.0 | 82,372 |
/*
* cycx_cfm.h Cyclom 2X WAN Link Driver.
* Definitions for the Cyclom 2X Firmware Module (CFM).
*
* Author: Arnaldo Carvalho de Melo <[email protected]>
*
* Copyright: (c) 1998-2000 Arnaldo Carvalho de Melo
*
* Based on sdlasfm.h by Gene Kozin <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
* ============================================================================
* 1998/08/08 acme Initial version.
*/
#ifndef _CYCX_CFM_H
#define _CYCX_CFM_H
/* Defines */
#define CFM_VERSION 2
#define CFM_SIGNATURE "CFM - Cyclades CYCX Firmware Module"
/* min/max */
#define CFM_IMAGE_SIZE 0x20000 /* max size of CYCX code image file */
#define CFM_DESCR_LEN 256 /* max length of description string */
#define CFM_MAX_CYCX 1 /* max number of compatible adapters */
#define CFM_LOAD_BUFSZ 0x400 /* buffer size for reset code (buffer_load) */
/* Firmware Commands */
#define GEN_POWER_ON 0x1280
#define GEN_SET_SEG 0x1401 /* boot segment setting. */
#define GEN_BOOT_DAT 0x1402 /* boot data. */
#define GEN_START 0x1403 /* board start. */
#define GEN_DEFPAR 0x1404 /* buffer length for boot. */
/* Adapter Types */
#define CYCX_2X 2
/* for now only the 2X is supported, no plans to support 8X or 16X */
#define CYCX_8X 8
#define CYCX_16X 16
#define CFID_X25_2X 5200
/* Data Types */
typedef struct cfm_info /* firmware module information */
{
unsigned short codeid; /* firmware ID */
unsigned short version; /* firmware version number */
unsigned short adapter[CFM_MAX_CYCX]; /* compatible adapter types */
unsigned long memsize; /* minimum memory size */
unsigned short reserved[2]; /* reserved */
unsigned short startoffs; /* entry point offset */
unsigned short winoffs; /* dual-port memory window offset */
unsigned short codeoffs; /* code load offset */
unsigned long codesize; /* code size */
unsigned short dataoffs; /* configuration data load offset */
unsigned long datasize; /* configuration data size */
} cfm_info_t;
typedef struct cfm /* CYCX firmware file structure */
{
char signature[80]; /* CFM file signature */
unsigned short version; /* file format version */
unsigned short checksum; /* info + image */
unsigned short reserved[6]; /* reserved */
char descr[CFM_DESCR_LEN]; /* description string */
cfm_info_t info; /* firmware module info */
unsigned char image[1]; /* code image (variable size) */
} cfm_t;
typedef struct cycx_header_s {
unsigned long reset_size;
unsigned long data_size;
unsigned long code_size;
} cycx_header_t;
#endif /* _CYCX_CFM_H */
| ghmajx/asuswrt-merlin | tools/brcm/K24/hndtools-mipsel-uclibc-4.2.4/include/linux/cycx_cfm.h | C | gpl-2.0 | 2,754 |
dnl SPARC mpn_mul_1 -- Multiply a limb vector with a limb and store
dnl the result in a second limb vector.
dnl Copyright 1992-1994, 2000 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C INPUT PARAMETERS
C res_ptr o0
C s1_ptr o1
C size o2
C s2_limb o3
ASM_START()
PROLOGUE(mpn_mul_1)
C Make S1_PTR and RES_PTR point at the end of their blocks
C and put (- 4 x SIZE) in index/loop counter.
sll %o2,2,%o2
add %o0,%o2,%o4 C RES_PTR in o4 since o0 is retval
add %o1,%o2,%o1
sub %g0,%o2,%o2
cmp %o3,0xfff
bgu L(large)
nop
ld [%o1+%o2],%o5
mov 0,%o0
b L(0)
add %o4,-4,%o4
L(loop0):
st %g1,[%o4+%o2]
L(0): wr %g0,%o3,%y
sra %o5,31,%g2
and %o3,%g2,%g2
andcc %g1,0,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,%o5,%g1
mulscc %g1,0,%g1
sra %g1,20,%g4
sll %g1,12,%g1
rd %y,%g3
srl %g3,20,%g3
or %g1,%g3,%g1
addcc %g1,%o0,%g1
addx %g2,%g4,%o0 C add sign-compensation and cy to hi limb
addcc %o2,4,%o2 C loop counter
bne,a L(loop0)
ld [%o1+%o2],%o5
retl
st %g1,[%o4+%o2]
L(large):
ld [%o1+%o2],%o5
mov 0,%o0
sra %o3,31,%g4 C g4 = mask of ones iff S2_LIMB < 0
b L(1)
add %o4,-4,%o4
L(loop):
st %g3,[%o4+%o2]
L(1): wr %g0,%o5,%y
and %o5,%g4,%g2 C g2 = S1_LIMB iff S2_LIMB < 0, else 0
andcc %g0,%g0,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%o3,%g1
mulscc %g1,%g0,%g1
rd %y,%g3
addcc %g3,%o0,%g3
addx %g2,%g1,%o0 C add sign-compensation and cy to hi limb
addcc %o2,4,%o2 C loop counter
bne,a L(loop)
ld [%o1+%o2],%o5
retl
st %g3,[%o4+%o2]
EPILOGUE(mpn_mul_1)
| GarethNelson/BearLang | vendor/gmp-6.1.2/mpn/sparc32/mul_1.asm | Assembly | gpl-2.0 | 3,353 |
# We are fully aware of the dangers of __builtin_return_address()
FRAME_CFLAGS := $(call cc-disable-warning,frame-address)
KBUILD_CFLAGS += $(FRAME_CFLAGS)
# Do not instrument the tracer itself:
ifdef CONFIG_FUNCTION_TRACER
ORIG_CFLAGS := $(KBUILD_CFLAGS)
KBUILD_CFLAGS = $(subst $(CC_FLAGS_FTRACE),,$(ORIG_CFLAGS))
ifdef CONFIG_FTRACE_SELFTEST
# selftest needs instrumentation
CFLAGS_trace_selftest_dynamic.o = $(CC_FLAGS_FTRACE)
obj-y += trace_selftest_dynamic.o
endif
endif
# If unlikely tracing is enabled, do not trace these files
ifdef CONFIG_TRACING_BRANCHES
KBUILD_CFLAGS += -DDISABLE_BRANCH_PROFILING
endif
CFLAGS_trace_benchmark.o := -I$(src)
CFLAGS_trace_events_filter.o := -I$(src)
obj-$(CONFIG_TRACE_CLOCK) += trace_clock.o
obj-$(CONFIG_FUNCTION_TRACER) += libftrace.o
obj-$(CONFIG_RING_BUFFER) += ring_buffer.o
obj-$(CONFIG_RING_BUFFER_BENCHMARK) += ring_buffer_benchmark.o
obj-$(CONFIG_TRACING) += trace.o
obj-$(CONFIG_TRACING) += trace_output.o
obj-$(CONFIG_TRACING) += trace_seq.o
obj-$(CONFIG_TRACING) += trace_stat.o
obj-$(CONFIG_TRACING) += trace_printk.o
obj-$(CONFIG_TRACING_MAP) += tracing_map.o
obj-$(CONFIG_CONTEXT_SWITCH_TRACER) += trace_sched_switch.o
obj-$(CONFIG_FUNCTION_TRACER) += trace_functions.o
obj-$(CONFIG_IRQSOFF_TRACER) += trace_irqsoff.o
obj-$(CONFIG_PREEMPT_TRACER) += trace_irqsoff.o
obj-$(CONFIG_SCHED_TRACER) += trace_sched_wakeup.o
obj-$(CONFIG_NOP_TRACER) += trace_nop.o
obj-$(CONFIG_STACK_TRACER) += trace_stack.o
obj-$(CONFIG_MMIOTRACE) += trace_mmiotrace.o
obj-$(CONFIG_FUNCTION_GRAPH_TRACER) += trace_functions_graph.o
obj-$(CONFIG_TRACE_BRANCH_PROFILING) += trace_branch.o
obj-$(CONFIG_BLK_DEV_IO_TRACE) += blktrace.o
ifeq ($(CONFIG_BLOCK),y)
obj-$(CONFIG_EVENT_TRACING) += blktrace.o
endif
obj-$(CONFIG_EVENT_TRACING) += trace_events.o
obj-$(CONFIG_EVENT_TRACING) += trace_export.o
obj-$(CONFIG_FTRACE_SYSCALLS) += trace_syscalls.o
ifeq ($(CONFIG_PERF_EVENTS),y)
obj-$(CONFIG_EVENT_TRACING) += trace_event_perf.o
endif
obj-$(CONFIG_EVENT_TRACING) += trace_events_filter.o
obj-$(CONFIG_EVENT_TRACING) += trace_events_trigger.o
obj-$(CONFIG_HIST_TRIGGERS) += trace_events_hist.o
obj-$(CONFIG_BPF_EVENTS) += bpf_trace.o
obj-$(CONFIG_KPROBE_EVENT) += trace_kprobe.o
obj-$(CONFIG_TRACEPOINTS) += power-traces.o
ifeq ($(CONFIG_PM),y)
obj-$(CONFIG_TRACEPOINTS) += rpm-traces.o
endif
ifeq ($(CONFIG_TRACING),y)
obj-$(CONFIG_KGDB_KDB) += trace_kdb.o
endif
obj-$(CONFIG_PROBE_EVENTS) += trace_probe.o
obj-$(CONFIG_UPROBE_EVENT) += trace_uprobe.o
obj-$(CONFIG_TRACEPOINT_BENCHMARK) += trace_benchmark.o
libftrace-y := ftrace.o
| sfumato77/Kernel-4.8_Android-x86_BayTrail | kernel/trace/Makefile | Makefile | gpl-2.0 | 2,579 |
"""
Custom Roles
"""
from docutils import nodes, utils
from docutils.parsers.rst import roles
from sphinx import addnodes
from sphinx.util import ws_re, caption_ref_re
# http://www.doughellmann.com/articles/how-tos/sphinx-custom-roles/index.html
def sample_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Custom role.
Parameters
----------
name : str
The name of the role, as used in the document.
rawtext : str
The markup, including the role declaration.
text : str
The text to be marked up by the role.
lineno : int
The line number where `rawtext` appears.
inliner : Inliner
The instance that called the role.
options : dict
Directive options for customizatoin.
content : list
The directive content for customization.
Returns
-------
nodes : list
The list of nodes to insert into the document.
msgs : list
The list of system messages, perhaps an error message.
"""
pass
##################
prefixed_roles = {
# name: (prefix, baseuri)
'arxiv': ('arXiv:', 'http://arxiv.org/abs/'),
'doi': ('doi:', 'http://dx.doi.org/'),
}
no_text_roles = [
'url',
'pdf',
]
def prefixed_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
prefix, baseuri = prefixed_roles[name]
uri = baseuri + text
display = utils.unescape(text)
node = nodes.literal(prefix, prefix)
ref = nodes.reference(rawtext, display, refuri=uri, **options)
node += ref # keep it in the 'literal' background
return [node], []
def url_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
uri = text
display = 'url'
node = nodes.literal('', '')
node += nodes.reference(rawtext, name, refuri=uri, **options)
return [node], []
def trac_ticket_role(name, rawtext, text, lineno, inliner,
options={}, content=[]):
app = inliner.document.settings.env.app
try:
base = app.config.trac_url
if not base:
raise AttributeError
except AttributeError as err:
msg = 'trac_url configuration value is not set (%s)'
raise ValueError(msg % str(err))
slash = '/' if base[-1] != '/' else ''
prefix = 'ticket '
node = nodes.literal(prefix, prefix)
display = utils.unescape(text)
uri = base + slash + 'ticket/' + text
node += nodes.reference(rawtext, display, refuri=uri, **options)
return [node], []
def trac_changeset_role(name, rawtext, text, lineno, inliner,
options={}, content=[]):
app = inliner.document.settings.env.app
try:
base = app.config.trac_url
if not base:
raise AttributeError
except AttributeError as err:
msg = 'trac_url configuration value is not set (%s)'
raise ValueError(msg % str(err))
slash = '/' if base[-1] != '/' else ''
unescaped = utils.unescape(text)
prefix = 'changeset '
node = nodes.literal(prefix, prefix)
# Hard-coded for NetworkX
if unescaped.endswith('networkx-svn-archive'):
# Use the integer
display = unescaped.split('/')[0]
else:
# hg: use the first 12 hash characters
display = unescaped[:12]
uri = base + slash + 'changeset/' + text
node += nodes.reference(rawtext, display, refuri=uri, **options)
return [node], []
active_roles = {
'arxiv': prefixed_role,
'doi': prefixed_role,
'pdf': url_role,
'url': url_role,
'ticket': trac_ticket_role,
'changeset': trac_changeset_role,
}
# Add a generic docstring.
for role in active_roles.values():
role.__doc__ = sample_role.__doc__
def setup(app):
for role, func in active_roles.items():
roles.register_local_role(role, func)
app.add_config_value('trac_url', None, 'env')
| JFriel/honours_project | networkx/doc/sphinxext/customroles.py | Python | gpl-3.0 | 3,945 |
---
layout: "aws"
page_title: "AWS: efs_file_system"
sidebar_current: "docs-aws-datasource-efs-file-system"
description: |-
Provides an Elastic File System (EFS) data source.
---
# aws_efs_file_system
Provides information about an Elastic File System (EFS).
## Example Usage
```hcl
variable "file_system_id" {
type = "string"
default = ""
}
data "aws_efs_file_system" "by_id" {
file_system_id = "${var.file_system_id}"
}
```
## Argument Reference
The following arguments are supported:
* `file_system_id` - (Optional) The ID that identifies the file system (e.g. fs-ccfc0d65).
* `creation_token` - (Optional) Restricts the list to the file system with this creation token
## Attributes Reference
The following attributes are exported:
* `performance_mode` - The PerformanceMode of the file system.
* `tags` - The list of tags assigned to the file system.
| nathanielks/terraform | website/source/docs/providers/aws/d/efs_file_system.html.markdown | Markdown | mpl-2.0 | 875 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.cassandra.metrics;
import static org.junit.Assert.*;
import java.lang.management.ManagementFactory;
import java.util.Collection;
import org.apache.cassandra.metrics.CassandraMetricsRegistry.MetricName;
import org.junit.Test;
import com.codahale.metrics.jvm.BufferPoolMetricSet;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
public class CassandraMetricsRegistryTest
{
// A class with a name ending in '$'
private static class StrangeName$
{
}
@Test
public void testChooseType()
{
assertEquals("StrangeName", MetricName.chooseType(null, StrangeName$.class));
assertEquals("StrangeName", MetricName.chooseType("", StrangeName$.class));
assertEquals("String", MetricName.chooseType(null, String.class));
assertEquals("String", MetricName.chooseType("", String.class));
assertEquals("a", MetricName.chooseType("a", StrangeName$.class));
assertEquals("b", MetricName.chooseType("b", String.class));
}
@Test
public void testMetricName()
{
MetricName name = new MetricName(StrangeName$.class, "NaMe", "ScOpE");
assertEquals("StrangeName", name.getType());
}
@Test
public void testJvmMetricsRegistration()
{
CassandraMetricsRegistry registry = CassandraMetricsRegistry.Metrics;
// Same registration as CassandraDaemon
registry.register("jvm.buffers", new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
registry.register("jvm.gc", new GarbageCollectorMetricSet());
registry.register("jvm.memory", new MemoryUsageGaugeSet());
Collection<String> names = registry.getNames();
// No metric with ".." in name
assertTrue(names.stream()
.filter(name -> name.contains(".."))
.count()
== 0);
// There should be several metrics within each category
for (String category : new String[]{"jvm.buffers","jvm.gc","jvm.memory"})
{
assertTrue(names.stream()
.filter(name -> name.startsWith(category+'.'))
.count() > 1);
}
}
@Test
public void testDeltaBaseCase()
{
long[] last = new long[10];
long[] now = new long[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// difference between all zeros and a value should be the value
assertArrayEquals(now, CassandraMetricsRegistry.delta(now, last));
// the difference between itself should be all 0s
assertArrayEquals(last, CassandraMetricsRegistry.delta(now, now));
// verifying each value is calculated
assertArrayEquals(new long[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
CassandraMetricsRegistry.delta(new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, now));
}
@Test
public void testDeltaHistogramSizeChange()
{
long[] count = new long[]{0, 1, 2, 3, 4, 5};
assertArrayEquals(count, CassandraMetricsRegistry.delta(count, new long[3]));
assertArrayEquals(new long[6], CassandraMetricsRegistry.delta(count, new long[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
}
}
| tommystendahl/cassandra | test/unit/org/apache/cassandra/metrics/CassandraMetricsRegistryTest.java | Java | apache-2.0 | 4,072 |
#folders .special li a.trash { background:url(../img/trash.png) no-repeat; }
| chicuongit913/zend_kacana | zend2test/public/js/tinymce/plugins/imagemanager/plugins/Trash/css/trash.css | CSS | bsd-3-clause | 77 |
/**
* lscache library
* Copyright (c) 2011, Pamela Fox
*
* 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.
*/
/* jshint undef:true, browser:true, node:true */
/* global define */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof module !== "undefined" && module.exports) {
// CommonJS/Node module
module.exports = factory();
} else {
// Browser globals
root.lscache = factory();
}
}(this, function () {
// Prefix for all lscache keys
var CACHE_PREFIX = 'lscache-';
// Suffix for the key name on the expiration items in localStorage
var CACHE_SUFFIX = '-cacheexpiration';
// expiration date radix (set to Base-36 for most space savings)
var EXPIRY_RADIX = 10;
// time resolution in minutes
var EXPIRY_UNITS = 60 * 1000;
// ECMAScript max Date (epoch + 1e8 days)
var MAX_DATE = Math.floor(8.64e15/EXPIRY_UNITS);
var cachedStorage;
var cachedJSON;
var cacheBucket = '';
var warnings = false;
// Determines if localStorage is supported in the browser;
// result is cached for better performance instead of being run each time.
// Feature detection is based on how Modernizr does it;
// it's not straightforward due to FF4 issues.
// It's not run at parse-time as it takes 200ms in Android.
function supportsStorage() {
var key = '__lscachetest__';
var value = key;
if (cachedStorage !== undefined) {
return cachedStorage;
}
// some browsers will throw an error if you try to access local storage (e.g. brave browser)
// hence check is inside a try/catch
try {
if (!localStorage) {
return false;
}
} catch (ex) {
return false;
}
try {
setItem(key, value);
removeItem(key);
cachedStorage = true;
} catch (e) {
// If we hit the limit, and we don't have an empty localStorage then it means we have support
if (isOutOfSpace(e) && localStorage.length) {
cachedStorage = true; // just maxed it out and even the set test failed.
} else {
cachedStorage = false;
}
}
return cachedStorage;
}
// Check to set if the error is us dealing with being out of space
function isOutOfSpace(e) {
if (e && e.name === 'QUOTA_EXCEEDED_ERR' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED' ||
e.name === 'QuotaExceededError') {
return true;
}
return false;
}
// Determines if native JSON (de-)serialization is supported in the browser.
function supportsJSON() {
/*jshint eqnull:true */
if (cachedJSON === undefined) {
cachedJSON = (window.JSON != null);
}
return cachedJSON;
}
/**
* Returns a string where all RegExp special characters are escaped with a \.
* @param {String} text
* @return {string}
*/
function escapeRegExpSpecialCharacters(text) {
return text.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&');
}
/**
* Returns the full string for the localStorage expiration item.
* @param {String} key
* @return {string}
*/
function expirationKey(key) {
return key + CACHE_SUFFIX;
}
/**
* Returns the number of minutes since the epoch.
* @return {number}
*/
function currentTime() {
return Math.floor((new Date().getTime())/EXPIRY_UNITS);
}
/**
* Wrapper functions for localStorage methods
*/
function getItem(key) {
return localStorage.getItem(CACHE_PREFIX + cacheBucket + key);
}
function setItem(key, value) {
// Fix for iPad issue - sometimes throws QUOTA_EXCEEDED_ERR on setItem.
localStorage.removeItem(CACHE_PREFIX + cacheBucket + key);
localStorage.setItem(CACHE_PREFIX + cacheBucket + key, value);
}
function removeItem(key) {
localStorage.removeItem(CACHE_PREFIX + cacheBucket + key);
}
function eachKey(fn) {
var prefixRegExp = new RegExp('^' + CACHE_PREFIX + escapeRegExpSpecialCharacters(cacheBucket) + '(.*)');
// Loop in reverse as removing items will change indices of tail
for (var i = localStorage.length-1; i >= 0 ; --i) {
var key = localStorage.key(i);
key = key && key.match(prefixRegExp);
key = key && key[1];
if (key && key.indexOf(CACHE_SUFFIX) < 0) {
fn(key, expirationKey(key));
}
}
}
function flushItem(key) {
var exprKey = expirationKey(key);
removeItem(key);
removeItem(exprKey);
}
function flushExpiredItem(key) {
var exprKey = expirationKey(key);
var expr = getItem(exprKey);
if (expr) {
var expirationTime = parseInt(expr, EXPIRY_RADIX);
// Check if we should actually kick item out of storage
if (currentTime() >= expirationTime) {
removeItem(key);
removeItem(exprKey);
return true;
}
}
}
function warn(message, err) {
if (!warnings) return;
if (!('console' in window) || typeof window.console.warn !== 'function') return;
window.console.warn("lscache - " + message);
if (err) window.console.warn("lscache - The error was: " + err.message);
}
var lscache = {
/**
* Stores the value in localStorage. Expires after specified number of minutes.
* @param {string} key
* @param {Object|string} value
* @param {number} time
*/
set: function(key, value, time) {
if (!supportsStorage()) return;
// If we don't get a string value, try to stringify
// In future, localStorage may properly support storing non-strings
// and this can be removed.
if (typeof value !== 'string') {
if (!supportsJSON()) return;
try {
value = JSON.stringify(value);
} catch (e) {
// Sometimes we can't stringify due to circular refs
// in complex objects, so we won't bother storing then.
return;
}
}
try {
setItem(key, value);
} catch (e) {
if (isOutOfSpace(e)) {
// If we exceeded the quota, then we will sort
// by the expire time, and then remove the N oldest
var storedKeys = [];
var storedKey;
eachKey(function(key, exprKey) {
var expiration = getItem(exprKey);
if (expiration) {
expiration = parseInt(expiration, EXPIRY_RADIX);
} else {
// TODO: Store date added for non-expiring items for smarter removal
expiration = MAX_DATE;
}
storedKeys.push({
key: key,
size: (getItem(key) || '').length,
expiration: expiration
});
});
// Sorts the keys with oldest expiration time last
storedKeys.sort(function(a, b) { return (b.expiration-a.expiration); });
var targetSize = (value||'').length;
while (storedKeys.length && targetSize > 0) {
storedKey = storedKeys.pop();
warn("Cache is full, removing item with key '" + key + "'");
flushItem(storedKey.key);
targetSize -= storedKey.size;
}
try {
setItem(key, value);
} catch (e) {
// value may be larger than total quota
warn("Could not add item with key '" + key + "', perhaps it's too big?", e);
return;
}
} else {
// If it was some other error, just give up.
warn("Could not add item with key '" + key + "'", e);
return;
}
}
// If a time is specified, store expiration info in localStorage
if (time) {
setItem(expirationKey(key), (currentTime() + time).toString(EXPIRY_RADIX));
} else {
// In case they previously set a time, remove that info from localStorage.
removeItem(expirationKey(key));
}
},
/**
* Retrieves specified value from localStorage, if not expired.
* @param {string} key
* @return {string|Object}
*/
get: function(key) {
if (!supportsStorage()) return null;
// Return the de-serialized item if not expired
if (flushExpiredItem(key)) { return null; }
// Tries to de-serialize stored value if its an object, and returns the normal value otherwise.
var value = getItem(key);
if (!value || !supportsJSON()) {
return value;
}
try {
// We can't tell if its JSON or a string, so we try to parse
return JSON.parse(value);
} catch (e) {
// If we can't parse, it's probably because it isn't an object
return value;
}
},
/**
* Removes a value from localStorage.
* Equivalent to 'delete' in memcache, but that's a keyword in JS.
* @param {string} key
*/
remove: function(key) {
if (!supportsStorage()) return;
flushItem(key);
},
/**
* Returns whether local storage is supported.
* Currently exposed for testing purposes.
* @return {boolean}
*/
supported: function() {
return supportsStorage();
},
/**
* Flushes all lscache items and expiry markers without affecting rest of localStorage
*/
flush: function() {
if (!supportsStorage()) return;
eachKey(function(key) {
flushItem(key);
});
},
/**
* Flushes expired lscache items and expiry markers without affecting rest of localStorage
*/
flushExpired: function() {
if (!supportsStorage()) return;
eachKey(function(key) {
flushExpiredItem(key);
});
},
/**
* Appends CACHE_PREFIX so lscache will partition data in to different buckets.
* @param {string} bucket
*/
setBucket: function(bucket) {
cacheBucket = bucket;
},
/**
* Resets the string being appended to CACHE_PREFIX so lscache will use the default storage behavior.
*/
resetBucket: function() {
cacheBucket = '';
},
/**
* Sets whether to display warnings when an item is removed from the cache or not.
*/
enableWarnings: function(enabled) {
warnings = enabled;
}
};
// Return the module
return lscache;
}));
| brix/cdnjs | ajax/libs/lscache/1.0.7/lscache.js | JavaScript | mit | 11,142 |
/*
* Copyright (c) 2011 Atheros Communications Inc.
* Copyright (c) 2011-2012 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/of.h>
#include <linux/mmc/sdio_func.h>
#include <linux/vmalloc.h>
#include "core.h"
#include "cfg80211.h"
#include "target.h"
#include "debug.h"
#include "hif-ops.h"
#include "htc-ops.h"
static const struct ath6kl_hw hw_list[] = {
{
.id = AR6003_HW_2_0_VERSION,
.name = "ar6003 hw 2.0",
.dataset_patch_addr = 0x57e884,
.app_load_addr = 0x543180,
.board_ext_data_addr = 0x57e500,
.reserved_ram_size = 6912,
.refclk_hz = 26000000,
.uarttx_pin = 8,
.flags = ATH6KL_HW_SDIO_CRC_ERROR_WAR,
/* hw2.0 needs override address hardcoded */
.app_start_override_addr = 0x944C00,
.fw = {
.dir = AR6003_HW_2_0_FW_DIR,
.otp = AR6003_HW_2_0_OTP_FILE,
.fw = AR6003_HW_2_0_FIRMWARE_FILE,
.tcmd = AR6003_HW_2_0_TCMD_FIRMWARE_FILE,
.patch = AR6003_HW_2_0_PATCH_FILE,
},
.fw_board = AR6003_HW_2_0_BOARD_DATA_FILE,
.fw_default_board = AR6003_HW_2_0_DEFAULT_BOARD_DATA_FILE,
},
{
.id = AR6003_HW_2_1_1_VERSION,
.name = "ar6003 hw 2.1.1",
.dataset_patch_addr = 0x57ff74,
.app_load_addr = 0x1234,
.board_ext_data_addr = 0x542330,
.reserved_ram_size = 512,
.refclk_hz = 26000000,
.uarttx_pin = 8,
.testscript_addr = 0x57ef74,
.flags = ATH6KL_HW_SDIO_CRC_ERROR_WAR,
.fw = {
.dir = AR6003_HW_2_1_1_FW_DIR,
.otp = AR6003_HW_2_1_1_OTP_FILE,
.fw = AR6003_HW_2_1_1_FIRMWARE_FILE,
.tcmd = AR6003_HW_2_1_1_TCMD_FIRMWARE_FILE,
.patch = AR6003_HW_2_1_1_PATCH_FILE,
.utf = AR6003_HW_2_1_1_UTF_FIRMWARE_FILE,
.testscript = AR6003_HW_2_1_1_TESTSCRIPT_FILE,
},
.fw_board = AR6003_HW_2_1_1_BOARD_DATA_FILE,
.fw_default_board = AR6003_HW_2_1_1_DEFAULT_BOARD_DATA_FILE,
},
{
.id = AR6004_HW_1_0_VERSION,
.name = "ar6004 hw 1.0",
.dataset_patch_addr = 0x57e884,
.app_load_addr = 0x1234,
.board_ext_data_addr = 0x437000,
.reserved_ram_size = 19456,
.board_addr = 0x433900,
.refclk_hz = 26000000,
.uarttx_pin = 11,
.flags = 0,
.fw = {
.dir = AR6004_HW_1_0_FW_DIR,
.fw = AR6004_HW_1_0_FIRMWARE_FILE,
},
.fw_board = AR6004_HW_1_0_BOARD_DATA_FILE,
.fw_default_board = AR6004_HW_1_0_DEFAULT_BOARD_DATA_FILE,
},
{
.id = AR6004_HW_1_1_VERSION,
.name = "ar6004 hw 1.1",
.dataset_patch_addr = 0x57e884,
.app_load_addr = 0x1234,
.board_ext_data_addr = 0x437000,
.reserved_ram_size = 11264,
.board_addr = 0x43d400,
.refclk_hz = 40000000,
.uarttx_pin = 11,
.flags = 0,
.fw = {
.dir = AR6004_HW_1_1_FW_DIR,
.fw = AR6004_HW_1_1_FIRMWARE_FILE,
},
.fw_board = AR6004_HW_1_1_BOARD_DATA_FILE,
.fw_default_board = AR6004_HW_1_1_DEFAULT_BOARD_DATA_FILE,
},
{
.id = AR6004_HW_1_2_VERSION,
.name = "ar6004 hw 1.2",
.dataset_patch_addr = 0x436ecc,
.app_load_addr = 0x1234,
.board_ext_data_addr = 0x437000,
.reserved_ram_size = 9216,
.board_addr = 0x435c00,
.refclk_hz = 40000000,
.uarttx_pin = 11,
.flags = 0,
.fw = {
.dir = AR6004_HW_1_2_FW_DIR,
.fw = AR6004_HW_1_2_FIRMWARE_FILE,
},
.fw_board = AR6004_HW_1_2_BOARD_DATA_FILE,
.fw_default_board = AR6004_HW_1_2_DEFAULT_BOARD_DATA_FILE,
},
{
.id = AR6004_HW_1_3_VERSION,
.name = "ar6004 hw 1.3",
.dataset_patch_addr = 0x437860,
.app_load_addr = 0x1234,
.board_ext_data_addr = 0x437000,
.reserved_ram_size = 7168,
.board_addr = 0x436400,
.refclk_hz = 0,
.uarttx_pin = 11,
.flags = 0,
.fw = {
.dir = AR6004_HW_1_3_FW_DIR,
.fw = AR6004_HW_1_3_FIRMWARE_FILE,
.tcmd = AR6004_HW_1_3_TCMD_FIRMWARE_FILE,
.utf = AR6004_HW_1_3_UTF_FIRMWARE_FILE,
.testscript = AR6004_HW_1_3_TESTSCRIPT_FILE,
},
.fw_board = AR6004_HW_1_3_BOARD_DATA_FILE,
.fw_default_board = AR6004_HW_1_3_DEFAULT_BOARD_DATA_FILE,
},
{
.id = AR6004_HW_3_0_VERSION,
.name = "ar6004 hw 3.0",
.dataset_patch_addr = 0,
.app_load_addr = 0x1234,
.board_ext_data_addr = 0,
.reserved_ram_size = 7168,
.board_addr = 0x436400,
.testscript_addr = 0,
.uarttx_pin = 11,
.flags = 0,
.fw = {
.dir = AR6004_HW_3_0_FW_DIR,
.fw = AR6004_HW_3_0_FIRMWARE_FILE,
.tcmd = AR6004_HW_3_0_TCMD_FIRMWARE_FILE,
.utf = AR6004_HW_3_0_UTF_FIRMWARE_FILE,
.testscript = AR6004_HW_3_0_TESTSCRIPT_FILE,
},
.fw_board = AR6004_HW_3_0_BOARD_DATA_FILE,
.fw_default_board = AR6004_HW_3_0_DEFAULT_BOARD_DATA_FILE,
},
};
/*
* Include definitions here that can be used to tune the WLAN module
* behavior. Different customers can tune the behavior as per their needs,
* here.
*/
/*
* This configuration item enable/disable keepalive support.
* Keepalive support: In the absence of any data traffic to AP, null
* frames will be sent to the AP at periodic interval, to keep the association
* active. This configuration item defines the periodic interval.
* Use value of zero to disable keepalive support
* Default: 60 seconds
*/
#define WLAN_CONFIG_KEEP_ALIVE_INTERVAL 60
/*
* This configuration item sets the value of disconnect timeout
* Firmware delays sending the disconnec event to the host for this
* timeout after is gets disconnected from the current AP.
* If the firmware successly roams within the disconnect timeout
* it sends a new connect event
*/
#define WLAN_CONFIG_DISCONNECT_TIMEOUT 10
#define ATH6KL_DATA_OFFSET 64
struct sk_buff *ath6kl_buf_alloc(int size)
{
struct sk_buff *skb;
u16 reserved;
/* Add chacheline space at front and back of buffer */
reserved = roundup((2 * L1_CACHE_BYTES) + ATH6KL_DATA_OFFSET +
sizeof(struct htc_packet) + ATH6KL_HTC_ALIGN_BYTES, 4);
skb = dev_alloc_skb(size + reserved);
if (skb)
skb_reserve(skb, reserved - L1_CACHE_BYTES);
return skb;
}
void ath6kl_init_profile_info(struct ath6kl_vif *vif)
{
vif->ssid_len = 0;
memset(vif->ssid, 0, sizeof(vif->ssid));
vif->dot11_auth_mode = OPEN_AUTH;
vif->auth_mode = NONE_AUTH;
vif->prwise_crypto = NONE_CRYPT;
vif->prwise_crypto_len = 0;
vif->grp_crypto = NONE_CRYPT;
vif->grp_crypto_len = 0;
memset(vif->wep_key_list, 0, sizeof(vif->wep_key_list));
memset(vif->req_bssid, 0, sizeof(vif->req_bssid));
memset(vif->bssid, 0, sizeof(vif->bssid));
vif->bss_ch = 0;
}
static int ath6kl_set_host_app_area(struct ath6kl *ar)
{
u32 address, data;
struct host_app_area host_app_area;
/* Fetch the address of the host_app_area_s
* instance in the host interest area */
address = ath6kl_get_hi_item_addr(ar, HI_ITEM(hi_app_host_interest));
address = TARG_VTOP(ar->target_type, address);
if (ath6kl_diag_read32(ar, address, &data))
return -EIO;
address = TARG_VTOP(ar->target_type, data);
host_app_area.wmi_protocol_ver = cpu_to_le32(WMI_PROTOCOL_VERSION);
if (ath6kl_diag_write(ar, address, (u8 *) &host_app_area,
sizeof(struct host_app_area)))
return -EIO;
return 0;
}
static inline void set_ac2_ep_map(struct ath6kl *ar,
u8 ac,
enum htc_endpoint_id ep)
{
ar->ac2ep_map[ac] = ep;
ar->ep2ac_map[ep] = ac;
}
/* connect to a service */
static int ath6kl_connectservice(struct ath6kl *ar,
struct htc_service_connect_req *con_req,
char *desc)
{
int status;
struct htc_service_connect_resp response;
memset(&response, 0, sizeof(response));
status = ath6kl_htc_conn_service(ar->htc_target, con_req, &response);
if (status) {
ath6kl_err("failed to connect to %s service status:%d\n",
desc, status);
return status;
}
switch (con_req->svc_id) {
case WMI_CONTROL_SVC:
if (test_bit(WMI_ENABLED, &ar->flag))
ath6kl_wmi_set_control_ep(ar->wmi, response.endpoint);
ar->ctrl_ep = response.endpoint;
break;
case WMI_DATA_BE_SVC:
set_ac2_ep_map(ar, WMM_AC_BE, response.endpoint);
break;
case WMI_DATA_BK_SVC:
set_ac2_ep_map(ar, WMM_AC_BK, response.endpoint);
break;
case WMI_DATA_VI_SVC:
set_ac2_ep_map(ar, WMM_AC_VI, response.endpoint);
break;
case WMI_DATA_VO_SVC:
set_ac2_ep_map(ar, WMM_AC_VO, response.endpoint);
break;
default:
ath6kl_err("service id is not mapped %d\n", con_req->svc_id);
return -EINVAL;
}
return 0;
}
static int ath6kl_init_service_ep(struct ath6kl *ar)
{
struct htc_service_connect_req connect;
memset(&connect, 0, sizeof(connect));
/* these fields are the same for all service endpoints */
connect.ep_cb.tx_comp_multi = ath6kl_tx_complete;
connect.ep_cb.rx = ath6kl_rx;
connect.ep_cb.rx_refill = ath6kl_rx_refill;
connect.ep_cb.tx_full = ath6kl_tx_queue_full;
/*
* Set the max queue depth so that our ath6kl_tx_queue_full handler
* gets called.
*/
connect.max_txq_depth = MAX_DEFAULT_SEND_QUEUE_DEPTH;
connect.ep_cb.rx_refill_thresh = ATH6KL_MAX_RX_BUFFERS / 4;
if (!connect.ep_cb.rx_refill_thresh)
connect.ep_cb.rx_refill_thresh++;
/* connect to control service */
connect.svc_id = WMI_CONTROL_SVC;
if (ath6kl_connectservice(ar, &connect, "WMI CONTROL"))
return -EIO;
connect.flags |= HTC_FLGS_TX_BNDL_PAD_EN;
/*
* Limit the HTC message size on the send path, although e can
* receive A-MSDU frames of 4K, we will only send ethernet-sized
* (802.3) frames on the send path.
*/
connect.max_rxmsg_sz = WMI_MAX_TX_DATA_FRAME_LENGTH;
/*
* To reduce the amount of committed memory for larger A_MSDU
* frames, use the recv-alloc threshold mechanism for larger
* packets.
*/
connect.ep_cb.rx_alloc_thresh = ATH6KL_BUFFER_SIZE;
connect.ep_cb.rx_allocthresh = ath6kl_alloc_amsdu_rxbuf;
/*
* For the remaining data services set the connection flag to
* reduce dribbling, if configured to do so.
*/
connect.conn_flags |= HTC_CONN_FLGS_REDUCE_CRED_DRIB;
connect.conn_flags &= ~HTC_CONN_FLGS_THRESH_MASK;
connect.conn_flags |= HTC_CONN_FLGS_THRESH_LVL_HALF;
connect.svc_id = WMI_DATA_BE_SVC;
if (ath6kl_connectservice(ar, &connect, "WMI DATA BE"))
return -EIO;
/* connect to back-ground map this to WMI LOW_PRI */
connect.svc_id = WMI_DATA_BK_SVC;
if (ath6kl_connectservice(ar, &connect, "WMI DATA BK"))
return -EIO;
/* connect to Video service, map this to HI PRI */
connect.svc_id = WMI_DATA_VI_SVC;
if (ath6kl_connectservice(ar, &connect, "WMI DATA VI"))
return -EIO;
/*
* Connect to VO service, this is currently not mapped to a WMI
* priority stream due to historical reasons. WMI originally
* defined 3 priorities over 3 mailboxes We can change this when
* WMI is reworked so that priorities are not dependent on
* mailboxes.
*/
connect.svc_id = WMI_DATA_VO_SVC;
if (ath6kl_connectservice(ar, &connect, "WMI DATA VO"))
return -EIO;
return 0;
}
void ath6kl_init_control_info(struct ath6kl_vif *vif)
{
ath6kl_init_profile_info(vif);
vif->def_txkey_index = 0;
memset(vif->wep_key_list, 0, sizeof(vif->wep_key_list));
vif->ch_hint = 0;
}
/*
* Set HTC/Mbox operational parameters, this can only be called when the
* target is in the BMI phase.
*/
static int ath6kl_set_htc_params(struct ath6kl *ar, u32 mbox_isr_yield_val,
u8 htc_ctrl_buf)
{
int status;
u32 blk_size;
blk_size = ar->mbox_info.block_size;
if (htc_ctrl_buf)
blk_size |= ((u32)htc_ctrl_buf) << 16;
/* set the host interest area for the block size */
status = ath6kl_bmi_write_hi32(ar, hi_mbox_io_block_sz, blk_size);
if (status) {
ath6kl_err("bmi_write_memory for IO block size failed\n");
goto out;
}
ath6kl_dbg(ATH6KL_DBG_TRC, "block size set: %d (target addr:0x%X)\n",
blk_size,
ath6kl_get_hi_item_addr(ar, HI_ITEM(hi_mbox_io_block_sz)));
if (mbox_isr_yield_val) {
/* set the host interest area for the mbox ISR yield limit */
status = ath6kl_bmi_write_hi32(ar, hi_mbox_isr_yield_limit,
mbox_isr_yield_val);
if (status) {
ath6kl_err("bmi_write_memory for yield limit failed\n");
goto out;
}
}
out:
return status;
}
static int ath6kl_target_config_wlan_params(struct ath6kl *ar, int idx)
{
int ret;
/*
* Configure the device for rx dot11 header rules. "0,0" are the
* default values. Required if checksum offload is needed. Set
* RxMetaVersion to 2.
*/
ret = ath6kl_wmi_set_rx_frame_format_cmd(ar->wmi, idx,
ar->rx_meta_ver, 0, 0);
if (ret) {
ath6kl_err("unable to set the rx frame format: %d\n", ret);
return ret;
}
if (ar->conf_flags & ATH6KL_CONF_IGNORE_PS_FAIL_EVT_IN_SCAN) {
ret = ath6kl_wmi_pmparams_cmd(ar->wmi, idx, 0, 1, 0, 0, 1,
IGNORE_PS_FAIL_DURING_SCAN);
if (ret) {
ath6kl_err("unable to set power save fail event policy: %d\n",
ret);
return ret;
}
}
if (!(ar->conf_flags & ATH6KL_CONF_IGNORE_ERP_BARKER)) {
ret = ath6kl_wmi_set_lpreamble_cmd(ar->wmi, idx, 0,
WMI_FOLLOW_BARKER_IN_ERP);
if (ret) {
ath6kl_err("unable to set barker preamble policy: %d\n",
ret);
return ret;
}
}
ret = ath6kl_wmi_set_keepalive_cmd(ar->wmi, idx,
WLAN_CONFIG_KEEP_ALIVE_INTERVAL);
if (ret) {
ath6kl_err("unable to set keep alive interval: %d\n", ret);
return ret;
}
ret = ath6kl_wmi_disctimeout_cmd(ar->wmi, idx,
WLAN_CONFIG_DISCONNECT_TIMEOUT);
if (ret) {
ath6kl_err("unable to set disconnect timeout: %d\n", ret);
return ret;
}
if (!(ar->conf_flags & ATH6KL_CONF_ENABLE_TX_BURST)) {
ret = ath6kl_wmi_set_wmm_txop(ar->wmi, idx, WMI_TXOP_DISABLED);
if (ret) {
ath6kl_err("unable to set txop bursting: %d\n", ret);
return ret;
}
}
if (ar->p2p && (ar->vif_max == 1 || idx)) {
ret = ath6kl_wmi_info_req_cmd(ar->wmi, idx,
P2P_FLAG_CAPABILITIES_REQ |
P2P_FLAG_MACADDR_REQ |
P2P_FLAG_HMODEL_REQ);
if (ret) {
ath6kl_dbg(ATH6KL_DBG_TRC,
"failed to request P2P capabilities (%d) - assuming P2P not supported\n",
ret);
ar->p2p = false;
}
}
if (ar->p2p && (ar->vif_max == 1 || idx)) {
/* Enable Probe Request reporting for P2P */
ret = ath6kl_wmi_probe_report_req_cmd(ar->wmi, idx, true);
if (ret) {
ath6kl_dbg(ATH6KL_DBG_TRC,
"failed to enable Probe Request reporting (%d)\n",
ret);
}
}
return ret;
}
int ath6kl_configure_target(struct ath6kl *ar)
{
u32 param, ram_reserved_size;
u8 fw_iftype, fw_mode = 0, fw_submode = 0;
int i, status;
param = !!(ar->conf_flags & ATH6KL_CONF_UART_DEBUG);
if (ath6kl_bmi_write_hi32(ar, hi_serial_enable, param)) {
ath6kl_err("bmi_write_memory for uart debug failed\n");
return -EIO;
}
/*
* Note: Even though the firmware interface type is
* chosen as BSS_STA for all three interfaces, can
* be configured to IBSS/AP as long as the fw submode
* remains normal mode (0 - AP, STA and IBSS). But
* due to an target assert in firmware only one interface is
* configured for now.
*/
fw_iftype = HI_OPTION_FW_MODE_BSS_STA;
for (i = 0; i < ar->vif_max; i++)
fw_mode |= fw_iftype << (i * HI_OPTION_FW_MODE_BITS);
/*
* Submodes when fw does not support dynamic interface
* switching:
* vif[0] - AP/STA/IBSS
* vif[1] - "P2P dev"/"P2P GO"/"P2P Client"
* vif[2] - "P2P dev"/"P2P GO"/"P2P Client"
* Otherwise, All the interface are initialized to p2p dev.
*/
if (test_bit(ATH6KL_FW_CAPABILITY_STA_P2PDEV_DUPLEX,
ar->fw_capabilities)) {
for (i = 0; i < ar->vif_max; i++)
fw_submode |= HI_OPTION_FW_SUBMODE_P2PDEV <<
(i * HI_OPTION_FW_SUBMODE_BITS);
} else {
for (i = 0; i < ar->max_norm_iface; i++)
fw_submode |= HI_OPTION_FW_SUBMODE_NONE <<
(i * HI_OPTION_FW_SUBMODE_BITS);
for (i = ar->max_norm_iface; i < ar->vif_max; i++)
fw_submode |= HI_OPTION_FW_SUBMODE_P2PDEV <<
(i * HI_OPTION_FW_SUBMODE_BITS);
if (ar->p2p && ar->vif_max == 1)
fw_submode = HI_OPTION_FW_SUBMODE_P2PDEV;
}
if (ath6kl_bmi_write_hi32(ar, hi_app_host_interest,
HTC_PROTOCOL_VERSION) != 0) {
ath6kl_err("bmi_write_memory for htc version failed\n");
return -EIO;
}
/* set the firmware mode to STA/IBSS/AP */
param = 0;
if (ath6kl_bmi_read_hi32(ar, hi_option_flag, ¶m) != 0) {
ath6kl_err("bmi_read_memory for setting fwmode failed\n");
return -EIO;
}
param |= (ar->vif_max << HI_OPTION_NUM_DEV_SHIFT);
param |= fw_mode << HI_OPTION_FW_MODE_SHIFT;
param |= fw_submode << HI_OPTION_FW_SUBMODE_SHIFT;
param |= (0 << HI_OPTION_MAC_ADDR_METHOD_SHIFT);
param |= (0 << HI_OPTION_FW_BRIDGE_SHIFT);
if (ath6kl_bmi_write_hi32(ar, hi_option_flag, param) != 0) {
ath6kl_err("bmi_write_memory for setting fwmode failed\n");
return -EIO;
}
ath6kl_dbg(ATH6KL_DBG_TRC, "firmware mode set\n");
/*
* Hardcode the address use for the extended board data
* Ideally this should be pre-allocate by the OS at boot time
* But since it is a new feature and board data is loaded
* at init time, we have to workaround this from host.
* It is difficult to patch the firmware boot code,
* but possible in theory.
*/
if ((ar->target_type == TARGET_TYPE_AR6003) ||
(ar->version.target_ver == AR6004_HW_1_3_VERSION) ||
(ar->version.target_ver == AR6004_HW_3_0_VERSION)) {
param = ar->hw.board_ext_data_addr;
ram_reserved_size = ar->hw.reserved_ram_size;
if (ath6kl_bmi_write_hi32(ar, hi_board_ext_data, param) != 0) {
ath6kl_err("bmi_write_memory for hi_board_ext_data failed\n");
return -EIO;
}
if (ath6kl_bmi_write_hi32(ar, hi_end_ram_reserve_sz,
ram_reserved_size) != 0) {
ath6kl_err("bmi_write_memory for hi_end_ram_reserve_sz failed\n");
return -EIO;
}
}
/* set the block size for the target */
if (ath6kl_set_htc_params(ar, MBOX_YIELD_LIMIT, 0))
/* use default number of control buffers */
return -EIO;
/* Configure GPIO AR600x UART */
status = ath6kl_bmi_write_hi32(ar, hi_dbg_uart_txpin,
ar->hw.uarttx_pin);
if (status)
return status;
/* Only set the baud rate if we're actually doing debug */
if (ar->conf_flags & ATH6KL_CONF_UART_DEBUG) {
status = ath6kl_bmi_write_hi32(ar, hi_desired_baud_rate,
ar->hw.uarttx_rate);
if (status)
return status;
}
/* Configure target refclk_hz */
if (ar->hw.refclk_hz != 0) {
status = ath6kl_bmi_write_hi32(ar, hi_refclk_hz,
ar->hw.refclk_hz);
if (status)
return status;
}
return 0;
}
/* firmware upload */
static int ath6kl_get_fw(struct ath6kl *ar, const char *filename,
u8 **fw, size_t *fw_len)
{
const struct firmware *fw_entry;
int ret;
ret = request_firmware(&fw_entry, filename, ar->dev);
if (ret)
return ret;
*fw_len = fw_entry->size;
*fw = kmemdup(fw_entry->data, fw_entry->size, GFP_KERNEL);
if (*fw == NULL)
ret = -ENOMEM;
release_firmware(fw_entry);
return ret;
}
#ifdef CONFIG_OF
/*
* Check the device tree for a board-id and use it to construct
* the pathname to the firmware file. Used (for now) to find a
* fallback to the "bdata.bin" file--typically a symlink to the
* appropriate board-specific file.
*/
static bool check_device_tree(struct ath6kl *ar)
{
static const char *board_id_prop = "atheros,board-id";
struct device_node *node;
char board_filename[64];
const char *board_id;
int ret;
for_each_compatible_node(node, NULL, "atheros,ath6kl") {
board_id = of_get_property(node, board_id_prop, NULL);
if (board_id == NULL) {
ath6kl_warn("No \"%s\" property on %pOFn node.\n",
board_id_prop, node);
continue;
}
snprintf(board_filename, sizeof(board_filename),
"%s/bdata.%s.bin", ar->hw.fw.dir, board_id);
ret = ath6kl_get_fw(ar, board_filename, &ar->fw_board,
&ar->fw_board_len);
if (ret) {
ath6kl_err("Failed to get DT board file %s: %d\n",
board_filename, ret);
continue;
}
of_node_put(node);
return true;
}
return false;
}
#else
static bool check_device_tree(struct ath6kl *ar)
{
return false;
}
#endif /* CONFIG_OF */
static int ath6kl_fetch_board_file(struct ath6kl *ar)
{
const char *filename;
int ret;
if (ar->fw_board != NULL)
return 0;
if (WARN_ON(ar->hw.fw_board == NULL))
return -EINVAL;
filename = ar->hw.fw_board;
ret = ath6kl_get_fw(ar, filename, &ar->fw_board,
&ar->fw_board_len);
if (ret == 0) {
/* managed to get proper board file */
return 0;
}
if (check_device_tree(ar)) {
/* got board file from device tree */
return 0;
}
/* there was no proper board file, try to use default instead */
ath6kl_warn("Failed to get board file %s (%d), trying to find default board file.\n",
filename, ret);
filename = ar->hw.fw_default_board;
ret = ath6kl_get_fw(ar, filename, &ar->fw_board,
&ar->fw_board_len);
if (ret) {
ath6kl_err("Failed to get default board file %s: %d\n",
filename, ret);
return ret;
}
ath6kl_warn("WARNING! No proper board file was not found, instead using a default board file.\n");
ath6kl_warn("Most likely your hardware won't work as specified. Install correct board file!\n");
return 0;
}
static int ath6kl_fetch_otp_file(struct ath6kl *ar)
{
char filename[100];
int ret;
if (ar->fw_otp != NULL)
return 0;
if (ar->hw.fw.otp == NULL) {
ath6kl_dbg(ATH6KL_DBG_BOOT,
"no OTP file configured for this hw\n");
return 0;
}
snprintf(filename, sizeof(filename), "%s/%s",
ar->hw.fw.dir, ar->hw.fw.otp);
ret = ath6kl_get_fw(ar, filename, &ar->fw_otp,
&ar->fw_otp_len);
if (ret) {
ath6kl_err("Failed to get OTP file %s: %d\n",
filename, ret);
return ret;
}
return 0;
}
static int ath6kl_fetch_testmode_file(struct ath6kl *ar)
{
char filename[100];
int ret;
if (ar->testmode == 0)
return 0;
ath6kl_dbg(ATH6KL_DBG_BOOT, "testmode %d\n", ar->testmode);
if (ar->testmode == 2) {
if (ar->hw.fw.utf == NULL) {
ath6kl_warn("testmode 2 not supported\n");
return -EOPNOTSUPP;
}
snprintf(filename, sizeof(filename), "%s/%s",
ar->hw.fw.dir, ar->hw.fw.utf);
} else {
if (ar->hw.fw.tcmd == NULL) {
ath6kl_warn("testmode 1 not supported\n");
return -EOPNOTSUPP;
}
snprintf(filename, sizeof(filename), "%s/%s",
ar->hw.fw.dir, ar->hw.fw.tcmd);
}
set_bit(TESTMODE, &ar->flag);
ret = ath6kl_get_fw(ar, filename, &ar->fw, &ar->fw_len);
if (ret) {
ath6kl_err("Failed to get testmode %d firmware file %s: %d\n",
ar->testmode, filename, ret);
return ret;
}
return 0;
}
static int ath6kl_fetch_fw_file(struct ath6kl *ar)
{
char filename[100];
int ret;
if (ar->fw != NULL)
return 0;
/* FIXME: remove WARN_ON() as we won't support FW API 1 for long */
if (WARN_ON(ar->hw.fw.fw == NULL))
return -EINVAL;
snprintf(filename, sizeof(filename), "%s/%s",
ar->hw.fw.dir, ar->hw.fw.fw);
ret = ath6kl_get_fw(ar, filename, &ar->fw, &ar->fw_len);
if (ret) {
ath6kl_err("Failed to get firmware file %s: %d\n",
filename, ret);
return ret;
}
return 0;
}
static int ath6kl_fetch_patch_file(struct ath6kl *ar)
{
char filename[100];
int ret;
if (ar->fw_patch != NULL)
return 0;
if (ar->hw.fw.patch == NULL)
return 0;
snprintf(filename, sizeof(filename), "%s/%s",
ar->hw.fw.dir, ar->hw.fw.patch);
ret = ath6kl_get_fw(ar, filename, &ar->fw_patch,
&ar->fw_patch_len);
if (ret) {
ath6kl_err("Failed to get patch file %s: %d\n",
filename, ret);
return ret;
}
return 0;
}
static int ath6kl_fetch_testscript_file(struct ath6kl *ar)
{
char filename[100];
int ret;
if (ar->testmode != 2)
return 0;
if (ar->fw_testscript != NULL)
return 0;
if (ar->hw.fw.testscript == NULL)
return 0;
snprintf(filename, sizeof(filename), "%s/%s",
ar->hw.fw.dir, ar->hw.fw.testscript);
ret = ath6kl_get_fw(ar, filename, &ar->fw_testscript,
&ar->fw_testscript_len);
if (ret) {
ath6kl_err("Failed to get testscript file %s: %d\n",
filename, ret);
return ret;
}
return 0;
}
static int ath6kl_fetch_fw_api1(struct ath6kl *ar)
{
int ret;
ret = ath6kl_fetch_otp_file(ar);
if (ret)
return ret;
ret = ath6kl_fetch_fw_file(ar);
if (ret)
return ret;
ret = ath6kl_fetch_patch_file(ar);
if (ret)
return ret;
ret = ath6kl_fetch_testscript_file(ar);
if (ret)
return ret;
return 0;
}
static int ath6kl_fetch_fw_apin(struct ath6kl *ar, const char *name)
{
size_t magic_len, len, ie_len;
const struct firmware *fw;
struct ath6kl_fw_ie *hdr;
char filename[100];
const u8 *data;
int ret, ie_id, i, index, bit;
__le32 *val;
snprintf(filename, sizeof(filename), "%s/%s", ar->hw.fw.dir, name);
ret = request_firmware(&fw, filename, ar->dev);
if (ret) {
ath6kl_err("Failed request firmware, rv: %d\n", ret);
return ret;
}
data = fw->data;
len = fw->size;
/* magic also includes the null byte, check that as well */
magic_len = strlen(ATH6KL_FIRMWARE_MAGIC) + 1;
if (len < magic_len) {
ath6kl_err("Magic length is invalid, len: %zd magic_len: %zd\n",
len, magic_len);
ret = -EINVAL;
goto out;
}
if (memcmp(data, ATH6KL_FIRMWARE_MAGIC, magic_len) != 0) {
ath6kl_err("Magic is invalid, magic_len: %zd\n",
magic_len);
ret = -EINVAL;
goto out;
}
len -= magic_len;
data += magic_len;
/* loop elements */
while (len > sizeof(struct ath6kl_fw_ie)) {
/* hdr is unaligned! */
hdr = (struct ath6kl_fw_ie *) data;
ie_id = le32_to_cpup(&hdr->id);
ie_len = le32_to_cpup(&hdr->len);
len -= sizeof(*hdr);
data += sizeof(*hdr);
ath6kl_dbg(ATH6KL_DBG_BOOT, "ie-id: %d len: %zd (0x%zx)\n",
ie_id, ie_len, ie_len);
if (len < ie_len) {
ath6kl_err("IE len is invalid, len: %zd ie_len: %zd ie-id: %d\n",
len, ie_len, ie_id);
ret = -EINVAL;
goto out;
}
switch (ie_id) {
case ATH6KL_FW_IE_FW_VERSION:
strlcpy(ar->wiphy->fw_version, data,
min(sizeof(ar->wiphy->fw_version), ie_len+1));
ath6kl_dbg(ATH6KL_DBG_BOOT,
"found fw version %s\n",
ar->wiphy->fw_version);
break;
case ATH6KL_FW_IE_OTP_IMAGE:
ath6kl_dbg(ATH6KL_DBG_BOOT, "found otp image ie (%zd B)\n",
ie_len);
ar->fw_otp = kmemdup(data, ie_len, GFP_KERNEL);
if (ar->fw_otp == NULL) {
ath6kl_err("fw_otp cannot be allocated\n");
ret = -ENOMEM;
goto out;
}
ar->fw_otp_len = ie_len;
break;
case ATH6KL_FW_IE_FW_IMAGE:
ath6kl_dbg(ATH6KL_DBG_BOOT, "found fw image ie (%zd B)\n",
ie_len);
/* in testmode we already might have a fw file */
if (ar->fw != NULL)
break;
ar->fw = vmalloc(ie_len);
if (ar->fw == NULL) {
ath6kl_err("fw storage cannot be allocated, len: %zd\n", ie_len);
ret = -ENOMEM;
goto out;
}
memcpy(ar->fw, data, ie_len);
ar->fw_len = ie_len;
break;
case ATH6KL_FW_IE_PATCH_IMAGE:
ath6kl_dbg(ATH6KL_DBG_BOOT, "found patch image ie (%zd B)\n",
ie_len);
ar->fw_patch = kmemdup(data, ie_len, GFP_KERNEL);
if (ar->fw_patch == NULL) {
ath6kl_err("fw_patch storage cannot be allocated, len: %zd\n", ie_len);
ret = -ENOMEM;
goto out;
}
ar->fw_patch_len = ie_len;
break;
case ATH6KL_FW_IE_RESERVED_RAM_SIZE:
val = (__le32 *) data;
ar->hw.reserved_ram_size = le32_to_cpup(val);
ath6kl_dbg(ATH6KL_DBG_BOOT,
"found reserved ram size ie %d\n",
ar->hw.reserved_ram_size);
break;
case ATH6KL_FW_IE_CAPABILITIES:
ath6kl_dbg(ATH6KL_DBG_BOOT,
"found firmware capabilities ie (%zd B)\n",
ie_len);
for (i = 0; i < ATH6KL_FW_CAPABILITY_MAX; i++) {
index = i / 8;
bit = i % 8;
if (index == ie_len)
break;
if (data[index] & (1 << bit))
__set_bit(i, ar->fw_capabilities);
}
ath6kl_dbg_dump(ATH6KL_DBG_BOOT, "capabilities", "",
ar->fw_capabilities,
sizeof(ar->fw_capabilities));
break;
case ATH6KL_FW_IE_PATCH_ADDR:
if (ie_len != sizeof(*val))
break;
val = (__le32 *) data;
ar->hw.dataset_patch_addr = le32_to_cpup(val);
ath6kl_dbg(ATH6KL_DBG_BOOT,
"found patch address ie 0x%x\n",
ar->hw.dataset_patch_addr);
break;
case ATH6KL_FW_IE_BOARD_ADDR:
if (ie_len != sizeof(*val))
break;
val = (__le32 *) data;
ar->hw.board_addr = le32_to_cpup(val);
ath6kl_dbg(ATH6KL_DBG_BOOT,
"found board address ie 0x%x\n",
ar->hw.board_addr);
break;
case ATH6KL_FW_IE_VIF_MAX:
if (ie_len != sizeof(*val))
break;
val = (__le32 *) data;
ar->vif_max = min_t(unsigned int, le32_to_cpup(val),
ATH6KL_VIF_MAX);
if (ar->vif_max > 1 && !ar->p2p)
ar->max_norm_iface = 2;
ath6kl_dbg(ATH6KL_DBG_BOOT,
"found vif max ie %d\n", ar->vif_max);
break;
default:
ath6kl_dbg(ATH6KL_DBG_BOOT, "Unknown fw ie: %u\n",
le32_to_cpup(&hdr->id));
break;
}
len -= ie_len;
data += ie_len;
};
ret = 0;
out:
release_firmware(fw);
return ret;
}
int ath6kl_init_fetch_firmwares(struct ath6kl *ar)
{
int ret;
ret = ath6kl_fetch_board_file(ar);
if (ret)
return ret;
ret = ath6kl_fetch_testmode_file(ar);
if (ret)
return ret;
ret = ath6kl_fetch_fw_apin(ar, ATH6KL_FW_API5_FILE);
if (ret == 0) {
ar->fw_api = 5;
goto out;
}
ret = ath6kl_fetch_fw_apin(ar, ATH6KL_FW_API4_FILE);
if (ret == 0) {
ar->fw_api = 4;
goto out;
}
ret = ath6kl_fetch_fw_apin(ar, ATH6KL_FW_API3_FILE);
if (ret == 0) {
ar->fw_api = 3;
goto out;
}
ret = ath6kl_fetch_fw_apin(ar, ATH6KL_FW_API2_FILE);
if (ret == 0) {
ar->fw_api = 2;
goto out;
}
ret = ath6kl_fetch_fw_api1(ar);
if (ret)
return ret;
ar->fw_api = 1;
out:
ath6kl_dbg(ATH6KL_DBG_BOOT, "using fw api %d\n", ar->fw_api);
return 0;
}
static int ath6kl_upload_board_file(struct ath6kl *ar)
{
u32 board_address, board_ext_address, param;
u32 board_data_size, board_ext_data_size;
int ret;
if (WARN_ON(ar->fw_board == NULL))
return -ENOENT;
/*
* Determine where in Target RAM to write Board Data.
* For AR6004, host determine Target RAM address for
* writing board data.
*/
if (ar->hw.board_addr != 0) {
board_address = ar->hw.board_addr;
ath6kl_bmi_write_hi32(ar, hi_board_data,
board_address);
} else {
ret = ath6kl_bmi_read_hi32(ar, hi_board_data, &board_address);
if (ret) {
ath6kl_err("Failed to get board file target address.\n");
return ret;
}
}
/* determine where in target ram to write extended board data */
ret = ath6kl_bmi_read_hi32(ar, hi_board_ext_data, &board_ext_address);
if (ret) {
ath6kl_err("Failed to get extended board file target address.\n");
return ret;
}
if (ar->target_type == TARGET_TYPE_AR6003 &&
board_ext_address == 0) {
ath6kl_err("Failed to get board file target address.\n");
return -EINVAL;
}
switch (ar->target_type) {
case TARGET_TYPE_AR6003:
board_data_size = AR6003_BOARD_DATA_SZ;
board_ext_data_size = AR6003_BOARD_EXT_DATA_SZ;
if (ar->fw_board_len > (board_data_size + board_ext_data_size))
board_ext_data_size = AR6003_BOARD_EXT_DATA_SZ_V2;
break;
case TARGET_TYPE_AR6004:
board_data_size = AR6004_BOARD_DATA_SZ;
board_ext_data_size = AR6004_BOARD_EXT_DATA_SZ;
break;
default:
WARN_ON(1);
return -EINVAL;
}
if (board_ext_address &&
ar->fw_board_len == (board_data_size + board_ext_data_size)) {
/* write extended board data */
ath6kl_dbg(ATH6KL_DBG_BOOT,
"writing extended board data to 0x%x (%d B)\n",
board_ext_address, board_ext_data_size);
ret = ath6kl_bmi_write(ar, board_ext_address,
ar->fw_board + board_data_size,
board_ext_data_size);
if (ret) {
ath6kl_err("Failed to write extended board data: %d\n",
ret);
return ret;
}
/* record that extended board data is initialized */
param = (board_ext_data_size << 16) | 1;
ath6kl_bmi_write_hi32(ar, hi_board_ext_data_config, param);
}
if (ar->fw_board_len < board_data_size) {
ath6kl_err("Too small board file: %zu\n", ar->fw_board_len);
ret = -EINVAL;
return ret;
}
ath6kl_dbg(ATH6KL_DBG_BOOT, "writing board file to 0x%x (%d B)\n",
board_address, board_data_size);
ret = ath6kl_bmi_write(ar, board_address, ar->fw_board,
board_data_size);
if (ret) {
ath6kl_err("Board file bmi write failed: %d\n", ret);
return ret;
}
/* record the fact that Board Data IS initialized */
if ((ar->version.target_ver == AR6004_HW_1_3_VERSION) ||
(ar->version.target_ver == AR6004_HW_3_0_VERSION))
param = board_data_size;
else
param = 1;
ath6kl_bmi_write_hi32(ar, hi_board_data_initialized, param);
return ret;
}
static int ath6kl_upload_otp(struct ath6kl *ar)
{
u32 address, param;
bool from_hw = false;
int ret;
if (ar->fw_otp == NULL)
return 0;
address = ar->hw.app_load_addr;
ath6kl_dbg(ATH6KL_DBG_BOOT, "writing otp to 0x%x (%zd B)\n", address,
ar->fw_otp_len);
ret = ath6kl_bmi_fast_download(ar, address, ar->fw_otp,
ar->fw_otp_len);
if (ret) {
ath6kl_err("Failed to upload OTP file: %d\n", ret);
return ret;
}
/* read firmware start address */
ret = ath6kl_bmi_read_hi32(ar, hi_app_start, &address);
if (ret) {
ath6kl_err("Failed to read hi_app_start: %d\n", ret);
return ret;
}
if (ar->hw.app_start_override_addr == 0) {
ar->hw.app_start_override_addr = address;
from_hw = true;
}
ath6kl_dbg(ATH6KL_DBG_BOOT, "app_start_override_addr%s 0x%x\n",
from_hw ? " (from hw)" : "",
ar->hw.app_start_override_addr);
/* execute the OTP code */
ath6kl_dbg(ATH6KL_DBG_BOOT, "executing OTP at 0x%x\n",
ar->hw.app_start_override_addr);
param = 0;
ath6kl_bmi_execute(ar, ar->hw.app_start_override_addr, ¶m);
return ret;
}
static int ath6kl_upload_firmware(struct ath6kl *ar)
{
u32 address;
int ret;
if (WARN_ON(ar->fw == NULL))
return 0;
address = ar->hw.app_load_addr;
ath6kl_dbg(ATH6KL_DBG_BOOT, "writing firmware to 0x%x (%zd B)\n",
address, ar->fw_len);
ret = ath6kl_bmi_fast_download(ar, address, ar->fw, ar->fw_len);
if (ret) {
ath6kl_err("Failed to write firmware: %d\n", ret);
return ret;
}
/*
* Set starting address for firmware
* Don't need to setup app_start override addr on AR6004
*/
if (ar->target_type != TARGET_TYPE_AR6004) {
address = ar->hw.app_start_override_addr;
ath6kl_bmi_set_app_start(ar, address);
}
return ret;
}
static int ath6kl_upload_patch(struct ath6kl *ar)
{
u32 address;
int ret;
if (ar->fw_patch == NULL)
return 0;
address = ar->hw.dataset_patch_addr;
ath6kl_dbg(ATH6KL_DBG_BOOT, "writing patch to 0x%x (%zd B)\n",
address, ar->fw_patch_len);
ret = ath6kl_bmi_write(ar, address, ar->fw_patch, ar->fw_patch_len);
if (ret) {
ath6kl_err("Failed to write patch file: %d\n", ret);
return ret;
}
ath6kl_bmi_write_hi32(ar, hi_dset_list_head, address);
return 0;
}
static int ath6kl_upload_testscript(struct ath6kl *ar)
{
u32 address;
int ret;
if (ar->testmode != 2)
return 0;
if (ar->fw_testscript == NULL)
return 0;
address = ar->hw.testscript_addr;
ath6kl_dbg(ATH6KL_DBG_BOOT, "writing testscript to 0x%x (%zd B)\n",
address, ar->fw_testscript_len);
ret = ath6kl_bmi_write(ar, address, ar->fw_testscript,
ar->fw_testscript_len);
if (ret) {
ath6kl_err("Failed to write testscript file: %d\n", ret);
return ret;
}
ath6kl_bmi_write_hi32(ar, hi_ota_testscript, address);
if ((ar->version.target_ver != AR6004_HW_1_3_VERSION) &&
(ar->version.target_ver != AR6004_HW_3_0_VERSION))
ath6kl_bmi_write_hi32(ar, hi_end_ram_reserve_sz, 4096);
ath6kl_bmi_write_hi32(ar, hi_test_apps_related, 1);
return 0;
}
static int ath6kl_init_upload(struct ath6kl *ar)
{
u32 param, options, sleep, address;
int status = 0;
if (ar->target_type != TARGET_TYPE_AR6003 &&
ar->target_type != TARGET_TYPE_AR6004)
return -EINVAL;
/* temporarily disable system sleep */
address = MBOX_BASE_ADDRESS + LOCAL_SCRATCH_ADDRESS;
status = ath6kl_bmi_reg_read(ar, address, ¶m);
if (status)
return status;
options = param;
param |= ATH6KL_OPTION_SLEEP_DISABLE;
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
address = RTC_BASE_ADDRESS + SYSTEM_SLEEP_ADDRESS;
status = ath6kl_bmi_reg_read(ar, address, ¶m);
if (status)
return status;
sleep = param;
param |= SM(SYSTEM_SLEEP_DISABLE, 1);
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
ath6kl_dbg(ATH6KL_DBG_TRC, "old options: %d, old sleep: %d\n",
options, sleep);
/* program analog PLL register */
/* no need to control 40/44MHz clock on AR6004 */
if (ar->target_type != TARGET_TYPE_AR6004) {
status = ath6kl_bmi_reg_write(ar, ATH6KL_ANALOG_PLL_REGISTER,
0xF9104001);
if (status)
return status;
/* Run at 80/88MHz by default */
param = SM(CPU_CLOCK_STANDARD, 1);
address = RTC_BASE_ADDRESS + CPU_CLOCK_ADDRESS;
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
}
param = 0;
address = RTC_BASE_ADDRESS + LPO_CAL_ADDRESS;
param = SM(LPO_CAL_ENABLE, 1);
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
/* WAR to avoid SDIO CRC err */
if (ar->hw.flags & ATH6KL_HW_SDIO_CRC_ERROR_WAR) {
ath6kl_err("temporary war to avoid sdio crc error\n");
param = 0x28;
address = GPIO_BASE_ADDRESS + GPIO_PIN9_ADDRESS;
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
param = 0x20;
address = GPIO_BASE_ADDRESS + GPIO_PIN10_ADDRESS;
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
address = GPIO_BASE_ADDRESS + GPIO_PIN11_ADDRESS;
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
address = GPIO_BASE_ADDRESS + GPIO_PIN12_ADDRESS;
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
address = GPIO_BASE_ADDRESS + GPIO_PIN13_ADDRESS;
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
}
/* write EEPROM data to Target RAM */
status = ath6kl_upload_board_file(ar);
if (status)
return status;
/* transfer One time Programmable data */
status = ath6kl_upload_otp(ar);
if (status)
return status;
/* Download Target firmware */
status = ath6kl_upload_firmware(ar);
if (status)
return status;
status = ath6kl_upload_patch(ar);
if (status)
return status;
/* Download the test script */
status = ath6kl_upload_testscript(ar);
if (status)
return status;
/* Restore system sleep */
address = RTC_BASE_ADDRESS + SYSTEM_SLEEP_ADDRESS;
status = ath6kl_bmi_reg_write(ar, address, sleep);
if (status)
return status;
address = MBOX_BASE_ADDRESS + LOCAL_SCRATCH_ADDRESS;
param = options | 0x20;
status = ath6kl_bmi_reg_write(ar, address, param);
if (status)
return status;
return status;
}
int ath6kl_init_hw_params(struct ath6kl *ar)
{
const struct ath6kl_hw *uninitialized_var(hw);
int i;
for (i = 0; i < ARRAY_SIZE(hw_list); i++) {
hw = &hw_list[i];
if (hw->id == ar->version.target_ver)
break;
}
if (i == ARRAY_SIZE(hw_list)) {
ath6kl_err("Unsupported hardware version: 0x%x\n",
ar->version.target_ver);
return -EINVAL;
}
ar->hw = *hw;
ath6kl_dbg(ATH6KL_DBG_BOOT,
"target_ver 0x%x target_type 0x%x dataset_patch 0x%x app_load_addr 0x%x\n",
ar->version.target_ver, ar->target_type,
ar->hw.dataset_patch_addr, ar->hw.app_load_addr);
ath6kl_dbg(ATH6KL_DBG_BOOT,
"app_start_override_addr 0x%x board_ext_data_addr 0x%x reserved_ram_size 0x%x",
ar->hw.app_start_override_addr, ar->hw.board_ext_data_addr,
ar->hw.reserved_ram_size);
ath6kl_dbg(ATH6KL_DBG_BOOT,
"refclk_hz %d uarttx_pin %d",
ar->hw.refclk_hz, ar->hw.uarttx_pin);
return 0;
}
static const char *ath6kl_init_get_hif_name(enum ath6kl_hif_type type)
{
switch (type) {
case ATH6KL_HIF_TYPE_SDIO:
return "sdio";
case ATH6KL_HIF_TYPE_USB:
return "usb";
}
return NULL;
}
static const struct fw_capa_str_map {
int id;
const char *name;
} fw_capa_map[] = {
{ ATH6KL_FW_CAPABILITY_HOST_P2P, "host-p2p" },
{ ATH6KL_FW_CAPABILITY_SCHED_SCAN, "sched-scan" },
{ ATH6KL_FW_CAPABILITY_STA_P2PDEV_DUPLEX, "sta-p2pdev-duplex" },
{ ATH6KL_FW_CAPABILITY_INACTIVITY_TIMEOUT, "inactivity-timeout" },
{ ATH6KL_FW_CAPABILITY_RSN_CAP_OVERRIDE, "rsn-cap-override" },
{ ATH6KL_FW_CAPABILITY_WOW_MULTICAST_FILTER, "wow-mc-filter" },
{ ATH6KL_FW_CAPABILITY_BMISS_ENHANCE, "bmiss-enhance" },
{ ATH6KL_FW_CAPABILITY_SCHED_SCAN_MATCH_LIST, "sscan-match-list" },
{ ATH6KL_FW_CAPABILITY_RSSI_SCAN_THOLD, "rssi-scan-thold" },
{ ATH6KL_FW_CAPABILITY_CUSTOM_MAC_ADDR, "custom-mac-addr" },
{ ATH6KL_FW_CAPABILITY_TX_ERR_NOTIFY, "tx-err-notify" },
{ ATH6KL_FW_CAPABILITY_REGDOMAIN, "regdomain" },
{ ATH6KL_FW_CAPABILITY_SCHED_SCAN_V2, "sched-scan-v2" },
{ ATH6KL_FW_CAPABILITY_HEART_BEAT_POLL, "hb-poll" },
{ ATH6KL_FW_CAPABILITY_64BIT_RATES, "64bit-rates" },
{ ATH6KL_FW_CAPABILITY_AP_INACTIVITY_MINS, "ap-inactivity-mins" },
{ ATH6KL_FW_CAPABILITY_MAP_LP_ENDPOINT, "map-lp-endpoint" },
{ ATH6KL_FW_CAPABILITY_RATETABLE_MCS15, "ratetable-mcs15" },
{ ATH6KL_FW_CAPABILITY_NO_IP_CHECKSUM, "no-ip-checksum" },
};
static const char *ath6kl_init_get_fw_capa_name(unsigned int id)
{
int i;
for (i = 0; i < ARRAY_SIZE(fw_capa_map); i++) {
if (fw_capa_map[i].id == id)
return fw_capa_map[i].name;
}
return "<unknown>";
}
static void ath6kl_init_get_fwcaps(struct ath6kl *ar, char *buf, size_t buf_len)
{
u8 *data = (u8 *) ar->fw_capabilities;
size_t trunc_len, len = 0;
int i, index, bit;
char *trunc = "...";
for (i = 0; i < ATH6KL_FW_CAPABILITY_MAX; i++) {
index = i / 8;
bit = i % 8;
if (index >= sizeof(ar->fw_capabilities) * 4)
break;
if (buf_len - len < 4) {
ath6kl_warn("firmware capability buffer too small!\n");
/* add "..." to the end of string */
trunc_len = strlen(trunc) + 1;
strncpy(buf + buf_len - trunc_len, trunc, trunc_len);
return;
}
if (data[index] & (1 << bit)) {
len += scnprintf(buf + len, buf_len - len, "%s,",
ath6kl_init_get_fw_capa_name(i));
}
}
/* overwrite the last comma */
if (len > 0)
len--;
buf[len] = '\0';
}
static int ath6kl_init_hw_reset(struct ath6kl *ar)
{
ath6kl_dbg(ATH6KL_DBG_BOOT, "cold resetting the device");
return ath6kl_diag_write32(ar, RESET_CONTROL_ADDRESS,
cpu_to_le32(RESET_CONTROL_COLD_RST));
}
static int __ath6kl_init_hw_start(struct ath6kl *ar)
{
long timeleft;
int ret, i;
char buf[200];
ath6kl_dbg(ATH6KL_DBG_BOOT, "hw start\n");
ret = ath6kl_hif_power_on(ar);
if (ret)
return ret;
ret = ath6kl_configure_target(ar);
if (ret)
goto err_power_off;
ret = ath6kl_init_upload(ar);
if (ret)
goto err_power_off;
/* Do we need to finish the BMI phase */
ret = ath6kl_bmi_done(ar);
if (ret)
goto err_power_off;
/*
* The reason we have to wait for the target here is that the
* driver layer has to init BMI in order to set the host block
* size.
*/
ret = ath6kl_htc_wait_target(ar->htc_target);
if (ret == -ETIMEDOUT) {
/*
* Most likely USB target is in odd state after reboot and
* needs a reset. A cold reset makes the whole device
* disappear from USB bus and initialisation starts from
* beginning.
*/
ath6kl_warn("htc wait target timed out, resetting device\n");
ath6kl_init_hw_reset(ar);
goto err_power_off;
} else if (ret) {
ath6kl_err("htc wait target failed: %d\n", ret);
goto err_power_off;
}
ret = ath6kl_init_service_ep(ar);
if (ret) {
ath6kl_err("Endpoint service initilisation failed: %d\n", ret);
goto err_cleanup_scatter;
}
/* setup credit distribution */
ath6kl_htc_credit_setup(ar->htc_target, &ar->credit_state_info);
/* start HTC */
ret = ath6kl_htc_start(ar->htc_target);
if (ret) {
/* FIXME: call this */
ath6kl_cookie_cleanup(ar);
goto err_cleanup_scatter;
}
/* Wait for Wmi event to be ready */
timeleft = wait_event_interruptible_timeout(ar->event_wq,
test_bit(WMI_READY,
&ar->flag),
WMI_TIMEOUT);
if (timeleft <= 0) {
clear_bit(WMI_READY, &ar->flag);
ath6kl_err("wmi is not ready or wait was interrupted: %ld\n",
timeleft);
ret = -EIO;
goto err_htc_stop;
}
ath6kl_dbg(ATH6KL_DBG_BOOT, "firmware booted\n");
if (test_and_clear_bit(FIRST_BOOT, &ar->flag)) {
ath6kl_info("%s %s fw %s api %d%s\n",
ar->hw.name,
ath6kl_init_get_hif_name(ar->hif_type),
ar->wiphy->fw_version,
ar->fw_api,
test_bit(TESTMODE, &ar->flag) ? " testmode" : "");
ath6kl_init_get_fwcaps(ar, buf, sizeof(buf));
ath6kl_info("firmware supports: %s\n", buf);
}
if (ar->version.abi_ver != ATH6KL_ABI_VERSION) {
ath6kl_err("abi version mismatch: host(0x%x), target(0x%x)\n",
ATH6KL_ABI_VERSION, ar->version.abi_ver);
ret = -EIO;
goto err_htc_stop;
}
ath6kl_dbg(ATH6KL_DBG_TRC, "%s: wmi is ready\n", __func__);
/* communicate the wmi protocol verision to the target */
/* FIXME: return error */
if ((ath6kl_set_host_app_area(ar)) != 0)
ath6kl_err("unable to set the host app area\n");
for (i = 0; i < ar->vif_max; i++) {
ret = ath6kl_target_config_wlan_params(ar, i);
if (ret)
goto err_htc_stop;
}
return 0;
err_htc_stop:
ath6kl_htc_stop(ar->htc_target);
err_cleanup_scatter:
ath6kl_hif_cleanup_scatter(ar);
err_power_off:
ath6kl_hif_power_off(ar);
return ret;
}
int ath6kl_init_hw_start(struct ath6kl *ar)
{
int err;
err = __ath6kl_init_hw_start(ar);
if (err)
return err;
ar->state = ATH6KL_STATE_ON;
return 0;
}
static int __ath6kl_init_hw_stop(struct ath6kl *ar)
{
int ret;
ath6kl_dbg(ATH6KL_DBG_BOOT, "hw stop\n");
ath6kl_htc_stop(ar->htc_target);
ath6kl_hif_stop(ar);
ath6kl_bmi_reset(ar);
ret = ath6kl_hif_power_off(ar);
if (ret)
ath6kl_warn("failed to power off hif: %d\n", ret);
return 0;
}
int ath6kl_init_hw_stop(struct ath6kl *ar)
{
int err;
err = __ath6kl_init_hw_stop(ar);
if (err)
return err;
ar->state = ATH6KL_STATE_OFF;
return 0;
}
void ath6kl_init_hw_restart(struct ath6kl *ar)
{
clear_bit(WMI_READY, &ar->flag);
ath6kl_cfg80211_stop_all(ar);
if (__ath6kl_init_hw_stop(ar)) {
ath6kl_dbg(ATH6KL_DBG_RECOVERY, "Failed to stop during fw error recovery\n");
return;
}
if (__ath6kl_init_hw_start(ar)) {
ath6kl_dbg(ATH6KL_DBG_RECOVERY, "Failed to restart during fw error recovery\n");
return;
}
}
void ath6kl_stop_txrx(struct ath6kl *ar)
{
struct ath6kl_vif *vif, *tmp_vif;
int i;
set_bit(DESTROY_IN_PROGRESS, &ar->flag);
if (down_interruptible(&ar->sem)) {
ath6kl_err("down_interruptible failed\n");
return;
}
for (i = 0; i < AP_MAX_NUM_STA; i++)
aggr_reset_state(ar->sta_list[i].aggr_conn);
spin_lock_bh(&ar->list_lock);
list_for_each_entry_safe(vif, tmp_vif, &ar->vif_list, list) {
list_del(&vif->list);
spin_unlock_bh(&ar->list_lock);
ath6kl_cfg80211_vif_stop(vif, test_bit(WMI_READY, &ar->flag));
rtnl_lock();
ath6kl_cfg80211_vif_cleanup(vif);
rtnl_unlock();
spin_lock_bh(&ar->list_lock);
}
spin_unlock_bh(&ar->list_lock);
clear_bit(WMI_READY, &ar->flag);
if (ar->fw_recovery.enable)
del_timer_sync(&ar->fw_recovery.hb_timer);
/*
* After wmi_shudown all WMI events will be dropped. We
* need to cleanup the buffers allocated in AP mode and
* give disconnect notification to stack, which usually
* happens in the disconnect_event. Simulate the disconnect
* event by calling the function directly. Sometimes
* disconnect_event will be received when the debug logs
* are collected.
*/
ath6kl_wmi_shutdown(ar->wmi);
clear_bit(WMI_ENABLED, &ar->flag);
if (ar->htc_target) {
ath6kl_dbg(ATH6KL_DBG_TRC, "%s: shut down htc\n", __func__);
ath6kl_htc_stop(ar->htc_target);
}
/*
* Try to reset the device if we can. The driver may have been
* configure NOT to reset the target during a debug session.
*/
ath6kl_init_hw_reset(ar);
up(&ar->sem);
}
EXPORT_SYMBOL(ath6kl_stop_txrx);
| codeaurora-unoffical/linux-msm | drivers/net/wireless/ath/ath6kl/init.c | C | gpl-2.0 | 48,308 |
#
# Copyright (C) 2010 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=python-cjson
PKG_VERSION:=1.0.5
PKG_RELEASE:=1
PKG_SOURCE:=python-cjson-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=http://pypi.python.org/packages/source/p/python-cjson/
PKG_MD5SUM:=4d55b66ecdf0300313af9d030d9644a3
PKG_BUILD_DIR:=$(BUILD_DIR)/python-cjson-$(PKG_VERSION)
PKG_BUILD_DEPENDS:=python
include $(INCLUDE_DIR)/package.mk
$(call include_mk, python-package.mk)
define Package/python-cjson
SUBMENU:=Python
SECTION:=lang
CATEGORY:=Languages
TITLE:=python-cjson
URL:=http://pypi.python.org/pypi/python-cjson/
DEPENDS:=+python
endef
define Package/python-cjson/description
Fast JSON encoder/decoder for Python
endef
define Build/Compile
$(call Build/Compile/PyMod,,install --prefix="$(PKG_INSTALL_DIR)/usr")
endef
define Package/python-cjson/install
$(INSTALL_DIR) $(1)$(PYTHON_PKG_DIR)
$(CP) \
$(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
$(1)$(PYTHON_PKG_DIR)
endef
$(eval $(call BuildPackage,python-cjson))
| wjrsonic/openwrt | qca/feeds/packages/lang/python-cjson/Makefile | Makefile | gpl-2.0 | 1,129 |
/* Target-dependent code for Darwin x86-64.
Copyright (C) 2009-2014 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef __AMD64_DARWIN_TDEP_H__
#define __AMD64_DARWIN_TDEP_H__
/* Mapping between the general-purpose registers in Darwin x86-64 thread
state and GDB's register cache layout.
Indexed by amd64_regnum. */
extern int amd64_darwin_thread_state_reg_offset[];
extern const int amd64_darwin_thread_state_num_regs;
#endif /* __AMD64_DARWIN_TDEP_H__ */
| zxombie/aarch64-freebsd-binutils | gdb/amd64-darwin-tdep.h | C | gpl-2.0 | 1,134 |
/**
* SyntaxHighlighter
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (Wed, 16 Apr 2014 03:56:09 GMT)
*
* @copyright
* Copyright (C) 2004-2013 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
SyntaxHighlighter = SyntaxHighlighter || (typeof require !== 'undefined'? require('shCore').SyntaxHighlighter : null);
function Brush()
{
// Contributed by Joel 'Jaykul' Bennett, http://PoshCode.org | http://HuddledMasses.org
var keywords = 'while validateset validaterange validatepattern validatelength validatecount ' +
'until trap switch return ref process param parameter in if global: '+
'function foreach for finally filter end elseif else dynamicparam do default ' +
'continue cmdletbinding break begin alias \\? % #script #private #local #global '+
'mandatory parametersetname position valuefrompipeline ' +
'valuefrompipelinebypropertyname valuefromremainingarguments helpmessage ';
var operators = ' and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle ' +
'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains ' +
'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt ' +
'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like ' +
'lt match ne not notcontains notlike notmatch or regex replace wildcard';
var verbs = 'write where wait use update unregister undo trace test tee take suspend ' +
'stop start split sort skip show set send select scroll resume restore ' +
'restart resolve resize reset rename remove register receive read push ' +
'pop ping out new move measure limit join invoke import group get format ' +
'foreach export expand exit enter enable disconnect disable debug cxnew ' +
'copy convertto convertfrom convert connect complete compare clear ' +
'checkpoint aggregate add';
// I can't find a way to match the comment based help in multi-line comments, because SH won't highlight in highlights, and javascript doesn't support lookbehind
var commenthelp = ' component description example externalhelp forwardhelpcategory forwardhelptargetname forwardhelptargetname functionality inputs link notes outputs parameter remotehelprunspace role synopsis';
this.regexList = [
{ regex: new RegExp('^\\s*#[#\\s]*\\.('+this.getKeywords(commenthelp)+').*$', 'gim'), css: 'preprocessor help bold' }, // comment-based help
{ regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments
{ regex: /(<|<)#[\s\S]*?#(>|>)/gm, css: 'comments here' }, // multi-line comments
{ regex: new RegExp('@"\\n[\\s\\S]*?\\n"@', 'gm'), css: 'script string here' }, // double quoted here-strings
{ regex: new RegExp("@'\\n[\\s\\S]*?\\n'@", 'gm'), css: 'script string single here' }, // single quoted here-strings
{ regex: new RegExp('"(?:\\$\\([^\\)]*\\)|[^"]|`"|"")*[^`]"','g'), css: 'string' }, // double quoted strings
{ regex: new RegExp("'(?:[^']|'')*'", 'g'), css: 'string single' }, // single quoted strings
{ regex: new RegExp('[\\$|@|@@](?:(?:global|script|private|env):)?[A-Z0-9_]+', 'gi'), css: 'variable' }, // $variables
{ regex: new RegExp('(?:\\b'+verbs.replace(/ /g, '\\b|\\b')+')-[a-zA-Z_][a-zA-Z0-9_]*', 'gmi'), css: 'functions' }, // functions and cmdlets
{ regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' }, // keywords
{ regex: new RegExp('-'+this.getKeywords(operators), 'gmi'), css: 'operator value' }, // operators
{ regex: new RegExp('\\[[A-Z_\\[][A-Z0-9_. `,\\[\\]]*\\]', 'gi'), css: 'constants' }, // .Net [Type]s
{ regex: new RegExp('\\s+-(?!'+this.getKeywords(operators)+')[a-zA-Z_][a-zA-Z0-9_]*', 'gmi'), css: 'color1' }, // parameters
];
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['powershell', 'ps', 'posh'];
SyntaxHighlighter.brushes.PowerShell = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| joao-gabriel/phpage | wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/scripts/shBrushPowerShell.js | JavaScript | gpl-2.0 | 4,361 |
/*
* mm/rmap.c - physical to virtual reverse mappings
*
* Copyright 2001, Rik van Riel <[email protected]>
* Released under the General Public License (GPL).
*
* Simple, low overhead reverse mapping scheme.
* Please try to keep this thing as modular as possible.
*
* Provides methods for unmapping each kind of mapped page:
* the anon methods track anonymous pages, and
* the file methods track pages belonging to an inode.
*
* Original design by Rik van Riel <[email protected]> 2001
* File methods by Dave McCracken <[email protected]> 2003, 2004
* Anonymous methods by Andrea Arcangeli <[email protected]> 2004
* Contributions by Hugh Dickins 2003, 2004
*/
/*
* Lock ordering in mm:
*
* inode->i_mutex (while writing or truncating, not reading or faulting)
* mm->mmap_sem
* page->flags PG_locked (lock_page)
* mapping->i_mmap_mutex
* anon_vma->rwsem
* mm->page_table_lock or pte_lock
* zone->lru_lock (in mark_page_accessed, isolate_lru_page)
* swap_lock (in swap_duplicate, swap_info_get)
* mmlist_lock (in mmput, drain_mmlist and others)
* mapping->private_lock (in __set_page_dirty_buffers)
* inode->i_lock (in set_page_dirty's __mark_inode_dirty)
* bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
* sb_lock (within inode_lock in fs/fs-writeback.c)
* mapping->tree_lock (widely used, in set_page_dirty,
* in arch-dependent flush_dcache_mmap_lock,
* within bdi.wb->list_lock in __sync_single_inode)
*
* anon_vma->rwsem,mapping->i_mutex (memory_failure, collect_procs_anon)
* ->tasklist_lock
* pte map lock
*/
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/ksm.h>
#include <linux/rmap.h>
#include <linux/rcupdate.h>
#include <linux/export.h>
#include <linux/memcontrol.h>
#include <linux/mmu_notifier.h>
#include <linux/migrate.h>
#include <linux/hugetlb.h>
#include <linux/backing-dev.h>
#include <asm/tlbflush.h>
#include "internal.h"
static struct kmem_cache *anon_vma_cachep;
static struct kmem_cache *anon_vma_chain_cachep;
static inline struct anon_vma *anon_vma_alloc(void)
{
struct anon_vma *anon_vma;
anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
if (anon_vma) {
atomic_set(&anon_vma->refcount, 1);
/*
* Initialise the anon_vma root to point to itself. If called
* from fork, the root will be reset to the parents anon_vma.
*/
anon_vma->root = anon_vma;
}
return anon_vma;
}
static inline void anon_vma_free(struct anon_vma *anon_vma)
{
VM_BUG_ON(atomic_read(&anon_vma->refcount));
/*
* Synchronize against page_lock_anon_vma_read() such that
* we can safely hold the lock without the anon_vma getting
* freed.
*
* Relies on the full mb implied by the atomic_dec_and_test() from
* put_anon_vma() against the acquire barrier implied by
* down_read_trylock() from page_lock_anon_vma_read(). This orders:
*
* page_lock_anon_vma_read() VS put_anon_vma()
* down_read_trylock() atomic_dec_and_test()
* LOCK MB
* atomic_read() rwsem_is_locked()
*
* LOCK should suffice since the actual taking of the lock must
* happen _before_ what follows.
*/
if (rwsem_is_locked(&anon_vma->root->rwsem)) {
anon_vma_lock_write(anon_vma);
anon_vma_unlock_write(anon_vma);
}
kmem_cache_free(anon_vma_cachep, anon_vma);
}
static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
{
return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
}
static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
{
kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
}
static void anon_vma_chain_link(struct vm_area_struct *vma,
struct anon_vma_chain *avc,
struct anon_vma *anon_vma)
{
avc->vma = vma;
avc->anon_vma = anon_vma;
list_add(&avc->same_vma, &vma->anon_vma_chain);
anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
}
/**
* anon_vma_prepare - attach an anon_vma to a memory region
* @vma: the memory region in question
*
* This makes sure the memory mapping described by 'vma' has
* an 'anon_vma' attached to it, so that we can associate the
* anonymous pages mapped into it with that anon_vma.
*
* The common case will be that we already have one, but if
* not we either need to find an adjacent mapping that we
* can re-use the anon_vma from (very common when the only
* reason for splitting a vma has been mprotect()), or we
* allocate a new one.
*
* Anon-vma allocations are very subtle, because we may have
* optimistically looked up an anon_vma in page_lock_anon_vma_read()
* and that may actually touch the spinlock even in the newly
* allocated vma (it depends on RCU to make sure that the
* anon_vma isn't actually destroyed).
*
* As a result, we need to do proper anon_vma locking even
* for the new allocation. At the same time, we do not want
* to do any locking for the common case of already having
* an anon_vma.
*
* This must be called with the mmap_sem held for reading.
*/
int anon_vma_prepare(struct vm_area_struct *vma)
{
struct anon_vma *anon_vma = vma->anon_vma;
struct anon_vma_chain *avc;
might_sleep();
if (unlikely(!anon_vma)) {
struct mm_struct *mm = vma->vm_mm;
struct anon_vma *allocated;
avc = anon_vma_chain_alloc(GFP_KERNEL);
if (!avc)
goto out_enomem;
anon_vma = find_mergeable_anon_vma(vma);
allocated = NULL;
if (!anon_vma) {
anon_vma = anon_vma_alloc();
if (unlikely(!anon_vma))
goto out_enomem_free_avc;
allocated = anon_vma;
}
anon_vma_lock_write(anon_vma);
/* page_table_lock to protect against threads */
spin_lock(&mm->page_table_lock);
if (likely(!vma->anon_vma)) {
vma->anon_vma = anon_vma;
anon_vma_chain_link(vma, avc, anon_vma);
allocated = NULL;
avc = NULL;
}
spin_unlock(&mm->page_table_lock);
anon_vma_unlock_write(anon_vma);
if (unlikely(allocated))
put_anon_vma(allocated);
if (unlikely(avc))
anon_vma_chain_free(avc);
}
return 0;
out_enomem_free_avc:
anon_vma_chain_free(avc);
out_enomem:
return -ENOMEM;
}
/*
* This is a useful helper function for locking the anon_vma root as
* we traverse the vma->anon_vma_chain, looping over anon_vma's that
* have the same vma.
*
* Such anon_vma's should have the same root, so you'd expect to see
* just a single mutex_lock for the whole traversal.
*/
static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
{
struct anon_vma *new_root = anon_vma->root;
if (new_root != root) {
if (WARN_ON_ONCE(root))
up_write(&root->rwsem);
root = new_root;
down_write(&root->rwsem);
}
return root;
}
static inline void unlock_anon_vma_root(struct anon_vma *root)
{
if (root)
up_write(&root->rwsem);
}
/*
* Attach the anon_vmas from src to dst.
* Returns 0 on success, -ENOMEM on failure.
*/
int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
{
struct anon_vma_chain *avc, *pavc;
struct anon_vma *root = NULL;
list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
struct anon_vma *anon_vma;
avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
if (unlikely(!avc)) {
unlock_anon_vma_root(root);
root = NULL;
avc = anon_vma_chain_alloc(GFP_KERNEL);
if (!avc)
goto enomem_failure;
}
anon_vma = pavc->anon_vma;
root = lock_anon_vma_root(root, anon_vma);
anon_vma_chain_link(dst, avc, anon_vma);
}
unlock_anon_vma_root(root);
return 0;
enomem_failure:
unlink_anon_vmas(dst);
return -ENOMEM;
}
/*
* Attach vma to its own anon_vma, as well as to the anon_vmas that
* the corresponding VMA in the parent process is attached to.
* Returns 0 on success, non-zero on failure.
*/
int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
{
struct anon_vma_chain *avc;
struct anon_vma *anon_vma;
/* Don't bother if the parent process has no anon_vma here. */
if (!pvma->anon_vma)
return 0;
/*
* First, attach the new VMA to the parent VMA's anon_vmas,
* so rmap can find non-COWed pages in child processes.
*/
if (anon_vma_clone(vma, pvma))
return -ENOMEM;
/* Then add our own anon_vma. */
anon_vma = anon_vma_alloc();
if (!anon_vma)
goto out_error;
avc = anon_vma_chain_alloc(GFP_KERNEL);
if (!avc)
goto out_error_free_anon_vma;
/*
* The root anon_vma's spinlock is the lock actually used when we
* lock any of the anon_vmas in this anon_vma tree.
*/
anon_vma->root = pvma->anon_vma->root;
/*
* With refcounts, an anon_vma can stay around longer than the
* process it belongs to. The root anon_vma needs to be pinned until
* this anon_vma is freed, because the lock lives in the root.
*/
get_anon_vma(anon_vma->root);
/* Mark this anon_vma as the one where our new (COWed) pages go. */
vma->anon_vma = anon_vma;
anon_vma_lock_write(anon_vma);
anon_vma_chain_link(vma, avc, anon_vma);
anon_vma_unlock_write(anon_vma);
return 0;
out_error_free_anon_vma:
put_anon_vma(anon_vma);
out_error:
unlink_anon_vmas(vma);
return -ENOMEM;
}
void unlink_anon_vmas(struct vm_area_struct *vma)
{
struct anon_vma_chain *avc, *next;
struct anon_vma *root = NULL;
/*
* Unlink each anon_vma chained to the VMA. This list is ordered
* from newest to oldest, ensuring the root anon_vma gets freed last.
*/
list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
struct anon_vma *anon_vma = avc->anon_vma;
root = lock_anon_vma_root(root, anon_vma);
anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
/*
* Leave empty anon_vmas on the list - we'll need
* to free them outside the lock.
*/
if (RB_EMPTY_ROOT(&anon_vma->rb_root))
continue;
list_del(&avc->same_vma);
anon_vma_chain_free(avc);
}
unlock_anon_vma_root(root);
/*
* Iterate the list once more, it now only contains empty and unlinked
* anon_vmas, destroy them. Could not do before due to __put_anon_vma()
* needing to write-acquire the anon_vma->root->rwsem.
*/
list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
struct anon_vma *anon_vma = avc->anon_vma;
put_anon_vma(anon_vma);
list_del(&avc->same_vma);
anon_vma_chain_free(avc);
}
}
static void anon_vma_ctor(void *data)
{
struct anon_vma *anon_vma = data;
init_rwsem(&anon_vma->rwsem);
atomic_set(&anon_vma->refcount, 0);
anon_vma->rb_root = RB_ROOT;
}
void __init anon_vma_init(void)
{
anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
0, SLAB_DESTROY_BY_RCU|SLAB_PANIC, anon_vma_ctor);
anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain, SLAB_PANIC);
}
/*
* Getting a lock on a stable anon_vma from a page off the LRU is tricky!
*
* Since there is no serialization what so ever against page_remove_rmap()
* the best this function can do is return a locked anon_vma that might
* have been relevant to this page.
*
* The page might have been remapped to a different anon_vma or the anon_vma
* returned may already be freed (and even reused).
*
* In case it was remapped to a different anon_vma, the new anon_vma will be a
* child of the old anon_vma, and the anon_vma lifetime rules will therefore
* ensure that any anon_vma obtained from the page will still be valid for as
* long as we observe page_mapped() [ hence all those page_mapped() tests ].
*
* All users of this function must be very careful when walking the anon_vma
* chain and verify that the page in question is indeed mapped in it
* [ something equivalent to page_mapped_in_vma() ].
*
* Since anon_vma's slab is DESTROY_BY_RCU and we know from page_remove_rmap()
* that the anon_vma pointer from page->mapping is valid if there is a
* mapcount, we can dereference the anon_vma after observing those.
*/
struct anon_vma *page_get_anon_vma(struct page *page)
{
struct anon_vma *anon_vma = NULL;
unsigned long anon_mapping;
rcu_read_lock();
anon_mapping = (unsigned long) ACCESS_ONCE(page->mapping);
if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
goto out;
if (!page_mapped(page))
goto out;
anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
if (!atomic_inc_not_zero(&anon_vma->refcount)) {
anon_vma = NULL;
goto out;
}
/*
* If this page is still mapped, then its anon_vma cannot have been
* freed. But if it has been unmapped, we have no security against the
* anon_vma structure being freed and reused (for another anon_vma:
* SLAB_DESTROY_BY_RCU guarantees that - so the atomic_inc_not_zero()
* above cannot corrupt).
*/
if (!page_mapped(page)) {
put_anon_vma(anon_vma);
anon_vma = NULL;
}
out:
rcu_read_unlock();
return anon_vma;
}
/*
* Similar to page_get_anon_vma() except it locks the anon_vma.
*
* Its a little more complex as it tries to keep the fast path to a single
* atomic op -- the trylock. If we fail the trylock, we fall back to getting a
* reference like with page_get_anon_vma() and then block on the mutex.
*/
struct anon_vma *page_lock_anon_vma_read(struct page *page)
{
struct anon_vma *anon_vma = NULL;
struct anon_vma *root_anon_vma;
unsigned long anon_mapping;
rcu_read_lock();
anon_mapping = (unsigned long) ACCESS_ONCE(page->mapping);
if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
goto out;
if (!page_mapped(page))
goto out;
anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
root_anon_vma = ACCESS_ONCE(anon_vma->root);
if (down_read_trylock(&root_anon_vma->rwsem)) {
/*
* If the page is still mapped, then this anon_vma is still
* its anon_vma, and holding the mutex ensures that it will
* not go away, see anon_vma_free().
*/
if (!page_mapped(page)) {
up_read(&root_anon_vma->rwsem);
anon_vma = NULL;
}
goto out;
}
/* trylock failed, we got to sleep */
if (!atomic_inc_not_zero(&anon_vma->refcount)) {
anon_vma = NULL;
goto out;
}
if (!page_mapped(page)) {
put_anon_vma(anon_vma);
anon_vma = NULL;
goto out;
}
/* we pinned the anon_vma, its safe to sleep */
rcu_read_unlock();
anon_vma_lock_read(anon_vma);
if (atomic_dec_and_test(&anon_vma->refcount)) {
/*
* Oops, we held the last refcount, release the lock
* and bail -- can't simply use put_anon_vma() because
* we'll deadlock on the anon_vma_lock_write() recursion.
*/
anon_vma_unlock_read(anon_vma);
__put_anon_vma(anon_vma);
anon_vma = NULL;
}
return anon_vma;
out:
rcu_read_unlock();
return anon_vma;
}
void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
{
anon_vma_unlock_read(anon_vma);
}
/*
* At what user virtual address is page expected in @vma?
*/
static inline unsigned long
__vma_address(struct page *page, struct vm_area_struct *vma)
{
pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
if (unlikely(is_vm_hugetlb_page(vma)))
pgoff = page->index << huge_page_order(page_hstate(page));
return vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
}
inline unsigned long
vma_address(struct page *page, struct vm_area_struct *vma)
{
unsigned long address = __vma_address(page, vma);
/* page should be within @vma mapping range */
VM_BUG_ON(address < vma->vm_start || address >= vma->vm_end);
return address;
}
/*
* At what user virtual address is page expected in vma?
* Caller should check the page is actually part of the vma.
*/
unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
{
unsigned long address;
if (PageAnon(page)) {
struct anon_vma *page__anon_vma = page_anon_vma(page);
/*
* Note: swapoff's unuse_vma() is more efficient with this
* check, and needs it to match anon_vma when KSM is active.
*/
if (!vma->anon_vma || !page__anon_vma ||
vma->anon_vma->root != page__anon_vma->root)
return -EFAULT;
} else if (page->mapping && !(vma->vm_flags & VM_NONLINEAR)) {
if (!vma->vm_file ||
vma->vm_file->f_mapping != page->mapping)
return -EFAULT;
} else
return -EFAULT;
address = __vma_address(page, vma);
if (unlikely(address < vma->vm_start || address >= vma->vm_end))
return -EFAULT;
return address;
}
pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd = NULL;
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
goto out;
pud = pud_offset(pgd, address);
if (!pud_present(*pud))
goto out;
pmd = pmd_offset(pud, address);
if (!pmd_present(*pmd))
pmd = NULL;
out:
return pmd;
}
/*
* Check that @page is mapped at @address into @mm.
*
* If @sync is false, page_check_address may perform a racy check to avoid
* the page table lock when the pte is not present (helpful when reclaiming
* highly shared pages).
*
* On success returns with pte mapped and locked.
*/
pte_t *__page_check_address(struct page *page, struct mm_struct *mm,
unsigned long address, spinlock_t **ptlp, int sync)
{
pmd_t *pmd;
pte_t *pte;
spinlock_t *ptl;
if (unlikely(PageHuge(page))) {
pte = huge_pte_offset(mm, address);
ptl = &mm->page_table_lock;
goto check;
}
pmd = mm_find_pmd(mm, address);
if (!pmd)
return NULL;
if (pmd_trans_huge(*pmd))
return NULL;
pte = pte_offset_map(pmd, address);
/* Make a quick check before getting the lock */
if (!sync && !pte_present(*pte)) {
pte_unmap(pte);
return NULL;
}
ptl = pte_lockptr(mm, pmd);
check:
spin_lock(ptl);
if (pte_present(*pte) && page_to_pfn(page) == pte_pfn(*pte)) {
*ptlp = ptl;
return pte;
}
pte_unmap_unlock(pte, ptl);
return NULL;
}
/**
* page_mapped_in_vma - check whether a page is really mapped in a VMA
* @page: the page to test
* @vma: the VMA to test
*
* Returns 1 if the page is mapped into the page tables of the VMA, 0
* if the page is not mapped into the page tables of this VMA. Only
* valid for normal file or anonymous VMAs.
*/
int page_mapped_in_vma(struct page *page, struct vm_area_struct *vma)
{
unsigned long address;
pte_t *pte;
spinlock_t *ptl;
address = __vma_address(page, vma);
if (unlikely(address < vma->vm_start || address >= vma->vm_end))
return 0;
pte = page_check_address(page, vma->vm_mm, address, &ptl, 1);
if (!pte) /* the page is not in this mm */
return 0;
pte_unmap_unlock(pte, ptl);
return 1;
}
/*
* Subfunctions of page_referenced: page_referenced_one called
* repeatedly from either page_referenced_anon or page_referenced_file.
*/
int page_referenced_one(struct page *page, struct vm_area_struct *vma,
unsigned long address, unsigned int *mapcount,
unsigned long *vm_flags)
{
struct mm_struct *mm = vma->vm_mm;
int referenced = 0;
if (unlikely(PageTransHuge(page))) {
pmd_t *pmd;
spin_lock(&mm->page_table_lock);
/*
* rmap might return false positives; we must filter
* these out using page_check_address_pmd().
*/
pmd = page_check_address_pmd(page, mm, address,
PAGE_CHECK_ADDRESS_PMD_FLAG);
if (!pmd) {
spin_unlock(&mm->page_table_lock);
goto out;
}
if (vma->vm_flags & VM_LOCKED) {
spin_unlock(&mm->page_table_lock);
*mapcount = 0; /* break early from loop */
*vm_flags |= VM_LOCKED;
goto out;
}
/* go ahead even if the pmd is pmd_trans_splitting() */
if (pmdp_clear_flush_young_notify(vma, address, pmd))
referenced++;
spin_unlock(&mm->page_table_lock);
} else {
pte_t *pte;
spinlock_t *ptl;
/*
* rmap might return false positives; we must filter
* these out using page_check_address().
*/
pte = page_check_address(page, mm, address, &ptl, 0);
if (!pte)
goto out;
if (vma->vm_flags & VM_LOCKED) {
pte_unmap_unlock(pte, ptl);
*mapcount = 0; /* break early from loop */
*vm_flags |= VM_LOCKED;
goto out;
}
if (ptep_clear_flush_young_notify(vma, address, pte)) {
/*
* Don't treat a reference through a sequentially read
* mapping as such. If the page has been used in
* another mapping, we will catch it; if this other
* mapping is already gone, the unmap path will have
* set PG_referenced or activated the page.
*/
if (likely(!(vma->vm_flags & VM_SEQ_READ)))
referenced++;
}
pte_unmap_unlock(pte, ptl);
}
(*mapcount)--;
if (referenced)
*vm_flags |= vma->vm_flags;
out:
return referenced;
}
static int page_referenced_anon(struct page *page,
struct mem_cgroup *memcg,
unsigned long *vm_flags)
{
unsigned int mapcount;
struct anon_vma *anon_vma;
pgoff_t pgoff;
struct anon_vma_chain *avc;
int referenced = 0;
anon_vma = page_lock_anon_vma_read(page);
if (!anon_vma)
return referenced;
mapcount = page_mapcount(page);
pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
struct vm_area_struct *vma = avc->vma;
unsigned long address = vma_address(page, vma);
/*
* If we are reclaiming on behalf of a cgroup, skip
* counting on behalf of references from different
* cgroups
*/
if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
continue;
referenced += page_referenced_one(page, vma, address,
&mapcount, vm_flags);
if (!mapcount)
break;
}
page_unlock_anon_vma_read(anon_vma);
return referenced;
}
/**
* page_referenced_file - referenced check for object-based rmap
* @page: the page we're checking references on.
* @memcg: target memory control group
* @vm_flags: collect encountered vma->vm_flags who actually referenced the page
*
* For an object-based mapped page, find all the places it is mapped and
* check/clear the referenced flag. This is done by following the page->mapping
* pointer, then walking the chain of vmas it holds. It returns the number
* of references it found.
*
* This function is only called from page_referenced for object-based pages.
*/
static int page_referenced_file(struct page *page,
struct mem_cgroup *memcg,
unsigned long *vm_flags)
{
unsigned int mapcount;
struct address_space *mapping = page->mapping;
pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
struct vm_area_struct *vma;
int referenced = 0;
/*
* The caller's checks on page->mapping and !PageAnon have made
* sure that this is a file page: the check for page->mapping
* excludes the case just before it gets set on an anon page.
*/
BUG_ON(PageAnon(page));
/*
* The page lock not only makes sure that page->mapping cannot
* suddenly be NULLified by truncation, it makes sure that the
* structure at mapping cannot be freed and reused yet,
* so we can safely take mapping->i_mmap_mutex.
*/
BUG_ON(!PageLocked(page));
mutex_lock(&mapping->i_mmap_mutex);
/*
* i_mmap_mutex does not stabilize mapcount at all, but mapcount
* is more likely to be accurate if we note it after spinning.
*/
mapcount = page_mapcount(page);
vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
unsigned long address = vma_address(page, vma);
/*
* If we are reclaiming on behalf of a cgroup, skip
* counting on behalf of references from different
* cgroups
*/
if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
continue;
referenced += page_referenced_one(page, vma, address,
&mapcount, vm_flags);
if (!mapcount)
break;
}
mutex_unlock(&mapping->i_mmap_mutex);
return referenced;
}
/**
* page_referenced - test if the page was referenced
* @page: the page to test
* @is_locked: caller holds lock on the page
* @memcg: target memory cgroup
* @vm_flags: collect encountered vma->vm_flags who actually referenced the page
*
* Quick test_and_clear_referenced for all mappings to a page,
* returns the number of ptes which referenced the page.
*/
int page_referenced(struct page *page,
int is_locked,
struct mem_cgroup *memcg,
unsigned long *vm_flags)
{
int referenced = 0;
int we_locked = 0;
*vm_flags = 0;
if (page_mapped(page) && page_rmapping(page)) {
if (!is_locked && (!PageAnon(page) || PageKsm(page))) {
we_locked = trylock_page(page);
if (!we_locked) {
referenced++;
goto out;
}
}
if (unlikely(PageKsm(page)))
referenced += page_referenced_ksm(page, memcg,
vm_flags);
else if (PageAnon(page))
referenced += page_referenced_anon(page, memcg,
vm_flags);
else if (page->mapping)
referenced += page_referenced_file(page, memcg,
vm_flags);
if (we_locked)
unlock_page(page);
}
out:
return referenced;
}
static int page_mkclean_one(struct page *page, struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
pte_t *pte;
spinlock_t *ptl;
int ret = 0;
pte = page_check_address(page, mm, address, &ptl, 1);
if (!pte)
goto out;
if (pte_dirty(*pte) || pte_write(*pte)) {
pte_t entry;
flush_cache_page(vma, address, pte_pfn(*pte));
entry = ptep_clear_flush(vma, address, pte);
entry = pte_wrprotect(entry);
entry = pte_mkclean(entry);
set_pte_at(mm, address, pte, entry);
ret = 1;
}
pte_unmap_unlock(pte, ptl);
if (ret)
mmu_notifier_invalidate_page(mm, address);
out:
return ret;
}
static int page_mkclean_file(struct address_space *mapping, struct page *page)
{
pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
struct vm_area_struct *vma;
int ret = 0;
BUG_ON(PageAnon(page));
mutex_lock(&mapping->i_mmap_mutex);
vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
if (vma->vm_flags & VM_SHARED) {
unsigned long address = vma_address(page, vma);
ret += page_mkclean_one(page, vma, address);
}
}
mutex_unlock(&mapping->i_mmap_mutex);
return ret;
}
int page_mkclean(struct page *page)
{
int ret = 0;
BUG_ON(!PageLocked(page));
if (page_mapped(page)) {
struct address_space *mapping = page_mapping(page);
if (mapping)
ret = page_mkclean_file(mapping, page);
}
return ret;
}
EXPORT_SYMBOL_GPL(page_mkclean);
/**
* page_move_anon_rmap - move a page to our anon_vma
* @page: the page to move to our anon_vma
* @vma: the vma the page belongs to
* @address: the user virtual address mapped
*
* When a page belongs exclusively to one process after a COW event,
* that page can be moved into the anon_vma that belongs to just that
* process, so the rmap code will not search the parent or sibling
* processes.
*/
void page_move_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
struct anon_vma *anon_vma = vma->anon_vma;
VM_BUG_ON(!PageLocked(page));
VM_BUG_ON(!anon_vma);
VM_BUG_ON(page->index != linear_page_index(vma, address));
anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
page->mapping = (struct address_space *) anon_vma;
}
/**
* __page_set_anon_rmap - set up new anonymous rmap
* @page: Page to add to rmap
* @vma: VM area to add page to.
* @address: User virtual address of the mapping
* @exclusive: the page is exclusively owned by the current process
*/
static void __page_set_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address, int exclusive)
{
struct anon_vma *anon_vma = vma->anon_vma;
BUG_ON(!anon_vma);
if (PageAnon(page))
return;
/*
* If the page isn't exclusively mapped into this vma,
* we must use the _oldest_ possible anon_vma for the
* page mapping!
*/
if (!exclusive)
anon_vma = anon_vma->root;
anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
page->mapping = (struct address_space *) anon_vma;
page->index = linear_page_index(vma, address);
}
/**
* __page_check_anon_rmap - sanity check anonymous rmap addition
* @page: the page to add the mapping to
* @vma: the vm area in which the mapping is added
* @address: the user virtual address mapped
*/
static void __page_check_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
#ifdef CONFIG_DEBUG_VM
/*
* The page's anon-rmap details (mapping and index) are guaranteed to
* be set up correctly at this point.
*
* We have exclusion against page_add_anon_rmap because the caller
* always holds the page locked, except if called from page_dup_rmap,
* in which case the page is already known to be setup.
*
* We have exclusion against page_add_new_anon_rmap because those pages
* are initially only visible via the pagetables, and the pte is locked
* over the call to page_add_new_anon_rmap.
*/
BUG_ON(page_anon_vma(page)->root != vma->anon_vma->root);
BUG_ON(page->index != linear_page_index(vma, address));
#endif
}
/**
* page_add_anon_rmap - add pte mapping to an anonymous page
* @page: the page to add the mapping to
* @vma: the vm area in which the mapping is added
* @address: the user virtual address mapped
*
* The caller needs to hold the pte lock, and the page must be locked in
* the anon_vma case: to serialize mapping,index checking after setting,
* and to ensure that PageAnon is not being upgraded racily to PageKsm
* (but PageKsm is never downgraded to PageAnon).
*/
void page_add_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
do_page_add_anon_rmap(page, vma, address, 0);
}
/*
* Special version of the above for do_swap_page, which often runs
* into pages that are exclusively owned by the current process.
* Everybody else should continue to use page_add_anon_rmap above.
*/
void do_page_add_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address, int exclusive)
{
int first = atomic_inc_and_test(&page->_mapcount);
if (first) {
if (PageTransHuge(page))
__inc_zone_page_state(page,
NR_ANON_TRANSPARENT_HUGEPAGES);
__mod_zone_page_state(page_zone(page), NR_ANON_PAGES,
hpage_nr_pages(page));
}
if (unlikely(PageKsm(page)))
return;
VM_BUG_ON(!PageLocked(page));
/* address might be in next vma when migration races vma_adjust */
if (first)
__page_set_anon_rmap(page, vma, address, exclusive);
else
__page_check_anon_rmap(page, vma, address);
}
/**
* page_add_new_anon_rmap - add pte mapping to a new anonymous page
* @page: the page to add the mapping to
* @vma: the vm area in which the mapping is added
* @address: the user virtual address mapped
*
* Same as page_add_anon_rmap but must only be called on *new* pages.
* This means the inc-and-test can be bypassed.
* Page does not have to be locked.
*/
void page_add_new_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
VM_BUG_ON(address < vma->vm_start || address >= vma->vm_end);
SetPageSwapBacked(page);
atomic_set(&page->_mapcount, 0); /* increment count (starts at -1) */
if (PageTransHuge(page))
__inc_zone_page_state(page, NR_ANON_TRANSPARENT_HUGEPAGES);
__mod_zone_page_state(page_zone(page), NR_ANON_PAGES,
hpage_nr_pages(page));
__page_set_anon_rmap(page, vma, address, 1);
if (!mlocked_vma_newpage(vma, page)) {
SetPageActive(page);
lru_cache_add(page);
} else
add_page_to_unevictable_list(page);
}
/**
* page_add_file_rmap - add pte mapping to a file page
* @page: the page to add the mapping to
*
* The caller needs to hold the pte lock.
*/
void page_add_file_rmap(struct page *page)
{
bool locked;
unsigned long flags;
mem_cgroup_begin_update_page_stat(page, &locked, &flags);
if (atomic_inc_and_test(&page->_mapcount)) {
__inc_zone_page_state(page, NR_FILE_MAPPED);
mem_cgroup_inc_page_stat(page, MEM_CGROUP_STAT_FILE_MAPPED);
}
mem_cgroup_end_update_page_stat(page, &locked, &flags);
}
/**
* page_remove_rmap - take down pte mapping from a page
* @page: page to remove mapping from
*
* The caller needs to hold the pte lock.
*/
void page_remove_rmap(struct page *page)
{
bool anon = PageAnon(page);
bool locked;
unsigned long flags;
/*
* The anon case has no mem_cgroup page_stat to update; but may
* uncharge_page() below, where the lock ordering can deadlock if
* we hold the lock against page_stat move: so avoid it on anon.
*/
if (!anon)
mem_cgroup_begin_update_page_stat(page, &locked, &flags);
/* page still mapped by someone else? */
if (!atomic_add_negative(-1, &page->_mapcount))
goto out;
/*
* Hugepages are not counted in NR_ANON_PAGES nor NR_FILE_MAPPED
* and not charged by memcg for now.
*/
if (unlikely(PageHuge(page)))
goto out;
if (anon) {
mem_cgroup_uncharge_page(page);
if (PageTransHuge(page))
__dec_zone_page_state(page,
NR_ANON_TRANSPARENT_HUGEPAGES);
__mod_zone_page_state(page_zone(page), NR_ANON_PAGES,
-hpage_nr_pages(page));
} else {
__dec_zone_page_state(page, NR_FILE_MAPPED);
mem_cgroup_dec_page_stat(page, MEM_CGROUP_STAT_FILE_MAPPED);
mem_cgroup_end_update_page_stat(page, &locked, &flags);
}
if (unlikely(PageMlocked(page)))
clear_page_mlock(page);
/*
* It would be tidy to reset the PageAnon mapping here,
* but that might overwrite a racing page_add_anon_rmap
* which increments mapcount after us but sets mapping
* before us: so leave the reset to free_hot_cold_page,
* and remember that it's only reliable while mapped.
* Leaving it set also helps swapoff to reinstate ptes
* faster for those pages still in swapcache.
*/
return;
out:
if (!anon)
mem_cgroup_end_update_page_stat(page, &locked, &flags);
}
/*
* Subfunctions of try_to_unmap: try_to_unmap_one called
* repeatedly from try_to_unmap_ksm, try_to_unmap_anon or try_to_unmap_file.
*/
int try_to_unmap_one(struct page *page, struct vm_area_struct *vma,
unsigned long address, enum ttu_flags flags)
{
struct mm_struct *mm = vma->vm_mm;
pte_t *pte;
pte_t pteval;
spinlock_t *ptl;
int ret = SWAP_AGAIN;
pte = page_check_address(page, mm, address, &ptl, 0);
if (!pte)
goto out;
/*
* If the page is mlock()d, we cannot swap it out.
* If it's recently referenced (perhaps page_referenced
* skipped over this mm) then we should reactivate it.
*/
if (!(flags & TTU_IGNORE_MLOCK)) {
if (vma->vm_flags & VM_LOCKED)
goto out_mlock;
if (TTU_ACTION(flags) == TTU_MUNLOCK)
goto out_unmap;
}
if (!(flags & TTU_IGNORE_ACCESS)) {
if (ptep_clear_flush_young_notify(vma, address, pte)) {
ret = SWAP_FAIL;
goto out_unmap;
}
}
/* Nuke the page table entry. */
flush_cache_page(vma, address, page_to_pfn(page));
pteval = ptep_clear_flush(vma, address, pte);
/* Move the dirty bit to the physical page now the pte is gone. */
if (pte_dirty(pteval))
set_page_dirty(page);
/* Update high watermark before we lower rss */
update_hiwater_rss(mm);
if (PageHWPoison(page) && !(flags & TTU_IGNORE_HWPOISON)) {
if (!PageHuge(page)) {
if (PageAnon(page))
dec_mm_counter(mm, MM_ANONPAGES);
else
dec_mm_counter(mm, MM_FILEPAGES);
}
set_pte_at(mm, address, pte,
swp_entry_to_pte(make_hwpoison_entry(page)));
} else if (PageAnon(page)) {
swp_entry_t entry = { .val = page_private(page) };
pte_t swp_pte;
if (PageSwapCache(page)) {
/*
* Store the swap location in the pte.
* See handle_pte_fault() ...
*/
if (swap_duplicate(entry) < 0) {
set_pte_at(mm, address, pte, pteval);
ret = SWAP_FAIL;
goto out_unmap;
}
if (list_empty(&mm->mmlist)) {
spin_lock(&mmlist_lock);
if (list_empty(&mm->mmlist))
list_add(&mm->mmlist, &init_mm.mmlist);
spin_unlock(&mmlist_lock);
}
dec_mm_counter(mm, MM_ANONPAGES);
inc_mm_counter(mm, MM_SWAPENTS);
} else if (IS_ENABLED(CONFIG_MIGRATION)) {
/*
* Store the pfn of the page in a special migration
* pte. do_swap_page() will wait until the migration
* pte is removed and then restart fault handling.
*/
BUG_ON(TTU_ACTION(flags) != TTU_MIGRATION);
entry = make_migration_entry(page, pte_write(pteval));
}
swp_pte = swp_entry_to_pte(entry);
if (pte_soft_dirty(pteval))
swp_pte = pte_swp_mksoft_dirty(swp_pte);
set_pte_at(mm, address, pte, swp_pte);
BUG_ON(pte_file(*pte));
} else if (IS_ENABLED(CONFIG_MIGRATION) &&
(TTU_ACTION(flags) == TTU_MIGRATION)) {
/* Establish migration entry for a file page */
swp_entry_t entry;
entry = make_migration_entry(page, pte_write(pteval));
set_pte_at(mm, address, pte, swp_entry_to_pte(entry));
} else
dec_mm_counter(mm, MM_FILEPAGES);
page_remove_rmap(page);
page_cache_release(page);
out_unmap:
pte_unmap_unlock(pte, ptl);
if (ret != SWAP_FAIL)
mmu_notifier_invalidate_page(mm, address);
out:
return ret;
out_mlock:
pte_unmap_unlock(pte, ptl);
/*
* We need mmap_sem locking, Otherwise VM_LOCKED check makes
* unstable result and race. Plus, We can't wait here because
* we now hold anon_vma->rwsem or mapping->i_mmap_mutex.
* if trylock failed, the page remain in evictable lru and later
* vmscan could retry to move the page to unevictable lru if the
* page is actually mlocked.
*/
if (down_read_trylock(&vma->vm_mm->mmap_sem)) {
if (vma->vm_flags & VM_LOCKED) {
mlock_vma_page(page);
ret = SWAP_MLOCK;
}
up_read(&vma->vm_mm->mmap_sem);
}
return ret;
}
/*
* objrmap doesn't work for nonlinear VMAs because the assumption that
* offset-into-file correlates with offset-into-virtual-addresses does not hold.
* Consequently, given a particular page and its ->index, we cannot locate the
* ptes which are mapping that page without an exhaustive linear search.
*
* So what this code does is a mini "virtual scan" of each nonlinear VMA which
* maps the file to which the target page belongs. The ->vm_private_data field
* holds the current cursor into that scan. Successive searches will circulate
* around the vma's virtual address space.
*
* So as more replacement pressure is applied to the pages in a nonlinear VMA,
* more scanning pressure is placed against them as well. Eventually pages
* will become fully unmapped and are eligible for eviction.
*
* For very sparsely populated VMAs this is a little inefficient - chances are
* there there won't be many ptes located within the scan cluster. In this case
* maybe we could scan further - to the end of the pte page, perhaps.
*
* Mlocked pages: check VM_LOCKED under mmap_sem held for read, if we can
* acquire it without blocking. If vma locked, mlock the pages in the cluster,
* rather than unmapping them. If we encounter the "check_page" that vmscan is
* trying to unmap, return SWAP_MLOCK, else default SWAP_AGAIN.
*/
#define CLUSTER_SIZE min(32*PAGE_SIZE, PMD_SIZE)
#define CLUSTER_MASK (~(CLUSTER_SIZE - 1))
static int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount,
struct vm_area_struct *vma, struct page *check_page)
{
struct mm_struct *mm = vma->vm_mm;
pmd_t *pmd;
pte_t *pte;
pte_t pteval;
spinlock_t *ptl;
struct page *page;
unsigned long address;
unsigned long mmun_start; /* For mmu_notifiers */
unsigned long mmun_end; /* For mmu_notifiers */
unsigned long end;
int ret = SWAP_AGAIN;
int locked_vma = 0;
address = (vma->vm_start + cursor) & CLUSTER_MASK;
end = address + CLUSTER_SIZE;
if (address < vma->vm_start)
address = vma->vm_start;
if (end > vma->vm_end)
end = vma->vm_end;
pmd = mm_find_pmd(mm, address);
if (!pmd)
return ret;
mmun_start = address;
mmun_end = end;
mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
/*
* If we can acquire the mmap_sem for read, and vma is VM_LOCKED,
* keep the sem while scanning the cluster for mlocking pages.
*/
if (down_read_trylock(&vma->vm_mm->mmap_sem)) {
locked_vma = (vma->vm_flags & VM_LOCKED);
if (!locked_vma)
up_read(&vma->vm_mm->mmap_sem); /* don't need it */
}
pte = pte_offset_map_lock(mm, pmd, address, &ptl);
/* Update high watermark before we lower rss */
update_hiwater_rss(mm);
for (; address < end; pte++, address += PAGE_SIZE) {
if (!pte_present(*pte))
continue;
page = vm_normal_page(vma, address, *pte);
BUG_ON(!page || PageAnon(page));
if (locked_vma) {
mlock_vma_page(page); /* no-op if already mlocked */
if (page == check_page)
ret = SWAP_MLOCK;
continue; /* don't unmap */
}
if (ptep_clear_flush_young_notify(vma, address, pte))
continue;
/* Nuke the page table entry. */
flush_cache_page(vma, address, pte_pfn(*pte));
pteval = ptep_clear_flush(vma, address, pte);
/* If nonlinear, store the file page offset in the pte. */
if (page->index != linear_page_index(vma, address)) {
pte_t ptfile = pgoff_to_pte(page->index);
if (pte_soft_dirty(pteval))
pte_file_mksoft_dirty(ptfile);
set_pte_at(mm, address, pte, ptfile);
}
/* Move the dirty bit to the physical page now the pte is gone. */
if (pte_dirty(pteval))
set_page_dirty(page);
page_remove_rmap(page);
page_cache_release(page);
dec_mm_counter(mm, MM_FILEPAGES);
(*mapcount)--;
}
pte_unmap_unlock(pte - 1, ptl);
mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
if (locked_vma)
up_read(&vma->vm_mm->mmap_sem);
return ret;
}
bool is_vma_temporary_stack(struct vm_area_struct *vma)
{
int maybe_stack = vma->vm_flags & (VM_GROWSDOWN | VM_GROWSUP);
if (!maybe_stack)
return false;
if ((vma->vm_flags & VM_STACK_INCOMPLETE_SETUP) ==
VM_STACK_INCOMPLETE_SETUP)
return true;
return false;
}
/**
* try_to_unmap_anon - unmap or unlock anonymous page using the object-based
* rmap method
* @page: the page to unmap/unlock
* @flags: action and flags
*
* Find all the mappings of a page using the mapping pointer and the vma chains
* contained in the anon_vma struct it points to.
*
* This function is only called from try_to_unmap/try_to_munlock for
* anonymous pages.
* When called from try_to_munlock(), the mmap_sem of the mm containing the vma
* where the page was found will be held for write. So, we won't recheck
* vm_flags for that VMA. That should be OK, because that vma shouldn't be
* 'LOCKED.
*/
static int try_to_unmap_anon(struct page *page, enum ttu_flags flags)
{
struct anon_vma *anon_vma;
pgoff_t pgoff;
struct anon_vma_chain *avc;
int ret = SWAP_AGAIN;
anon_vma = page_lock_anon_vma_read(page);
if (!anon_vma)
return ret;
pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
struct vm_area_struct *vma = avc->vma;
unsigned long address;
/*
* During exec, a temporary VMA is setup and later moved.
* The VMA is moved under the anon_vma lock but not the
* page tables leading to a race where migration cannot
* find the migration ptes. Rather than increasing the
* locking requirements of exec(), migration skips
* temporary VMAs until after exec() completes.
*/
if (IS_ENABLED(CONFIG_MIGRATION) && (flags & TTU_MIGRATION) &&
is_vma_temporary_stack(vma))
continue;
address = vma_address(page, vma);
ret = try_to_unmap_one(page, vma, address, flags);
if (ret != SWAP_AGAIN || !page_mapped(page))
break;
}
page_unlock_anon_vma_read(anon_vma);
return ret;
}
/**
* try_to_unmap_file - unmap/unlock file page using the object-based rmap method
* @page: the page to unmap/unlock
* @flags: action and flags
*
* Find all the mappings of a page using the mapping pointer and the vma chains
* contained in the address_space struct it points to.
*
* This function is only called from try_to_unmap/try_to_munlock for
* object-based pages.
* When called from try_to_munlock(), the mmap_sem of the mm containing the vma
* where the page was found will be held for write. So, we won't recheck
* vm_flags for that VMA. That should be OK, because that vma shouldn't be
* 'LOCKED.
*/
static int try_to_unmap_file(struct page *page, enum ttu_flags flags)
{
struct address_space *mapping = page->mapping;
pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
struct vm_area_struct *vma;
int ret = SWAP_AGAIN;
unsigned long cursor;
unsigned long max_nl_cursor = 0;
unsigned long max_nl_size = 0;
unsigned int mapcount;
if (PageHuge(page))
pgoff = page->index << compound_order(page);
mutex_lock(&mapping->i_mmap_mutex);
vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
unsigned long address = vma_address(page, vma);
ret = try_to_unmap_one(page, vma, address, flags);
if (ret != SWAP_AGAIN || !page_mapped(page))
goto out;
}
if (list_empty(&mapping->i_mmap_nonlinear))
goto out;
/*
* We don't bother to try to find the munlocked page in nonlinears.
* It's costly. Instead, later, page reclaim logic may call
* try_to_unmap(TTU_MUNLOCK) and recover PG_mlocked lazily.
*/
if (TTU_ACTION(flags) == TTU_MUNLOCK)
goto out;
list_for_each_entry(vma, &mapping->i_mmap_nonlinear,
shared.nonlinear) {
cursor = (unsigned long) vma->vm_private_data;
if (cursor > max_nl_cursor)
max_nl_cursor = cursor;
cursor = vma->vm_end - vma->vm_start;
if (cursor > max_nl_size)
max_nl_size = cursor;
}
if (max_nl_size == 0) { /* all nonlinears locked or reserved ? */
ret = SWAP_FAIL;
goto out;
}
/*
* We don't try to search for this page in the nonlinear vmas,
* and page_referenced wouldn't have found it anyway. Instead
* just walk the nonlinear vmas trying to age and unmap some.
* The mapcount of the page we came in with is irrelevant,
* but even so use it as a guide to how hard we should try?
*/
mapcount = page_mapcount(page);
if (!mapcount)
goto out;
cond_resched();
max_nl_size = (max_nl_size + CLUSTER_SIZE - 1) & CLUSTER_MASK;
if (max_nl_cursor == 0)
max_nl_cursor = CLUSTER_SIZE;
do {
list_for_each_entry(vma, &mapping->i_mmap_nonlinear,
shared.nonlinear) {
cursor = (unsigned long) vma->vm_private_data;
while ( cursor < max_nl_cursor &&
cursor < vma->vm_end - vma->vm_start) {
if (try_to_unmap_cluster(cursor, &mapcount,
vma, page) == SWAP_MLOCK)
ret = SWAP_MLOCK;
cursor += CLUSTER_SIZE;
vma->vm_private_data = (void *) cursor;
if ((int)mapcount <= 0)
goto out;
}
vma->vm_private_data = (void *) max_nl_cursor;
}
cond_resched();
max_nl_cursor += CLUSTER_SIZE;
} while (max_nl_cursor <= max_nl_size);
/*
* Don't loop forever (perhaps all the remaining pages are
* in locked vmas). Reset cursor on all unreserved nonlinear
* vmas, now forgetting on which ones it had fallen behind.
*/
list_for_each_entry(vma, &mapping->i_mmap_nonlinear, shared.nonlinear)
vma->vm_private_data = NULL;
out:
mutex_unlock(&mapping->i_mmap_mutex);
return ret;
}
/**
* try_to_unmap - try to remove all page table mappings to a page
* @page: the page to get unmapped
* @flags: action and flags
*
* Tries to remove all the page table entries which are mapping this
* page, used in the pageout path. Caller must hold the page lock.
* Return values are:
*
* SWAP_SUCCESS - we succeeded in removing all mappings
* SWAP_AGAIN - we missed a mapping, try again later
* SWAP_FAIL - the page is unswappable
* SWAP_MLOCK - page is mlocked.
*/
int try_to_unmap(struct page *page, enum ttu_flags flags)
{
int ret;
BUG_ON(!PageLocked(page));
VM_BUG_ON(!PageHuge(page) && PageTransHuge(page));
if (unlikely(PageKsm(page)))
ret = try_to_unmap_ksm(page, flags);
else if (PageAnon(page))
ret = try_to_unmap_anon(page, flags);
else
ret = try_to_unmap_file(page, flags);
if (ret != SWAP_MLOCK && !page_mapped(page))
ret = SWAP_SUCCESS;
return ret;
}
/**
* try_to_munlock - try to munlock a page
* @page: the page to be munlocked
*
* Called from munlock code. Checks all of the VMAs mapping the page
* to make sure nobody else has this page mlocked. The page will be
* returned with PG_mlocked cleared if no other vmas have it mlocked.
*
* Return values are:
*
* SWAP_AGAIN - no vma is holding page mlocked, or,
* SWAP_AGAIN - page mapped in mlocked vma -- couldn't acquire mmap sem
* SWAP_FAIL - page cannot be located at present
* SWAP_MLOCK - page is now mlocked.
*/
int try_to_munlock(struct page *page)
{
VM_BUG_ON(!PageLocked(page) || PageLRU(page));
if (unlikely(PageKsm(page)))
return try_to_unmap_ksm(page, TTU_MUNLOCK);
else if (PageAnon(page))
return try_to_unmap_anon(page, TTU_MUNLOCK);
else
return try_to_unmap_file(page, TTU_MUNLOCK);
}
void __put_anon_vma(struct anon_vma *anon_vma)
{
struct anon_vma *root = anon_vma->root;
if (root != anon_vma && atomic_dec_and_test(&root->refcount))
anon_vma_free(root);
anon_vma_free(anon_vma);
}
#ifdef CONFIG_MIGRATION
/*
* rmap_walk() and its helpers rmap_walk_anon() and rmap_walk_file():
* Called by migrate.c to remove migration ptes, but might be used more later.
*/
static int rmap_walk_anon(struct page *page, int (*rmap_one)(struct page *,
struct vm_area_struct *, unsigned long, void *), void *arg)
{
struct anon_vma *anon_vma;
pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
struct anon_vma_chain *avc;
int ret = SWAP_AGAIN;
/*
* Note: remove_migration_ptes() cannot use page_lock_anon_vma_read()
* because that depends on page_mapped(); but not all its usages
* are holding mmap_sem. Users without mmap_sem are required to
* take a reference count to prevent the anon_vma disappearing
*/
anon_vma = page_anon_vma(page);
if (!anon_vma)
return ret;
anon_vma_lock_read(anon_vma);
anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root, pgoff, pgoff) {
struct vm_area_struct *vma = avc->vma;
unsigned long address = vma_address(page, vma);
ret = rmap_one(page, vma, address, arg);
if (ret != SWAP_AGAIN)
break;
}
anon_vma_unlock_read(anon_vma);
return ret;
}
static int rmap_walk_file(struct page *page, int (*rmap_one)(struct page *,
struct vm_area_struct *, unsigned long, void *), void *arg)
{
struct address_space *mapping = page->mapping;
pgoff_t pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
struct vm_area_struct *vma;
int ret = SWAP_AGAIN;
if (!mapping)
return ret;
mutex_lock(&mapping->i_mmap_mutex);
vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
unsigned long address = vma_address(page, vma);
ret = rmap_one(page, vma, address, arg);
if (ret != SWAP_AGAIN)
break;
}
/*
* No nonlinear handling: being always shared, nonlinear vmas
* never contain migration ptes. Decide what to do about this
* limitation to linear when we need rmap_walk() on nonlinear.
*/
mutex_unlock(&mapping->i_mmap_mutex);
return ret;
}
int rmap_walk(struct page *page, int (*rmap_one)(struct page *,
struct vm_area_struct *, unsigned long, void *), void *arg)
{
VM_BUG_ON(!PageLocked(page));
if (unlikely(PageKsm(page)))
return rmap_walk_ksm(page, rmap_one, arg);
else if (PageAnon(page))
return rmap_walk_anon(page, rmap_one, arg);
else
return rmap_walk_file(page, rmap_one, arg);
}
#endif /* CONFIG_MIGRATION */
#ifdef CONFIG_HUGETLB_PAGE
/*
* The following three functions are for anonymous (private mapped) hugepages.
* Unlike common anonymous pages, anonymous hugepages have no accounting code
* and no lru code, because we handle hugepages differently from common pages.
*/
static void __hugepage_set_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address, int exclusive)
{
struct anon_vma *anon_vma = vma->anon_vma;
BUG_ON(!anon_vma);
if (PageAnon(page))
return;
if (!exclusive)
anon_vma = anon_vma->root;
anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
page->mapping = (struct address_space *) anon_vma;
page->index = linear_page_index(vma, address);
}
void hugepage_add_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
struct anon_vma *anon_vma = vma->anon_vma;
int first;
BUG_ON(!PageLocked(page));
BUG_ON(!anon_vma);
/* address might be in next vma when migration races vma_adjust */
first = atomic_inc_and_test(&page->_mapcount);
if (first)
__hugepage_set_anon_rmap(page, vma, address, 0);
}
void hugepage_add_new_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
BUG_ON(address < vma->vm_start || address >= vma->vm_end);
atomic_set(&page->_mapcount, 0);
__hugepage_set_anon_rmap(page, vma, address, 1);
}
#endif /* CONFIG_HUGETLB_PAGE */
| erikvanzijst/flatlinux | mm/rmap.c | C | gpl-2.0 | 51,911 |
/* CPU data header for mt.
THIS FILE IS MACHINE GENERATED WITH CGEN.
Copyright (C) 1996-2014 Free Software Foundation, Inc.
This file is part of the GNU Binutils and/or GDB, the GNU debugger.
This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef MT_CPU_H
#define MT_CPU_H
#define CGEN_ARCH mt
/* Given symbol S, return mt_cgen_<S>. */
#define CGEN_SYM(s) mt##_cgen_##s
/* Selected cpu families. */
#define HAVE_CPU_MS1BF
#define HAVE_CPU_MS1_003BF
#define HAVE_CPU_MS2BF
#define CGEN_INSN_LSB0_P 1
/* Minimum size of any insn (in bytes). */
#define CGEN_MIN_INSN_SIZE 4
/* Maximum size of any insn (in bytes). */
#define CGEN_MAX_INSN_SIZE 4
#define CGEN_INT_INSN_P 1
/* Maximum number of syntax elements in an instruction. */
#define CGEN_ACTUAL_MAX_SYNTAX_ELEMENTS 40
/* CGEN_MNEMONIC_OPERANDS is defined if mnemonics have operands.
e.g. In "b,a foo" the ",a" is an operand. If mnemonics have operands
we can't hash on everything up to the space. */
#define CGEN_MNEMONIC_OPERANDS
/* Maximum number of fields in an instruction. */
#define CGEN_ACTUAL_MAX_IFMT_OPERANDS 14
/* Enums. */
/* Enum declaration for msys enums. */
typedef enum insn_msys {
MSYS_NO, MSYS_YES
} INSN_MSYS;
/* Enum declaration for opc enums. */
typedef enum insn_opc {
OPC_ADD = 0, OPC_ADDU = 1, OPC_SUB = 2, OPC_SUBU = 3
, OPC_MUL = 4, OPC_AND = 8, OPC_OR = 9, OPC_XOR = 10
, OPC_NAND = 11, OPC_NOR = 12, OPC_XNOR = 13, OPC_LDUI = 14
, OPC_LSL = 16, OPC_LSR = 17, OPC_ASR = 18, OPC_BRLT = 24
, OPC_BRLE = 25, OPC_BREQ = 26, OPC_JMP = 27, OPC_JAL = 28
, OPC_BRNEQ = 29, OPC_DBNZ = 30, OPC_LOOP = 31, OPC_LDW = 32
, OPC_STW = 33, OPC_EI = 48, OPC_DI = 49, OPC_SI = 50
, OPC_RETI = 51, OPC_BREAK = 52, OPC_IFLUSH = 53
} INSN_OPC;
/* Enum declaration for msopc enums. */
typedef enum insn_msopc {
MSOPC_LDCTXT, MSOPC_LDFB, MSOPC_STFB, MSOPC_FBCB
, MSOPC_MFBCB, MSOPC_FBCCI, MSOPC_FBRCI, MSOPC_FBCRI
, MSOPC_FBRRI, MSOPC_MFBCCI, MSOPC_MFBRCI, MSOPC_MFBCRI
, MSOPC_MFBRRI, MSOPC_FBCBDR, MSOPC_RCFBCB, MSOPC_MRCFBCB
, MSOPC_CBCAST, MSOPC_DUPCBCAST, MSOPC_WFBI, MSOPC_WFB
, MSOPC_RCRISC, MSOPC_FBCBINC, MSOPC_RCXMODE, MSOPC_INTLVR
, MSOPC_WFBINC, MSOPC_MWFBINC, MSOPC_WFBINCR, MSOPC_MWFBINCR
, MSOPC_FBCBINCS, MSOPC_MFBCBINCS, MSOPC_FBCBINCRS, MSOPC_MFBCBINCRS
} INSN_MSOPC;
/* Enum declaration for imm enums. */
typedef enum insn_imm {
IMM_NO, IMM_YES
} INSN_IMM;
/* Enum declaration for . */
typedef enum msys_syms {
H_NIL_DUP = 1, H_NIL_XX = 0
} MSYS_SYMS;
/* Attributes. */
/* Enum declaration for machine type selection. */
typedef enum mach_attr {
MACH_BASE, MACH_MS1, MACH_MS1_003, MACH_MS2
, MACH_MAX
} MACH_ATTR;
/* Enum declaration for instruction set selection. */
typedef enum isa_attr {
ISA_MT, ISA_MAX
} ISA_ATTR;
/* Number of architecture variants. */
#define MAX_ISAS 1
#define MAX_MACHS ((int) MACH_MAX)
/* Ifield support. */
/* Ifield attribute indices. */
/* Enum declaration for cgen_ifld attrs. */
typedef enum cgen_ifld_attr {
CGEN_IFLD_VIRTUAL, CGEN_IFLD_PCREL_ADDR, CGEN_IFLD_ABS_ADDR, CGEN_IFLD_RESERVED
, CGEN_IFLD_SIGN_OPT, CGEN_IFLD_SIGNED, CGEN_IFLD_END_BOOLS, CGEN_IFLD_START_NBOOLS = 31
, CGEN_IFLD_MACH, CGEN_IFLD_END_NBOOLS
} CGEN_IFLD_ATTR;
/* Number of non-boolean elements in cgen_ifld_attr. */
#define CGEN_IFLD_NBOOL_ATTRS (CGEN_IFLD_END_NBOOLS - CGEN_IFLD_START_NBOOLS - 1)
/* cgen_ifld attribute accessor macros. */
#define CGEN_ATTR_CGEN_IFLD_MACH_VALUE(attrs) ((attrs)->nonbool[CGEN_IFLD_MACH-CGEN_IFLD_START_NBOOLS-1].nonbitset)
#define CGEN_ATTR_CGEN_IFLD_VIRTUAL_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_IFLD_VIRTUAL)) != 0)
#define CGEN_ATTR_CGEN_IFLD_PCREL_ADDR_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_IFLD_PCREL_ADDR)) != 0)
#define CGEN_ATTR_CGEN_IFLD_ABS_ADDR_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_IFLD_ABS_ADDR)) != 0)
#define CGEN_ATTR_CGEN_IFLD_RESERVED_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_IFLD_RESERVED)) != 0)
#define CGEN_ATTR_CGEN_IFLD_SIGN_OPT_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_IFLD_SIGN_OPT)) != 0)
#define CGEN_ATTR_CGEN_IFLD_SIGNED_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_IFLD_SIGNED)) != 0)
/* Enum declaration for mt ifield types. */
typedef enum ifield_type {
MT_F_NIL, MT_F_ANYOF, MT_F_MSYS, MT_F_OPC
, MT_F_IMM, MT_F_UU24, MT_F_SR1, MT_F_SR2
, MT_F_DR, MT_F_DRRR, MT_F_IMM16U, MT_F_IMM16S
, MT_F_IMM16A, MT_F_UU4A, MT_F_UU4B, MT_F_UU12
, MT_F_UU8, MT_F_UU16, MT_F_UU1, MT_F_MSOPC
, MT_F_UU_26_25, MT_F_MASK, MT_F_BANKADDR, MT_F_RDA
, MT_F_UU_2_25, MT_F_RBBC, MT_F_PERM, MT_F_MODE
, MT_F_UU_1_24, MT_F_WR, MT_F_FBINCR, MT_F_UU_2_23
, MT_F_XMODE, MT_F_A23, MT_F_MASK1, MT_F_CR
, MT_F_TYPE, MT_F_INCAMT, MT_F_CBS, MT_F_UU_1_19
, MT_F_BALL, MT_F_COLNUM, MT_F_BRC, MT_F_INCR
, MT_F_FBDISP, MT_F_UU_4_15, MT_F_LENGTH, MT_F_UU_1_15
, MT_F_RC, MT_F_RCNUM, MT_F_ROWNUM, MT_F_CBX
, MT_F_ID, MT_F_SIZE, MT_F_ROWNUM1, MT_F_UU_3_11
, MT_F_RC1, MT_F_CCB, MT_F_CBRB, MT_F_CDB
, MT_F_ROWNUM2, MT_F_CELL, MT_F_UU_3_9, MT_F_CONTNUM
, MT_F_UU_1_6, MT_F_DUP, MT_F_RC2, MT_F_CTXDISP
, MT_F_IMM16L, MT_F_LOOPO, MT_F_CB1SEL, MT_F_CB2SEL
, MT_F_CB1INCR, MT_F_CB2INCR, MT_F_RC3, MT_F_MSYSFRSR2
, MT_F_BRC2, MT_F_BALL2, MT_F_MAX
} IFIELD_TYPE;
#define MAX_IFLD ((int) MT_F_MAX)
/* Hardware attribute indices. */
/* Enum declaration for cgen_hw attrs. */
typedef enum cgen_hw_attr {
CGEN_HW_VIRTUAL, CGEN_HW_CACHE_ADDR, CGEN_HW_PC, CGEN_HW_PROFILE
, CGEN_HW_END_BOOLS, CGEN_HW_START_NBOOLS = 31, CGEN_HW_MACH, CGEN_HW_END_NBOOLS
} CGEN_HW_ATTR;
/* Number of non-boolean elements in cgen_hw_attr. */
#define CGEN_HW_NBOOL_ATTRS (CGEN_HW_END_NBOOLS - CGEN_HW_START_NBOOLS - 1)
/* cgen_hw attribute accessor macros. */
#define CGEN_ATTR_CGEN_HW_MACH_VALUE(attrs) ((attrs)->nonbool[CGEN_HW_MACH-CGEN_HW_START_NBOOLS-1].nonbitset)
#define CGEN_ATTR_CGEN_HW_VIRTUAL_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_HW_VIRTUAL)) != 0)
#define CGEN_ATTR_CGEN_HW_CACHE_ADDR_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_HW_CACHE_ADDR)) != 0)
#define CGEN_ATTR_CGEN_HW_PC_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_HW_PC)) != 0)
#define CGEN_ATTR_CGEN_HW_PROFILE_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_HW_PROFILE)) != 0)
/* Enum declaration for mt hardware types. */
typedef enum cgen_hw_type {
HW_H_MEMORY, HW_H_SINT, HW_H_UINT, HW_H_ADDR
, HW_H_IADDR, HW_H_SPR, HW_H_PC, HW_MAX
} CGEN_HW_TYPE;
#define MAX_HW ((int) HW_MAX)
/* Operand attribute indices. */
/* Enum declaration for cgen_operand attrs. */
typedef enum cgen_operand_attr {
CGEN_OPERAND_VIRTUAL, CGEN_OPERAND_PCREL_ADDR, CGEN_OPERAND_ABS_ADDR, CGEN_OPERAND_SIGN_OPT
, CGEN_OPERAND_SIGNED, CGEN_OPERAND_NEGATIVE, CGEN_OPERAND_RELAX, CGEN_OPERAND_SEM_ONLY
, CGEN_OPERAND_END_BOOLS, CGEN_OPERAND_START_NBOOLS = 31, CGEN_OPERAND_MACH, CGEN_OPERAND_END_NBOOLS
} CGEN_OPERAND_ATTR;
/* Number of non-boolean elements in cgen_operand_attr. */
#define CGEN_OPERAND_NBOOL_ATTRS (CGEN_OPERAND_END_NBOOLS - CGEN_OPERAND_START_NBOOLS - 1)
/* cgen_operand attribute accessor macros. */
#define CGEN_ATTR_CGEN_OPERAND_MACH_VALUE(attrs) ((attrs)->nonbool[CGEN_OPERAND_MACH-CGEN_OPERAND_START_NBOOLS-1].nonbitset)
#define CGEN_ATTR_CGEN_OPERAND_VIRTUAL_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_OPERAND_VIRTUAL)) != 0)
#define CGEN_ATTR_CGEN_OPERAND_PCREL_ADDR_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_OPERAND_PCREL_ADDR)) != 0)
#define CGEN_ATTR_CGEN_OPERAND_ABS_ADDR_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_OPERAND_ABS_ADDR)) != 0)
#define CGEN_ATTR_CGEN_OPERAND_SIGN_OPT_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_OPERAND_SIGN_OPT)) != 0)
#define CGEN_ATTR_CGEN_OPERAND_SIGNED_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_OPERAND_SIGNED)) != 0)
#define CGEN_ATTR_CGEN_OPERAND_NEGATIVE_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_OPERAND_NEGATIVE)) != 0)
#define CGEN_ATTR_CGEN_OPERAND_RELAX_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_OPERAND_RELAX)) != 0)
#define CGEN_ATTR_CGEN_OPERAND_SEM_ONLY_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_OPERAND_SEM_ONLY)) != 0)
/* Enum declaration for mt operand types. */
typedef enum cgen_operand_type {
MT_OPERAND_PC, MT_OPERAND_FRSR1, MT_OPERAND_FRSR2, MT_OPERAND_FRDR
, MT_OPERAND_FRDRRR, MT_OPERAND_IMM16, MT_OPERAND_IMM16Z, MT_OPERAND_IMM16O
, MT_OPERAND_RC, MT_OPERAND_RCNUM, MT_OPERAND_CONTNUM, MT_OPERAND_RBBC
, MT_OPERAND_COLNUM, MT_OPERAND_ROWNUM, MT_OPERAND_ROWNUM1, MT_OPERAND_ROWNUM2
, MT_OPERAND_RC1, MT_OPERAND_RC2, MT_OPERAND_CBRB, MT_OPERAND_CELL
, MT_OPERAND_DUP, MT_OPERAND_CTXDISP, MT_OPERAND_FBDISP, MT_OPERAND_TYPE
, MT_OPERAND_MASK, MT_OPERAND_BANKADDR, MT_OPERAND_INCAMT, MT_OPERAND_XMODE
, MT_OPERAND_MASK1, MT_OPERAND_BALL, MT_OPERAND_BRC, MT_OPERAND_RDA
, MT_OPERAND_WR, MT_OPERAND_BALL2, MT_OPERAND_BRC2, MT_OPERAND_PERM
, MT_OPERAND_A23, MT_OPERAND_CR, MT_OPERAND_CBS, MT_OPERAND_INCR
, MT_OPERAND_LENGTH, MT_OPERAND_CBX, MT_OPERAND_CCB, MT_OPERAND_CDB
, MT_OPERAND_MODE, MT_OPERAND_ID, MT_OPERAND_SIZE, MT_OPERAND_FBINCR
, MT_OPERAND_LOOPSIZE, MT_OPERAND_IMM16L, MT_OPERAND_RC3, MT_OPERAND_CB1SEL
, MT_OPERAND_CB2SEL, MT_OPERAND_CB1INCR, MT_OPERAND_CB2INCR, MT_OPERAND_MAX
} CGEN_OPERAND_TYPE;
/* Number of operands types. */
#define MAX_OPERANDS 55
/* Maximum number of operands referenced by any insn. */
#define MAX_OPERAND_INSTANCES 8
/* Insn attribute indices. */
/* Enum declaration for cgen_insn attrs. */
typedef enum cgen_insn_attr {
CGEN_INSN_ALIAS, CGEN_INSN_VIRTUAL, CGEN_INSN_UNCOND_CTI, CGEN_INSN_COND_CTI
, CGEN_INSN_SKIP_CTI, CGEN_INSN_DELAY_SLOT, CGEN_INSN_RELAXABLE, CGEN_INSN_RELAXED
, CGEN_INSN_NO_DIS, CGEN_INSN_PBB, CGEN_INSN_LOAD_DELAY, CGEN_INSN_MEMORY_ACCESS
, CGEN_INSN_AL_INSN, CGEN_INSN_IO_INSN, CGEN_INSN_BR_INSN, CGEN_INSN_JAL_HAZARD
, CGEN_INSN_USES_FRDR, CGEN_INSN_USES_FRDRRR, CGEN_INSN_USES_FRSR1, CGEN_INSN_USES_FRSR2
, CGEN_INSN_SKIPA, CGEN_INSN_END_BOOLS, CGEN_INSN_START_NBOOLS = 31, CGEN_INSN_MACH
, CGEN_INSN_END_NBOOLS
} CGEN_INSN_ATTR;
/* Number of non-boolean elements in cgen_insn_attr. */
#define CGEN_INSN_NBOOL_ATTRS (CGEN_INSN_END_NBOOLS - CGEN_INSN_START_NBOOLS - 1)
/* cgen_insn attribute accessor macros. */
#define CGEN_ATTR_CGEN_INSN_MACH_VALUE(attrs) ((attrs)->nonbool[CGEN_INSN_MACH-CGEN_INSN_START_NBOOLS-1].nonbitset)
#define CGEN_ATTR_CGEN_INSN_ALIAS_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_ALIAS)) != 0)
#define CGEN_ATTR_CGEN_INSN_VIRTUAL_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_VIRTUAL)) != 0)
#define CGEN_ATTR_CGEN_INSN_UNCOND_CTI_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_UNCOND_CTI)) != 0)
#define CGEN_ATTR_CGEN_INSN_COND_CTI_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_COND_CTI)) != 0)
#define CGEN_ATTR_CGEN_INSN_SKIP_CTI_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_SKIP_CTI)) != 0)
#define CGEN_ATTR_CGEN_INSN_DELAY_SLOT_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_DELAY_SLOT)) != 0)
#define CGEN_ATTR_CGEN_INSN_RELAXABLE_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_RELAXABLE)) != 0)
#define CGEN_ATTR_CGEN_INSN_RELAXED_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_RELAXED)) != 0)
#define CGEN_ATTR_CGEN_INSN_NO_DIS_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_NO_DIS)) != 0)
#define CGEN_ATTR_CGEN_INSN_PBB_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_PBB)) != 0)
#define CGEN_ATTR_CGEN_INSN_LOAD_DELAY_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_LOAD_DELAY)) != 0)
#define CGEN_ATTR_CGEN_INSN_MEMORY_ACCESS_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_MEMORY_ACCESS)) != 0)
#define CGEN_ATTR_CGEN_INSN_AL_INSN_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_AL_INSN)) != 0)
#define CGEN_ATTR_CGEN_INSN_IO_INSN_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_IO_INSN)) != 0)
#define CGEN_ATTR_CGEN_INSN_BR_INSN_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_BR_INSN)) != 0)
#define CGEN_ATTR_CGEN_INSN_JAL_HAZARD_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_JAL_HAZARD)) != 0)
#define CGEN_ATTR_CGEN_INSN_USES_FRDR_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_USES_FRDR)) != 0)
#define CGEN_ATTR_CGEN_INSN_USES_FRDRRR_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_USES_FRDRRR)) != 0)
#define CGEN_ATTR_CGEN_INSN_USES_FRSR1_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_USES_FRSR1)) != 0)
#define CGEN_ATTR_CGEN_INSN_USES_FRSR2_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_USES_FRSR2)) != 0)
#define CGEN_ATTR_CGEN_INSN_SKIPA_VALUE(attrs) (((attrs)->bool_ & (1 << CGEN_INSN_SKIPA)) != 0)
/* cgen.h uses things we just defined. */
#include "opcode/cgen.h"
extern const struct cgen_ifld mt_cgen_ifld_table[];
/* Attributes. */
extern const CGEN_ATTR_TABLE mt_cgen_hardware_attr_table[];
extern const CGEN_ATTR_TABLE mt_cgen_ifield_attr_table[];
extern const CGEN_ATTR_TABLE mt_cgen_operand_attr_table[];
extern const CGEN_ATTR_TABLE mt_cgen_insn_attr_table[];
/* Hardware decls. */
extern CGEN_KEYWORD mt_cgen_opval_h_spr;
extern const CGEN_HW_ENTRY mt_cgen_hw_table[];
#endif /* MT_CPU_H */
| jlspyaozhongkai/Uter | third_party_backup/binutils-2.25/opcodes/mt-desc.h | C | gpl-3.0 | 13,511 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
============================================================================*/
// This is a program to test if compiler is compatible with CUDA.
#define __CUDACC__
#include "crt/host_config.h"
int main(void) {
return 0;
}
| ghchinoy/tensorflow | tensorflow/contrib/cmake/tests/cuda/compatibility_test.cc | C++ | apache-2.0 | 814 |
AliAnalysisGrid* CreateAlienHandler()
{
AliAnalysisAlien *plugin = new AliAnalysisAlien();
plugin->SetUser("jonderwa");
plugin->SetOverwriteMode();
// --- Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
//plugin->SetRunMode("terminate"); // use to merge output when jobs are done
plugin->SetRunMode("test"); // use to test code
//plugin->SetRunMode("full"); // use to submit code
plugin->SetNtestFiles(1);
// Set versions of used packages
plugin->SetAPIVersion("V1.1x");
plugin->SetROOTVersion("v5-34-30-alice-7");
plugin->SetAliROOTVersion("v5-07-15-1");
plugin->SetAliPhysicsVersion("vAN-20151130-1");
//plugin->SetCheckCopy(kFALSE);
//plugin->EnablePackage("PWGPPevcharQnInterface.par");
//plugin->SetInputFile("/hera/alice/jonderw/gridanalysis/CalibrationFiles/000137161/CalibrationHistograms.root");
//plugin->SetMergeDirName("/hera/alice/jonderw/gridanalysis/CalibrationFiles/000137162/");
plugin->SetGridDataDir("/alice/data/2010/LHC10h/");
//plugin->SetGridDataDir("/alice/data/2015/LHC15o/");
//plugin->SetGridDataDir("/alice/data/2011/LHC11h_2/");
//plugin->SetDataPattern("ESDs/pass2/AOD086/*/AliAOD.root"); // all segments for running on Grid
//plugin->SetDataPattern("ESDs/pass2/AOD086/0001/AliAOD.root"); // single segment for testing
//plugin->SetDataPattern("ESDs/pass2/AliESDs.root"); // single segment for testing
plugin->SetDataPattern("*ESDs/pass2/*ESDs.root"); // 2010|2011
//plugin->SetDataPattern("/pass1/*/AliESDs.root"); // 2015
plugin->SetRunPrefix("000");
//plugin->AddRunNumber(245145); // LHC15o
//plugin->AddRunNumber(137161);
//plugin->AddRunNumber(137162);
plugin->AddRunNumber(138534);
//gROOT->ProcessLine(".L AddRunNumbers.C");
//int added = AddRunNumbers(plugin,0,1,"lhc10h"); // adds one run number for testing
//int added = AddRunNumbers(plugin,0,5,"lhc10h"); // adds multiple run numbers for running on grid
//int added = AddRunNumbers(plugin,0,90,"lhc10h"); // adds multiple run numbers for running on grid
//if(added<0) return NULL;
// Define alien work directory where all files will be copied. Relative to alien $HOME.
plugin->SetGridWorkingDir("AnalysisTesting");
// Declare alien output directory. Relative to working directory.
plugin->SetGridOutputDir("output"); // In this case will be $HOME/work/output
plugin->SetOutputToRunNo(); // Write output to runnumber directory
//plugin->SetAnalysisSource("AddTask_ep.C");
//plugin->SetAnalysisSource("AliAnalyisTaskEventPlaneCalibration.cxx");
//plugin->SetAdditionalLibs("AliAnalyisTaskEventPlaneCalibration.h AliAnalyisTaskEventPlaneCalibration.cxx");
plugin->SetAdditionalLibs("libSTEERBase libESD libAOD libANALYSIS libANALYSISalice libANALYSISaliceBase libCORRFW libOADB");
// Declare the analysis source files names separated by blancs. To be compiled runtime
// using ACLiC on the worker nodes.
//plugin->SetAnalysisSource("AliAnalyisTaskEventPlaneCalibration.cxx");
// Declare all libraries (other than the default ones for the framework. These will be
// loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
//plugin->SetAdditionalLibs("AliAnalyisTaskEventPlaneCalibration.h AliAnalyisTaskEventPlaneCalibration.cxx");
// Declare the output file names separated by blancs.
//plugin->SetOutputFiles("dstTree.root");
//plugin->SetDefaultOutputs();
// Optionally set a name for the generated analysis macro (default MyAnalysis.C)
plugin->SetAnalysisMacro("MyTask.C");
// Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
plugin->SetSplitMaxInputFileNumber(100);
// Optionally modify the executable name (default analysis.sh)
plugin->SetExecutable("MyTask.sh");
// Optionally set time to live (default 30000 sec)
plugin->SetTTL(30000);
// Optionally set input format (default xml-single)
plugin->SetInputFormat("xml-single");
// Optionally modify the name of the generated JDL (default analysis.jdl)
plugin->SetJDLName("MyTask.jdl");
//plugin->SetMergeViaJDL(kTRUE); //prp new // ???
// Optionally modify job price (default 1)
plugin->SetPrice(1);
// Optionally modify split mode (default 'se')
plugin->SetSplitMode("se");
return plugin;
}
| yowatana/AliPhysics | PWGCF/FLOW/CME/TwoPwrtRP/macros/CreateAlienHandler.C | C++ | bsd-3-clause | 4,278 |
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Users/ex3ndr/Develop/actor-proprietary/actor-apps/core/src/main/java/im/actor/model/modules/messages/ConversationHistoryActor.java
//
#ifndef _ImActorModelModulesMessagesConversationHistoryActor_H_
#define _ImActorModelModulesMessagesConversationHistoryActor_H_
#include "J2ObjC_header.h"
#include "im/actor/model/modules/utils/ModuleActor.h"
@class AMPeer;
@class ImActorModelModulesModules;
@interface ImActorModelModulesMessagesConversationHistoryActor : ImActorModelModulesUtilsModuleActor
#pragma mark Public
- (instancetype)initWithAMPeer:(AMPeer *)peer
withImActorModelModulesModules:(ImActorModelModulesModules *)modules;
- (void)onReceiveWithId:(id)message;
- (void)preStart;
@end
J2OBJC_EMPTY_STATIC_INIT(ImActorModelModulesMessagesConversationHistoryActor)
FOUNDATION_EXPORT void ImActorModelModulesMessagesConversationHistoryActor_initWithAMPeer_withImActorModelModulesModules_(ImActorModelModulesMessagesConversationHistoryActor *self, AMPeer *peer, ImActorModelModulesModules *modules);
FOUNDATION_EXPORT ImActorModelModulesMessagesConversationHistoryActor *new_ImActorModelModulesMessagesConversationHistoryActor_initWithAMPeer_withImActorModelModulesModules_(AMPeer *peer, ImActorModelModulesModules *modules) NS_RETURNS_RETAINED;
J2OBJC_TYPE_LITERAL_HEADER(ImActorModelModulesMessagesConversationHistoryActor)
@interface ImActorModelModulesMessagesConversationHistoryActor_LoadMore : NSObject
#pragma mark Public
- (instancetype)init;
@end
J2OBJC_EMPTY_STATIC_INIT(ImActorModelModulesMessagesConversationHistoryActor_LoadMore)
FOUNDATION_EXPORT void ImActorModelModulesMessagesConversationHistoryActor_LoadMore_init(ImActorModelModulesMessagesConversationHistoryActor_LoadMore *self);
FOUNDATION_EXPORT ImActorModelModulesMessagesConversationHistoryActor_LoadMore *new_ImActorModelModulesMessagesConversationHistoryActor_LoadMore_init() NS_RETURNS_RETAINED;
J2OBJC_TYPE_LITERAL_HEADER(ImActorModelModulesMessagesConversationHistoryActor_LoadMore)
@interface ImActorModelModulesMessagesConversationHistoryActor_LoadedMore : NSObject
#pragma mark Public
- (instancetype)initWithInt:(jint)loaded
withLong:(jlong)maxLoadedDate;
@end
J2OBJC_EMPTY_STATIC_INIT(ImActorModelModulesMessagesConversationHistoryActor_LoadedMore)
FOUNDATION_EXPORT void ImActorModelModulesMessagesConversationHistoryActor_LoadedMore_initWithInt_withLong_(ImActorModelModulesMessagesConversationHistoryActor_LoadedMore *self, jint loaded, jlong maxLoadedDate);
FOUNDATION_EXPORT ImActorModelModulesMessagesConversationHistoryActor_LoadedMore *new_ImActorModelModulesMessagesConversationHistoryActor_LoadedMore_initWithInt_withLong_(jint loaded, jlong maxLoadedDate) NS_RETURNS_RETAINED;
J2OBJC_TYPE_LITERAL_HEADER(ImActorModelModulesMessagesConversationHistoryActor_LoadedMore)
#endif // _ImActorModelModulesMessagesConversationHistoryActor_H_
| Rogerlin2013/actor-platform | actor-apps/core-cocoa/src/im/actor/model/modules/messages/ConversationHistoryActor.h | C | mit | 2,950 |
// this code is borrowed from RxOfficial(rx.codeplex.com) and modified
using System;
using System.Collections.Generic;
namespace UniRx.InternalUtil
{
/// <summary>
/// Asynchronous lock.
/// </summary>
internal sealed class AsyncLock : IDisposable
{
private readonly Queue<Action> queue = new Queue<Action>();
private bool isAcquired = false;
private bool hasFaulted = false;
/// <summary>
/// Queues the action for execution. If the caller acquires the lock and becomes the owner,
/// the queue is processed. If the lock is already owned, the action is queued and will get
/// processed by the owner.
/// </summary>
/// <param name="action">Action to queue for execution.</param>
/// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
public void Wait(Action action)
{
if (action == null)
throw new ArgumentNullException("action");
var isOwner = false;
lock (queue)
{
if (!hasFaulted)
{
queue.Enqueue(action);
isOwner = !isAcquired;
isAcquired = true;
}
}
if (isOwner)
{
while (true)
{
var work = default(Action);
lock (queue)
{
if (queue.Count > 0)
work = queue.Dequeue();
else
{
isAcquired = false;
break;
}
}
try
{
work();
}
catch
{
lock (queue)
{
queue.Clear();
hasFaulted = true;
}
throw;
}
}
}
}
/// <summary>
/// Clears the work items in the queue and drops further work being queued.
/// </summary>
public void Dispose()
{
lock (queue)
{
queue.Clear();
hasFaulted = true;
}
}
}
}
| Stormancer/Stormancer-sdk-net-unity | src/Clients/Unity/Stormancer.Unity.Package/Assets/Stormancer/UniRx/InternalUtil/AscynLock.cs | C# | mit | 2,503 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio;
//import org.apache.harmony.nio.internal.DirectBuffer;
//import org.apache.harmony.luni.platform.PlatformAddress;
/**
* This class wraps a byte buffer to be a double buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by
* the adapter. It must NOT be accessed outside the adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter.
* The adapter extends Buffer, thus has its own position and limit.</li>
* </ul>
* </p>
*
*/
final class DoubleToByteBufferAdapter extends DoubleBuffer {
//implements DirectBuffer {
static DoubleBuffer wrap(ByteBuffer byteBuffer) {
return new DoubleToByteBufferAdapter(byteBuffer.slice());
}
private final ByteBuffer byteBuffer;
DoubleToByteBufferAdapter(ByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 3));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
}
// public int getByteCapacity() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getByteCapacity();
// }
// assert false : byteBuffer;
// return -1;
// }
//
// public PlatformAddress getEffectiveAddress() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getEffectiveAddress();
// }
// assert false : byteBuffer;
// return null;
// }
//
// public PlatformAddress getBaseAddress() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getBaseAddress();
// }
// assert false : byteBuffer;
// return null;
// }
//
// public boolean isAddressValid() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).isAddressValid();
// }
// assert false : byteBuffer;
// return false;
// }
//
// public void addressValidityCheck() {
// if (byteBuffer instanceof DirectBuffer) {
// ((DirectBuffer) byteBuffer).addressValidityCheck();
// } else {
// assert false : byteBuffer;
// }
// }
//
// public void free() {
// if (byteBuffer instanceof DirectBuffer) {
// ((DirectBuffer) byteBuffer).free();
// } else {
// assert false : byteBuffer;
// }
// }
@Override
public DoubleBuffer asReadOnlyBuffer() {
DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter(
byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public DoubleBuffer compact() {
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
byteBuffer.limit(limit << 3);
byteBuffer.position(position << 3);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public DoubleBuffer duplicate() {
DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter(
byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public double get() {
if (position == limit) {
throw new BufferUnderflowException();
}
return byteBuffer.getDouble(position++ << 3);
}
@Override
public double get(int index) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
return byteBuffer.getDouble(index << 3);
}
@Override
public boolean isDirect() {
return byteBuffer.isDirect();
}
@Override
public boolean isReadOnly() {
return byteBuffer.isReadOnly();
}
@Override
public ByteOrder order() {
return byteBuffer.order();
}
@Override
protected double[] protectedArray() {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset() {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray() {
return false;
}
@Override
public DoubleBuffer put(double c) {
if (position == limit) {
throw new BufferOverflowException();
}
byteBuffer.putDouble(position++ << 3, c);
return this;
}
@Override
public DoubleBuffer put(int index, double c) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
byteBuffer.putDouble(index << 3, c);
return this;
}
@Override
public DoubleBuffer slice() {
byteBuffer.limit(limit << 3);
byteBuffer.position(position << 3);
DoubleBuffer result = new DoubleToByteBufferAdapter(byteBuffer.slice());
byteBuffer.clear();
return result;
}
}
| ECToo/quake2-gwt-port | src/com/google/gwt/corp/emul/java/nio/DoubleToByteBufferAdapter.java | Java | gpl-2.0 | 5,951 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>Responsive example - Foundation styling</title>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.3.1/css/foundation.min.css">
<link rel="stylesheet" type="text/css" href="../../../Plugins/integration/foundation/dataTables.foundation.css">
<link rel="stylesheet" type="text/css" href="../../css/dataTables.responsive.css">
<link rel="stylesheet" type="text/css" href="../../../../examples/resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../../../../examples/resources/demo.css">
<style type="text/css" class="init">
table.dataTable th,
table.dataTable td {
white-space: nowrap;
}
</style>
<script type="text/javascript" language="javascript" src="../../../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="../../js/dataTables.responsive.js"></script>
<script type="text/javascript" language="javascript" src="../../../Plugins/integration/foundation/dataTables.foundation.js"></script>
<script type="text/javascript" language="javascript" src="../../../../examples/resources/syntax/shCore.js"></script>
<script type="text/javascript" language="javascript" src="../../../../examples/resources/demo.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>Responsive example <span>Foundation styling</span></h1>
<div class="info">
<p>This example shows DataTables and the Responsive extension being used with the <a href="http://foundation.zurb.com">Foundation</a> framework providing the
styling. The <a href="//datatables.net/manual/styling/foundation">DataTables / Foundation integration files</a> prove seamless integration for DataTables to be
used in a Foundation page.</p>
</div>
<table id="example" class="tdisplay responsive" cellspacing="0" width="100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
<td>5421</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Garrett</td>
<td>Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
<td>8422</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Ashton</td>
<td>Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
<td>1562</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Cedric</td>
<td>Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
<td>6224</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Airi</td>
<td>Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
<td>5407</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Brielle</td>
<td>Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
<td>4804</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Herrod</td>
<td>Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
<td>9608</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Rhona</td>
<td>Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
<td>6200</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Colleen</td>
<td>Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
<td>2360</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Sonya</td>
<td>Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
<td>1667</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Jena</td>
<td>Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
<td>3814</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Quinn</td>
<td>Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
<td>9497</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Charde</td>
<td>Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
<td>6741</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Haley</td>
<td>Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
<td>3597</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Tatyana</td>
<td>Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
<td>1965</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Michael</td>
<td>Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
<td>1581</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Paul</td>
<td>Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
<td>3059</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Gloria</td>
<td>Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
<td>1721</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Bradley</td>
<td>Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
<td>2558</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Dai</td>
<td>Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
<td>2290</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Jenette</td>
<td>Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
<td>1937</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Yuri</td>
<td>Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
<td>6154</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Caesar</td>
<td>Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
<td>8330</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Doris</td>
<td>Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
<td>3023</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Angelica</td>
<td>Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
<td>5797</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Gavin</td>
<td>Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
<td>8822</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Jennifer</td>
<td>Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
<td>9239</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Brenden</td>
<td>Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
<td>1314</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Fiona</td>
<td>Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
<td>2947</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Shou</td>
<td>Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
<td>8899</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Michelle</td>
<td>House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
<td>2769</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Suki</td>
<td>Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
<td>6832</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Prescott</td>
<td>Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
<td>3606</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Gavin</td>
<td>Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
<td>2860</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Martena</td>
<td>Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
<td>8240</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Unity</td>
<td>Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
<td>5384</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Howard</td>
<td>Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
<td>7031</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Hope</td>
<td>Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
<td>6318</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Vivian</td>
<td>Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
<td>9422</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Timothy</td>
<td>Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
<td>7580</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Jackson</td>
<td>Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
<td>1042</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Olivia</td>
<td>Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
<td>2120</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Bruno</td>
<td>Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
<td>6222</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Sakura</td>
<td>Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
<td>9383</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Thor</td>
<td>Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
<td>8327</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Finn</td>
<td>Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
<td>2927</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Serge</td>
<td>Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
<td>8352</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Zenaida</td>
<td>Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
<td>7439</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Zorita</td>
<td>Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
<td>4389</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Jennifer</td>
<td>Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
<td>3431</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Cara</td>
<td>Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
<td>3990</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Hermione</td>
<td>Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
<td>1016</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Lael</td>
<td>Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
<td>6733</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Jonas</td>
<td>Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
<td>8196</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Shad</td>
<td>Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
<td>6373</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Michael</td>
<td>Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
<td>5384</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Donna</td>
<td>Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
<td>4226</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() {
$('#example').DataTable();
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p>
<ul>
<li><a href="../../../../media/js/jquery.js">../../../../media/js/jquery.js</a></li>
<li><a href="../../../../media/js/jquery.dataTables.js">../../../../media/js/jquery.dataTables.js</a></li>
<li><a href="../../js/dataTables.responsive.js">../../js/dataTables.responsive.js</a></li>
<li><a href="../../../Plugins/integration/foundation/dataTables.foundation.js">../../../Plugins/integration/foundation/dataTables.foundation.js</a></li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The
additional CSS used is shown below:</p><code class="multiline language-css">table.dataTable th,
table.dataTable td {
white-space: nowrap;
}</code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p>
<ul>
<li><a href=
"//cdnjs.cloudflare.com/ajax/libs/foundation/4.3.1/css/foundation.min.css">//cdnjs.cloudflare.com/ajax/libs/foundation/4.3.1/css/foundation.min.css</a></li>
<li><a href="../../../Plugins/integration/foundation/dataTables.foundation.css">../../../Plugins/integration/foundation/dataTables.foundation.css</a></li>
<li><a href="../../css/dataTables.responsive.css">../../css/dataTables.responsive.css</a></li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is
loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side
processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables
documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="../initialisation/index.html">Basic initialisation</a></h3>
<ul class="toc">
<li><a href="../initialisation/className.html">Class name</a></li>
<li><a href="../initialisation/option.html">Configuration option</a></li>
<li><a href="../initialisation/new.html">`new` constructor</a></li>
<li><a href="../initialisation/ajax.html">Ajax data</a></li>
<li><a href="../initialisation/default.html">Default initialisation</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="./index.html">Styling</a></h3>
<ul class="toc active">
<li><a href="./bootstrap.html">Bootstrap styling</a></li>
<li class="active"><a href="./foundation.html">Foundation styling</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../display-control/index.html">Display control</a></h3>
<ul class="toc">
<li><a href="../display-control/auto.html">Automatic column hiding</a></li>
<li><a href="../display-control/classes.html">Class control</a></li>
<li><a href="../display-control/init-classes.html">Assigned class control</a></li>
<li><a href="../display-control/fixedHeader.html">With FixedHeader</a></li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../child-rows/index.html">Child rows</a></h3>
<ul class="toc">
<li><a href="../child-rows/disable-child-rows.html">Disable child rows</a></li>
<li><a href="../child-rows/column-control.html">Column controlled child rows</a></li>
<li><a href="../child-rows/right-column.html">Column control - right</a></li>
<li><a href="../child-rows/whole-row-control.html">Whole row child row control</a></li>
<li><a href="../child-rows/custom-renderer.html">Custom child row renderer</a></li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a>
which extend the capabilities of DataTables.</p>
<p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2015<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | ahsina/StudExpo | wp-content/plugins/StePack/JS/DataTables-1.10.5/extensions/Responsive/examples/styling/foundation.html | HTML | gpl-2.0 | 22,323 |
class Object
def __metaclass__
class << self; self; end
end
end | Jonv/earth | vendor/plugins/mocha/lib/mocha/metaclass.rb | Ruby | gpl-2.0 | 75 |
/*
* Copyright (c) 2007-2014 Nicira, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/init.h>
#include <linux/module.h>
#include <linux/if_arp.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/jhash.h>
#include <linux/delay.h>
#include <linux/time.h>
#include <linux/etherdevice.h>
#include <linux/genetlink.h>
#include <linux/kernel.h>
#include <linux/kthread.h>
#include <linux/mutex.h>
#include <linux/percpu.h>
#include <linux/rcupdate.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/ethtool.h>
#include <linux/wait.h>
#include <asm/div64.h>
#include <linux/highmem.h>
#include <linux/netfilter_bridge.h>
#include <linux/netfilter_ipv4.h>
#include <linux/inetdevice.h>
#include <linux/list.h>
#include <linux/openvswitch.h>
#include <linux/rculist.h>
#include <linux/dmi.h>
#include <net/genetlink.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include "datapath.h"
#include "flow.h"
#include "flow_table.h"
#include "flow_netlink.h"
#include "vport-internal_dev.h"
#include "vport-netdev.h"
int ovs_net_id __read_mostly;
EXPORT_SYMBOL_GPL(ovs_net_id);
static struct genl_family dp_packet_genl_family;
static struct genl_family dp_flow_genl_family;
static struct genl_family dp_datapath_genl_family;
static const struct genl_multicast_group ovs_dp_flow_multicast_group = {
.name = OVS_FLOW_MCGROUP,
};
static const struct genl_multicast_group ovs_dp_datapath_multicast_group = {
.name = OVS_DATAPATH_MCGROUP,
};
static const struct genl_multicast_group ovs_dp_vport_multicast_group = {
.name = OVS_VPORT_MCGROUP,
};
/* Check if need to build a reply message.
* OVS userspace sets the NLM_F_ECHO flag if it needs the reply. */
static bool ovs_must_notify(struct genl_family *family, struct genl_info *info,
unsigned int group)
{
return info->nlhdr->nlmsg_flags & NLM_F_ECHO ||
genl_has_listeners(family, genl_info_net(info), group);
}
static void ovs_notify(struct genl_family *family,
struct sk_buff *skb, struct genl_info *info)
{
genl_notify(family, skb, genl_info_net(info), info->snd_portid,
0, info->nlhdr, GFP_KERNEL);
}
/**
* DOC: Locking:
*
* All writes e.g. Writes to device state (add/remove datapath, port, set
* operations on vports, etc.), Writes to other state (flow table
* modifications, set miscellaneous datapath parameters, etc.) are protected
* by ovs_lock.
*
* Reads are protected by RCU.
*
* There are a few special cases (mostly stats) that have their own
* synchronization but they nest under all of above and don't interact with
* each other.
*
* The RTNL lock nests inside ovs_mutex.
*/
static DEFINE_MUTEX(ovs_mutex);
void ovs_lock(void)
{
mutex_lock(&ovs_mutex);
}
void ovs_unlock(void)
{
mutex_unlock(&ovs_mutex);
}
#ifdef CONFIG_LOCKDEP
int lockdep_ovsl_is_held(void)
{
if (debug_locks)
return lockdep_is_held(&ovs_mutex);
else
return 1;
}
EXPORT_SYMBOL_GPL(lockdep_ovsl_is_held);
#endif
static struct vport *new_vport(const struct vport_parms *);
static int queue_gso_packets(struct datapath *dp, struct sk_buff *,
const struct sw_flow_key *,
const struct dp_upcall_info *);
static int queue_userspace_packet(struct datapath *dp, struct sk_buff *,
const struct sw_flow_key *,
const struct dp_upcall_info *);
/* Must be called with rcu_read_lock. */
static struct datapath *get_dp_rcu(struct net *net, int dp_ifindex)
{
struct net_device *dev = dev_get_by_index_rcu(net, dp_ifindex);
if (dev) {
struct vport *vport = ovs_internal_dev_get_vport(dev);
if (vport)
return vport->dp;
}
return NULL;
}
/* The caller must hold either ovs_mutex or rcu_read_lock to keep the
* returned dp pointer valid.
*/
static inline struct datapath *get_dp(struct net *net, int dp_ifindex)
{
struct datapath *dp;
WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_ovsl_is_held());
rcu_read_lock();
dp = get_dp_rcu(net, dp_ifindex);
rcu_read_unlock();
return dp;
}
/* Must be called with rcu_read_lock or ovs_mutex. */
const char *ovs_dp_name(const struct datapath *dp)
{
struct vport *vport = ovs_vport_ovsl_rcu(dp, OVSP_LOCAL);
return vport->ops->get_name(vport);
}
static int get_dpifindex(const struct datapath *dp)
{
struct vport *local;
int ifindex;
rcu_read_lock();
local = ovs_vport_rcu(dp, OVSP_LOCAL);
if (local)
ifindex = netdev_vport_priv(local)->dev->ifindex;
else
ifindex = 0;
rcu_read_unlock();
return ifindex;
}
static void destroy_dp_rcu(struct rcu_head *rcu)
{
struct datapath *dp = container_of(rcu, struct datapath, rcu);
ovs_flow_tbl_destroy(&dp->table);
free_percpu(dp->stats_percpu);
release_net(ovs_dp_get_net(dp));
kfree(dp->ports);
kfree(dp);
}
static struct hlist_head *vport_hash_bucket(const struct datapath *dp,
u16 port_no)
{
return &dp->ports[port_no & (DP_VPORT_HASH_BUCKETS - 1)];
}
/* Called with ovs_mutex or RCU read lock. */
struct vport *ovs_lookup_vport(const struct datapath *dp, u16 port_no)
{
struct vport *vport;
struct hlist_head *head;
head = vport_hash_bucket(dp, port_no);
hlist_for_each_entry_rcu(vport, head, dp_hash_node) {
if (vport->port_no == port_no)
return vport;
}
return NULL;
}
/* Called with ovs_mutex. */
static struct vport *new_vport(const struct vport_parms *parms)
{
struct vport *vport;
vport = ovs_vport_add(parms);
if (!IS_ERR(vport)) {
struct datapath *dp = parms->dp;
struct hlist_head *head = vport_hash_bucket(dp, vport->port_no);
hlist_add_head_rcu(&vport->dp_hash_node, head);
}
return vport;
}
void ovs_dp_detach_port(struct vport *p)
{
ASSERT_OVSL();
/* First drop references to device. */
hlist_del_rcu(&p->dp_hash_node);
/* Then destroy it. */
ovs_vport_del(p);
}
/* Must be called with rcu_read_lock. */
void ovs_dp_process_packet(struct sk_buff *skb, struct sw_flow_key *key)
{
const struct vport *p = OVS_CB(skb)->input_vport;
struct datapath *dp = p->dp;
struct sw_flow *flow;
struct sw_flow_actions *sf_acts;
struct dp_stats_percpu *stats;
u64 *stats_counter;
u32 n_mask_hit;
stats = this_cpu_ptr(dp->stats_percpu);
/* Look up flow. */
flow = ovs_flow_tbl_lookup_stats(&dp->table, key, &n_mask_hit);
if (unlikely(!flow)) {
struct dp_upcall_info upcall;
int error;
upcall.cmd = OVS_PACKET_CMD_MISS;
upcall.userdata = NULL;
upcall.portid = ovs_vport_find_upcall_portid(p, skb);
upcall.egress_tun_info = NULL;
error = ovs_dp_upcall(dp, skb, key, &upcall);
if (unlikely(error))
kfree_skb(skb);
else
consume_skb(skb);
stats_counter = &stats->n_missed;
goto out;
}
ovs_flow_stats_update(flow, key->tp.flags, skb);
sf_acts = rcu_dereference(flow->sf_acts);
ovs_execute_actions(dp, skb, sf_acts, key);
stats_counter = &stats->n_hit;
out:
/* Update datapath statistics. */
u64_stats_update_begin(&stats->syncp);
(*stats_counter)++;
stats->n_mask_hit += n_mask_hit;
u64_stats_update_end(&stats->syncp);
}
int ovs_dp_upcall(struct datapath *dp, struct sk_buff *skb,
const struct sw_flow_key *key,
const struct dp_upcall_info *upcall_info)
{
struct dp_stats_percpu *stats;
int err;
if (upcall_info->portid == 0) {
err = -ENOTCONN;
goto err;
}
if (!skb_is_gso(skb))
err = queue_userspace_packet(dp, skb, key, upcall_info);
else
err = queue_gso_packets(dp, skb, key, upcall_info);
if (err)
goto err;
return 0;
err:
stats = this_cpu_ptr(dp->stats_percpu);
u64_stats_update_begin(&stats->syncp);
stats->n_lost++;
u64_stats_update_end(&stats->syncp);
return err;
}
static int queue_gso_packets(struct datapath *dp, struct sk_buff *skb,
const struct sw_flow_key *key,
const struct dp_upcall_info *upcall_info)
{
unsigned short gso_type = skb_shinfo(skb)->gso_type;
struct sw_flow_key later_key;
struct sk_buff *segs, *nskb;
struct ovs_skb_cb ovs_cb;
int err;
ovs_cb = *OVS_CB(skb);
segs = __skb_gso_segment(skb, NETIF_F_SG, false);
*OVS_CB(skb) = ovs_cb;
if (IS_ERR(segs))
return PTR_ERR(segs);
if (segs == NULL)
return -EINVAL;
if (gso_type & SKB_GSO_UDP) {
/* The initial flow key extracted by ovs_flow_key_extract()
* in this case is for a first fragment, so we need to
* properly mark later fragments.
*/
later_key = *key;
later_key.ip.frag = OVS_FRAG_TYPE_LATER;
}
/* Queue all of the segments. */
skb = segs;
do {
*OVS_CB(skb) = ovs_cb;
if (gso_type & SKB_GSO_UDP && skb != segs)
key = &later_key;
err = queue_userspace_packet(dp, skb, key, upcall_info);
if (err)
break;
} while ((skb = skb->next));
/* Free all of the segments. */
skb = segs;
do {
nskb = skb->next;
if (err)
kfree_skb(skb);
else
consume_skb(skb);
} while ((skb = nskb));
return err;
}
static size_t upcall_msg_size(const struct dp_upcall_info *upcall_info,
unsigned int hdrlen)
{
size_t size = NLMSG_ALIGN(sizeof(struct ovs_header))
+ nla_total_size(hdrlen) /* OVS_PACKET_ATTR_PACKET */
+ nla_total_size(ovs_key_attr_size()); /* OVS_PACKET_ATTR_KEY */
/* OVS_PACKET_ATTR_USERDATA */
if (upcall_info->userdata)
size += NLA_ALIGN(upcall_info->userdata->nla_len);
/* OVS_PACKET_ATTR_EGRESS_TUN_KEY */
if (upcall_info->egress_tun_info)
size += nla_total_size(ovs_tun_key_attr_size());
return size;
}
static int queue_userspace_packet(struct datapath *dp, struct sk_buff *skb,
const struct sw_flow_key *key,
const struct dp_upcall_info *upcall_info)
{
struct ovs_header *upcall;
struct sk_buff *nskb = NULL;
struct sk_buff *user_skb = NULL; /* to be queued to userspace */
struct nlattr *nla;
struct genl_info info = {
.dst_sk = ovs_dp_get_net(dp)->genl_sock,
.snd_portid = upcall_info->portid,
};
size_t len;
unsigned int hlen;
int err, dp_ifindex;
dp_ifindex = get_dpifindex(dp);
if (!dp_ifindex)
return -ENODEV;
if (vlan_tx_tag_present(skb)) {
nskb = skb_clone(skb, GFP_ATOMIC);
if (!nskb)
return -ENOMEM;
nskb = __vlan_hwaccel_push_inside(nskb);
if (!nskb)
return -ENOMEM;
skb = nskb;
}
if (nla_attr_size(skb->len) > USHRT_MAX) {
err = -EFBIG;
goto out;
}
/* Complete checksum if needed */
if (skb->ip_summed == CHECKSUM_PARTIAL &&
(err = skb_checksum_help(skb)))
goto out;
/* Older versions of OVS user space enforce alignment of the last
* Netlink attribute to NLA_ALIGNTO which would require extensive
* padding logic. Only perform zerocopy if padding is not required.
*/
if (dp->user_features & OVS_DP_F_UNALIGNED)
hlen = skb_zerocopy_headlen(skb);
else
hlen = skb->len;
len = upcall_msg_size(upcall_info, hlen);
user_skb = genlmsg_new_unicast(len, &info, GFP_ATOMIC);
if (!user_skb) {
err = -ENOMEM;
goto out;
}
upcall = genlmsg_put(user_skb, 0, 0, &dp_packet_genl_family,
0, upcall_info->cmd);
upcall->dp_ifindex = dp_ifindex;
nla = nla_nest_start(user_skb, OVS_PACKET_ATTR_KEY);
err = ovs_nla_put_flow(key, key, user_skb);
BUG_ON(err);
nla_nest_end(user_skb, nla);
if (upcall_info->userdata)
__nla_put(user_skb, OVS_PACKET_ATTR_USERDATA,
nla_len(upcall_info->userdata),
nla_data(upcall_info->userdata));
if (upcall_info->egress_tun_info) {
nla = nla_nest_start(user_skb, OVS_PACKET_ATTR_EGRESS_TUN_KEY);
err = ovs_nla_put_egress_tunnel_key(user_skb,
upcall_info->egress_tun_info);
BUG_ON(err);
nla_nest_end(user_skb, nla);
}
/* Only reserve room for attribute header, packet data is added
* in skb_zerocopy() */
if (!(nla = nla_reserve(user_skb, OVS_PACKET_ATTR_PACKET, 0))) {
err = -ENOBUFS;
goto out;
}
nla->nla_len = nla_attr_size(skb->len);
err = skb_zerocopy(user_skb, skb, skb->len, hlen);
if (err)
goto out;
/* Pad OVS_PACKET_ATTR_PACKET if linear copy was performed */
if (!(dp->user_features & OVS_DP_F_UNALIGNED)) {
size_t plen = NLA_ALIGN(user_skb->len) - user_skb->len;
if (plen > 0)
memset(skb_put(user_skb, plen), 0, plen);
}
((struct nlmsghdr *) user_skb->data)->nlmsg_len = user_skb->len;
err = genlmsg_unicast(ovs_dp_get_net(dp), user_skb, upcall_info->portid);
user_skb = NULL;
out:
if (err)
skb_tx_error(skb);
kfree_skb(user_skb);
kfree_skb(nskb);
return err;
}
static int ovs_packet_cmd_execute(struct sk_buff *skb, struct genl_info *info)
{
struct ovs_header *ovs_header = info->userhdr;
struct nlattr **a = info->attrs;
struct sw_flow_actions *acts;
struct sk_buff *packet;
struct sw_flow *flow;
struct sw_flow_actions *sf_acts;
struct datapath *dp;
struct ethhdr *eth;
struct vport *input_vport;
int len;
int err;
bool log = !a[OVS_PACKET_ATTR_PROBE];
err = -EINVAL;
if (!a[OVS_PACKET_ATTR_PACKET] || !a[OVS_PACKET_ATTR_KEY] ||
!a[OVS_PACKET_ATTR_ACTIONS])
goto err;
len = nla_len(a[OVS_PACKET_ATTR_PACKET]);
packet = __dev_alloc_skb(NET_IP_ALIGN + len, GFP_KERNEL);
err = -ENOMEM;
if (!packet)
goto err;
skb_reserve(packet, NET_IP_ALIGN);
nla_memcpy(__skb_put(packet, len), a[OVS_PACKET_ATTR_PACKET], len);
skb_reset_mac_header(packet);
eth = eth_hdr(packet);
/* Normally, setting the skb 'protocol' field would be handled by a
* call to eth_type_trans(), but it assumes there's a sending
* device, which we may not have. */
if (ntohs(eth->h_proto) >= ETH_P_802_3_MIN)
packet->protocol = eth->h_proto;
else
packet->protocol = htons(ETH_P_802_2);
/* Build an sw_flow for sending this packet. */
flow = ovs_flow_alloc();
err = PTR_ERR(flow);
if (IS_ERR(flow))
goto err_kfree_skb;
err = ovs_flow_key_extract_userspace(a[OVS_PACKET_ATTR_KEY], packet,
&flow->key, log);
if (err)
goto err_flow_free;
err = ovs_nla_copy_actions(a[OVS_PACKET_ATTR_ACTIONS],
&flow->key, &acts, log);
if (err)
goto err_flow_free;
rcu_assign_pointer(flow->sf_acts, acts);
OVS_CB(packet)->egress_tun_info = NULL;
packet->priority = flow->key.phy.priority;
packet->mark = flow->key.phy.skb_mark;
rcu_read_lock();
dp = get_dp_rcu(sock_net(skb->sk), ovs_header->dp_ifindex);
err = -ENODEV;
if (!dp)
goto err_unlock;
input_vport = ovs_vport_rcu(dp, flow->key.phy.in_port);
if (!input_vport)
input_vport = ovs_vport_rcu(dp, OVSP_LOCAL);
if (!input_vport)
goto err_unlock;
OVS_CB(packet)->input_vport = input_vport;
sf_acts = rcu_dereference(flow->sf_acts);
local_bh_disable();
err = ovs_execute_actions(dp, packet, sf_acts, &flow->key);
local_bh_enable();
rcu_read_unlock();
ovs_flow_free(flow, false);
return err;
err_unlock:
rcu_read_unlock();
err_flow_free:
ovs_flow_free(flow, false);
err_kfree_skb:
kfree_skb(packet);
err:
return err;
}
static const struct nla_policy packet_policy[OVS_PACKET_ATTR_MAX + 1] = {
[OVS_PACKET_ATTR_PACKET] = { .len = ETH_HLEN },
[OVS_PACKET_ATTR_KEY] = { .type = NLA_NESTED },
[OVS_PACKET_ATTR_ACTIONS] = { .type = NLA_NESTED },
[OVS_PACKET_ATTR_PROBE] = { .type = NLA_FLAG },
};
static const struct genl_ops dp_packet_genl_ops[] = {
{ .cmd = OVS_PACKET_CMD_EXECUTE,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = packet_policy,
.doit = ovs_packet_cmd_execute
}
};
static struct genl_family dp_packet_genl_family = {
.id = GENL_ID_GENERATE,
.hdrsize = sizeof(struct ovs_header),
.name = OVS_PACKET_FAMILY,
.version = OVS_PACKET_VERSION,
.maxattr = OVS_PACKET_ATTR_MAX,
.netnsok = true,
.parallel_ops = true,
.ops = dp_packet_genl_ops,
.n_ops = ARRAY_SIZE(dp_packet_genl_ops),
};
static void get_dp_stats(const struct datapath *dp, struct ovs_dp_stats *stats,
struct ovs_dp_megaflow_stats *mega_stats)
{
int i;
memset(mega_stats, 0, sizeof(*mega_stats));
stats->n_flows = ovs_flow_tbl_count(&dp->table);
mega_stats->n_masks = ovs_flow_tbl_num_masks(&dp->table);
stats->n_hit = stats->n_missed = stats->n_lost = 0;
for_each_possible_cpu(i) {
const struct dp_stats_percpu *percpu_stats;
struct dp_stats_percpu local_stats;
unsigned int start;
percpu_stats = per_cpu_ptr(dp->stats_percpu, i);
do {
start = u64_stats_fetch_begin_irq(&percpu_stats->syncp);
local_stats = *percpu_stats;
} while (u64_stats_fetch_retry_irq(&percpu_stats->syncp, start));
stats->n_hit += local_stats.n_hit;
stats->n_missed += local_stats.n_missed;
stats->n_lost += local_stats.n_lost;
mega_stats->n_mask_hit += local_stats.n_mask_hit;
}
}
static size_t ovs_flow_cmd_msg_size(const struct sw_flow_actions *acts)
{
return NLMSG_ALIGN(sizeof(struct ovs_header))
+ nla_total_size(ovs_key_attr_size()) /* OVS_FLOW_ATTR_KEY */
+ nla_total_size(ovs_key_attr_size()) /* OVS_FLOW_ATTR_MASK */
+ nla_total_size(sizeof(struct ovs_flow_stats)) /* OVS_FLOW_ATTR_STATS */
+ nla_total_size(1) /* OVS_FLOW_ATTR_TCP_FLAGS */
+ nla_total_size(8) /* OVS_FLOW_ATTR_USED */
+ nla_total_size(acts->actions_len); /* OVS_FLOW_ATTR_ACTIONS */
}
/* Called with ovs_mutex or RCU read lock. */
static int ovs_flow_cmd_fill_match(const struct sw_flow *flow,
struct sk_buff *skb)
{
struct nlattr *nla;
int err;
/* Fill flow key. */
nla = nla_nest_start(skb, OVS_FLOW_ATTR_KEY);
if (!nla)
return -EMSGSIZE;
err = ovs_nla_put_flow(&flow->unmasked_key, &flow->unmasked_key, skb);
if (err)
return err;
nla_nest_end(skb, nla);
/* Fill flow mask. */
nla = nla_nest_start(skb, OVS_FLOW_ATTR_MASK);
if (!nla)
return -EMSGSIZE;
err = ovs_nla_put_flow(&flow->key, &flow->mask->key, skb);
if (err)
return err;
nla_nest_end(skb, nla);
return 0;
}
/* Called with ovs_mutex or RCU read lock. */
static int ovs_flow_cmd_fill_stats(const struct sw_flow *flow,
struct sk_buff *skb)
{
struct ovs_flow_stats stats;
__be16 tcp_flags;
unsigned long used;
ovs_flow_stats_get(flow, &stats, &used, &tcp_flags);
if (used &&
nla_put_u64(skb, OVS_FLOW_ATTR_USED, ovs_flow_used_time(used)))
return -EMSGSIZE;
if (stats.n_packets &&
nla_put(skb, OVS_FLOW_ATTR_STATS, sizeof(struct ovs_flow_stats), &stats))
return -EMSGSIZE;
if ((u8)ntohs(tcp_flags) &&
nla_put_u8(skb, OVS_FLOW_ATTR_TCP_FLAGS, (u8)ntohs(tcp_flags)))
return -EMSGSIZE;
return 0;
}
/* Called with ovs_mutex or RCU read lock. */
static int ovs_flow_cmd_fill_actions(const struct sw_flow *flow,
struct sk_buff *skb, int skb_orig_len)
{
struct nlattr *start;
int err;
/* If OVS_FLOW_ATTR_ACTIONS doesn't fit, skip dumping the actions if
* this is the first flow to be dumped into 'skb'. This is unusual for
* Netlink but individual action lists can be longer than
* NLMSG_GOODSIZE and thus entirely undumpable if we didn't do this.
* The userspace caller can always fetch the actions separately if it
* really wants them. (Most userspace callers in fact don't care.)
*
* This can only fail for dump operations because the skb is always
* properly sized for single flows.
*/
start = nla_nest_start(skb, OVS_FLOW_ATTR_ACTIONS);
if (start) {
const struct sw_flow_actions *sf_acts;
sf_acts = rcu_dereference_ovsl(flow->sf_acts);
err = ovs_nla_put_actions(sf_acts->actions,
sf_acts->actions_len, skb);
if (!err)
nla_nest_end(skb, start);
else {
if (skb_orig_len)
return err;
nla_nest_cancel(skb, start);
}
} else if (skb_orig_len) {
return -EMSGSIZE;
}
return 0;
}
/* Called with ovs_mutex or RCU read lock. */
static int ovs_flow_cmd_fill_info(const struct sw_flow *flow, int dp_ifindex,
struct sk_buff *skb, u32 portid,
u32 seq, u32 flags, u8 cmd)
{
const int skb_orig_len = skb->len;
struct ovs_header *ovs_header;
int err;
ovs_header = genlmsg_put(skb, portid, seq, &dp_flow_genl_family,
flags, cmd);
if (!ovs_header)
return -EMSGSIZE;
ovs_header->dp_ifindex = dp_ifindex;
err = ovs_flow_cmd_fill_match(flow, skb);
if (err)
goto error;
err = ovs_flow_cmd_fill_stats(flow, skb);
if (err)
goto error;
err = ovs_flow_cmd_fill_actions(flow, skb, skb_orig_len);
if (err)
goto error;
return genlmsg_end(skb, ovs_header);
error:
genlmsg_cancel(skb, ovs_header);
return err;
}
/* May not be called with RCU read lock. */
static struct sk_buff *ovs_flow_cmd_alloc_info(const struct sw_flow_actions *acts,
struct genl_info *info,
bool always)
{
struct sk_buff *skb;
if (!always && !ovs_must_notify(&dp_flow_genl_family, info, 0))
return NULL;
skb = genlmsg_new_unicast(ovs_flow_cmd_msg_size(acts), info, GFP_KERNEL);
if (!skb)
return ERR_PTR(-ENOMEM);
return skb;
}
/* Called with ovs_mutex. */
static struct sk_buff *ovs_flow_cmd_build_info(const struct sw_flow *flow,
int dp_ifindex,
struct genl_info *info, u8 cmd,
bool always)
{
struct sk_buff *skb;
int retval;
skb = ovs_flow_cmd_alloc_info(ovsl_dereference(flow->sf_acts), info,
always);
if (IS_ERR_OR_NULL(skb))
return skb;
retval = ovs_flow_cmd_fill_info(flow, dp_ifindex, skb,
info->snd_portid, info->snd_seq, 0,
cmd);
BUG_ON(retval < 0);
return skb;
}
static int ovs_flow_cmd_new(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct ovs_header *ovs_header = info->userhdr;
struct sw_flow *flow, *new_flow;
struct sw_flow_mask mask;
struct sk_buff *reply;
struct datapath *dp;
struct sw_flow_actions *acts;
struct sw_flow_match match;
int error;
bool log = !a[OVS_FLOW_ATTR_PROBE];
/* Must have key and actions. */
error = -EINVAL;
if (!a[OVS_FLOW_ATTR_KEY]) {
OVS_NLERR(log, "Flow key attr not present in new flow.");
goto error;
}
if (!a[OVS_FLOW_ATTR_ACTIONS]) {
OVS_NLERR(log, "Flow actions attr not present in new flow.");
goto error;
}
/* Most of the time we need to allocate a new flow, do it before
* locking.
*/
new_flow = ovs_flow_alloc();
if (IS_ERR(new_flow)) {
error = PTR_ERR(new_flow);
goto error;
}
/* Extract key. */
ovs_match_init(&match, &new_flow->unmasked_key, &mask);
error = ovs_nla_get_match(&match, a[OVS_FLOW_ATTR_KEY],
a[OVS_FLOW_ATTR_MASK], log);
if (error)
goto err_kfree_flow;
ovs_flow_mask_key(&new_flow->key, &new_flow->unmasked_key, &mask);
/* Validate actions. */
error = ovs_nla_copy_actions(a[OVS_FLOW_ATTR_ACTIONS], &new_flow->key,
&acts, log);
if (error) {
OVS_NLERR(log, "Flow actions may not be safe on all matching packets.");
goto err_kfree_flow;
}
reply = ovs_flow_cmd_alloc_info(acts, info, false);
if (IS_ERR(reply)) {
error = PTR_ERR(reply);
goto err_kfree_acts;
}
ovs_lock();
dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
if (unlikely(!dp)) {
error = -ENODEV;
goto err_unlock_ovs;
}
/* Check if this is a duplicate flow */
flow = ovs_flow_tbl_lookup(&dp->table, &new_flow->unmasked_key);
if (likely(!flow)) {
rcu_assign_pointer(new_flow->sf_acts, acts);
/* Put flow in bucket. */
error = ovs_flow_tbl_insert(&dp->table, new_flow, &mask);
if (unlikely(error)) {
acts = NULL;
goto err_unlock_ovs;
}
if (unlikely(reply)) {
error = ovs_flow_cmd_fill_info(new_flow,
ovs_header->dp_ifindex,
reply, info->snd_portid,
info->snd_seq, 0,
OVS_FLOW_CMD_NEW);
BUG_ON(error < 0);
}
ovs_unlock();
} else {
struct sw_flow_actions *old_acts;
/* Bail out if we're not allowed to modify an existing flow.
* We accept NLM_F_CREATE in place of the intended NLM_F_EXCL
* because Generic Netlink treats the latter as a dump
* request. We also accept NLM_F_EXCL in case that bug ever
* gets fixed.
*/
if (unlikely(info->nlhdr->nlmsg_flags & (NLM_F_CREATE
| NLM_F_EXCL))) {
error = -EEXIST;
goto err_unlock_ovs;
}
/* The unmasked key has to be the same for flow updates. */
if (unlikely(!ovs_flow_cmp_unmasked_key(flow, &match))) {
/* Look for any overlapping flow. */
flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
if (!flow) {
error = -ENOENT;
goto err_unlock_ovs;
}
}
/* Update actions. */
old_acts = ovsl_dereference(flow->sf_acts);
rcu_assign_pointer(flow->sf_acts, acts);
if (unlikely(reply)) {
error = ovs_flow_cmd_fill_info(flow,
ovs_header->dp_ifindex,
reply, info->snd_portid,
info->snd_seq, 0,
OVS_FLOW_CMD_NEW);
BUG_ON(error < 0);
}
ovs_unlock();
ovs_nla_free_flow_actions(old_acts);
ovs_flow_free(new_flow, false);
}
if (reply)
ovs_notify(&dp_flow_genl_family, reply, info);
return 0;
err_unlock_ovs:
ovs_unlock();
kfree_skb(reply);
err_kfree_acts:
kfree(acts);
err_kfree_flow:
ovs_flow_free(new_flow, false);
error:
return error;
}
/* Factor out action copy to avoid "Wframe-larger-than=1024" warning. */
static struct sw_flow_actions *get_flow_actions(const struct nlattr *a,
const struct sw_flow_key *key,
const struct sw_flow_mask *mask,
bool log)
{
struct sw_flow_actions *acts;
struct sw_flow_key masked_key;
int error;
ovs_flow_mask_key(&masked_key, key, mask);
error = ovs_nla_copy_actions(a, &masked_key, &acts, log);
if (error) {
OVS_NLERR(log,
"Actions may not be safe on all matching packets");
return ERR_PTR(error);
}
return acts;
}
static int ovs_flow_cmd_set(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct ovs_header *ovs_header = info->userhdr;
struct sw_flow_key key;
struct sw_flow *flow;
struct sw_flow_mask mask;
struct sk_buff *reply = NULL;
struct datapath *dp;
struct sw_flow_actions *old_acts = NULL, *acts = NULL;
struct sw_flow_match match;
int error;
bool log = !a[OVS_FLOW_ATTR_PROBE];
/* Extract key. */
error = -EINVAL;
if (!a[OVS_FLOW_ATTR_KEY]) {
OVS_NLERR(log, "Flow key attribute not present in set flow.");
goto error;
}
ovs_match_init(&match, &key, &mask);
error = ovs_nla_get_match(&match, a[OVS_FLOW_ATTR_KEY],
a[OVS_FLOW_ATTR_MASK], log);
if (error)
goto error;
/* Validate actions. */
if (a[OVS_FLOW_ATTR_ACTIONS]) {
acts = get_flow_actions(a[OVS_FLOW_ATTR_ACTIONS], &key, &mask,
log);
if (IS_ERR(acts)) {
error = PTR_ERR(acts);
goto error;
}
/* Can allocate before locking if have acts. */
reply = ovs_flow_cmd_alloc_info(acts, info, false);
if (IS_ERR(reply)) {
error = PTR_ERR(reply);
goto err_kfree_acts;
}
}
ovs_lock();
dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
if (unlikely(!dp)) {
error = -ENODEV;
goto err_unlock_ovs;
}
/* Check that the flow exists. */
flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
if (unlikely(!flow)) {
error = -ENOENT;
goto err_unlock_ovs;
}
/* Update actions, if present. */
if (likely(acts)) {
old_acts = ovsl_dereference(flow->sf_acts);
rcu_assign_pointer(flow->sf_acts, acts);
if (unlikely(reply)) {
error = ovs_flow_cmd_fill_info(flow,
ovs_header->dp_ifindex,
reply, info->snd_portid,
info->snd_seq, 0,
OVS_FLOW_CMD_NEW);
BUG_ON(error < 0);
}
} else {
/* Could not alloc without acts before locking. */
reply = ovs_flow_cmd_build_info(flow, ovs_header->dp_ifindex,
info, OVS_FLOW_CMD_NEW, false);
if (unlikely(IS_ERR(reply))) {
error = PTR_ERR(reply);
goto err_unlock_ovs;
}
}
/* Clear stats. */
if (a[OVS_FLOW_ATTR_CLEAR])
ovs_flow_stats_clear(flow);
ovs_unlock();
if (reply)
ovs_notify(&dp_flow_genl_family, reply, info);
if (old_acts)
ovs_nla_free_flow_actions(old_acts);
return 0;
err_unlock_ovs:
ovs_unlock();
kfree_skb(reply);
err_kfree_acts:
kfree(acts);
error:
return error;
}
static int ovs_flow_cmd_get(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct ovs_header *ovs_header = info->userhdr;
struct sw_flow_key key;
struct sk_buff *reply;
struct sw_flow *flow;
struct datapath *dp;
struct sw_flow_match match;
int err;
bool log = !a[OVS_FLOW_ATTR_PROBE];
if (!a[OVS_FLOW_ATTR_KEY]) {
OVS_NLERR(log,
"Flow get message rejected, Key attribute missing.");
return -EINVAL;
}
ovs_match_init(&match, &key, NULL);
err = ovs_nla_get_match(&match, a[OVS_FLOW_ATTR_KEY], NULL, log);
if (err)
return err;
ovs_lock();
dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
if (!dp) {
err = -ENODEV;
goto unlock;
}
flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
if (!flow) {
err = -ENOENT;
goto unlock;
}
reply = ovs_flow_cmd_build_info(flow, ovs_header->dp_ifindex, info,
OVS_FLOW_CMD_NEW, true);
if (IS_ERR(reply)) {
err = PTR_ERR(reply);
goto unlock;
}
ovs_unlock();
return genlmsg_reply(reply, info);
unlock:
ovs_unlock();
return err;
}
static int ovs_flow_cmd_del(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct ovs_header *ovs_header = info->userhdr;
struct sw_flow_key key;
struct sk_buff *reply;
struct sw_flow *flow;
struct datapath *dp;
struct sw_flow_match match;
int err;
bool log = !a[OVS_FLOW_ATTR_PROBE];
if (likely(a[OVS_FLOW_ATTR_KEY])) {
ovs_match_init(&match, &key, NULL);
err = ovs_nla_get_match(&match, a[OVS_FLOW_ATTR_KEY], NULL,
log);
if (unlikely(err))
return err;
}
ovs_lock();
dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
if (unlikely(!dp)) {
err = -ENODEV;
goto unlock;
}
if (unlikely(!a[OVS_FLOW_ATTR_KEY])) {
err = ovs_flow_tbl_flush(&dp->table);
goto unlock;
}
flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
if (unlikely(!flow)) {
err = -ENOENT;
goto unlock;
}
ovs_flow_tbl_remove(&dp->table, flow);
ovs_unlock();
reply = ovs_flow_cmd_alloc_info((const struct sw_flow_actions __force *) flow->sf_acts,
info, false);
if (likely(reply)) {
if (likely(!IS_ERR(reply))) {
rcu_read_lock(); /*To keep RCU checker happy. */
err = ovs_flow_cmd_fill_info(flow, ovs_header->dp_ifindex,
reply, info->snd_portid,
info->snd_seq, 0,
OVS_FLOW_CMD_DEL);
rcu_read_unlock();
BUG_ON(err < 0);
ovs_notify(&dp_flow_genl_family, reply, info);
} else {
netlink_set_err(sock_net(skb->sk)->genl_sock, 0, 0, PTR_ERR(reply));
}
}
ovs_flow_free(flow, true);
return 0;
unlock:
ovs_unlock();
return err;
}
static int ovs_flow_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct ovs_header *ovs_header = genlmsg_data(nlmsg_data(cb->nlh));
struct table_instance *ti;
struct datapath *dp;
rcu_read_lock();
dp = get_dp_rcu(sock_net(skb->sk), ovs_header->dp_ifindex);
if (!dp) {
rcu_read_unlock();
return -ENODEV;
}
ti = rcu_dereference(dp->table.ti);
for (;;) {
struct sw_flow *flow;
u32 bucket, obj;
bucket = cb->args[0];
obj = cb->args[1];
flow = ovs_flow_tbl_dump_next(ti, &bucket, &obj);
if (!flow)
break;
if (ovs_flow_cmd_fill_info(flow, ovs_header->dp_ifindex, skb,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
OVS_FLOW_CMD_NEW) < 0)
break;
cb->args[0] = bucket;
cb->args[1] = obj;
}
rcu_read_unlock();
return skb->len;
}
static const struct nla_policy flow_policy[OVS_FLOW_ATTR_MAX + 1] = {
[OVS_FLOW_ATTR_KEY] = { .type = NLA_NESTED },
[OVS_FLOW_ATTR_MASK] = { .type = NLA_NESTED },
[OVS_FLOW_ATTR_ACTIONS] = { .type = NLA_NESTED },
[OVS_FLOW_ATTR_CLEAR] = { .type = NLA_FLAG },
[OVS_FLOW_ATTR_PROBE] = { .type = NLA_FLAG },
};
static const struct genl_ops dp_flow_genl_ops[] = {
{ .cmd = OVS_FLOW_CMD_NEW,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = flow_policy,
.doit = ovs_flow_cmd_new
},
{ .cmd = OVS_FLOW_CMD_DEL,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = flow_policy,
.doit = ovs_flow_cmd_del
},
{ .cmd = OVS_FLOW_CMD_GET,
.flags = 0, /* OK for unprivileged users. */
.policy = flow_policy,
.doit = ovs_flow_cmd_get,
.dumpit = ovs_flow_cmd_dump
},
{ .cmd = OVS_FLOW_CMD_SET,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = flow_policy,
.doit = ovs_flow_cmd_set,
},
};
static struct genl_family dp_flow_genl_family = {
.id = GENL_ID_GENERATE,
.hdrsize = sizeof(struct ovs_header),
.name = OVS_FLOW_FAMILY,
.version = OVS_FLOW_VERSION,
.maxattr = OVS_FLOW_ATTR_MAX,
.netnsok = true,
.parallel_ops = true,
.ops = dp_flow_genl_ops,
.n_ops = ARRAY_SIZE(dp_flow_genl_ops),
.mcgrps = &ovs_dp_flow_multicast_group,
.n_mcgrps = 1,
};
static size_t ovs_dp_cmd_msg_size(void)
{
size_t msgsize = NLMSG_ALIGN(sizeof(struct ovs_header));
msgsize += nla_total_size(IFNAMSIZ);
msgsize += nla_total_size(sizeof(struct ovs_dp_stats));
msgsize += nla_total_size(sizeof(struct ovs_dp_megaflow_stats));
msgsize += nla_total_size(sizeof(u32)); /* OVS_DP_ATTR_USER_FEATURES */
return msgsize;
}
/* Called with ovs_mutex. */
static int ovs_dp_cmd_fill_info(struct datapath *dp, struct sk_buff *skb,
u32 portid, u32 seq, u32 flags, u8 cmd)
{
struct ovs_header *ovs_header;
struct ovs_dp_stats dp_stats;
struct ovs_dp_megaflow_stats dp_megaflow_stats;
int err;
ovs_header = genlmsg_put(skb, portid, seq, &dp_datapath_genl_family,
flags, cmd);
if (!ovs_header)
goto error;
ovs_header->dp_ifindex = get_dpifindex(dp);
err = nla_put_string(skb, OVS_DP_ATTR_NAME, ovs_dp_name(dp));
if (err)
goto nla_put_failure;
get_dp_stats(dp, &dp_stats, &dp_megaflow_stats);
if (nla_put(skb, OVS_DP_ATTR_STATS, sizeof(struct ovs_dp_stats),
&dp_stats))
goto nla_put_failure;
if (nla_put(skb, OVS_DP_ATTR_MEGAFLOW_STATS,
sizeof(struct ovs_dp_megaflow_stats),
&dp_megaflow_stats))
goto nla_put_failure;
if (nla_put_u32(skb, OVS_DP_ATTR_USER_FEATURES, dp->user_features))
goto nla_put_failure;
return genlmsg_end(skb, ovs_header);
nla_put_failure:
genlmsg_cancel(skb, ovs_header);
error:
return -EMSGSIZE;
}
static struct sk_buff *ovs_dp_cmd_alloc_info(struct genl_info *info)
{
return genlmsg_new_unicast(ovs_dp_cmd_msg_size(), info, GFP_KERNEL);
}
/* Called with rcu_read_lock or ovs_mutex. */
static struct datapath *lookup_datapath(struct net *net,
const struct ovs_header *ovs_header,
struct nlattr *a[OVS_DP_ATTR_MAX + 1])
{
struct datapath *dp;
if (!a[OVS_DP_ATTR_NAME])
dp = get_dp(net, ovs_header->dp_ifindex);
else {
struct vport *vport;
vport = ovs_vport_locate(net, nla_data(a[OVS_DP_ATTR_NAME]));
dp = vport && vport->port_no == OVSP_LOCAL ? vport->dp : NULL;
}
return dp ? dp : ERR_PTR(-ENODEV);
}
static void ovs_dp_reset_user_features(struct sk_buff *skb, struct genl_info *info)
{
struct datapath *dp;
dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
if (IS_ERR(dp))
return;
WARN(dp->user_features, "Dropping previously announced user features\n");
dp->user_features = 0;
}
static void ovs_dp_change(struct datapath *dp, struct nlattr *a[])
{
if (a[OVS_DP_ATTR_USER_FEATURES])
dp->user_features = nla_get_u32(a[OVS_DP_ATTR_USER_FEATURES]);
}
static int ovs_dp_cmd_new(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct vport_parms parms;
struct sk_buff *reply;
struct datapath *dp;
struct vport *vport;
struct ovs_net *ovs_net;
int err, i;
err = -EINVAL;
if (!a[OVS_DP_ATTR_NAME] || !a[OVS_DP_ATTR_UPCALL_PID])
goto err;
reply = ovs_dp_cmd_alloc_info(info);
if (!reply)
return -ENOMEM;
err = -ENOMEM;
dp = kzalloc(sizeof(*dp), GFP_KERNEL);
if (dp == NULL)
goto err_free_reply;
ovs_dp_set_net(dp, hold_net(sock_net(skb->sk)));
/* Allocate table. */
err = ovs_flow_tbl_init(&dp->table);
if (err)
goto err_free_dp;
dp->stats_percpu = netdev_alloc_pcpu_stats(struct dp_stats_percpu);
if (!dp->stats_percpu) {
err = -ENOMEM;
goto err_destroy_table;
}
dp->ports = kmalloc(DP_VPORT_HASH_BUCKETS * sizeof(struct hlist_head),
GFP_KERNEL);
if (!dp->ports) {
err = -ENOMEM;
goto err_destroy_percpu;
}
for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++)
INIT_HLIST_HEAD(&dp->ports[i]);
/* Set up our datapath device. */
parms.name = nla_data(a[OVS_DP_ATTR_NAME]);
parms.type = OVS_VPORT_TYPE_INTERNAL;
parms.options = NULL;
parms.dp = dp;
parms.port_no = OVSP_LOCAL;
parms.upcall_portids = a[OVS_DP_ATTR_UPCALL_PID];
ovs_dp_change(dp, a);
/* So far only local changes have been made, now need the lock. */
ovs_lock();
vport = new_vport(&parms);
if (IS_ERR(vport)) {
err = PTR_ERR(vport);
if (err == -EBUSY)
err = -EEXIST;
if (err == -EEXIST) {
/* An outdated user space instance that does not understand
* the concept of user_features has attempted to create a new
* datapath and is likely to reuse it. Drop all user features.
*/
if (info->genlhdr->version < OVS_DP_VER_FEATURES)
ovs_dp_reset_user_features(skb, info);
}
goto err_destroy_ports_array;
}
err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
info->snd_seq, 0, OVS_DP_CMD_NEW);
BUG_ON(err < 0);
ovs_net = net_generic(ovs_dp_get_net(dp), ovs_net_id);
list_add_tail_rcu(&dp->list_node, &ovs_net->dps);
ovs_unlock();
ovs_notify(&dp_datapath_genl_family, reply, info);
return 0;
err_destroy_ports_array:
ovs_unlock();
kfree(dp->ports);
err_destroy_percpu:
free_percpu(dp->stats_percpu);
err_destroy_table:
ovs_flow_tbl_destroy(&dp->table);
err_free_dp:
release_net(ovs_dp_get_net(dp));
kfree(dp);
err_free_reply:
kfree_skb(reply);
err:
return err;
}
/* Called with ovs_mutex. */
static void __dp_destroy(struct datapath *dp)
{
int i;
for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
struct vport *vport;
struct hlist_node *n;
hlist_for_each_entry_safe(vport, n, &dp->ports[i], dp_hash_node)
if (vport->port_no != OVSP_LOCAL)
ovs_dp_detach_port(vport);
}
list_del_rcu(&dp->list_node);
/* OVSP_LOCAL is datapath internal port. We need to make sure that
* all ports in datapath are destroyed first before freeing datapath.
*/
ovs_dp_detach_port(ovs_vport_ovsl(dp, OVSP_LOCAL));
/* RCU destroy the flow table */
call_rcu(&dp->rcu, destroy_dp_rcu);
}
static int ovs_dp_cmd_del(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *reply;
struct datapath *dp;
int err;
reply = ovs_dp_cmd_alloc_info(info);
if (!reply)
return -ENOMEM;
ovs_lock();
dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
err = PTR_ERR(dp);
if (IS_ERR(dp))
goto err_unlock_free;
err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
info->snd_seq, 0, OVS_DP_CMD_DEL);
BUG_ON(err < 0);
__dp_destroy(dp);
ovs_unlock();
ovs_notify(&dp_datapath_genl_family, reply, info);
return 0;
err_unlock_free:
ovs_unlock();
kfree_skb(reply);
return err;
}
static int ovs_dp_cmd_set(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *reply;
struct datapath *dp;
int err;
reply = ovs_dp_cmd_alloc_info(info);
if (!reply)
return -ENOMEM;
ovs_lock();
dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
err = PTR_ERR(dp);
if (IS_ERR(dp))
goto err_unlock_free;
ovs_dp_change(dp, info->attrs);
err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
info->snd_seq, 0, OVS_DP_CMD_NEW);
BUG_ON(err < 0);
ovs_unlock();
ovs_notify(&dp_datapath_genl_family, reply, info);
return 0;
err_unlock_free:
ovs_unlock();
kfree_skb(reply);
return err;
}
static int ovs_dp_cmd_get(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *reply;
struct datapath *dp;
int err;
reply = ovs_dp_cmd_alloc_info(info);
if (!reply)
return -ENOMEM;
ovs_lock();
dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
if (IS_ERR(dp)) {
err = PTR_ERR(dp);
goto err_unlock_free;
}
err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
info->snd_seq, 0, OVS_DP_CMD_NEW);
BUG_ON(err < 0);
ovs_unlock();
return genlmsg_reply(reply, info);
err_unlock_free:
ovs_unlock();
kfree_skb(reply);
return err;
}
static int ovs_dp_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
struct datapath *dp;
int skip = cb->args[0];
int i = 0;
ovs_lock();
list_for_each_entry(dp, &ovs_net->dps, list_node) {
if (i >= skip &&
ovs_dp_cmd_fill_info(dp, skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
OVS_DP_CMD_NEW) < 0)
break;
i++;
}
ovs_unlock();
cb->args[0] = i;
return skb->len;
}
static const struct nla_policy datapath_policy[OVS_DP_ATTR_MAX + 1] = {
[OVS_DP_ATTR_NAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 },
[OVS_DP_ATTR_UPCALL_PID] = { .type = NLA_U32 },
[OVS_DP_ATTR_USER_FEATURES] = { .type = NLA_U32 },
};
static const struct genl_ops dp_datapath_genl_ops[] = {
{ .cmd = OVS_DP_CMD_NEW,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = datapath_policy,
.doit = ovs_dp_cmd_new
},
{ .cmd = OVS_DP_CMD_DEL,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = datapath_policy,
.doit = ovs_dp_cmd_del
},
{ .cmd = OVS_DP_CMD_GET,
.flags = 0, /* OK for unprivileged users. */
.policy = datapath_policy,
.doit = ovs_dp_cmd_get,
.dumpit = ovs_dp_cmd_dump
},
{ .cmd = OVS_DP_CMD_SET,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = datapath_policy,
.doit = ovs_dp_cmd_set,
},
};
static struct genl_family dp_datapath_genl_family = {
.id = GENL_ID_GENERATE,
.hdrsize = sizeof(struct ovs_header),
.name = OVS_DATAPATH_FAMILY,
.version = OVS_DATAPATH_VERSION,
.maxattr = OVS_DP_ATTR_MAX,
.netnsok = true,
.parallel_ops = true,
.ops = dp_datapath_genl_ops,
.n_ops = ARRAY_SIZE(dp_datapath_genl_ops),
.mcgrps = &ovs_dp_datapath_multicast_group,
.n_mcgrps = 1,
};
/* Called with ovs_mutex or RCU read lock. */
static int ovs_vport_cmd_fill_info(struct vport *vport, struct sk_buff *skb,
u32 portid, u32 seq, u32 flags, u8 cmd)
{
struct ovs_header *ovs_header;
struct ovs_vport_stats vport_stats;
int err;
ovs_header = genlmsg_put(skb, portid, seq, &dp_vport_genl_family,
flags, cmd);
if (!ovs_header)
return -EMSGSIZE;
ovs_header->dp_ifindex = get_dpifindex(vport->dp);
if (nla_put_u32(skb, OVS_VPORT_ATTR_PORT_NO, vport->port_no) ||
nla_put_u32(skb, OVS_VPORT_ATTR_TYPE, vport->ops->type) ||
nla_put_string(skb, OVS_VPORT_ATTR_NAME,
vport->ops->get_name(vport)))
goto nla_put_failure;
ovs_vport_get_stats(vport, &vport_stats);
if (nla_put(skb, OVS_VPORT_ATTR_STATS, sizeof(struct ovs_vport_stats),
&vport_stats))
goto nla_put_failure;
if (ovs_vport_get_upcall_portids(vport, skb))
goto nla_put_failure;
err = ovs_vport_get_options(vport, skb);
if (err == -EMSGSIZE)
goto error;
return genlmsg_end(skb, ovs_header);
nla_put_failure:
err = -EMSGSIZE;
error:
genlmsg_cancel(skb, ovs_header);
return err;
}
static struct sk_buff *ovs_vport_cmd_alloc_info(void)
{
return nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
}
/* Called with ovs_mutex, only via ovs_dp_notify_wq(). */
struct sk_buff *ovs_vport_cmd_build_info(struct vport *vport, u32 portid,
u32 seq, u8 cmd)
{
struct sk_buff *skb;
int retval;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
retval = ovs_vport_cmd_fill_info(vport, skb, portid, seq, 0, cmd);
BUG_ON(retval < 0);
return skb;
}
/* Called with ovs_mutex or RCU read lock. */
static struct vport *lookup_vport(struct net *net,
const struct ovs_header *ovs_header,
struct nlattr *a[OVS_VPORT_ATTR_MAX + 1])
{
struct datapath *dp;
struct vport *vport;
if (a[OVS_VPORT_ATTR_NAME]) {
vport = ovs_vport_locate(net, nla_data(a[OVS_VPORT_ATTR_NAME]));
if (!vport)
return ERR_PTR(-ENODEV);
if (ovs_header->dp_ifindex &&
ovs_header->dp_ifindex != get_dpifindex(vport->dp))
return ERR_PTR(-ENODEV);
return vport;
} else if (a[OVS_VPORT_ATTR_PORT_NO]) {
u32 port_no = nla_get_u32(a[OVS_VPORT_ATTR_PORT_NO]);
if (port_no >= DP_MAX_PORTS)
return ERR_PTR(-EFBIG);
dp = get_dp(net, ovs_header->dp_ifindex);
if (!dp)
return ERR_PTR(-ENODEV);
vport = ovs_vport_ovsl_rcu(dp, port_no);
if (!vport)
return ERR_PTR(-ENODEV);
return vport;
} else
return ERR_PTR(-EINVAL);
}
static int ovs_vport_cmd_new(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct ovs_header *ovs_header = info->userhdr;
struct vport_parms parms;
struct sk_buff *reply;
struct vport *vport;
struct datapath *dp;
u32 port_no;
int err;
if (!a[OVS_VPORT_ATTR_NAME] || !a[OVS_VPORT_ATTR_TYPE] ||
!a[OVS_VPORT_ATTR_UPCALL_PID])
return -EINVAL;
port_no = a[OVS_VPORT_ATTR_PORT_NO]
? nla_get_u32(a[OVS_VPORT_ATTR_PORT_NO]) : 0;
if (port_no >= DP_MAX_PORTS)
return -EFBIG;
reply = ovs_vport_cmd_alloc_info();
if (!reply)
return -ENOMEM;
ovs_lock();
restart:
dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
err = -ENODEV;
if (!dp)
goto exit_unlock_free;
if (port_no) {
vport = ovs_vport_ovsl(dp, port_no);
err = -EBUSY;
if (vport)
goto exit_unlock_free;
} else {
for (port_no = 1; ; port_no++) {
if (port_no >= DP_MAX_PORTS) {
err = -EFBIG;
goto exit_unlock_free;
}
vport = ovs_vport_ovsl(dp, port_no);
if (!vport)
break;
}
}
parms.name = nla_data(a[OVS_VPORT_ATTR_NAME]);
parms.type = nla_get_u32(a[OVS_VPORT_ATTR_TYPE]);
parms.options = a[OVS_VPORT_ATTR_OPTIONS];
parms.dp = dp;
parms.port_no = port_no;
parms.upcall_portids = a[OVS_VPORT_ATTR_UPCALL_PID];
vport = new_vport(&parms);
err = PTR_ERR(vport);
if (IS_ERR(vport)) {
if (err == -EAGAIN)
goto restart;
goto exit_unlock_free;
}
err = ovs_vport_cmd_fill_info(vport, reply, info->snd_portid,
info->snd_seq, 0, OVS_VPORT_CMD_NEW);
BUG_ON(err < 0);
ovs_unlock();
ovs_notify(&dp_vport_genl_family, reply, info);
return 0;
exit_unlock_free:
ovs_unlock();
kfree_skb(reply);
return err;
}
static int ovs_vport_cmd_set(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct sk_buff *reply;
struct vport *vport;
int err;
reply = ovs_vport_cmd_alloc_info();
if (!reply)
return -ENOMEM;
ovs_lock();
vport = lookup_vport(sock_net(skb->sk), info->userhdr, a);
err = PTR_ERR(vport);
if (IS_ERR(vport))
goto exit_unlock_free;
if (a[OVS_VPORT_ATTR_TYPE] &&
nla_get_u32(a[OVS_VPORT_ATTR_TYPE]) != vport->ops->type) {
err = -EINVAL;
goto exit_unlock_free;
}
if (a[OVS_VPORT_ATTR_OPTIONS]) {
err = ovs_vport_set_options(vport, a[OVS_VPORT_ATTR_OPTIONS]);
if (err)
goto exit_unlock_free;
}
if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
struct nlattr *ids = a[OVS_VPORT_ATTR_UPCALL_PID];
err = ovs_vport_set_upcall_portids(vport, ids);
if (err)
goto exit_unlock_free;
}
err = ovs_vport_cmd_fill_info(vport, reply, info->snd_portid,
info->snd_seq, 0, OVS_VPORT_CMD_NEW);
BUG_ON(err < 0);
ovs_unlock();
ovs_notify(&dp_vport_genl_family, reply, info);
return 0;
exit_unlock_free:
ovs_unlock();
kfree_skb(reply);
return err;
}
static int ovs_vport_cmd_del(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct sk_buff *reply;
struct vport *vport;
int err;
reply = ovs_vport_cmd_alloc_info();
if (!reply)
return -ENOMEM;
ovs_lock();
vport = lookup_vport(sock_net(skb->sk), info->userhdr, a);
err = PTR_ERR(vport);
if (IS_ERR(vport))
goto exit_unlock_free;
if (vport->port_no == OVSP_LOCAL) {
err = -EINVAL;
goto exit_unlock_free;
}
err = ovs_vport_cmd_fill_info(vport, reply, info->snd_portid,
info->snd_seq, 0, OVS_VPORT_CMD_DEL);
BUG_ON(err < 0);
ovs_dp_detach_port(vport);
ovs_unlock();
ovs_notify(&dp_vport_genl_family, reply, info);
return 0;
exit_unlock_free:
ovs_unlock();
kfree_skb(reply);
return err;
}
static int ovs_vport_cmd_get(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr **a = info->attrs;
struct ovs_header *ovs_header = info->userhdr;
struct sk_buff *reply;
struct vport *vport;
int err;
reply = ovs_vport_cmd_alloc_info();
if (!reply)
return -ENOMEM;
rcu_read_lock();
vport = lookup_vport(sock_net(skb->sk), ovs_header, a);
err = PTR_ERR(vport);
if (IS_ERR(vport))
goto exit_unlock_free;
err = ovs_vport_cmd_fill_info(vport, reply, info->snd_portid,
info->snd_seq, 0, OVS_VPORT_CMD_NEW);
BUG_ON(err < 0);
rcu_read_unlock();
return genlmsg_reply(reply, info);
exit_unlock_free:
rcu_read_unlock();
kfree_skb(reply);
return err;
}
static int ovs_vport_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct ovs_header *ovs_header = genlmsg_data(nlmsg_data(cb->nlh));
struct datapath *dp;
int bucket = cb->args[0], skip = cb->args[1];
int i, j = 0;
rcu_read_lock();
dp = get_dp_rcu(sock_net(skb->sk), ovs_header->dp_ifindex);
if (!dp) {
rcu_read_unlock();
return -ENODEV;
}
for (i = bucket; i < DP_VPORT_HASH_BUCKETS; i++) {
struct vport *vport;
j = 0;
hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node) {
if (j >= skip &&
ovs_vport_cmd_fill_info(vport, skb,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
NLM_F_MULTI,
OVS_VPORT_CMD_NEW) < 0)
goto out;
j++;
}
skip = 0;
}
out:
rcu_read_unlock();
cb->args[0] = i;
cb->args[1] = j;
return skb->len;
}
static const struct nla_policy vport_policy[OVS_VPORT_ATTR_MAX + 1] = {
[OVS_VPORT_ATTR_NAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 },
[OVS_VPORT_ATTR_STATS] = { .len = sizeof(struct ovs_vport_stats) },
[OVS_VPORT_ATTR_PORT_NO] = { .type = NLA_U32 },
[OVS_VPORT_ATTR_TYPE] = { .type = NLA_U32 },
[OVS_VPORT_ATTR_UPCALL_PID] = { .type = NLA_U32 },
[OVS_VPORT_ATTR_OPTIONS] = { .type = NLA_NESTED },
};
static const struct genl_ops dp_vport_genl_ops[] = {
{ .cmd = OVS_VPORT_CMD_NEW,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = vport_policy,
.doit = ovs_vport_cmd_new
},
{ .cmd = OVS_VPORT_CMD_DEL,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = vport_policy,
.doit = ovs_vport_cmd_del
},
{ .cmd = OVS_VPORT_CMD_GET,
.flags = 0, /* OK for unprivileged users. */
.policy = vport_policy,
.doit = ovs_vport_cmd_get,
.dumpit = ovs_vport_cmd_dump
},
{ .cmd = OVS_VPORT_CMD_SET,
.flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
.policy = vport_policy,
.doit = ovs_vport_cmd_set,
},
};
struct genl_family dp_vport_genl_family = {
.id = GENL_ID_GENERATE,
.hdrsize = sizeof(struct ovs_header),
.name = OVS_VPORT_FAMILY,
.version = OVS_VPORT_VERSION,
.maxattr = OVS_VPORT_ATTR_MAX,
.netnsok = true,
.parallel_ops = true,
.ops = dp_vport_genl_ops,
.n_ops = ARRAY_SIZE(dp_vport_genl_ops),
.mcgrps = &ovs_dp_vport_multicast_group,
.n_mcgrps = 1,
};
static struct genl_family * const dp_genl_families[] = {
&dp_datapath_genl_family,
&dp_vport_genl_family,
&dp_flow_genl_family,
&dp_packet_genl_family,
};
static void dp_unregister_genl(int n_families)
{
int i;
for (i = 0; i < n_families; i++)
genl_unregister_family(dp_genl_families[i]);
}
static int dp_register_genl(void)
{
int err;
int i;
for (i = 0; i < ARRAY_SIZE(dp_genl_families); i++) {
err = genl_register_family(dp_genl_families[i]);
if (err)
goto error;
}
return 0;
error:
dp_unregister_genl(i);
return err;
}
static int __net_init ovs_init_net(struct net *net)
{
struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
INIT_LIST_HEAD(&ovs_net->dps);
INIT_WORK(&ovs_net->dp_notify_work, ovs_dp_notify_wq);
return 0;
}
static void __net_exit ovs_exit_net(struct net *net)
{
struct datapath *dp, *dp_next;
struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
ovs_lock();
list_for_each_entry_safe(dp, dp_next, &ovs_net->dps, list_node)
__dp_destroy(dp);
ovs_unlock();
cancel_work_sync(&ovs_net->dp_notify_work);
}
static struct pernet_operations ovs_net_ops = {
.init = ovs_init_net,
.exit = ovs_exit_net,
.id = &ovs_net_id,
.size = sizeof(struct ovs_net),
};
static int __init dp_init(void)
{
int err;
BUILD_BUG_ON(sizeof(struct ovs_skb_cb) > FIELD_SIZEOF(struct sk_buff, cb));
pr_info("Open vSwitch switching datapath\n");
err = action_fifos_init();
if (err)
goto error;
err = ovs_internal_dev_rtnl_link_register();
if (err)
goto error_action_fifos_exit;
err = ovs_flow_init();
if (err)
goto error_unreg_rtnl_link;
err = ovs_vport_init();
if (err)
goto error_flow_exit;
err = register_pernet_device(&ovs_net_ops);
if (err)
goto error_vport_exit;
err = register_netdevice_notifier(&ovs_dp_device_notifier);
if (err)
goto error_netns_exit;
err = ovs_netdev_init();
if (err)
goto error_unreg_notifier;
err = dp_register_genl();
if (err < 0)
goto error_unreg_netdev;
return 0;
error_unreg_netdev:
ovs_netdev_exit();
error_unreg_notifier:
unregister_netdevice_notifier(&ovs_dp_device_notifier);
error_netns_exit:
unregister_pernet_device(&ovs_net_ops);
error_vport_exit:
ovs_vport_exit();
error_flow_exit:
ovs_flow_exit();
error_unreg_rtnl_link:
ovs_internal_dev_rtnl_link_unregister();
error_action_fifos_exit:
action_fifos_exit();
error:
return err;
}
static void dp_cleanup(void)
{
dp_unregister_genl(ARRAY_SIZE(dp_genl_families));
ovs_netdev_exit();
unregister_netdevice_notifier(&ovs_dp_device_notifier);
unregister_pernet_device(&ovs_net_ops);
rcu_barrier();
ovs_vport_exit();
ovs_flow_exit();
ovs_internal_dev_rtnl_link_unregister();
action_fifos_exit();
}
module_init(dp_init);
module_exit(dp_cleanup);
MODULE_DESCRIPTION("Open vSwitch switching datapath");
MODULE_LICENSE("GPL");
| Flipkart/linux | net/openvswitch/datapath.c | C | gpl-2.0 | 53,936 |
/******************************************************************************
* edd.h
*
* Copyright (C) 2002, 2003, 2004 Dell Inc.
* by Matt Domsch <[email protected]>
*
* structures and definitions for the int 13h, ax={41,48}h
* BIOS Enhanced Disk Drive Services
* This is based on the T13 group document D1572 Revision 0 (August 14 2002)
* available at http://www.t13.org/docs2002/d1572r0.pdf. It is
* very similar to D1484 Revision 3 http://www.t13.org/docs2002/d1484r3.pdf
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License v2.0 as published by
* the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef __XEN_EDD_H__
#define __XEN_EDD_H__
#ifndef __ASSEMBLY__
struct __packed edd_info {
/* Int13, Fn48: Check Extensions Present. */
u8 device; /* %dl: device */
u8 version; /* %ah: major version */
u16 interface_support; /* %cx: interface support bitmap */
/* Int13, Fn08: Legacy Get Device Parameters. */
u16 legacy_max_cylinder; /* %cl[7:6]:%ch: maximum cylinder number */
u8 legacy_max_head; /* %dh: maximum head number */
u8 legacy_sectors_per_track; /* %cl[5:0]: maximum sector number */
/* Int13, Fn41: Get Device Parameters (as filled into %ds:%esi). */
struct __packed edd_device_params {
u16 length;
u16 info_flags;
u32 num_default_cylinders;
u32 num_default_heads;
u32 sectors_per_track;
u64 number_of_sectors;
u16 bytes_per_sector;
u32 dpte_ptr; /* 0xFFFFFFFF for our purposes */
u16 key; /* = 0xBEDD */
u8 device_path_info_length;
u8 reserved2;
u16 reserved3;
u8 host_bus_type[4];
u8 interface_type[8];
union {
struct __packed {
u16 base_address;
u16 reserved1;
u32 reserved2;
} isa;
struct __packed {
u8 bus;
u8 slot;
u8 function;
u8 channel;
u32 reserved;
} pci;
/* pcix is same as pci */
struct __packed {
u64 reserved;
} ibnd;
struct __packed {
u64 reserved;
} xprs;
struct __packed {
u64 reserved;
} htpt;
struct __packed {
u64 reserved;
} unknown;
} interface_path;
union {
struct __packed {
u8 device;
u8 reserved1;
u16 reserved2;
u32 reserved3;
u64 reserved4;
} ata;
struct __packed {
u8 device;
u8 lun;
u8 reserved1;
u8 reserved2;
u32 reserved3;
u64 reserved4;
} atapi;
struct __packed {
u16 id;
u64 lun;
u16 reserved1;
u32 reserved2;
} scsi;
struct __packed {
u64 serial_number;
u64 reserved;
} usb;
struct __packed {
u64 eui;
u64 reserved;
} i1394;
struct __packed {
u64 wwid;
u64 lun;
} fibre;
struct __packed {
u64 identity_tag;
u64 reserved;
} i2o;
struct __packed {
u32 array_number;
u32 reserved1;
u64 reserved2;
} raid;
struct __packed {
u8 device;
u8 reserved1;
u16 reserved2;
u32 reserved3;
u64 reserved4;
} sata;
struct __packed {
u64 reserved1;
u64 reserved2;
} unknown;
} device_path;
u8 reserved4;
u8 checksum;
} edd_device_params;
};
struct __packed mbr_signature {
u8 device;
u8 pad[3];
u32 signature;
};
/* These all reside in the boot trampoline. Access via bootsym(). */
extern struct mbr_signature boot_mbr_signature[];
extern u8 boot_mbr_signature_nr;
extern struct edd_info boot_edd_info[];
extern u8 boot_edd_info_nr;
#endif /* __ASSEMBLY__ */
/* Maximum number of EDD information structures at boot_edd_info. */
#define EDD_INFO_MAX 6
/* Maximum number of MBR signatures at boot_mbr_signature. */
#define EDD_MBR_SIG_MAX 16
/* Size of components of EDD information structure. */
#define EDDEXTSIZE 8
#define EDDPARMSIZE 74
#endif /* __XEN_EDD_H__ */
| Chong-Li/RTDS-ToolStack | xen/include/asm-x86/edd.h | C | gpl-2.0 | 5,099 |
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "null-common.h"
namespace capnp {
namespace benchmark {
namespace null {
enum class Operation {
ADD,
SUBTRACT,
MULTIPLY,
DIVIDE,
MODULUS
};
uint OPERATION_RANGE = static_cast<uint>(Operation::MODULUS) + 1;
struct Expression {
Operation op;
bool leftIsValue;
bool rightIsValue;
union {
int32_t leftValue;
Expression* leftExpression;
};
union {
int32_t rightValue;
Expression* rightExpression;
};
};
int32_t makeExpression(Expression* exp, uint depth) {
exp->op = (Operation)(fastRand(OPERATION_RANGE));
int32_t left, right;
if (fastRand(8) < depth) {
exp->leftIsValue = true;
left = fastRand(128) + 1;
exp->leftValue = left;
} else {
exp->leftIsValue = false;
exp->leftExpression = allocate<Expression>();
left = makeExpression(exp->leftExpression, depth + 1);
}
if (fastRand(8) < depth) {
exp->rightIsValue = true;
right = fastRand(128) + 1;
exp->rightValue = right;
} else {
exp->rightIsValue = false;
exp->rightExpression = allocate<Expression>();
right = makeExpression(exp->rightExpression, depth + 1);
}
switch (exp->op) {
case Operation::ADD:
return left + right;
case Operation::SUBTRACT:
return left - right;
case Operation::MULTIPLY:
return left * right;
case Operation::DIVIDE:
return div(left, right);
case Operation::MODULUS:
return mod(left, right);
}
throw std::logic_error("Can't get here.");
}
int32_t evaluateExpression(const Expression& exp) {
uint32_t left, right;
if (exp.leftIsValue) {
left = exp.leftValue;
} else {
left = evaluateExpression(*exp.leftExpression);
}
if (exp.rightIsValue) {
right = exp.rightValue;
} else {
right = evaluateExpression(*exp.rightExpression);
}
switch (exp.op) {
case Operation::ADD:
return left + right;
case Operation::SUBTRACT:
return left - right;
case Operation::MULTIPLY:
return left * right;
case Operation::DIVIDE:
return div(left, right);
case Operation::MODULUS:
return mod(left, right);
}
throw std::logic_error("Can't get here.");
}
class ExpressionTestCase {
public:
typedef Expression Request;
typedef int32_t Response;
typedef int32_t Expectation;
static inline int32_t setupRequest(Expression* request) {
return makeExpression(request, 0);
}
static inline void handleRequest(const Expression& request, int32_t* response) {
*response = evaluateExpression(request);
}
static inline bool checkResponse(int32_t response, int32_t expected) {
return response == expected;
}
static size_t spaceUsed(const Expression& expression) {
return sizeof(Expression) +
(expression.leftExpression == nullptr ? 0 : spaceUsed(*expression.leftExpression)) +
(expression.rightExpression == nullptr ? 0 : spaceUsed(*expression.rightExpression));
}
};
} // namespace null
} // namespace benchmark
} // namespace capnp
int main(int argc, char* argv[]) {
return capnp::benchmark::benchmarkMain<
capnp::benchmark::null::BenchmarkTypes,
capnp::benchmark::null::ExpressionTestCase>(argc, argv);
}
| yingjunwu/peloton | third_party/capnproto/c++/src/benchmark/null-eval.c++ | C++ | apache-2.0 | 4,371 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Reference: ::marker pseudo elements styled with 'content' property</title>
<link rel="author" title="Mats Palmgren" href="mailto:[email protected]">
<style>
span { font-size: 32pt; }
</style>
</head>
<body>
<ol><li></li><li>B</li><li><span>C</span></li></ol>
</body>
</html>
| scheib/chromium | third_party/blink/web_tests/external/wpt/css/css-pseudo/marker-content-001-ref.html | HTML | bsd-3-clause | 338 |
/*
* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 only,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is included
* in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; If not, see
* http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* GPL HEADER END
*/
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*
* Copyright (c) 2012, Intel Corporation.
*/
/*
* This file is part of Lustre, http://www.lustre.org/
* Lustre is a trademark of Sun Microsystems, Inc.
*/
#define DEBUG_SUBSYSTEM S_LOV
#include <linux/libcfs/libcfs.h>
#include <obd_class.h>
#include <obd_lov.h>
#include "lov_internal.h"
/** Merge the lock value block(&lvb) attributes and KMS from each of the
* stripes in a file into a single lvb. It is expected that the caller
* initializes the current atime, mtime, ctime to avoid regressing a more
* uptodate time on the local client.
*/
int lov_merge_lvb_kms(struct lov_stripe_md *lsm,
struct ost_lvb *lvb, __u64 *kms_place)
{
__u64 size = 0;
__u64 kms = 0;
__u64 blocks = 0;
obd_time current_mtime = lvb->lvb_mtime;
obd_time current_atime = lvb->lvb_atime;
obd_time current_ctime = lvb->lvb_ctime;
int i;
int rc = 0;
LASSERT(spin_is_locked(&lsm->lsm_lock));
LASSERT(lsm->lsm_lock_owner == current_pid());
CDEBUG(D_INODE, "MDT ID "DOSTID" initial value: s="LPU64" m="LPU64
" a="LPU64" c="LPU64" b="LPU64"\n", POSTID(&lsm->lsm_oi),
lvb->lvb_size, lvb->lvb_mtime, lvb->lvb_atime, lvb->lvb_ctime,
lvb->lvb_blocks);
for (i = 0; i < lsm->lsm_stripe_count; i++) {
struct lov_oinfo *loi = lsm->lsm_oinfo[i];
obd_size lov_size, tmpsize;
if (OST_LVB_IS_ERR(loi->loi_lvb.lvb_blocks)) {
rc = OST_LVB_GET_ERR(loi->loi_lvb.lvb_blocks);
continue;
}
tmpsize = loi->loi_kms;
lov_size = lov_stripe_size(lsm, tmpsize, i);
if (lov_size > kms)
kms = lov_size;
if (loi->loi_lvb.lvb_size > tmpsize)
tmpsize = loi->loi_lvb.lvb_size;
lov_size = lov_stripe_size(lsm, tmpsize, i);
if (lov_size > size)
size = lov_size;
/* merge blocks, mtime, atime */
blocks += loi->loi_lvb.lvb_blocks;
if (loi->loi_lvb.lvb_mtime > current_mtime)
current_mtime = loi->loi_lvb.lvb_mtime;
if (loi->loi_lvb.lvb_atime > current_atime)
current_atime = loi->loi_lvb.lvb_atime;
if (loi->loi_lvb.lvb_ctime > current_ctime)
current_ctime = loi->loi_lvb.lvb_ctime;
CDEBUG(D_INODE, "MDT ID "DOSTID" on OST[%u]: s="LPU64" m="LPU64
" a="LPU64" c="LPU64" b="LPU64"\n", POSTID(&lsm->lsm_oi),
loi->loi_ost_idx, loi->loi_lvb.lvb_size,
loi->loi_lvb.lvb_mtime, loi->loi_lvb.lvb_atime,
loi->loi_lvb.lvb_ctime, loi->loi_lvb.lvb_blocks);
}
*kms_place = kms;
lvb->lvb_size = size;
lvb->lvb_blocks = blocks;
lvb->lvb_mtime = current_mtime;
lvb->lvb_atime = current_atime;
lvb->lvb_ctime = current_ctime;
return rc;
}
/** Merge the lock value block(&lvb) attributes from each of the stripes in a
* file into a single lvb. It is expected that the caller initializes the
* current atime, mtime, ctime to avoid regressing a more uptodate time on
* the local client.
*
* If \a kms_only is set then we do not consider the recently seen size (rss)
* when updating the known minimum size (kms). Even when merging RSS, we will
* take the KMS value if it's larger. This prevents getattr from stomping on
* dirty cached pages which extend the file size. */
int lov_merge_lvb(struct obd_export *exp,
struct lov_stripe_md *lsm, struct ost_lvb *lvb, int kms_only)
{
int rc;
__u64 kms;
lov_stripe_lock(lsm);
rc = lov_merge_lvb_kms(lsm, lvb, &kms);
lov_stripe_unlock(lsm);
if (kms_only)
lvb->lvb_size = kms;
CDEBUG(D_INODE, "merged for ID "DOSTID" s="LPU64" m="LPU64" a="LPU64
" c="LPU64" b="LPU64"\n", POSTID(&lsm->lsm_oi), lvb->lvb_size,
lvb->lvb_mtime, lvb->lvb_atime, lvb->lvb_ctime, lvb->lvb_blocks);
return rc;
}
/* Must be called under the lov_stripe_lock() */
int lov_adjust_kms(struct obd_export *exp, struct lov_stripe_md *lsm,
obd_off size, int shrink)
{
struct lov_oinfo *loi;
int stripe = 0;
__u64 kms;
LASSERT(spin_is_locked(&lsm->lsm_lock));
LASSERT(lsm->lsm_lock_owner == current_pid());
if (shrink) {
for (; stripe < lsm->lsm_stripe_count; stripe++) {
struct lov_oinfo *loi = lsm->lsm_oinfo[stripe];
kms = lov_size_to_stripe(lsm, size, stripe);
CDEBUG(D_INODE,
"stripe %d KMS %sing "LPU64"->"LPU64"\n",
stripe, kms > loi->loi_kms ? "increase":"shrink",
loi->loi_kms, kms);
loi_kms_set(loi, loi->loi_lvb.lvb_size = kms);
}
return 0;
}
if (size > 0)
stripe = lov_stripe_number(lsm, size - 1);
kms = lov_size_to_stripe(lsm, size, stripe);
loi = lsm->lsm_oinfo[stripe];
CDEBUG(D_INODE, "stripe %d KMS %sincreasing "LPU64"->"LPU64"\n",
stripe, kms > loi->loi_kms ? "" : "not ", loi->loi_kms, kms);
if (kms > loi->loi_kms)
loi_kms_set(loi, kms);
return 0;
}
void lov_merge_attrs(struct obdo *tgt, struct obdo *src, obd_valid valid,
struct lov_stripe_md *lsm, int stripeno, int *set)
{
valid &= src->o_valid;
if (*set) {
if (valid & OBD_MD_FLSIZE) {
/* this handles sparse files properly */
obd_size lov_size;
lov_size = lov_stripe_size(lsm, src->o_size, stripeno);
if (lov_size > tgt->o_size)
tgt->o_size = lov_size;
}
if (valid & OBD_MD_FLBLOCKS)
tgt->o_blocks += src->o_blocks;
if (valid & OBD_MD_FLBLKSZ)
tgt->o_blksize += src->o_blksize;
if (valid & OBD_MD_FLCTIME && tgt->o_ctime < src->o_ctime)
tgt->o_ctime = src->o_ctime;
if (valid & OBD_MD_FLMTIME && tgt->o_mtime < src->o_mtime)
tgt->o_mtime = src->o_mtime;
if (valid & OBD_MD_FLDATAVERSION)
tgt->o_data_version += src->o_data_version;
} else {
memcpy(tgt, src, sizeof(*tgt));
tgt->o_oi = lsm->lsm_oi;
if (valid & OBD_MD_FLSIZE)
tgt->o_size = lov_stripe_size(lsm, src->o_size,
stripeno);
}
/* data_version needs to be valid on all stripes to be correct! */
if (!(valid & OBD_MD_FLDATAVERSION))
tgt->o_valid &= ~OBD_MD_FLDATAVERSION;
*set += 1;
}
| iwinoto/v4l-media_build-devel | media/drivers/staging/lustre/lustre/lov/lov_merge.c | C | gpl-2.0 | 6,848 |
# -*- coding: utf-8 -*-
"""
flask.testsuite.helpers
~~~~~~~~~~~~~~~~~~~~~~~
Various helpers.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
import os
import flask
import unittest
from logging import StreamHandler
from StringIO import StringIO
from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr
from werkzeug.http import parse_cache_control_header, parse_options_header
def has_encoding(name):
try:
import codecs
codecs.lookup(name)
return True
except LookupError:
return False
class JSONTestCase(FlaskTestCase):
def test_json_bad_requests(self):
app = flask.Flask(__name__)
@app.route('/json', methods=['POST'])
def return_json():
return unicode(flask.request.json)
c = app.test_client()
rv = c.post('/json', data='malformed', content_type='application/json')
self.assert_equal(rv.status_code, 400)
def test_json_bad_requests_content_type(self):
app = flask.Flask(__name__)
@app.route('/json', methods=['POST'])
def return_json():
return unicode(flask.request.json)
c = app.test_client()
rv = c.post('/json', data='malformed', content_type='application/json')
self.assert_equal(rv.status_code, 400)
self.assert_equal(rv.mimetype, 'application/json')
self.assert_('description' in flask.json.loads(rv.data))
self.assert_('<p>' not in flask.json.loads(rv.data)['description'])
def test_json_body_encoding(self):
app = flask.Flask(__name__)
app.testing = True
@app.route('/')
def index():
return flask.request.json
c = app.test_client()
resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),
content_type='application/json; charset=iso-8859-15')
self.assert_equal(resp.data, u'Hällo Wörld'.encode('utf-8'))
def test_jsonify(self):
d = dict(a=23, b=42, c=[1, 2, 3])
app = flask.Flask(__name__)
@app.route('/kw')
def return_kwargs():
return flask.jsonify(**d)
@app.route('/dict')
def return_dict():
return flask.jsonify(d)
c = app.test_client()
for url in '/kw', '/dict':
rv = c.get(url)
self.assert_equal(rv.mimetype, 'application/json')
self.assert_equal(flask.json.loads(rv.data), d)
def test_json_attr(self):
app = flask.Flask(__name__)
@app.route('/add', methods=['POST'])
def add():
return unicode(flask.request.json['a'] + flask.request.json['b'])
c = app.test_client()
rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),
content_type='application/json')
self.assert_equal(rv.data, '3')
def test_template_escaping(self):
app = flask.Flask(__name__)
render = flask.render_template_string
with app.test_request_context():
rv = render('{{ "</script>"|tojson|safe }}')
self.assert_equal(rv, '"<\\/script>"')
rv = render('{{ "<\0/script>"|tojson|safe }}')
self.assert_equal(rv, '"<\\u0000\\/script>"')
def test_modified_url_encoding(self):
class ModifiedRequest(flask.Request):
url_charset = 'euc-kr'
app = flask.Flask(__name__)
app.request_class = ModifiedRequest
app.url_map.charset = 'euc-kr'
@app.route('/')
def index():
return flask.request.args['foo']
rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))
self.assert_equal(rv.status_code, 200)
self.assert_equal(rv.data, u'정상처리'.encode('utf-8'))
if not has_encoding('euc-kr'):
test_modified_url_encoding = None
class SendfileTestCase(FlaskTestCase):
def test_send_file_regular(self):
app = flask.Flask(__name__)
with app.test_request_context():
rv = flask.send_file('static/index.html')
self.assert_(rv.direct_passthrough)
self.assert_equal(rv.mimetype, 'text/html')
with app.open_resource('static/index.html') as f:
self.assert_equal(rv.data, f.read())
def test_send_file_xsendfile(self):
app = flask.Flask(__name__)
app.use_x_sendfile = True
with app.test_request_context():
rv = flask.send_file('static/index.html')
self.assert_(rv.direct_passthrough)
self.assert_('x-sendfile' in rv.headers)
self.assert_equal(rv.headers['x-sendfile'],
os.path.join(app.root_path, 'static/index.html'))
self.assert_equal(rv.mimetype, 'text/html')
def test_send_file_object(self):
app = flask.Flask(__name__)
with catch_warnings() as captured:
with app.test_request_context():
f = open(os.path.join(app.root_path, 'static/index.html'))
rv = flask.send_file(f)
with app.open_resource('static/index.html') as f:
self.assert_equal(rv.data, f.read())
self.assert_equal(rv.mimetype, 'text/html')
# mimetypes + etag
self.assert_equal(len(captured), 2)
app.use_x_sendfile = True
with catch_warnings() as captured:
with app.test_request_context():
f = open(os.path.join(app.root_path, 'static/index.html'))
rv = flask.send_file(f)
self.assert_equal(rv.mimetype, 'text/html')
self.assert_('x-sendfile' in rv.headers)
self.assert_equal(rv.headers['x-sendfile'],
os.path.join(app.root_path, 'static/index.html'))
# mimetypes + etag
self.assert_equal(len(captured), 2)
app.use_x_sendfile = False
with app.test_request_context():
with catch_warnings() as captured:
f = StringIO('Test')
rv = flask.send_file(f)
self.assert_equal(rv.data, 'Test')
self.assert_equal(rv.mimetype, 'application/octet-stream')
# etags
self.assert_equal(len(captured), 1)
with catch_warnings() as captured:
f = StringIO('Test')
rv = flask.send_file(f, mimetype='text/plain')
self.assert_equal(rv.data, 'Test')
self.assert_equal(rv.mimetype, 'text/plain')
# etags
self.assert_equal(len(captured), 1)
app.use_x_sendfile = True
with catch_warnings() as captured:
with app.test_request_context():
f = StringIO('Test')
rv = flask.send_file(f)
self.assert_('x-sendfile' not in rv.headers)
# etags
self.assert_equal(len(captured), 1)
def test_attachment(self):
app = flask.Flask(__name__)
with catch_warnings() as captured:
with app.test_request_context():
f = open(os.path.join(app.root_path, 'static/index.html'))
rv = flask.send_file(f, as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment')
# mimetypes + etag
self.assert_equal(len(captured), 2)
with app.test_request_context():
self.assert_equal(options['filename'], 'index.html')
rv = flask.send_file('static/index.html', as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment')
self.assert_equal(options['filename'], 'index.html')
with app.test_request_context():
rv = flask.send_file(StringIO('Test'), as_attachment=True,
attachment_filename='index.txt',
add_etags=False)
self.assert_equal(rv.mimetype, 'text/plain')
value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment')
self.assert_equal(options['filename'], 'index.txt')
def test_static_file(self):
app = flask.Flask(__name__)
# default cache timeout is 12 hours
with app.test_request_context():
# Test with static file handler.
rv = app.send_static_file('index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 12 * 60 * 60)
# Test again with direct use of send_file utility.
rv = flask.send_file('static/index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 12 * 60 * 60)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600
with app.test_request_context():
# Test with static file handler.
rv = app.send_static_file('index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 3600)
# Test again with direct use of send_file utility.
rv = flask.send_file('static/index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 3600)
class StaticFileApp(flask.Flask):
def get_send_file_max_age(self, filename):
return 10
app = StaticFileApp(__name__)
with app.test_request_context():
# Test with static file handler.
rv = app.send_static_file('index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 10)
# Test again with direct use of send_file utility.
rv = flask.send_file('static/index.html')
cc = parse_cache_control_header(rv.headers['Cache-Control'])
self.assert_equal(cc.max_age, 10)
class LoggingTestCase(FlaskTestCase):
def test_logger_cache(self):
app = flask.Flask(__name__)
logger1 = app.logger
self.assert_(app.logger is logger1)
self.assert_equal(logger1.name, __name__)
app.logger_name = __name__ + '/test_logger_cache'
self.assert_(app.logger is not logger1)
def test_debug_log(self):
app = flask.Flask(__name__)
app.debug = True
@app.route('/')
def index():
app.logger.warning('the standard library is dead')
app.logger.debug('this is a debug statement')
return ''
@app.route('/exc')
def exc():
1/0
with app.test_client() as c:
with catch_stderr() as err:
c.get('/')
out = err.getvalue()
self.assert_('WARNING in helpers [' in out)
self.assert_(os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out)
self.assert_('the standard library is dead' in out)
self.assert_('this is a debug statement' in out)
with catch_stderr() as err:
try:
c.get('/exc')
except ZeroDivisionError:
pass
else:
self.assert_(False, 'debug log ate the exception')
def test_debug_log_override(self):
app = flask.Flask(__name__)
app.debug = True
app.logger_name = 'flask_tests/test_debug_log_override'
app.logger.level = 10
self.assert_equal(app.logger.level, 10)
def test_exception_logging(self):
out = StringIO()
app = flask.Flask(__name__)
app.logger_name = 'flask_tests/test_exception_logging'
app.logger.addHandler(StreamHandler(out))
@app.route('/')
def index():
1/0
rv = app.test_client().get('/')
self.assert_equal(rv.status_code, 500)
self.assert_('Internal Server Error' in rv.data)
err = out.getvalue()
self.assert_('Exception on / [GET]' in err)
self.assert_('Traceback (most recent call last):' in err)
self.assert_('1/0' in err)
self.assert_('ZeroDivisionError:' in err)
def test_processor_exceptions(self):
app = flask.Flask(__name__)
@app.before_request
def before_request():
if trigger == 'before':
1/0
@app.after_request
def after_request(response):
if trigger == 'after':
1/0
return response
@app.route('/')
def index():
return 'Foo'
@app.errorhandler(500)
def internal_server_error(e):
return 'Hello Server Error', 500
for trigger in 'before', 'after':
rv = app.test_client().get('/')
self.assert_equal(rv.status_code, 500)
self.assert_equal(rv.data, 'Hello Server Error')
def test_url_for_with_anchor(self):
app = flask.Flask(__name__)
@app.route('/')
def index():
return '42'
with app.test_request_context():
self.assert_equal(flask.url_for('index', _anchor='x y'),
'/#x%20y')
def test_url_with_method(self):
from flask.views import MethodView
app = flask.Flask(__name__)
class MyView(MethodView):
def get(self, id=None):
if id is None:
return 'List'
return 'Get %d' % id
def post(self):
return 'Create'
myview = MyView.as_view('myview')
app.add_url_rule('/myview/', methods=['GET'],
view_func=myview)
app.add_url_rule('/myview/<int:id>', methods=['GET'],
view_func=myview)
app.add_url_rule('/myview/create', methods=['POST'],
view_func=myview)
with app.test_request_context():
self.assert_equal(flask.url_for('myview', _method='GET'),
'/myview/')
self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
'/myview/42')
self.assert_equal(flask.url_for('myview', _method='POST'),
'/myview/create')
class NoImportsTestCase(FlaskTestCase):
"""Test Flasks are created without import.
Avoiding ``__import__`` helps create Flask instances where there are errors
at import time. Those runtime errors will be apparent to the user soon
enough, but tools which build Flask instances meta-programmatically benefit
from a Flask which does not ``__import__``. Instead of importing to
retrieve file paths or metadata on a module or package, use the pkgutil and
imp modules in the Python standard library.
"""
def test_name_with_import_error(self):
try:
flask.Flask('importerror')
except NotImplementedError:
self.fail('Flask(import_name) is importing import_name.')
class StreamingTestCase(FlaskTestCase):
def test_streaming_with_context(self):
app = flask.Flask(__name__)
app.testing = True
@app.route('/')
def index():
def generate():
yield 'Hello '
yield flask.request.args['name']
yield '!'
return flask.Response(flask.stream_with_context(generate()))
c = app.test_client()
rv = c.get('/?name=World')
self.assertEqual(rv.data, 'Hello World!')
def test_streaming_with_context_as_decorator(self):
app = flask.Flask(__name__)
app.testing = True
@app.route('/')
def index():
@flask.stream_with_context
def generate():
yield 'Hello '
yield flask.request.args['name']
yield '!'
return flask.Response(generate())
c = app.test_client()
rv = c.get('/?name=World')
self.assertEqual(rv.data, 'Hello World!')
def test_streaming_with_context_and_custom_close(self):
app = flask.Flask(__name__)
app.testing = True
called = []
class Wrapper(object):
def __init__(self, gen):
self._gen = gen
def __iter__(self):
return self
def close(self):
called.append(42)
def next(self):
return self._gen.next()
@app.route('/')
def index():
def generate():
yield 'Hello '
yield flask.request.args['name']
yield '!'
return flask.Response(flask.stream_with_context(
Wrapper(generate())))
c = app.test_client()
rv = c.get('/?name=World')
self.assertEqual(rv.data, 'Hello World!')
self.assertEqual(called, [42])
def suite():
suite = unittest.TestSuite()
if flask.json_available:
suite.addTest(unittest.makeSuite(JSONTestCase))
suite.addTest(unittest.makeSuite(SendfileTestCase))
suite.addTest(unittest.makeSuite(LoggingTestCase))
suite.addTest(unittest.makeSuite(NoImportsTestCase))
suite.addTest(unittest.makeSuite(StreamingTestCase))
return suite
| SohKai/ChronoLogger | web/flask/lib/python2.7/site-packages/flask/testsuite/helpers.py | Python | mit | 17,585 |
/*
* probe.c - PCI detection and setup code
*/
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/cpumask.h>
#include <linux/pci-aspm.h>
#include <asm-generic/pci-bridge.h>
#include "pci.h"
#define CARDBUS_LATENCY_TIMER 176 /* secondary latency timer */
#define CARDBUS_RESERVE_BUSNR 3
struct resource busn_resource = {
.name = "PCI busn",
.start = 0,
.end = 255,
.flags = IORESOURCE_BUS,
};
/* Ugh. Need to stop exporting this to modules. */
LIST_HEAD(pci_root_buses);
EXPORT_SYMBOL(pci_root_buses);
static LIST_HEAD(pci_domain_busn_res_list);
struct pci_domain_busn_res {
struct list_head list;
struct resource res;
int domain_nr;
};
static struct resource *get_pci_domain_busn_res(int domain_nr)
{
struct pci_domain_busn_res *r;
list_for_each_entry(r, &pci_domain_busn_res_list, list)
if (r->domain_nr == domain_nr)
return &r->res;
r = kzalloc(sizeof(*r), GFP_KERNEL);
if (!r)
return NULL;
r->domain_nr = domain_nr;
r->res.start = 0;
r->res.end = 0xff;
r->res.flags = IORESOURCE_BUS | IORESOURCE_PCI_FIXED;
list_add_tail(&r->list, &pci_domain_busn_res_list);
return &r->res;
}
static int find_anything(struct device *dev, void *data)
{
return 1;
}
/*
* Some device drivers need know if pci is initiated.
* Basically, we think pci is not initiated when there
* is no device to be found on the pci_bus_type.
*/
int no_pci_devices(void)
{
struct device *dev;
int no_devices;
dev = bus_find_device(&pci_bus_type, NULL, NULL, find_anything);
no_devices = (dev == NULL);
put_device(dev);
return no_devices;
}
EXPORT_SYMBOL(no_pci_devices);
/*
* PCI Bus Class
*/
static void release_pcibus_dev(struct device *dev)
{
struct pci_bus *pci_bus = to_pci_bus(dev);
if (pci_bus->bridge)
put_device(pci_bus->bridge);
pci_bus_remove_resources(pci_bus);
pci_release_bus_of_node(pci_bus);
kfree(pci_bus);
}
static struct class pcibus_class = {
.name = "pci_bus",
.dev_release = &release_pcibus_dev,
.dev_attrs = pcibus_dev_attrs,
};
static int __init pcibus_class_init(void)
{
return class_register(&pcibus_class);
}
postcore_initcall(pcibus_class_init);
static u64 pci_size(u64 base, u64 maxbase, u64 mask)
{
u64 size = mask & maxbase; /* Find the significant bits */
if (!size)
return 0;
/* Get the lowest of them to find the decode size, and
from that the extent. */
size = (size & ~(size-1)) - 1;
/* base == maxbase can be valid only if the BAR has
already been programmed with all 1s. */
if (base == maxbase && ((base | size) & mask) != mask)
return 0;
return size;
}
static inline unsigned long decode_bar(struct pci_dev *dev, u32 bar)
{
u32 mem_type;
unsigned long flags;
if ((bar & PCI_BASE_ADDRESS_SPACE) == PCI_BASE_ADDRESS_SPACE_IO) {
flags = bar & ~PCI_BASE_ADDRESS_IO_MASK;
flags |= IORESOURCE_IO;
return flags;
}
flags = bar & ~PCI_BASE_ADDRESS_MEM_MASK;
flags |= IORESOURCE_MEM;
if (flags & PCI_BASE_ADDRESS_MEM_PREFETCH)
flags |= IORESOURCE_PREFETCH;
mem_type = bar & PCI_BASE_ADDRESS_MEM_TYPE_MASK;
switch (mem_type) {
case PCI_BASE_ADDRESS_MEM_TYPE_32:
break;
case PCI_BASE_ADDRESS_MEM_TYPE_1M:
/* 1M mem BAR treated as 32-bit BAR */
break;
case PCI_BASE_ADDRESS_MEM_TYPE_64:
flags |= IORESOURCE_MEM_64;
break;
default:
/* mem unknown type treated as 32-bit BAR */
break;
}
return flags;
}
/**
* pci_read_base - read a PCI BAR
* @dev: the PCI device
* @type: type of the BAR
* @res: resource buffer to be filled in
* @pos: BAR position in the config space
*
* Returns 1 if the BAR is 64-bit, or 0 if 32-bit.
*/
int __pci_read_base(struct pci_dev *dev, enum pci_bar_type type,
struct resource *res, unsigned int pos)
{
u32 l, sz, mask;
u16 orig_cmd;
struct pci_bus_region region;
bool bar_too_big = false, bar_disabled = false;
mask = type ? PCI_ROM_ADDRESS_MASK : ~0;
/* No printks while decoding is disabled! */
if (!dev->mmio_always_on) {
pci_read_config_word(dev, PCI_COMMAND, &orig_cmd);
pci_write_config_word(dev, PCI_COMMAND,
orig_cmd & ~(PCI_COMMAND_MEMORY | PCI_COMMAND_IO));
}
res->name = pci_name(dev);
pci_read_config_dword(dev, pos, &l);
pci_write_config_dword(dev, pos, l | mask);
pci_read_config_dword(dev, pos, &sz);
pci_write_config_dword(dev, pos, l);
/*
* All bits set in sz means the device isn't working properly.
* If the BAR isn't implemented, all bits must be 0. If it's a
* memory BAR or a ROM, bit 0 must be clear; if it's an io BAR, bit
* 1 must be clear.
*/
if (!sz || sz == 0xffffffff)
goto fail;
/*
* I don't know how l can have all bits set. Copied from old code.
* Maybe it fixes a bug on some ancient platform.
*/
if (l == 0xffffffff)
l = 0;
if (type == pci_bar_unknown) {
res->flags = decode_bar(dev, l);
res->flags |= IORESOURCE_SIZEALIGN;
if (res->flags & IORESOURCE_IO) {
l &= PCI_BASE_ADDRESS_IO_MASK;
mask = PCI_BASE_ADDRESS_IO_MASK & (u32) IO_SPACE_LIMIT;
} else {
l &= PCI_BASE_ADDRESS_MEM_MASK;
mask = (u32)PCI_BASE_ADDRESS_MEM_MASK;
}
} else {
res->flags |= (l & IORESOURCE_ROM_ENABLE);
l &= PCI_ROM_ADDRESS_MASK;
mask = (u32)PCI_ROM_ADDRESS_MASK;
}
if (res->flags & IORESOURCE_MEM_64) {
u64 l64 = l;
u64 sz64 = sz;
u64 mask64 = mask | (u64)~0 << 32;
pci_read_config_dword(dev, pos + 4, &l);
pci_write_config_dword(dev, pos + 4, ~0);
pci_read_config_dword(dev, pos + 4, &sz);
pci_write_config_dword(dev, pos + 4, l);
l64 |= ((u64)l << 32);
sz64 |= ((u64)sz << 32);
sz64 = pci_size(l64, sz64, mask64);
if (!sz64)
goto fail;
if ((sizeof(resource_size_t) < 8) && (sz64 > 0x100000000ULL)) {
bar_too_big = true;
goto fail;
}
if ((sizeof(resource_size_t) < 8) && l) {
/* Address above 32-bit boundary; disable the BAR */
pci_write_config_dword(dev, pos, 0);
pci_write_config_dword(dev, pos + 4, 0);
region.start = 0;
region.end = sz64;
pcibios_bus_to_resource(dev, res, ®ion);
bar_disabled = true;
} else {
region.start = l64;
region.end = l64 + sz64;
pcibios_bus_to_resource(dev, res, ®ion);
}
} else {
sz = pci_size(l, sz, mask);
if (!sz)
goto fail;
region.start = l;
region.end = l + sz;
pcibios_bus_to_resource(dev, res, ®ion);
}
goto out;
fail:
res->flags = 0;
out:
if (!dev->mmio_always_on)
pci_write_config_word(dev, PCI_COMMAND, orig_cmd);
if (bar_too_big)
dev_err(&dev->dev, "reg %x: can't handle 64-bit BAR\n", pos);
if (res->flags && !bar_disabled)
dev_printk(KERN_DEBUG, &dev->dev, "reg %x: %pR\n", pos, res);
return (res->flags & IORESOURCE_MEM_64) ? 1 : 0;
}
static void pci_read_bases(struct pci_dev *dev, unsigned int howmany, int rom)
{
unsigned int pos, reg;
for (pos = 0; pos < howmany; pos++) {
struct resource *res = &dev->resource[pos];
reg = PCI_BASE_ADDRESS_0 + (pos << 2);
pos += __pci_read_base(dev, pci_bar_unknown, res, reg);
}
if (rom) {
struct resource *res = &dev->resource[PCI_ROM_RESOURCE];
dev->rom_base_reg = rom;
res->flags = IORESOURCE_MEM | IORESOURCE_PREFETCH |
IORESOURCE_READONLY | IORESOURCE_CACHEABLE |
IORESOURCE_SIZEALIGN;
__pci_read_base(dev, pci_bar_mem32, res, rom);
}
}
static void __devinit pci_read_bridge_io(struct pci_bus *child)
{
struct pci_dev *dev = child->self;
u8 io_base_lo, io_limit_lo;
unsigned long io_mask, io_granularity, base, limit;
struct pci_bus_region region;
struct resource *res;
io_mask = PCI_IO_RANGE_MASK;
io_granularity = 0x1000;
if (dev->io_window_1k) {
/* Support 1K I/O space granularity */
io_mask = PCI_IO_1K_RANGE_MASK;
io_granularity = 0x400;
}
res = child->resource[0];
pci_read_config_byte(dev, PCI_IO_BASE, &io_base_lo);
pci_read_config_byte(dev, PCI_IO_LIMIT, &io_limit_lo);
base = (io_base_lo & io_mask) << 8;
limit = (io_limit_lo & io_mask) << 8;
if ((io_base_lo & PCI_IO_RANGE_TYPE_MASK) == PCI_IO_RANGE_TYPE_32) {
u16 io_base_hi, io_limit_hi;
pci_read_config_word(dev, PCI_IO_BASE_UPPER16, &io_base_hi);
pci_read_config_word(dev, PCI_IO_LIMIT_UPPER16, &io_limit_hi);
base |= ((unsigned long) io_base_hi << 16);
limit |= ((unsigned long) io_limit_hi << 16);
}
if (base <= limit) {
res->flags = (io_base_lo & PCI_IO_RANGE_TYPE_MASK) | IORESOURCE_IO;
region.start = base;
region.end = limit + io_granularity - 1;
pcibios_bus_to_resource(dev, res, ®ion);
dev_printk(KERN_DEBUG, &dev->dev, " bridge window %pR\n", res);
}
}
static void __devinit pci_read_bridge_mmio(struct pci_bus *child)
{
struct pci_dev *dev = child->self;
u16 mem_base_lo, mem_limit_lo;
unsigned long base, limit;
struct pci_bus_region region;
struct resource *res;
res = child->resource[1];
pci_read_config_word(dev, PCI_MEMORY_BASE, &mem_base_lo);
pci_read_config_word(dev, PCI_MEMORY_LIMIT, &mem_limit_lo);
base = ((unsigned long) mem_base_lo & PCI_MEMORY_RANGE_MASK) << 16;
limit = ((unsigned long) mem_limit_lo & PCI_MEMORY_RANGE_MASK) << 16;
if (base <= limit) {
res->flags = (mem_base_lo & PCI_MEMORY_RANGE_TYPE_MASK) | IORESOURCE_MEM;
region.start = base;
region.end = limit + 0xfffff;
pcibios_bus_to_resource(dev, res, ®ion);
dev_printk(KERN_DEBUG, &dev->dev, " bridge window %pR\n", res);
}
}
static void __devinit pci_read_bridge_mmio_pref(struct pci_bus *child)
{
struct pci_dev *dev = child->self;
u16 mem_base_lo, mem_limit_lo;
unsigned long base, limit;
struct pci_bus_region region;
struct resource *res;
res = child->resource[2];
pci_read_config_word(dev, PCI_PREF_MEMORY_BASE, &mem_base_lo);
pci_read_config_word(dev, PCI_PREF_MEMORY_LIMIT, &mem_limit_lo);
base = ((unsigned long) mem_base_lo & PCI_PREF_RANGE_MASK) << 16;
limit = ((unsigned long) mem_limit_lo & PCI_PREF_RANGE_MASK) << 16;
if ((mem_base_lo & PCI_PREF_RANGE_TYPE_MASK) == PCI_PREF_RANGE_TYPE_64) {
u32 mem_base_hi, mem_limit_hi;
pci_read_config_dword(dev, PCI_PREF_BASE_UPPER32, &mem_base_hi);
pci_read_config_dword(dev, PCI_PREF_LIMIT_UPPER32, &mem_limit_hi);
/*
* Some bridges set the base > limit by default, and some
* (broken) BIOSes do not initialize them. If we find
* this, just assume they are not being used.
*/
if (mem_base_hi <= mem_limit_hi) {
#if BITS_PER_LONG == 64
base |= ((unsigned long) mem_base_hi) << 32;
limit |= ((unsigned long) mem_limit_hi) << 32;
#else
if (mem_base_hi || mem_limit_hi) {
dev_err(&dev->dev, "can't handle 64-bit "
"address space for bridge\n");
return;
}
#endif
}
}
if (base <= limit) {
res->flags = (mem_base_lo & PCI_PREF_RANGE_TYPE_MASK) |
IORESOURCE_MEM | IORESOURCE_PREFETCH;
if (res->flags & PCI_PREF_RANGE_TYPE_64)
res->flags |= IORESOURCE_MEM_64;
region.start = base;
region.end = limit + 0xfffff;
pcibios_bus_to_resource(dev, res, ®ion);
dev_printk(KERN_DEBUG, &dev->dev, " bridge window %pR\n", res);
}
}
void __devinit pci_read_bridge_bases(struct pci_bus *child)
{
struct pci_dev *dev = child->self;
struct resource *res;
int i;
if (pci_is_root_bus(child)) /* It's a host bus, nothing to read */
return;
dev_info(&dev->dev, "PCI bridge to %pR%s\n",
&child->busn_res,
dev->transparent ? " (subtractive decode)" : "");
pci_bus_remove_resources(child);
for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++)
child->resource[i] = &dev->resource[PCI_BRIDGE_RESOURCES+i];
pci_read_bridge_io(child);
pci_read_bridge_mmio(child);
pci_read_bridge_mmio_pref(child);
if (dev->transparent) {
pci_bus_for_each_resource(child->parent, res, i) {
if (res) {
pci_bus_add_resource(child, res,
PCI_SUBTRACTIVE_DECODE);
dev_printk(KERN_DEBUG, &dev->dev,
" bridge window %pR (subtractive decode)\n",
res);
}
}
}
}
static struct pci_bus * pci_alloc_bus(void)
{
struct pci_bus *b;
b = kzalloc(sizeof(*b), GFP_KERNEL);
if (b) {
INIT_LIST_HEAD(&b->node);
INIT_LIST_HEAD(&b->children);
INIT_LIST_HEAD(&b->devices);
INIT_LIST_HEAD(&b->slots);
INIT_LIST_HEAD(&b->resources);
b->max_bus_speed = PCI_SPEED_UNKNOWN;
b->cur_bus_speed = PCI_SPEED_UNKNOWN;
}
return b;
}
static struct pci_host_bridge *pci_alloc_host_bridge(struct pci_bus *b)
{
struct pci_host_bridge *bridge;
bridge = kzalloc(sizeof(*bridge), GFP_KERNEL);
if (bridge) {
INIT_LIST_HEAD(&bridge->windows);
bridge->bus = b;
}
return bridge;
}
static unsigned char pcix_bus_speed[] = {
PCI_SPEED_UNKNOWN, /* 0 */
PCI_SPEED_66MHz_PCIX, /* 1 */
PCI_SPEED_100MHz_PCIX, /* 2 */
PCI_SPEED_133MHz_PCIX, /* 3 */
PCI_SPEED_UNKNOWN, /* 4 */
PCI_SPEED_66MHz_PCIX_ECC, /* 5 */
PCI_SPEED_100MHz_PCIX_ECC, /* 6 */
PCI_SPEED_133MHz_PCIX_ECC, /* 7 */
PCI_SPEED_UNKNOWN, /* 8 */
PCI_SPEED_66MHz_PCIX_266, /* 9 */
PCI_SPEED_100MHz_PCIX_266, /* A */
PCI_SPEED_133MHz_PCIX_266, /* B */
PCI_SPEED_UNKNOWN, /* C */
PCI_SPEED_66MHz_PCIX_533, /* D */
PCI_SPEED_100MHz_PCIX_533, /* E */
PCI_SPEED_133MHz_PCIX_533 /* F */
};
static unsigned char pcie_link_speed[] = {
PCI_SPEED_UNKNOWN, /* 0 */
PCIE_SPEED_2_5GT, /* 1 */
PCIE_SPEED_5_0GT, /* 2 */
PCIE_SPEED_8_0GT, /* 3 */
PCI_SPEED_UNKNOWN, /* 4 */
PCI_SPEED_UNKNOWN, /* 5 */
PCI_SPEED_UNKNOWN, /* 6 */
PCI_SPEED_UNKNOWN, /* 7 */
PCI_SPEED_UNKNOWN, /* 8 */
PCI_SPEED_UNKNOWN, /* 9 */
PCI_SPEED_UNKNOWN, /* A */
PCI_SPEED_UNKNOWN, /* B */
PCI_SPEED_UNKNOWN, /* C */
PCI_SPEED_UNKNOWN, /* D */
PCI_SPEED_UNKNOWN, /* E */
PCI_SPEED_UNKNOWN /* F */
};
void pcie_update_link_speed(struct pci_bus *bus, u16 linksta)
{
bus->cur_bus_speed = pcie_link_speed[linksta & 0xf];
}
EXPORT_SYMBOL_GPL(pcie_update_link_speed);
static unsigned char agp_speeds[] = {
AGP_UNKNOWN,
AGP_1X,
AGP_2X,
AGP_4X,
AGP_8X
};
static enum pci_bus_speed agp_speed(int agp3, int agpstat)
{
int index = 0;
if (agpstat & 4)
index = 3;
else if (agpstat & 2)
index = 2;
else if (agpstat & 1)
index = 1;
else
goto out;
if (agp3) {
index += 2;
if (index == 5)
index = 0;
}
out:
return agp_speeds[index];
}
static void pci_set_bus_speed(struct pci_bus *bus)
{
struct pci_dev *bridge = bus->self;
int pos;
pos = pci_find_capability(bridge, PCI_CAP_ID_AGP);
if (!pos)
pos = pci_find_capability(bridge, PCI_CAP_ID_AGP3);
if (pos) {
u32 agpstat, agpcmd;
pci_read_config_dword(bridge, pos + PCI_AGP_STATUS, &agpstat);
bus->max_bus_speed = agp_speed(agpstat & 8, agpstat & 7);
pci_read_config_dword(bridge, pos + PCI_AGP_COMMAND, &agpcmd);
bus->cur_bus_speed = agp_speed(agpstat & 8, agpcmd & 7);
}
pos = pci_find_capability(bridge, PCI_CAP_ID_PCIX);
if (pos) {
u16 status;
enum pci_bus_speed max;
pci_read_config_word(bridge, pos + 2, &status);
if (status & 0x8000) {
max = PCI_SPEED_133MHz_PCIX_533;
} else if (status & 0x4000) {
max = PCI_SPEED_133MHz_PCIX_266;
} else if (status & 0x0002) {
if (((status >> 12) & 0x3) == 2) {
max = PCI_SPEED_133MHz_PCIX_ECC;
} else {
max = PCI_SPEED_133MHz_PCIX;
}
} else {
max = PCI_SPEED_66MHz_PCIX;
}
bus->max_bus_speed = max;
bus->cur_bus_speed = pcix_bus_speed[(status >> 6) & 0xf];
return;
}
pos = pci_find_capability(bridge, PCI_CAP_ID_EXP);
if (pos) {
u32 linkcap;
u16 linksta;
pcie_capability_read_dword(bridge, PCI_EXP_LNKCAP, &linkcap);
bus->max_bus_speed = pcie_link_speed[linkcap & 0xf];
pcie_capability_read_word(bridge, PCI_EXP_LNKSTA, &linksta);
pcie_update_link_speed(bus, linksta);
}
}
static struct pci_bus *pci_alloc_child_bus(struct pci_bus *parent,
struct pci_dev *bridge, int busnr)
{
struct pci_bus *child;
int i;
/*
* Allocate a new bus, and inherit stuff from the parent..
*/
child = pci_alloc_bus();
if (!child)
return NULL;
child->parent = parent;
child->ops = parent->ops;
child->sysdata = parent->sysdata;
child->bus_flags = parent->bus_flags;
/* initialize some portions of the bus device, but don't register it
* now as the parent is not properly set up yet. This device will get
* registered later in pci_bus_add_devices()
*/
child->dev.class = &pcibus_class;
dev_set_name(&child->dev, "%04x:%02x", pci_domain_nr(child), busnr);
/*
* Set up the primary, secondary and subordinate
* bus numbers.
*/
child->number = child->busn_res.start = busnr;
child->primary = parent->busn_res.start;
child->busn_res.end = 0xff;
if (!bridge)
return child;
child->self = bridge;
child->bridge = get_device(&bridge->dev);
pci_set_bus_of_node(child);
pci_set_bus_speed(child);
/* Set up default resource pointers and names.. */
for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++) {
child->resource[i] = &bridge->resource[PCI_BRIDGE_RESOURCES+i];
child->resource[i]->name = child->name;
}
bridge->subordinate = child;
return child;
}
struct pci_bus *__ref pci_add_new_bus(struct pci_bus *parent, struct pci_dev *dev, int busnr)
{
struct pci_bus *child;
child = pci_alloc_child_bus(parent, dev, busnr);
if (child) {
down_write(&pci_bus_sem);
list_add_tail(&child->node, &parent->children);
up_write(&pci_bus_sem);
}
return child;
}
static void pci_fixup_parent_subordinate_busnr(struct pci_bus *child, int max)
{
struct pci_bus *parent = child->parent;
/* Attempts to fix that up are really dangerous unless
we're going to re-assign all bus numbers. */
if (!pcibios_assign_all_busses())
return;
while (parent->parent && parent->busn_res.end < max) {
parent->busn_res.end = max;
pci_write_config_byte(parent->self, PCI_SUBORDINATE_BUS, max);
parent = parent->parent;
}
}
/*
* If it's a bridge, configure it and scan the bus behind it.
* For CardBus bridges, we don't scan behind as the devices will
* be handled by the bridge driver itself.
*
* We need to process bridges in two passes -- first we scan those
* already configured by the BIOS and after we are done with all of
* them, we proceed to assigning numbers to the remaining buses in
* order to avoid overlaps between old and new bus numbers.
*/
int __devinit pci_scan_bridge(struct pci_bus *bus, struct pci_dev *dev, int max, int pass)
{
struct pci_bus *child;
int is_cardbus = (dev->hdr_type == PCI_HEADER_TYPE_CARDBUS);
u32 buses, i, j = 0;
u16 bctl;
u8 primary, secondary, subordinate;
int broken = 0;
pci_read_config_dword(dev, PCI_PRIMARY_BUS, &buses);
primary = buses & 0xFF;
secondary = (buses >> 8) & 0xFF;
subordinate = (buses >> 16) & 0xFF;
dev_dbg(&dev->dev, "scanning [bus %02x-%02x] behind bridge, pass %d\n",
secondary, subordinate, pass);
if (!primary && (primary != bus->number) && secondary && subordinate) {
dev_warn(&dev->dev, "Primary bus is hard wired to 0\n");
primary = bus->number;
}
/* Check if setup is sensible at all */
if (!pass &&
(primary != bus->number || secondary <= bus->number ||
secondary > subordinate)) {
dev_info(&dev->dev, "bridge configuration invalid ([bus %02x-%02x]), reconfiguring\n",
secondary, subordinate);
broken = 1;
}
/* Disable MasterAbortMode during probing to avoid reporting
of bus errors (in some architectures) */
pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &bctl);
pci_write_config_word(dev, PCI_BRIDGE_CONTROL,
bctl & ~PCI_BRIDGE_CTL_MASTER_ABORT);
if ((secondary || subordinate) && !pcibios_assign_all_busses() &&
!is_cardbus && !broken) {
unsigned int cmax;
/*
* Bus already configured by firmware, process it in the first
* pass and just note the configuration.
*/
if (pass)
goto out;
/*
* If we already got to this bus through a different bridge,
* don't re-add it. This can happen with the i450NX chipset.
*
* However, we continue to descend down the hierarchy and
* scan remaining child buses.
*/
child = pci_find_bus(pci_domain_nr(bus), secondary);
if (!child) {
child = pci_add_new_bus(bus, dev, secondary);
if (!child)
goto out;
child->primary = primary;
pci_bus_insert_busn_res(child, secondary, subordinate);
child->bridge_ctl = bctl;
}
cmax = pci_scan_child_bus(child);
if (cmax > max)
max = cmax;
if (child->busn_res.end > max)
max = child->busn_res.end;
} else {
/*
* We need to assign a number to this bus which we always
* do in the second pass.
*/
if (!pass) {
if (pcibios_assign_all_busses() || broken)
/* Temporarily disable forwarding of the
configuration cycles on all bridges in
this bus segment to avoid possible
conflicts in the second pass between two
bridges programmed with overlapping
bus ranges. */
pci_write_config_dword(dev, PCI_PRIMARY_BUS,
buses & ~0xffffff);
goto out;
}
/* Clear errors */
pci_write_config_word(dev, PCI_STATUS, 0xffff);
/* Prevent assigning a bus number that already exists.
* This can happen when a bridge is hot-plugged, so in
* this case we only re-scan this bus. */
child = pci_find_bus(pci_domain_nr(bus), max+1);
if (!child) {
child = pci_add_new_bus(bus, dev, ++max);
if (!child)
goto out;
pci_bus_insert_busn_res(child, max, 0xff);
}
buses = (buses & 0xff000000)
| ((unsigned int)(child->primary) << 0)
| ((unsigned int)(child->busn_res.start) << 8)
| ((unsigned int)(child->busn_res.end) << 16);
/*
* yenta.c forces a secondary latency timer of 176.
* Copy that behaviour here.
*/
if (is_cardbus) {
buses &= ~0xff000000;
buses |= CARDBUS_LATENCY_TIMER << 24;
}
/*
* We need to blast all three values with a single write.
*/
pci_write_config_dword(dev, PCI_PRIMARY_BUS, buses);
if (!is_cardbus) {
child->bridge_ctl = bctl;
/*
* Adjust subordinate busnr in parent buses.
* We do this before scanning for children because
* some devices may not be detected if the bios
* was lazy.
*/
pci_fixup_parent_subordinate_busnr(child, max);
/* Now we can scan all subordinate buses... */
max = pci_scan_child_bus(child);
/*
* now fix it up again since we have found
* the real value of max.
*/
pci_fixup_parent_subordinate_busnr(child, max);
} else {
/*
* For CardBus bridges, we leave 4 bus numbers
* as cards with a PCI-to-PCI bridge can be
* inserted later.
*/
for (i=0; i<CARDBUS_RESERVE_BUSNR; i++) {
struct pci_bus *parent = bus;
if (pci_find_bus(pci_domain_nr(bus),
max+i+1))
break;
while (parent->parent) {
if ((!pcibios_assign_all_busses()) &&
(parent->busn_res.end > max) &&
(parent->busn_res.end <= max+i)) {
j = 1;
}
parent = parent->parent;
}
if (j) {
/*
* Often, there are two cardbus bridges
* -- try to leave one valid bus number
* for each one.
*/
i /= 2;
break;
}
}
max += i;
pci_fixup_parent_subordinate_busnr(child, max);
}
/*
* Set the subordinate bus number to its real value.
*/
pci_bus_update_busn_res_end(child, max);
pci_write_config_byte(dev, PCI_SUBORDINATE_BUS, max);
}
sprintf(child->name,
(is_cardbus ? "PCI CardBus %04x:%02x" : "PCI Bus %04x:%02x"),
pci_domain_nr(bus), child->number);
/* Has only triggered on CardBus, fixup is in yenta_socket */
while (bus->parent) {
if ((child->busn_res.end > bus->busn_res.end) ||
(child->number > bus->busn_res.end) ||
(child->number < bus->number) ||
(child->busn_res.end < bus->number)) {
dev_info(&child->dev, "%pR %s "
"hidden behind%s bridge %s %pR\n",
&child->busn_res,
(bus->number > child->busn_res.end &&
bus->busn_res.end < child->number) ?
"wholly" : "partially",
bus->self->transparent ? " transparent" : "",
dev_name(&bus->dev),
&bus->busn_res);
}
bus = bus->parent;
}
out:
pci_write_config_word(dev, PCI_BRIDGE_CONTROL, bctl);
return max;
}
/*
* Read interrupt line and base address registers.
* The architecture-dependent code can tweak these, of course.
*/
static void pci_read_irq(struct pci_dev *dev)
{
unsigned char irq;
pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &irq);
dev->pin = irq;
if (irq)
pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &irq);
dev->irq = irq;
}
void set_pcie_port_type(struct pci_dev *pdev)
{
int pos;
u16 reg16;
pos = pci_find_capability(pdev, PCI_CAP_ID_EXP);
if (!pos)
return;
pdev->is_pcie = 1;
pdev->pcie_cap = pos;
pci_read_config_word(pdev, pos + PCI_EXP_FLAGS, ®16);
pdev->pcie_flags_reg = reg16;
pci_read_config_word(pdev, pos + PCI_EXP_DEVCAP, ®16);
pdev->pcie_mpss = reg16 & PCI_EXP_DEVCAP_PAYLOAD;
}
void set_pcie_hotplug_bridge(struct pci_dev *pdev)
{
u32 reg32;
pcie_capability_read_dword(pdev, PCI_EXP_SLTCAP, ®32);
if (reg32 & PCI_EXP_SLTCAP_HPC)
pdev->is_hotplug_bridge = 1;
}
#define LEGACY_IO_RESOURCE (IORESOURCE_IO | IORESOURCE_PCI_FIXED)
/**
* pci_setup_device - fill in class and map information of a device
* @dev: the device structure to fill
*
* Initialize the device structure with information about the device's
* vendor,class,memory and IO-space addresses,IRQ lines etc.
* Called at initialisation of the PCI subsystem and by CardBus services.
* Returns 0 on success and negative if unknown type of device (not normal,
* bridge or CardBus).
*/
int pci_setup_device(struct pci_dev *dev)
{
u32 class;
u8 hdr_type;
struct pci_slot *slot;
int pos = 0;
struct pci_bus_region region;
struct resource *res;
if (pci_read_config_byte(dev, PCI_HEADER_TYPE, &hdr_type))
return -EIO;
dev->sysdata = dev->bus->sysdata;
dev->dev.parent = dev->bus->bridge;
dev->dev.bus = &pci_bus_type;
dev->hdr_type = hdr_type & 0x7f;
dev->multifunction = !!(hdr_type & 0x80);
dev->error_state = pci_channel_io_normal;
set_pcie_port_type(dev);
list_for_each_entry(slot, &dev->bus->slots, list)
if (PCI_SLOT(dev->devfn) == slot->number)
dev->slot = slot;
/* Assume 32-bit PCI; let 64-bit PCI cards (which are far rarer)
set this higher, assuming the system even supports it. */
dev->dma_mask = 0xffffffff;
dev_set_name(&dev->dev, "%04x:%02x:%02x.%d", pci_domain_nr(dev->bus),
dev->bus->number, PCI_SLOT(dev->devfn),
PCI_FUNC(dev->devfn));
pci_read_config_dword(dev, PCI_CLASS_REVISION, &class);
dev->revision = class & 0xff;
dev->class = class >> 8; /* upper 3 bytes */
dev_printk(KERN_DEBUG, &dev->dev, "[%04x:%04x] type %02x class %#08x\n",
dev->vendor, dev->device, dev->hdr_type, dev->class);
/* need to have dev->class ready */
dev->cfg_size = pci_cfg_space_size(dev);
/* "Unknown power state" */
dev->current_state = PCI_UNKNOWN;
/* Early fixups, before probing the BARs */
pci_fixup_device(pci_fixup_early, dev);
/* device class may be changed after fixup */
class = dev->class >> 8;
switch (dev->hdr_type) { /* header type */
case PCI_HEADER_TYPE_NORMAL: /* standard header */
if (class == PCI_CLASS_BRIDGE_PCI)
goto bad;
pci_read_irq(dev);
pci_read_bases(dev, 6, PCI_ROM_ADDRESS);
pci_read_config_word(dev, PCI_SUBSYSTEM_VENDOR_ID, &dev->subsystem_vendor);
pci_read_config_word(dev, PCI_SUBSYSTEM_ID, &dev->subsystem_device);
/*
* Do the ugly legacy mode stuff here rather than broken chip
* quirk code. Legacy mode ATA controllers have fixed
* addresses. These are not always echoed in BAR0-3, and
* BAR0-3 in a few cases contain junk!
*/
if (class == PCI_CLASS_STORAGE_IDE) {
u8 progif;
pci_read_config_byte(dev, PCI_CLASS_PROG, &progif);
if ((progif & 1) == 0) {
region.start = 0x1F0;
region.end = 0x1F7;
res = &dev->resource[0];
res->flags = LEGACY_IO_RESOURCE;
pcibios_bus_to_resource(dev, res, ®ion);
region.start = 0x3F6;
region.end = 0x3F6;
res = &dev->resource[1];
res->flags = LEGACY_IO_RESOURCE;
pcibios_bus_to_resource(dev, res, ®ion);
}
if ((progif & 4) == 0) {
region.start = 0x170;
region.end = 0x177;
res = &dev->resource[2];
res->flags = LEGACY_IO_RESOURCE;
pcibios_bus_to_resource(dev, res, ®ion);
region.start = 0x376;
region.end = 0x376;
res = &dev->resource[3];
res->flags = LEGACY_IO_RESOURCE;
pcibios_bus_to_resource(dev, res, ®ion);
}
}
break;
case PCI_HEADER_TYPE_BRIDGE: /* bridge header */
if (class != PCI_CLASS_BRIDGE_PCI)
goto bad;
/* The PCI-to-PCI bridge spec requires that subtractive
decoding (i.e. transparent) bridge must have programming
interface code of 0x01. */
pci_read_irq(dev);
dev->transparent = ((dev->class & 0xff) == 1);
pci_read_bases(dev, 2, PCI_ROM_ADDRESS1);
set_pcie_hotplug_bridge(dev);
pos = pci_find_capability(dev, PCI_CAP_ID_SSVID);
if (pos) {
pci_read_config_word(dev, pos + PCI_SSVID_VENDOR_ID, &dev->subsystem_vendor);
pci_read_config_word(dev, pos + PCI_SSVID_DEVICE_ID, &dev->subsystem_device);
}
break;
case PCI_HEADER_TYPE_CARDBUS: /* CardBus bridge header */
if (class != PCI_CLASS_BRIDGE_CARDBUS)
goto bad;
pci_read_irq(dev);
pci_read_bases(dev, 1, 0);
pci_read_config_word(dev, PCI_CB_SUBSYSTEM_VENDOR_ID, &dev->subsystem_vendor);
pci_read_config_word(dev, PCI_CB_SUBSYSTEM_ID, &dev->subsystem_device);
break;
default: /* unknown header */
dev_err(&dev->dev, "unknown header type %02x, "
"ignoring device\n", dev->hdr_type);
return -EIO;
bad:
dev_err(&dev->dev, "ignoring class %#08x (doesn't match header "
"type %02x)\n", dev->class, dev->hdr_type);
dev->class = PCI_CLASS_NOT_DEFINED;
}
/* We found a fine healthy device, go go go... */
return 0;
}
static void pci_release_capabilities(struct pci_dev *dev)
{
pci_vpd_release(dev);
pci_iov_release(dev);
pci_free_cap_save_buffers(dev);
}
/**
* pci_release_dev - free a pci device structure when all users of it are finished.
* @dev: device that's been disconnected
*
* Will be called only by the device core when all users of this pci device are
* done.
*/
static void pci_release_dev(struct device *dev)
{
struct pci_dev *pci_dev;
pci_dev = to_pci_dev(dev);
pci_release_capabilities(pci_dev);
pci_release_of_node(pci_dev);
kfree(pci_dev);
}
/**
* pci_cfg_space_size - get the configuration space size of the PCI device.
* @dev: PCI device
*
* Regular PCI devices have 256 bytes, but PCI-X 2 and PCI Express devices
* have 4096 bytes. Even if the device is capable, that doesn't mean we can
* access it. Maybe we don't have a way to generate extended config space
* accesses, or the device is behind a reverse Express bridge. So we try
* reading the dword at 0x100 which must either be 0 or a valid extended
* capability header.
*/
int pci_cfg_space_size_ext(struct pci_dev *dev)
{
u32 status;
int pos = PCI_CFG_SPACE_SIZE;
if (pci_read_config_dword(dev, pos, &status) != PCIBIOS_SUCCESSFUL)
goto fail;
if (status == 0xffffffff)
goto fail;
return PCI_CFG_SPACE_EXP_SIZE;
fail:
return PCI_CFG_SPACE_SIZE;
}
int pci_cfg_space_size(struct pci_dev *dev)
{
int pos;
u32 status;
u16 class;
class = dev->class >> 8;
if (class == PCI_CLASS_BRIDGE_HOST)
return pci_cfg_space_size_ext(dev);
if (!pci_is_pcie(dev)) {
pos = pci_find_capability(dev, PCI_CAP_ID_PCIX);
if (!pos)
goto fail;
pci_read_config_dword(dev, pos + PCI_X_STATUS, &status);
if (!(status & (PCI_X_STATUS_266MHZ | PCI_X_STATUS_533MHZ)))
goto fail;
}
return pci_cfg_space_size_ext(dev);
fail:
return PCI_CFG_SPACE_SIZE;
}
static void pci_release_bus_bridge_dev(struct device *dev)
{
struct pci_host_bridge *bridge = to_pci_host_bridge(dev);
if (bridge->release_fn)
bridge->release_fn(bridge);
pci_free_resource_list(&bridge->windows);
kfree(bridge);
}
struct pci_dev *alloc_pci_dev(void)
{
struct pci_dev *dev;
dev = kzalloc(sizeof(struct pci_dev), GFP_KERNEL);
if (!dev)
return NULL;
INIT_LIST_HEAD(&dev->bus_list);
return dev;
}
EXPORT_SYMBOL(alloc_pci_dev);
bool pci_bus_read_dev_vendor_id(struct pci_bus *bus, int devfn, u32 *l,
int crs_timeout)
{
int delay = 1;
if (pci_bus_read_config_dword(bus, devfn, PCI_VENDOR_ID, l))
return false;
/* some broken boards return 0 or ~0 if a slot is empty: */
if (*l == 0xffffffff || *l == 0x00000000 ||
*l == 0x0000ffff || *l == 0xffff0000)
return false;
/* Configuration request Retry Status */
while (*l == 0xffff0001) {
if (!crs_timeout)
return false;
msleep(delay);
delay *= 2;
if (pci_bus_read_config_dword(bus, devfn, PCI_VENDOR_ID, l))
return false;
/* Card hasn't responded in 60 seconds? Must be stuck. */
if (delay > crs_timeout) {
printk(KERN_WARNING "pci %04x:%02x:%02x.%d: not "
"responding\n", pci_domain_nr(bus),
bus->number, PCI_SLOT(devfn),
PCI_FUNC(devfn));
return false;
}
}
return true;
}
EXPORT_SYMBOL(pci_bus_read_dev_vendor_id);
/*
* Read the config data for a PCI device, sanity-check it
* and fill in the dev structure...
*/
static struct pci_dev *pci_scan_device(struct pci_bus *bus, int devfn)
{
struct pci_dev *dev;
u32 l;
if (!pci_bus_read_dev_vendor_id(bus, devfn, &l, 60*1000))
return NULL;
dev = alloc_pci_dev();
if (!dev)
return NULL;
dev->bus = bus;
dev->devfn = devfn;
dev->vendor = l & 0xffff;
dev->device = (l >> 16) & 0xffff;
pci_set_of_node(dev);
if (pci_setup_device(dev)) {
kfree(dev);
return NULL;
}
return dev;
}
static void pci_init_capabilities(struct pci_dev *dev)
{
/* MSI/MSI-X list */
pci_msi_init_pci_dev(dev);
/* Buffers for saving PCIe and PCI-X capabilities */
pci_allocate_cap_save_buffers(dev);
/* Power Management */
pci_pm_init(dev);
platform_pci_wakeup_init(dev);
/* Vital Product Data */
pci_vpd_pci22_init(dev);
/* Alternative Routing-ID Forwarding */
pci_enable_ari(dev);
/* Single Root I/O Virtualization */
pci_iov_init(dev);
/* Enable ACS P2P upstream forwarding */
pci_enable_acs(dev);
}
void pci_device_add(struct pci_dev *dev, struct pci_bus *bus)
{
device_initialize(&dev->dev);
dev->dev.release = pci_release_dev;
pci_dev_get(dev);
dev->dev.dma_mask = &dev->dma_mask;
dev->dev.dma_parms = &dev->dma_parms;
dev->dev.coherent_dma_mask = 0xffffffffull;
pci_set_dma_max_seg_size(dev, 65536);
pci_set_dma_seg_boundary(dev, 0xffffffff);
/* Fix up broken headers */
pci_fixup_device(pci_fixup_header, dev);
/* moved out from quirk header fixup code */
pci_reassigndev_resource_alignment(dev);
/* Clear the state_saved flag. */
dev->state_saved = false;
/* Initialize various capabilities */
pci_init_capabilities(dev);
/*
* Add the device to our list of discovered devices
* and the bus list for fixup functions, etc.
*/
down_write(&pci_bus_sem);
list_add_tail(&dev->bus_list, &bus->devices);
up_write(&pci_bus_sem);
}
struct pci_dev *__ref pci_scan_single_device(struct pci_bus *bus, int devfn)
{
struct pci_dev *dev;
dev = pci_get_slot(bus, devfn);
if (dev) {
pci_dev_put(dev);
return dev;
}
dev = pci_scan_device(bus, devfn);
if (!dev)
return NULL;
pci_device_add(dev, bus);
return dev;
}
EXPORT_SYMBOL(pci_scan_single_device);
static unsigned next_ari_fn(struct pci_dev *dev, unsigned fn)
{
u16 cap;
unsigned pos, next_fn;
if (!dev)
return 0;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ARI);
if (!pos)
return 0;
pci_read_config_word(dev, pos + 4, &cap);
next_fn = cap >> 8;
if (next_fn <= fn)
return 0;
return next_fn;
}
static unsigned next_trad_fn(struct pci_dev *dev, unsigned fn)
{
return (fn + 1) % 8;
}
static unsigned no_next_fn(struct pci_dev *dev, unsigned fn)
{
return 0;
}
static int only_one_child(struct pci_bus *bus)
{
struct pci_dev *parent = bus->self;
if (!parent || !pci_is_pcie(parent))
return 0;
if (pci_pcie_type(parent) == PCI_EXP_TYPE_ROOT_PORT)
return 1;
if (pci_pcie_type(parent) == PCI_EXP_TYPE_DOWNSTREAM &&
!pci_has_flag(PCI_SCAN_ALL_PCIE_DEVS))
return 1;
return 0;
}
/**
* pci_scan_slot - scan a PCI slot on a bus for devices.
* @bus: PCI bus to scan
* @devfn: slot number to scan (must have zero function.)
*
* Scan a PCI slot on the specified PCI bus for devices, adding
* discovered devices to the @bus->devices list. New devices
* will not have is_added set.
*
* Returns the number of new devices found.
*/
int pci_scan_slot(struct pci_bus *bus, int devfn)
{
unsigned fn, nr = 0;
struct pci_dev *dev;
unsigned (*next_fn)(struct pci_dev *, unsigned) = no_next_fn;
if (only_one_child(bus) && (devfn > 0))
return 0; /* Already scanned the entire slot */
dev = pci_scan_single_device(bus, devfn);
if (!dev)
return 0;
if (!dev->is_added)
nr++;
if (pci_ari_enabled(bus))
next_fn = next_ari_fn;
else if (dev->multifunction)
next_fn = next_trad_fn;
for (fn = next_fn(dev, 0); fn > 0; fn = next_fn(dev, fn)) {
dev = pci_scan_single_device(bus, devfn + fn);
if (dev) {
if (!dev->is_added)
nr++;
dev->multifunction = 1;
}
}
/* only one slot has pcie device */
if (bus->self && nr)
pcie_aspm_init_link_state(bus->self);
return nr;
}
static int pcie_find_smpss(struct pci_dev *dev, void *data)
{
u8 *smpss = data;
if (!pci_is_pcie(dev))
return 0;
/* For PCIE hotplug enabled slots not connected directly to a
* PCI-E root port, there can be problems when hotplugging
* devices. This is due to the possibility of hotplugging a
* device into the fabric with a smaller MPS that the devices
* currently running have configured. Modifying the MPS on the
* running devices could cause a fatal bus error due to an
* incoming frame being larger than the newly configured MPS.
* To work around this, the MPS for the entire fabric must be
* set to the minimum size. Any devices hotplugged into this
* fabric will have the minimum MPS set. If the PCI hotplug
* slot is directly connected to the root port and there are not
* other devices on the fabric (which seems to be the most
* common case), then this is not an issue and MPS discovery
* will occur as normal.
*/
if (dev->is_hotplug_bridge && (!list_is_singular(&dev->bus->devices) ||
(dev->bus->self &&
pci_pcie_type(dev->bus->self) != PCI_EXP_TYPE_ROOT_PORT)))
*smpss = 0;
if (*smpss > dev->pcie_mpss)
*smpss = dev->pcie_mpss;
return 0;
}
static void pcie_write_mps(struct pci_dev *dev, int mps)
{
int rc;
if (pcie_bus_config == PCIE_BUS_PERFORMANCE) {
mps = 128 << dev->pcie_mpss;
if (pci_pcie_type(dev) != PCI_EXP_TYPE_ROOT_PORT &&
dev->bus->self)
/* For "Performance", the assumption is made that
* downstream communication will never be larger than
* the MRRS. So, the MPS only needs to be configured
* for the upstream communication. This being the case,
* walk from the top down and set the MPS of the child
* to that of the parent bus.
*
* Configure the device MPS with the smaller of the
* device MPSS or the bridge MPS (which is assumed to be
* properly configured at this point to the largest
* allowable MPS based on its parent bus).
*/
mps = min(mps, pcie_get_mps(dev->bus->self));
}
rc = pcie_set_mps(dev, mps);
if (rc)
dev_err(&dev->dev, "Failed attempting to set the MPS\n");
}
static void pcie_write_mrrs(struct pci_dev *dev)
{
int rc, mrrs;
/* In the "safe" case, do not configure the MRRS. There appear to be
* issues with setting MRRS to 0 on a number of devices.
*/
if (pcie_bus_config != PCIE_BUS_PERFORMANCE)
return;
/* For Max performance, the MRRS must be set to the largest supported
* value. However, it cannot be configured larger than the MPS the
* device or the bus can support. This should already be properly
* configured by a prior call to pcie_write_mps.
*/
mrrs = pcie_get_mps(dev);
/* MRRS is a R/W register. Invalid values can be written, but a
* subsequent read will verify if the value is acceptable or not.
* If the MRRS value provided is not acceptable (e.g., too large),
* shrink the value until it is acceptable to the HW.
*/
while (mrrs != pcie_get_readrq(dev) && mrrs >= 128) {
rc = pcie_set_readrq(dev, mrrs);
if (!rc)
break;
dev_warn(&dev->dev, "Failed attempting to set the MRRS\n");
mrrs /= 2;
}
if (mrrs < 128)
dev_err(&dev->dev, "MRRS was unable to be configured with a "
"safe value. If problems are experienced, try running "
"with pci=pcie_bus_safe.\n");
}
static int pcie_bus_configure_set(struct pci_dev *dev, void *data)
{
int mps, orig_mps;
if (!pci_is_pcie(dev))
return 0;
mps = 128 << *(u8 *)data;
orig_mps = pcie_get_mps(dev);
pcie_write_mps(dev, mps);
pcie_write_mrrs(dev);
dev_info(&dev->dev, "PCI-E Max Payload Size set to %4d/%4d (was %4d), "
"Max Read Rq %4d\n", pcie_get_mps(dev), 128 << dev->pcie_mpss,
orig_mps, pcie_get_readrq(dev));
return 0;
}
/* pcie_bus_configure_settings requires that pci_walk_bus work in a top-down,
* parents then children fashion. If this changes, then this code will not
* work as designed.
*/
void pcie_bus_configure_settings(struct pci_bus *bus, u8 mpss)
{
u8 smpss;
if (!pci_is_pcie(bus->self))
return;
if (pcie_bus_config == PCIE_BUS_TUNE_OFF)
return;
/* FIXME - Peer to peer DMA is possible, though the endpoint would need
* to be aware to the MPS of the destination. To work around this,
* simply force the MPS of the entire system to the smallest possible.
*/
if (pcie_bus_config == PCIE_BUS_PEER2PEER)
smpss = 0;
if (pcie_bus_config == PCIE_BUS_SAFE) {
smpss = mpss;
pcie_find_smpss(bus->self, &smpss);
pci_walk_bus(bus, pcie_find_smpss, &smpss);
}
pcie_bus_configure_set(bus->self, &smpss);
pci_walk_bus(bus, pcie_bus_configure_set, &smpss);
}
EXPORT_SYMBOL_GPL(pcie_bus_configure_settings);
unsigned int __devinit pci_scan_child_bus(struct pci_bus *bus)
{
unsigned int devfn, pass, max = bus->busn_res.start;
struct pci_dev *dev;
dev_dbg(&bus->dev, "scanning bus\n");
/* Go find them, Rover! */
for (devfn = 0; devfn < 0x100; devfn += 8)
pci_scan_slot(bus, devfn);
/* Reserve buses for SR-IOV capability. */
max += pci_iov_bus_range(bus);
/*
* After performing arch-dependent fixup of the bus, look behind
* all PCI-to-PCI bridges on this bus.
*/
if (!bus->is_added) {
dev_dbg(&bus->dev, "fixups for bus\n");
pcibios_fixup_bus(bus);
if (pci_is_root_bus(bus))
bus->is_added = 1;
}
for (pass=0; pass < 2; pass++)
list_for_each_entry(dev, &bus->devices, bus_list) {
if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE ||
dev->hdr_type == PCI_HEADER_TYPE_CARDBUS)
max = pci_scan_bridge(bus, dev, max, pass);
}
/*
* We've scanned the bus and so we know all about what's on
* the other side of any bridges that may be on this bus plus
* any devices.
*
* Return how far we've got finding sub-buses.
*/
dev_dbg(&bus->dev, "bus scan returning with max=%02x\n", max);
return max;
}
struct pci_bus *pci_create_root_bus(struct device *parent, int bus,
struct pci_ops *ops, void *sysdata, struct list_head *resources)
{
int error;
struct pci_host_bridge *bridge;
struct pci_bus *b, *b2;
struct pci_host_bridge_window *window, *n;
struct resource *res;
resource_size_t offset;
char bus_addr[64];
char *fmt;
b = pci_alloc_bus();
if (!b)
return NULL;
b->sysdata = sysdata;
b->ops = ops;
b2 = pci_find_bus(pci_domain_nr(b), bus);
if (b2) {
/* If we already got to this bus through a different bridge, ignore it */
dev_dbg(&b2->dev, "bus already known\n");
goto err_out;
}
bridge = pci_alloc_host_bridge(b);
if (!bridge)
goto err_out;
bridge->dev.parent = parent;
bridge->dev.release = pci_release_bus_bridge_dev;
dev_set_name(&bridge->dev, "pci%04x:%02x", pci_domain_nr(b), bus);
error = device_register(&bridge->dev);
if (error)
goto bridge_dev_reg_err;
b->bridge = get_device(&bridge->dev);
device_enable_async_suspend(b->bridge);
pci_set_bus_of_node(b);
if (!parent)
set_dev_node(b->bridge, pcibus_to_node(b));
b->dev.class = &pcibus_class;
b->dev.parent = b->bridge;
dev_set_name(&b->dev, "%04x:%02x", pci_domain_nr(b), bus);
error = device_register(&b->dev);
if (error)
goto class_dev_reg_err;
/* Create legacy_io and legacy_mem files for this bus */
pci_create_legacy_files(b);
b->number = b->busn_res.start = bus;
if (parent)
dev_info(parent, "PCI host bridge to bus %s\n", dev_name(&b->dev));
else
printk(KERN_INFO "PCI host bridge to bus %s\n", dev_name(&b->dev));
/* Add initial resources to the bus */
list_for_each_entry_safe(window, n, resources, list) {
list_move_tail(&window->list, &bridge->windows);
res = window->res;
offset = window->offset;
if (res->flags & IORESOURCE_BUS)
pci_bus_insert_busn_res(b, bus, res->end);
else
pci_bus_add_resource(b, res, 0);
if (offset) {
if (resource_type(res) == IORESOURCE_IO)
fmt = " (bus address [%#06llx-%#06llx])";
else
fmt = " (bus address [%#010llx-%#010llx])";
snprintf(bus_addr, sizeof(bus_addr), fmt,
(unsigned long long) (res->start - offset),
(unsigned long long) (res->end - offset));
} else
bus_addr[0] = '\0';
dev_info(&b->dev, "root bus resource %pR%s\n", res, bus_addr);
}
down_write(&pci_bus_sem);
list_add_tail(&b->node, &pci_root_buses);
up_write(&pci_bus_sem);
return b;
class_dev_reg_err:
put_device(&bridge->dev);
device_unregister(&bridge->dev);
bridge_dev_reg_err:
kfree(bridge);
err_out:
kfree(b);
return NULL;
}
int pci_bus_insert_busn_res(struct pci_bus *b, int bus, int bus_max)
{
struct resource *res = &b->busn_res;
struct resource *parent_res, *conflict;
res->start = bus;
res->end = bus_max;
res->flags = IORESOURCE_BUS;
if (!pci_is_root_bus(b))
parent_res = &b->parent->busn_res;
else {
parent_res = get_pci_domain_busn_res(pci_domain_nr(b));
res->flags |= IORESOURCE_PCI_FIXED;
}
conflict = insert_resource_conflict(parent_res, res);
if (conflict)
dev_printk(KERN_DEBUG, &b->dev,
"busn_res: can not insert %pR under %s%pR (conflicts with %s %pR)\n",
res, pci_is_root_bus(b) ? "domain " : "",
parent_res, conflict->name, conflict);
return conflict == NULL;
}
int pci_bus_update_busn_res_end(struct pci_bus *b, int bus_max)
{
struct resource *res = &b->busn_res;
struct resource old_res = *res;
resource_size_t size;
int ret;
if (res->start > bus_max)
return -EINVAL;
size = bus_max - res->start + 1;
ret = adjust_resource(res, res->start, size);
dev_printk(KERN_DEBUG, &b->dev,
"busn_res: %pR end %s updated to %02x\n",
&old_res, ret ? "can not be" : "is", bus_max);
if (!ret && !res->parent)
pci_bus_insert_busn_res(b, res->start, res->end);
return ret;
}
void pci_bus_release_busn_res(struct pci_bus *b)
{
struct resource *res = &b->busn_res;
int ret;
if (!res->flags || !res->parent)
return;
ret = release_resource(res);
dev_printk(KERN_DEBUG, &b->dev,
"busn_res: %pR %s released\n",
res, ret ? "can not be" : "is");
}
struct pci_bus * __devinit pci_scan_root_bus(struct device *parent, int bus,
struct pci_ops *ops, void *sysdata, struct list_head *resources)
{
struct pci_host_bridge_window *window;
bool found = false;
struct pci_bus *b;
int max;
list_for_each_entry(window, resources, list)
if (window->res->flags & IORESOURCE_BUS) {
found = true;
break;
}
b = pci_create_root_bus(parent, bus, ops, sysdata, resources);
if (!b)
return NULL;
if (!found) {
dev_info(&b->dev,
"No busn resource found for root bus, will use [bus %02x-ff]\n",
bus);
pci_bus_insert_busn_res(b, bus, 255);
}
max = pci_scan_child_bus(b);
if (!found)
pci_bus_update_busn_res_end(b, max);
pci_bus_add_devices(b);
return b;
}
EXPORT_SYMBOL(pci_scan_root_bus);
/* Deprecated; use pci_scan_root_bus() instead */
struct pci_bus * __devinit pci_scan_bus_parented(struct device *parent,
int bus, struct pci_ops *ops, void *sysdata)
{
LIST_HEAD(resources);
struct pci_bus *b;
pci_add_resource(&resources, &ioport_resource);
pci_add_resource(&resources, &iomem_resource);
pci_add_resource(&resources, &busn_resource);
b = pci_create_root_bus(parent, bus, ops, sysdata, &resources);
if (b)
pci_scan_child_bus(b);
else
pci_free_resource_list(&resources);
return b;
}
EXPORT_SYMBOL(pci_scan_bus_parented);
struct pci_bus * __devinit pci_scan_bus(int bus, struct pci_ops *ops,
void *sysdata)
{
LIST_HEAD(resources);
struct pci_bus *b;
pci_add_resource(&resources, &ioport_resource);
pci_add_resource(&resources, &iomem_resource);
pci_add_resource(&resources, &busn_resource);
b = pci_create_root_bus(NULL, bus, ops, sysdata, &resources);
if (b) {
pci_scan_child_bus(b);
pci_bus_add_devices(b);
} else {
pci_free_resource_list(&resources);
}
return b;
}
EXPORT_SYMBOL(pci_scan_bus);
#ifdef CONFIG_HOTPLUG
/**
* pci_rescan_bus_bridge_resize - scan a PCI bus for devices.
* @bridge: PCI bridge for the bus to scan
*
* Scan a PCI bus and child buses for new devices, add them,
* and enable them, resizing bridge mmio/io resource if necessary
* and possible. The caller must ensure the child devices are already
* removed for resizing to occur.
*
* Returns the max number of subordinate bus discovered.
*/
unsigned int __ref pci_rescan_bus_bridge_resize(struct pci_dev *bridge)
{
unsigned int max;
struct pci_bus *bus = bridge->subordinate;
max = pci_scan_child_bus(bus);
pci_assign_unassigned_bridge_resources(bridge);
pci_bus_add_devices(bus);
return max;
}
EXPORT_SYMBOL(pci_add_new_bus);
EXPORT_SYMBOL(pci_scan_slot);
EXPORT_SYMBOL(pci_scan_bridge);
EXPORT_SYMBOL_GPL(pci_scan_child_bus);
#endif
static int __init pci_sort_bf_cmp(const struct device *d_a, const struct device *d_b)
{
const struct pci_dev *a = to_pci_dev(d_a);
const struct pci_dev *b = to_pci_dev(d_b);
if (pci_domain_nr(a->bus) < pci_domain_nr(b->bus)) return -1;
else if (pci_domain_nr(a->bus) > pci_domain_nr(b->bus)) return 1;
if (a->bus->number < b->bus->number) return -1;
else if (a->bus->number > b->bus->number) return 1;
if (a->devfn < b->devfn) return -1;
else if (a->devfn > b->devfn) return 1;
return 0;
}
void __init pci_sort_breadthfirst(void)
{
bus_sort_breadthfirst(&pci_bus_type, &pci_sort_bf_cmp);
}
| ystk/linux-poky-debian | drivers/pci/probe.c | C | gpl-2.0 | 50,002 |
/*
* arch/sh/boards/overdrive/time.c
*
* Copyright (C) 2000 Stuart Menefy ([email protected])
* Copyright (C) 2002 Paul Mundt ([email protected])
*
* May be copied or modified under the terms of the GNU General Public
* License. See linux/COPYING for more information.
*
* STMicroelectronics Overdrive Support.
*/
void od_time_init(void)
{
struct frqcr_data {
unsigned short frqcr;
struct {
unsigned char multiplier;
unsigned char divisor;
} factor[3];
};
static struct frqcr_data st40_frqcr_table[] = {
{ 0x000, {{1,1}, {1,1}, {1,2}}},
{ 0x002, {{1,1}, {1,1}, {1,4}}},
{ 0x004, {{1,1}, {1,1}, {1,8}}},
{ 0x008, {{1,1}, {1,2}, {1,2}}},
{ 0x00A, {{1,1}, {1,2}, {1,4}}},
{ 0x00C, {{1,1}, {1,2}, {1,8}}},
{ 0x011, {{1,1}, {2,3}, {1,6}}},
{ 0x013, {{1,1}, {2,3}, {1,3}}},
{ 0x01A, {{1,1}, {1,2}, {1,4}}},
{ 0x01C, {{1,1}, {1,2}, {1,8}}},
{ 0x023, {{1,1}, {2,3}, {1,3}}},
{ 0x02C, {{1,1}, {1,2}, {1,8}}},
{ 0x048, {{1,2}, {1,2}, {1,4}}},
{ 0x04A, {{1,2}, {1,2}, {1,6}}},
{ 0x04C, {{1,2}, {1,2}, {1,8}}},
{ 0x05A, {{1,2}, {1,3}, {1,6}}},
{ 0x05C, {{1,2}, {1,3}, {1,6}}},
{ 0x063, {{1,2}, {1,4}, {1,4}}},
{ 0x06C, {{1,2}, {1,4}, {1,8}}},
{ 0x091, {{1,3}, {1,3}, {1,6}}},
{ 0x093, {{1,3}, {1,3}, {1,6}}},
{ 0x0A3, {{1,3}, {1,6}, {1,6}}},
{ 0x0DA, {{1,4}, {1,4}, {1,8}}},
{ 0x0DC, {{1,4}, {1,4}, {1,8}}},
{ 0x0EC, {{1,4}, {1,8}, {1,8}}},
{ 0x123, {{1,4}, {1,4}, {1,8}}},
{ 0x16C, {{1,4}, {1,8}, {1,8}}},
};
struct memclk_data {
unsigned char multiplier;
unsigned char divisor;
};
static struct memclk_data st40_memclk_table[8] = {
{1,1}, // 000
{1,2}, // 001
{1,3}, // 010
{2,3}, // 011
{1,4}, // 100
{1,6}, // 101
{1,8}, // 110
{1,8} // 111
};
unsigned long pvr;
/*
* This should probably be moved into the SH3 probing code, and then
* use the processor structure to determine which CPU we are running
* on.
*/
pvr = ctrl_inl(CCN_PVR);
printk("PVR %08x\n", pvr);
if (((pvr >> CCN_PVR_CHIP_SHIFT) & CCN_PVR_CHIP_MASK) == CCN_PVR_CHIP_ST40STB1) {
/*
* Unfortunatly the STB1 FRQCR values are different from the
* 7750 ones.
*/
struct frqcr_data *d;
int a;
unsigned long memclkcr;
struct memclk_data *e;
for (a=0; a<ARRAY_SIZE(st40_frqcr_table); a++) {
d = &st40_frqcr_table[a];
if (d->frqcr == (frqcr & 0x1ff))
break;
}
if (a == ARRAY_SIZE(st40_frqcr_table)) {
d = st40_frqcr_table;
printk("ERROR: Unrecognised FRQCR value, using default multipliers\n");
}
memclkcr = ctrl_inl(CLOCKGEN_MEMCLKCR);
e = &st40_memclk_table[memclkcr & MEMCLKCR_RATIO_MASK];
printk("Clock multipliers: CPU: %d/%d Bus: %d/%d Mem: %d/%d Periph: %d/%d\n",
d->factor[0].multiplier, d->factor[0].divisor,
d->factor[1].multiplier, d->factor[1].divisor,
e->multiplier, e->divisor,
d->factor[2].multiplier, d->factor[2].divisor);
current_cpu_data.master_clock = current_cpu_data.module_clock *
d->factor[2].divisor /
d->factor[2].multiplier;
current_cpu_data.bus_clock = current_cpu_data.master_clock *
d->factor[1].multiplier /
d->factor[1].divisor;
current_cpu_data.memory_clock = current_cpu_data.master_clock *
e->multiplier / e->divisor;
current_cpu_data.cpu_clock = current_cpu_data.master_clock *
d->factor[0].multiplier /
d->factor[0].divisor;
}
| ipwndev/DSLinux-Mirror | linux-2.6.x/arch/sh/boards/overdrive/time.c | C | gpl-2.0 | 3,409 |
package edu.stanford.nlp.stats;
/**
* An interface for classes which are probability distributions over other probability distributions.
* This class could also represent non-conjugate priors, but we thought this name would be more
* representative of the common case.
*
* @author grenager
* @author jrfinkel
*
* @param <T>
* @param <E>
*/
public interface ConjugatePrior<T extends ProbabilityDistribution<E>, E> extends ProbabilityDistribution<T> {
/**
* Marginalizes over all possible likelihood distributions to give the marginal probability of
* the observation.
*
*/
double getPredictiveProbability(E observation);
double getPredictiveLogProbability(E observation);
/**
* Gets the posterior probability of the observation, after conditioning on all of the evidence.
* Marginalizes over all possible likelihood distributions.
*
*/
double getPosteriorPredictiveProbability(Counter<E> evidence, E observation);
double getPosteriorPredictiveLogProbability(Counter<E> evidence, E observation);
/**
* Gets the ConjugatePrior which results from conditioning on all of these evidence.
*
*/
ConjugatePrior<T,E> getPosteriorDistribution(Counter<E> evidence);
}
| heeyounglee/hcoref | src/edu/stanford/nlp/stats/ConjugatePrior.java | Java | gpl-2.0 | 1,240 |
/*
* Driver for Marvell NETA network card for Armada XP and Armada 370 SoCs.
*
* Copyright (C) 2012 Marvell
*
* Rami Rosen <[email protected]>
* Thomas Petazzoni <[email protected]>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/platform_device.h>
#include <linux/skbuff.h>
#include <linux/inetdevice.h>
#include <linux/mbus.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/if_vlan.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <linux/io.h>
#include <net/tso.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/of_mdio.h>
#include <linux/of_net.h>
#include <linux/of_address.h>
#include <linux/phy.h>
#include <linux/clk.h>
/* Registers */
#define MVNETA_RXQ_CONFIG_REG(q) (0x1400 + ((q) << 2))
#define MVNETA_RXQ_HW_BUF_ALLOC BIT(1)
#define MVNETA_RXQ_PKT_OFFSET_ALL_MASK (0xf << 8)
#define MVNETA_RXQ_PKT_OFFSET_MASK(offs) ((offs) << 8)
#define MVNETA_RXQ_THRESHOLD_REG(q) (0x14c0 + ((q) << 2))
#define MVNETA_RXQ_NON_OCCUPIED(v) ((v) << 16)
#define MVNETA_RXQ_BASE_ADDR_REG(q) (0x1480 + ((q) << 2))
#define MVNETA_RXQ_SIZE_REG(q) (0x14a0 + ((q) << 2))
#define MVNETA_RXQ_BUF_SIZE_SHIFT 19
#define MVNETA_RXQ_BUF_SIZE_MASK (0x1fff << 19)
#define MVNETA_RXQ_STATUS_REG(q) (0x14e0 + ((q) << 2))
#define MVNETA_RXQ_OCCUPIED_ALL_MASK 0x3fff
#define MVNETA_RXQ_STATUS_UPDATE_REG(q) (0x1500 + ((q) << 2))
#define MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT 16
#define MVNETA_RXQ_ADD_NON_OCCUPIED_MAX 255
#define MVNETA_PORT_RX_RESET 0x1cc0
#define MVNETA_PORT_RX_DMA_RESET BIT(0)
#define MVNETA_PHY_ADDR 0x2000
#define MVNETA_PHY_ADDR_MASK 0x1f
#define MVNETA_MBUS_RETRY 0x2010
#define MVNETA_UNIT_INTR_CAUSE 0x2080
#define MVNETA_UNIT_CONTROL 0x20B0
#define MVNETA_PHY_POLLING_ENABLE BIT(1)
#define MVNETA_WIN_BASE(w) (0x2200 + ((w) << 3))
#define MVNETA_WIN_SIZE(w) (0x2204 + ((w) << 3))
#define MVNETA_WIN_REMAP(w) (0x2280 + ((w) << 2))
#define MVNETA_BASE_ADDR_ENABLE 0x2290
#define MVNETA_PORT_CONFIG 0x2400
#define MVNETA_UNI_PROMISC_MODE BIT(0)
#define MVNETA_DEF_RXQ(q) ((q) << 1)
#define MVNETA_DEF_RXQ_ARP(q) ((q) << 4)
#define MVNETA_TX_UNSET_ERR_SUM BIT(12)
#define MVNETA_DEF_RXQ_TCP(q) ((q) << 16)
#define MVNETA_DEF_RXQ_UDP(q) ((q) << 19)
#define MVNETA_DEF_RXQ_BPDU(q) ((q) << 22)
#define MVNETA_RX_CSUM_WITH_PSEUDO_HDR BIT(25)
#define MVNETA_PORT_CONFIG_DEFL_VALUE(q) (MVNETA_DEF_RXQ(q) | \
MVNETA_DEF_RXQ_ARP(q) | \
MVNETA_DEF_RXQ_TCP(q) | \
MVNETA_DEF_RXQ_UDP(q) | \
MVNETA_DEF_RXQ_BPDU(q) | \
MVNETA_TX_UNSET_ERR_SUM | \
MVNETA_RX_CSUM_WITH_PSEUDO_HDR)
#define MVNETA_PORT_CONFIG_EXTEND 0x2404
#define MVNETA_MAC_ADDR_LOW 0x2414
#define MVNETA_MAC_ADDR_HIGH 0x2418
#define MVNETA_SDMA_CONFIG 0x241c
#define MVNETA_SDMA_BRST_SIZE_16 4
#define MVNETA_RX_BRST_SZ_MASK(burst) ((burst) << 1)
#define MVNETA_RX_NO_DATA_SWAP BIT(4)
#define MVNETA_TX_NO_DATA_SWAP BIT(5)
#define MVNETA_DESC_SWAP BIT(6)
#define MVNETA_TX_BRST_SZ_MASK(burst) ((burst) << 22)
#define MVNETA_PORT_STATUS 0x2444
#define MVNETA_TX_IN_PRGRS BIT(1)
#define MVNETA_TX_FIFO_EMPTY BIT(8)
#define MVNETA_RX_MIN_FRAME_SIZE 0x247c
#define MVNETA_SERDES_CFG 0x24A0
#define MVNETA_SGMII_SERDES_PROTO 0x0cc7
#define MVNETA_QSGMII_SERDES_PROTO 0x0667
#define MVNETA_TYPE_PRIO 0x24bc
#define MVNETA_FORCE_UNI BIT(21)
#define MVNETA_TXQ_CMD_1 0x24e4
#define MVNETA_TXQ_CMD 0x2448
#define MVNETA_TXQ_DISABLE_SHIFT 8
#define MVNETA_TXQ_ENABLE_MASK 0x000000ff
#define MVNETA_ACC_MODE 0x2500
#define MVNETA_CPU_MAP(cpu) (0x2540 + ((cpu) << 2))
#define MVNETA_CPU_RXQ_ACCESS_ALL_MASK 0x000000ff
#define MVNETA_CPU_TXQ_ACCESS_ALL_MASK 0x0000ff00
#define MVNETA_RXQ_TIME_COAL_REG(q) (0x2580 + ((q) << 2))
/* Exception Interrupt Port/Queue Cause register */
#define MVNETA_INTR_NEW_CAUSE 0x25a0
#define MVNETA_INTR_NEW_MASK 0x25a4
/* bits 0..7 = TXQ SENT, one bit per queue.
* bits 8..15 = RXQ OCCUP, one bit per queue.
* bits 16..23 = RXQ FREE, one bit per queue.
* bit 29 = OLD_REG_SUM, see old reg ?
* bit 30 = TX_ERR_SUM, one bit for 4 ports
* bit 31 = MISC_SUM, one bit for 4 ports
*/
#define MVNETA_TX_INTR_MASK(nr_txqs) (((1 << nr_txqs) - 1) << 0)
#define MVNETA_TX_INTR_MASK_ALL (0xff << 0)
#define MVNETA_RX_INTR_MASK(nr_rxqs) (((1 << nr_rxqs) - 1) << 8)
#define MVNETA_RX_INTR_MASK_ALL (0xff << 8)
#define MVNETA_INTR_OLD_CAUSE 0x25a8
#define MVNETA_INTR_OLD_MASK 0x25ac
/* Data Path Port/Queue Cause Register */
#define MVNETA_INTR_MISC_CAUSE 0x25b0
#define MVNETA_INTR_MISC_MASK 0x25b4
#define MVNETA_CAUSE_PHY_STATUS_CHANGE BIT(0)
#define MVNETA_CAUSE_LINK_CHANGE BIT(1)
#define MVNETA_CAUSE_PTP BIT(4)
#define MVNETA_CAUSE_INTERNAL_ADDR_ERR BIT(7)
#define MVNETA_CAUSE_RX_OVERRUN BIT(8)
#define MVNETA_CAUSE_RX_CRC_ERROR BIT(9)
#define MVNETA_CAUSE_RX_LARGE_PKT BIT(10)
#define MVNETA_CAUSE_TX_UNDERUN BIT(11)
#define MVNETA_CAUSE_PRBS_ERR BIT(12)
#define MVNETA_CAUSE_PSC_SYNC_CHANGE BIT(13)
#define MVNETA_CAUSE_SERDES_SYNC_ERR BIT(14)
#define MVNETA_CAUSE_BMU_ALLOC_ERR_SHIFT 16
#define MVNETA_CAUSE_BMU_ALLOC_ERR_ALL_MASK (0xF << MVNETA_CAUSE_BMU_ALLOC_ERR_SHIFT)
#define MVNETA_CAUSE_BMU_ALLOC_ERR_MASK(pool) (1 << (MVNETA_CAUSE_BMU_ALLOC_ERR_SHIFT + (pool)))
#define MVNETA_CAUSE_TXQ_ERROR_SHIFT 24
#define MVNETA_CAUSE_TXQ_ERROR_ALL_MASK (0xFF << MVNETA_CAUSE_TXQ_ERROR_SHIFT)
#define MVNETA_CAUSE_TXQ_ERROR_MASK(q) (1 << (MVNETA_CAUSE_TXQ_ERROR_SHIFT + (q)))
#define MVNETA_INTR_ENABLE 0x25b8
#define MVNETA_TXQ_INTR_ENABLE_ALL_MASK 0x0000ff00
#define MVNETA_RXQ_INTR_ENABLE_ALL_MASK 0xff000000 // note: neta says it's 0x000000FF
#define MVNETA_RXQ_CMD 0x2680
#define MVNETA_RXQ_DISABLE_SHIFT 8
#define MVNETA_RXQ_ENABLE_MASK 0x000000ff
#define MVETH_TXQ_TOKEN_COUNT_REG(q) (0x2700 + ((q) << 4))
#define MVETH_TXQ_TOKEN_CFG_REG(q) (0x2704 + ((q) << 4))
#define MVNETA_GMAC_CTRL_0 0x2c00
#define MVNETA_GMAC_MAX_RX_SIZE_SHIFT 2
#define MVNETA_GMAC_MAX_RX_SIZE_MASK 0x7ffc
#define MVNETA_GMAC0_PORT_ENABLE BIT(0)
#define MVNETA_GMAC_CTRL_2 0x2c08
#define MVNETA_GMAC2_PCS_ENABLE BIT(3)
#define MVNETA_GMAC2_PORT_RGMII BIT(4)
#define MVNETA_GMAC2_PORT_RESET BIT(6)
#define MVNETA_GMAC_STATUS 0x2c10
#define MVNETA_GMAC_LINK_UP BIT(0)
#define MVNETA_GMAC_SPEED_1000 BIT(1)
#define MVNETA_GMAC_SPEED_100 BIT(2)
#define MVNETA_GMAC_FULL_DUPLEX BIT(3)
#define MVNETA_GMAC_RX_FLOW_CTRL_ENABLE BIT(4)
#define MVNETA_GMAC_TX_FLOW_CTRL_ENABLE BIT(5)
#define MVNETA_GMAC_RX_FLOW_CTRL_ACTIVE BIT(6)
#define MVNETA_GMAC_TX_FLOW_CTRL_ACTIVE BIT(7)
#define MVNETA_GMAC_AUTONEG_CONFIG 0x2c0c
#define MVNETA_GMAC_FORCE_LINK_DOWN BIT(0)
#define MVNETA_GMAC_FORCE_LINK_PASS BIT(1)
#define MVNETA_GMAC_CONFIG_MII_SPEED BIT(5)
#define MVNETA_GMAC_CONFIG_GMII_SPEED BIT(6)
#define MVNETA_GMAC_AN_SPEED_EN BIT(7)
#define MVNETA_GMAC_CONFIG_FULL_DUPLEX BIT(12)
#define MVNETA_GMAC_AN_DUPLEX_EN BIT(13)
#define MVNETA_MIB_COUNTERS_BASE 0x3080
#define MVNETA_MIB_LATE_COLLISION 0x7c
#define MVNETA_DA_FILT_SPEC_MCAST 0x3400
#define MVNETA_DA_FILT_OTH_MCAST 0x3500
#define MVNETA_DA_FILT_UCAST_BASE 0x3600
#define MVNETA_TXQ_BASE_ADDR_REG(q) (0x3c00 + ((q) << 2))
#define MVNETA_TXQ_SIZE_REG(q) (0x3c20 + ((q) << 2))
#define MVNETA_TXQ_SENT_THRESH_ALL_MASK 0x3fff0000
#define MVNETA_TXQ_SENT_THRESH_MASK(coal) ((coal) << 16)
#define MVNETA_TXQ_UPDATE_REG(q) (0x3c60 + ((q) << 2))
#define MVNETA_TXQ_DEC_SENT_SHIFT 16
#define MVNETA_TXQ_STATUS_REG(q) (0x3c40 + ((q) << 2))
#define MVNETA_TXQ_SENT_DESC_SHIFT 16
#define MVNETA_TXQ_SENT_DESC_MASK 0x3fff0000
#define MVNETA_PORT_TX_RESET 0x3cf0
#define MVNETA_PORT_TX_DMA_RESET BIT(0)
#define MVNETA_TX_MTU 0x3e0c
#define MVNETA_TX_TOKEN_SIZE 0x3e14
#define MVNETA_TX_TOKEN_SIZE_MAX 0xffffffff
#define MVNETA_TXQ_TOKEN_SIZE_REG(q) (0x3e40 + ((q) << 2))
#define MVNETA_TXQ_TOKEN_SIZE_MAX 0x7fffffff
#define MVNETA_CAUSE_TXQ_SENT_DESC_ALL_MASK 0xff
/* Descriptor ring Macros */
#define MVNETA_QUEUE_NEXT_DESC(q, index) \
(((index) < (q)->last_desc) ? ((index) + 1) : 0)
/* Various constants */
/* Coalescing */
#define MVNETA_TXDONE_COAL_PKTS 0 /* interrupt per packet */
#define MVNETA_RX_COAL_PKTS 32
#define MVNETA_RX_COAL_USEC 100
/* The two bytes Marvell header. Either contains a special value used
* by Marvell switches when a specific hardware mode is enabled (not
* supported by this driver) or is filled automatically by zeroes on
* the RX side. Those two bytes being at the front of the Ethernet
* header, they allow to have the IP header aligned on a 4 bytes
* boundary automatically: the hardware skips those two bytes on its
* own.
*/
#define MVNETA_MH_SIZE 2
#define MVNETA_VLAN_TAG_LEN 4
#define MVNETA_CPU_D_CACHE_LINE_SIZE 32
#define MVNETA_TX_CSUM_MAX_SIZE 9800
#define MVNETA_ACC_MODE_EXT 1
/* Timeout constants */
#define MVNETA_TX_DISABLE_TIMEOUT_MSEC 1000
#define MVNETA_RX_DISABLE_TIMEOUT_MSEC 1000
#define MVNETA_TX_FIFO_EMPTY_TIMEOUT 10000
#define MVNETA_TX_MTU_MAX 0x3ffff
/* TSO header size */
#define TSO_HEADER_SIZE 128
/* Max number of Rx descriptors */
#define MVNETA_MAX_RXD 128
/* Max number of Tx descriptors */
#define MVNETA_MAX_TXD 532
/* Max number of allowed TCP segments for software TSO */
#define MVNETA_MAX_TSO_SEGS 100
#define MVNETA_MAX_SKB_DESCS (MVNETA_MAX_TSO_SEGS * 2 + MAX_SKB_FRAGS)
/* descriptor aligned size */
#define MVNETA_DESC_ALIGNED_SIZE 32
#define MVNETA_RX_PKT_SIZE(mtu) \
ALIGN((mtu) + MVNETA_MH_SIZE + MVNETA_VLAN_TAG_LEN + \
ETH_HLEN + ETH_FCS_LEN, \
MVNETA_CPU_D_CACHE_LINE_SIZE)
#define IS_TSO_HEADER(txq, addr) \
((addr >= txq->tso_hdrs_phys) && \
(addr < txq->tso_hdrs_phys + txq->size * TSO_HEADER_SIZE))
#define MVNETA_RX_BUF_SIZE(pkt_size) ((pkt_size) + NET_SKB_PAD)
struct mvneta_pcpu_stats {
struct u64_stats_sync syncp;
u64 rx_packets;
u64 rx_bytes;
u64 tx_packets;
u64 tx_bytes;
};
struct mvneta_port {
int pkt_size;
unsigned int frag_size;
void __iomem *base;
struct mvneta_rx_queue *rxqs;
struct mvneta_tx_queue *txqs;
struct net_device *dev;
u32 cause_rx_tx;
struct napi_struct napi;
/* Core clock */
struct clk *clk;
u8 mcast_count[256];
u16 tx_ring_size;
u16 rx_ring_size;
struct mvneta_pcpu_stats *stats;
struct mii_bus *mii_bus;
struct phy_device *phy_dev;
phy_interface_t phy_interface;
struct device_node *phy_node;
unsigned int link;
unsigned int duplex;
unsigned int speed;
unsigned int tx_csum_limit;
};
/* The mvneta_tx_desc and mvneta_rx_desc structures describe the
* layout of the transmit and reception DMA descriptors, and their
* layout is therefore defined by the hardware design
*/
#define MVNETA_TX_L3_OFF_SHIFT 0
#define MVNETA_TX_IP_HLEN_SHIFT 8
#define MVNETA_TX_L4_UDP BIT(16)
#define MVNETA_TX_L3_IP6 BIT(17)
#define MVNETA_TXD_IP_CSUM BIT(18)
#define MVNETA_TXD_Z_PAD BIT(19)
#define MVNETA_TXD_L_DESC BIT(20)
#define MVNETA_TXD_F_DESC BIT(21)
#define MVNETA_TXD_FLZ_DESC (MVNETA_TXD_Z_PAD | \
MVNETA_TXD_L_DESC | \
MVNETA_TXD_F_DESC)
#define MVNETA_TX_L4_CSUM_FULL BIT(30)
#define MVNETA_TX_L4_CSUM_NOT BIT(31)
#define MVNETA_RXD_ERR_CRC 0x0
#define MVNETA_RXD_ERR_SUMMARY BIT(16)
#define MVNETA_RXD_ERR_OVERRUN BIT(17)
#define MVNETA_RXD_ERR_LEN BIT(18)
#define MVNETA_RXD_ERR_RESOURCE (BIT(17) | BIT(18))
#define MVNETA_RXD_ERR_CODE_MASK (BIT(17) | BIT(18))
#define MVNETA_RXD_L3_IP4 BIT(25)
#define MVNETA_RXD_FIRST_LAST_DESC (BIT(26) | BIT(27))
#define MVNETA_RXD_L4_CSUM_OK BIT(30)
#if defined(__LITTLE_ENDIAN)
struct mvneta_tx_desc {
u32 command; /* Options used by HW for packet transmitting.*/
u16 reserverd1; /* csum_l4 (for future use) */
u16 data_size; /* Data size of transmitted packet in bytes */
u32 buf_phys_addr; /* Physical addr of transmitted buffer */
u32 reserved2; /* hw_cmd - (for future use, PMT) */
u32 reserved3[4]; /* Reserved - (for future use) */
};
struct mvneta_rx_desc {
u32 status; /* Info about received packet */
u16 reserved1; /* pnc_info - (for future use, PnC) */
u16 data_size; /* Size of received packet in bytes */
u32 buf_phys_addr; /* Physical address of the buffer */
u32 reserved2; /* pnc_flow_id (for future use, PnC) */
u32 buf_cookie; /* cookie for access to RX buffer in rx path */
u16 reserved3; /* prefetch_cmd, for future use */
u16 reserved4; /* csum_l4 - (for future use, PnC) */
u32 reserved5; /* pnc_extra PnC (for future use, PnC) */
u32 reserved6; /* hw_cmd (for future use, PnC and HWF) */
};
#else
struct mvneta_tx_desc {
u16 data_size; /* Data size of transmitted packet in bytes */
u16 reserverd1; /* csum_l4 (for future use) */
u32 command; /* Options used by HW for packet transmitting.*/
u32 reserved2; /* hw_cmd - (for future use, PMT) */
u32 buf_phys_addr; /* Physical addr of transmitted buffer */
u32 reserved3[4]; /* Reserved - (for future use) */
};
struct mvneta_rx_desc {
u16 data_size; /* Size of received packet in bytes */
u16 reserved1; /* pnc_info - (for future use, PnC) */
u32 status; /* Info about received packet */
u32 reserved2; /* pnc_flow_id (for future use, PnC) */
u32 buf_phys_addr; /* Physical address of the buffer */
u16 reserved4; /* csum_l4 - (for future use, PnC) */
u16 reserved3; /* prefetch_cmd, for future use */
u32 buf_cookie; /* cookie for access to RX buffer in rx path */
u32 reserved5; /* pnc_extra PnC (for future use, PnC) */
u32 reserved6; /* hw_cmd (for future use, PnC and HWF) */
};
#endif
struct mvneta_tx_queue {
/* Number of this TX queue, in the range 0-7 */
u8 id;
/* Number of TX DMA descriptors in the descriptor ring */
int size;
/* Number of currently used TX DMA descriptor in the
* descriptor ring
*/
int count;
int tx_stop_threshold;
int tx_wake_threshold;
/* Array of transmitted skb */
struct sk_buff **tx_skb;
/* Index of last TX DMA descriptor that was inserted */
int txq_put_index;
/* Index of the TX DMA descriptor to be cleaned up */
int txq_get_index;
u32 done_pkts_coal;
/* Virtual address of the TX DMA descriptors array */
struct mvneta_tx_desc *descs;
/* DMA address of the TX DMA descriptors array */
dma_addr_t descs_phys;
/* Index of the last TX DMA descriptor */
int last_desc;
/* Index of the next TX DMA descriptor to process */
int next_desc_to_proc;
/* DMA buffers for TSO headers */
char *tso_hdrs;
/* DMA address of TSO headers */
dma_addr_t tso_hdrs_phys;
};
struct mvneta_rx_queue {
/* rx queue number, in the range 0-7 */
u8 id;
/* num of rx descriptors in the rx descriptor ring */
int size;
/* counter of times when mvneta_refill() failed */
int missed;
u32 pkts_coal;
u32 time_coal;
/* Virtual address of the RX DMA descriptors array */
struct mvneta_rx_desc *descs;
/* DMA address of the RX DMA descriptors array */
dma_addr_t descs_phys;
/* Index of the last RX DMA descriptor */
int last_desc;
/* Index of the next RX DMA descriptor to process */
int next_desc_to_proc;
};
/* The hardware supports eight (8) rx queues, but we are only allowing
* the first one to be used. Therefore, let's just allocate one queue.
*/
static int rxq_number = 1;
static int txq_number = 8;
static int rxq_def;
static int rx_copybreak __read_mostly = 256;
#define MVNETA_DRIVER_NAME "mvneta"
#define MVNETA_DRIVER_VERSION "1.0"
/* Utility/helper methods */
/* Write helper method */
static void mvreg_write(struct mvneta_port *pp, u32 offset, u32 data)
{
writel(data, pp->base + offset);
}
/* Read helper method */
static u32 mvreg_read(struct mvneta_port *pp, u32 offset)
{
return readl(pp->base + offset);
}
/* Increment txq get counter */
static void mvneta_txq_inc_get(struct mvneta_tx_queue *txq)
{
txq->txq_get_index++;
if (txq->txq_get_index == txq->size)
txq->txq_get_index = 0;
}
/* Increment txq put counter */
static void mvneta_txq_inc_put(struct mvneta_tx_queue *txq)
{
txq->txq_put_index++;
if (txq->txq_put_index == txq->size)
txq->txq_put_index = 0;
}
/* Clear all MIB counters */
static void mvneta_mib_counters_clear(struct mvneta_port *pp)
{
int i;
u32 dummy;
/* Perform dummy reads from MIB counters */
for (i = 0; i < MVNETA_MIB_LATE_COLLISION; i += 4)
dummy = mvreg_read(pp, (MVNETA_MIB_COUNTERS_BASE + i));
}
/* Get System Network Statistics */
struct rtnl_link_stats64 *mvneta_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
struct mvneta_port *pp = netdev_priv(dev);
unsigned int start;
int cpu;
for_each_possible_cpu(cpu) {
struct mvneta_pcpu_stats *cpu_stats;
u64 rx_packets;
u64 rx_bytes;
u64 tx_packets;
u64 tx_bytes;
cpu_stats = per_cpu_ptr(pp->stats, cpu);
do {
start = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
rx_packets = cpu_stats->rx_packets;
rx_bytes = cpu_stats->rx_bytes;
tx_packets = cpu_stats->tx_packets;
tx_bytes = cpu_stats->tx_bytes;
} while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, start));
stats->rx_packets += rx_packets;
stats->rx_bytes += rx_bytes;
stats->tx_packets += tx_packets;
stats->tx_bytes += tx_bytes;
}
stats->rx_errors = dev->stats.rx_errors;
stats->rx_dropped = dev->stats.rx_dropped;
stats->tx_dropped = dev->stats.tx_dropped;
return stats;
}
/* Rx descriptors helper methods */
/* Checks whether the RX descriptor having this status is both the first
* and the last descriptor for the RX packet. Each RX packet is currently
* received through a single RX descriptor, so not having each RX
* descriptor with its first and last bits set is an error
*/
static int mvneta_rxq_desc_is_first_last(u32 status)
{
return (status & MVNETA_RXD_FIRST_LAST_DESC) ==
MVNETA_RXD_FIRST_LAST_DESC;
}
/* Add number of descriptors ready to receive new packets */
static void mvneta_rxq_non_occup_desc_add(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq,
int ndescs)
{
/* Only MVNETA_RXQ_ADD_NON_OCCUPIED_MAX (255) descriptors can
* be added at once
*/
while (ndescs > MVNETA_RXQ_ADD_NON_OCCUPIED_MAX) {
mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id),
(MVNETA_RXQ_ADD_NON_OCCUPIED_MAX <<
MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT));
ndescs -= MVNETA_RXQ_ADD_NON_OCCUPIED_MAX;
}
mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id),
(ndescs << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT));
}
/* Get number of RX descriptors occupied by received packets */
static int mvneta_rxq_busy_desc_num_get(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq)
{
u32 val;
val = mvreg_read(pp, MVNETA_RXQ_STATUS_REG(rxq->id));
return val & MVNETA_RXQ_OCCUPIED_ALL_MASK;
}
/* Update num of rx desc called upon return from rx path or
* from mvneta_rxq_drop_pkts().
*/
static void mvneta_rxq_desc_num_update(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq,
int rx_done, int rx_filled)
{
u32 val;
if ((rx_done <= 0xff) && (rx_filled <= 0xff)) {
val = rx_done |
(rx_filled << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT);
mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), val);
return;
}
/* Only 255 descriptors can be added at once */
while ((rx_done > 0) || (rx_filled > 0)) {
if (rx_done <= 0xff) {
val = rx_done;
rx_done = 0;
} else {
val = 0xff;
rx_done -= 0xff;
}
if (rx_filled <= 0xff) {
val |= rx_filled << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT;
rx_filled = 0;
} else {
val |= 0xff << MVNETA_RXQ_ADD_NON_OCCUPIED_SHIFT;
rx_filled -= 0xff;
}
mvreg_write(pp, MVNETA_RXQ_STATUS_UPDATE_REG(rxq->id), val);
}
}
/* Get pointer to next RX descriptor to be processed by SW */
static struct mvneta_rx_desc *
mvneta_rxq_next_desc_get(struct mvneta_rx_queue *rxq)
{
int rx_desc = rxq->next_desc_to_proc;
rxq->next_desc_to_proc = MVNETA_QUEUE_NEXT_DESC(rxq, rx_desc);
prefetch(rxq->descs + rxq->next_desc_to_proc);
return rxq->descs + rx_desc;
}
/* Change maximum receive size of the port. */
static void mvneta_max_rx_size_set(struct mvneta_port *pp, int max_rx_size)
{
u32 val;
val = mvreg_read(pp, MVNETA_GMAC_CTRL_0);
val &= ~MVNETA_GMAC_MAX_RX_SIZE_MASK;
val |= ((max_rx_size - MVNETA_MH_SIZE) / 2) <<
MVNETA_GMAC_MAX_RX_SIZE_SHIFT;
mvreg_write(pp, MVNETA_GMAC_CTRL_0, val);
}
/* Set rx queue offset */
static void mvneta_rxq_offset_set(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq,
int offset)
{
u32 val;
val = mvreg_read(pp, MVNETA_RXQ_CONFIG_REG(rxq->id));
val &= ~MVNETA_RXQ_PKT_OFFSET_ALL_MASK;
/* Offset is in */
val |= MVNETA_RXQ_PKT_OFFSET_MASK(offset >> 3);
mvreg_write(pp, MVNETA_RXQ_CONFIG_REG(rxq->id), val);
}
/* Tx descriptors helper methods */
/* Update HW with number of TX descriptors to be sent */
static void mvneta_txq_pend_desc_add(struct mvneta_port *pp,
struct mvneta_tx_queue *txq,
int pend_desc)
{
u32 val;
/* Only 255 descriptors can be added at once ; Assume caller
* process TX desriptors in quanta less than 256
*/
val = pend_desc;
mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val);
}
/* Get pointer to next TX descriptor to be processed (send) by HW */
static struct mvneta_tx_desc *
mvneta_txq_next_desc_get(struct mvneta_tx_queue *txq)
{
int tx_desc = txq->next_desc_to_proc;
txq->next_desc_to_proc = MVNETA_QUEUE_NEXT_DESC(txq, tx_desc);
return txq->descs + tx_desc;
}
/* Release the last allocated TX descriptor. Useful to handle DMA
* mapping failures in the TX path.
*/
static void mvneta_txq_desc_put(struct mvneta_tx_queue *txq)
{
if (txq->next_desc_to_proc == 0)
txq->next_desc_to_proc = txq->last_desc - 1;
else
txq->next_desc_to_proc--;
}
/* Set rxq buf size */
static void mvneta_rxq_buf_size_set(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq,
int buf_size)
{
u32 val;
val = mvreg_read(pp, MVNETA_RXQ_SIZE_REG(rxq->id));
val &= ~MVNETA_RXQ_BUF_SIZE_MASK;
val |= ((buf_size >> 3) << MVNETA_RXQ_BUF_SIZE_SHIFT);
mvreg_write(pp, MVNETA_RXQ_SIZE_REG(rxq->id), val);
}
/* Disable buffer management (BM) */
static void mvneta_rxq_bm_disable(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq)
{
u32 val;
val = mvreg_read(pp, MVNETA_RXQ_CONFIG_REG(rxq->id));
val &= ~MVNETA_RXQ_HW_BUF_ALLOC;
mvreg_write(pp, MVNETA_RXQ_CONFIG_REG(rxq->id), val);
}
/* Start the Ethernet port RX and TX activity */
static void mvneta_port_up(struct mvneta_port *pp)
{
int queue;
u32 q_map;
/* Enable all initialized TXs. */
mvneta_mib_counters_clear(pp);
q_map = 0;
for (queue = 0; queue < txq_number; queue++) {
struct mvneta_tx_queue *txq = &pp->txqs[queue];
if (txq->descs != NULL)
q_map |= (1 << queue);
}
mvreg_write(pp, MVNETA_TXQ_CMD, q_map);
/* Enable all initialized RXQs. */
q_map = 0;
for (queue = 0; queue < rxq_number; queue++) {
struct mvneta_rx_queue *rxq = &pp->rxqs[queue];
if (rxq->descs != NULL)
q_map |= (1 << queue);
}
mvreg_write(pp, MVNETA_RXQ_CMD, q_map);
}
/* Stop the Ethernet port activity */
static void mvneta_port_down(struct mvneta_port *pp)
{
u32 val;
int count;
/* Stop Rx port activity. Check port Rx activity. */
val = mvreg_read(pp, MVNETA_RXQ_CMD) & MVNETA_RXQ_ENABLE_MASK;
/* Issue stop command for active channels only */
if (val != 0)
mvreg_write(pp, MVNETA_RXQ_CMD,
val << MVNETA_RXQ_DISABLE_SHIFT);
/* Wait for all Rx activity to terminate. */
count = 0;
do {
if (count++ >= MVNETA_RX_DISABLE_TIMEOUT_MSEC) {
netdev_warn(pp->dev,
"TIMEOUT for RX stopped ! rx_queue_cmd: 0x08%x\n",
val);
break;
}
mdelay(1);
val = mvreg_read(pp, MVNETA_RXQ_CMD);
} while (val & 0xff);
/* Stop Tx port activity. Check port Tx activity. Issue stop
* command for active channels only
*/
val = (mvreg_read(pp, MVNETA_TXQ_CMD)) & MVNETA_TXQ_ENABLE_MASK;
if (val != 0)
mvreg_write(pp, MVNETA_TXQ_CMD,
(val << MVNETA_TXQ_DISABLE_SHIFT));
/* Wait for all Tx activity to terminate. */
count = 0;
do {
if (count++ >= MVNETA_TX_DISABLE_TIMEOUT_MSEC) {
netdev_warn(pp->dev,
"TIMEOUT for TX stopped status=0x%08x\n",
val);
break;
}
mdelay(1);
/* Check TX Command reg that all Txqs are stopped */
val = mvreg_read(pp, MVNETA_TXQ_CMD);
} while (val & 0xff);
/* Double check to verify that TX FIFO is empty */
count = 0;
do {
if (count++ >= MVNETA_TX_FIFO_EMPTY_TIMEOUT) {
netdev_warn(pp->dev,
"TX FIFO empty timeout status=0x08%x\n",
val);
break;
}
mdelay(1);
val = mvreg_read(pp, MVNETA_PORT_STATUS);
} while (!(val & MVNETA_TX_FIFO_EMPTY) &&
(val & MVNETA_TX_IN_PRGRS));
udelay(200);
}
/* Enable the port by setting the port enable bit of the MAC control register */
static void mvneta_port_enable(struct mvneta_port *pp)
{
u32 val;
/* Enable port */
val = mvreg_read(pp, MVNETA_GMAC_CTRL_0);
val |= MVNETA_GMAC0_PORT_ENABLE;
mvreg_write(pp, MVNETA_GMAC_CTRL_0, val);
}
/* Disable the port and wait for about 200 usec before retuning */
static void mvneta_port_disable(struct mvneta_port *pp)
{
u32 val;
/* Reset the Enable bit in the Serial Control Register */
val = mvreg_read(pp, MVNETA_GMAC_CTRL_0);
val &= ~MVNETA_GMAC0_PORT_ENABLE;
mvreg_write(pp, MVNETA_GMAC_CTRL_0, val);
udelay(200);
}
/* Multicast tables methods */
/* Set all entries in Unicast MAC Table; queue==-1 means reject all */
static void mvneta_set_ucast_table(struct mvneta_port *pp, int queue)
{
int offset;
u32 val;
if (queue == -1) {
val = 0;
} else {
val = 0x1 | (queue << 1);
val |= (val << 24) | (val << 16) | (val << 8);
}
for (offset = 0; offset <= 0xc; offset += 4)
mvreg_write(pp, MVNETA_DA_FILT_UCAST_BASE + offset, val);
}
/* Set all entries in Special Multicast MAC Table; queue==-1 means reject all */
static void mvneta_set_special_mcast_table(struct mvneta_port *pp, int queue)
{
int offset;
u32 val;
if (queue == -1) {
val = 0;
} else {
val = 0x1 | (queue << 1);
val |= (val << 24) | (val << 16) | (val << 8);
}
for (offset = 0; offset <= 0xfc; offset += 4)
mvreg_write(pp, MVNETA_DA_FILT_SPEC_MCAST + offset, val);
}
/* Set all entries in Other Multicast MAC Table. queue==-1 means reject all */
static void mvneta_set_other_mcast_table(struct mvneta_port *pp, int queue)
{
int offset;
u32 val;
if (queue == -1) {
memset(pp->mcast_count, 0, sizeof(pp->mcast_count));
val = 0;
} else {
memset(pp->mcast_count, 1, sizeof(pp->mcast_count));
val = 0x1 | (queue << 1);
val |= (val << 24) | (val << 16) | (val << 8);
}
for (offset = 0; offset <= 0xfc; offset += 4)
mvreg_write(pp, MVNETA_DA_FILT_OTH_MCAST + offset, val);
}
/* This method sets defaults to the NETA port:
* Clears interrupt Cause and Mask registers.
* Clears all MAC tables.
* Sets defaults to all registers.
* Resets RX and TX descriptor rings.
* Resets PHY.
* This method can be called after mvneta_port_down() to return the port
* settings to defaults.
*/
static void mvneta_defaults_set(struct mvneta_port *pp)
{
int cpu;
int queue;
u32 val;
/* Clear all Cause registers */
mvreg_write(pp, MVNETA_INTR_NEW_CAUSE, 0);
mvreg_write(pp, MVNETA_INTR_OLD_CAUSE, 0);
mvreg_write(pp, MVNETA_INTR_MISC_CAUSE, 0);
/* Mask all interrupts */
mvreg_write(pp, MVNETA_INTR_NEW_MASK, 0);
mvreg_write(pp, MVNETA_INTR_OLD_MASK, 0);
mvreg_write(pp, MVNETA_INTR_MISC_MASK, 0);
mvreg_write(pp, MVNETA_INTR_ENABLE, 0);
/* Enable MBUS Retry bit16 */
mvreg_write(pp, MVNETA_MBUS_RETRY, 0x20);
/* Set CPU queue access map - all CPUs have access to all RX
* queues and to all TX queues
*/
for (cpu = 0; cpu < CONFIG_NR_CPUS; cpu++)
mvreg_write(pp, MVNETA_CPU_MAP(cpu),
(MVNETA_CPU_RXQ_ACCESS_ALL_MASK |
MVNETA_CPU_TXQ_ACCESS_ALL_MASK));
/* Reset RX and TX DMAs */
mvreg_write(pp, MVNETA_PORT_RX_RESET, MVNETA_PORT_RX_DMA_RESET);
mvreg_write(pp, MVNETA_PORT_TX_RESET, MVNETA_PORT_TX_DMA_RESET);
/* Disable Legacy WRR, Disable EJP, Release from reset */
mvreg_write(pp, MVNETA_TXQ_CMD_1, 0);
for (queue = 0; queue < txq_number; queue++) {
mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(queue), 0);
mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(queue), 0);
}
mvreg_write(pp, MVNETA_PORT_TX_RESET, 0);
mvreg_write(pp, MVNETA_PORT_RX_RESET, 0);
/* Set Port Acceleration Mode */
val = MVNETA_ACC_MODE_EXT;
mvreg_write(pp, MVNETA_ACC_MODE, val);
/* Update val of portCfg register accordingly with all RxQueue types */
val = MVNETA_PORT_CONFIG_DEFL_VALUE(rxq_def);
mvreg_write(pp, MVNETA_PORT_CONFIG, val);
val = 0;
mvreg_write(pp, MVNETA_PORT_CONFIG_EXTEND, val);
mvreg_write(pp, MVNETA_RX_MIN_FRAME_SIZE, 64);
/* Build PORT_SDMA_CONFIG_REG */
val = 0;
/* Default burst size */
val |= MVNETA_TX_BRST_SZ_MASK(MVNETA_SDMA_BRST_SIZE_16);
val |= MVNETA_RX_BRST_SZ_MASK(MVNETA_SDMA_BRST_SIZE_16);
val |= MVNETA_RX_NO_DATA_SWAP | MVNETA_TX_NO_DATA_SWAP;
#if defined(__BIG_ENDIAN)
val |= MVNETA_DESC_SWAP;
#endif
/* Assign port SDMA configuration */
mvreg_write(pp, MVNETA_SDMA_CONFIG, val);
/* Disable PHY polling in hardware, since we're using the
* kernel phylib to do this.
*/
val = mvreg_read(pp, MVNETA_UNIT_CONTROL);
val &= ~MVNETA_PHY_POLLING_ENABLE;
mvreg_write(pp, MVNETA_UNIT_CONTROL, val);
mvneta_set_ucast_table(pp, -1);
mvneta_set_special_mcast_table(pp, -1);
mvneta_set_other_mcast_table(pp, -1);
/* Set port interrupt enable register - default enable all */
mvreg_write(pp, MVNETA_INTR_ENABLE,
(MVNETA_RXQ_INTR_ENABLE_ALL_MASK
| MVNETA_TXQ_INTR_ENABLE_ALL_MASK));
}
/* Set max sizes for tx queues */
static void mvneta_txq_max_tx_size_set(struct mvneta_port *pp, int max_tx_size)
{
u32 val, size, mtu;
int queue;
mtu = max_tx_size * 8;
if (mtu > MVNETA_TX_MTU_MAX)
mtu = MVNETA_TX_MTU_MAX;
/* Set MTU */
val = mvreg_read(pp, MVNETA_TX_MTU);
val &= ~MVNETA_TX_MTU_MAX;
val |= mtu;
mvreg_write(pp, MVNETA_TX_MTU, val);
/* TX token size and all TXQs token size must be larger that MTU */
val = mvreg_read(pp, MVNETA_TX_TOKEN_SIZE);
size = val & MVNETA_TX_TOKEN_SIZE_MAX;
if (size < mtu) {
size = mtu;
val &= ~MVNETA_TX_TOKEN_SIZE_MAX;
val |= size;
mvreg_write(pp, MVNETA_TX_TOKEN_SIZE, val);
}
for (queue = 0; queue < txq_number; queue++) {
val = mvreg_read(pp, MVNETA_TXQ_TOKEN_SIZE_REG(queue));
size = val & MVNETA_TXQ_TOKEN_SIZE_MAX;
if (size < mtu) {
size = mtu;
val &= ~MVNETA_TXQ_TOKEN_SIZE_MAX;
val |= size;
mvreg_write(pp, MVNETA_TXQ_TOKEN_SIZE_REG(queue), val);
}
}
}
/* Set unicast address */
static void mvneta_set_ucast_addr(struct mvneta_port *pp, u8 last_nibble,
int queue)
{
unsigned int unicast_reg;
unsigned int tbl_offset;
unsigned int reg_offset;
/* Locate the Unicast table entry */
last_nibble = (0xf & last_nibble);
/* offset from unicast tbl base */
tbl_offset = (last_nibble / 4) * 4;
/* offset within the above reg */
reg_offset = last_nibble % 4;
unicast_reg = mvreg_read(pp, (MVNETA_DA_FILT_UCAST_BASE + tbl_offset));
if (queue == -1) {
/* Clear accepts frame bit at specified unicast DA tbl entry */
unicast_reg &= ~(0xff << (8 * reg_offset));
} else {
unicast_reg &= ~(0xff << (8 * reg_offset));
unicast_reg |= ((0x01 | (queue << 1)) << (8 * reg_offset));
}
mvreg_write(pp, (MVNETA_DA_FILT_UCAST_BASE + tbl_offset), unicast_reg);
}
/* Set mac address */
static void mvneta_mac_addr_set(struct mvneta_port *pp, unsigned char *addr,
int queue)
{
unsigned int mac_h;
unsigned int mac_l;
if (queue != -1) {
mac_l = (addr[4] << 8) | (addr[5]);
mac_h = (addr[0] << 24) | (addr[1] << 16) |
(addr[2] << 8) | (addr[3] << 0);
mvreg_write(pp, MVNETA_MAC_ADDR_LOW, mac_l);
mvreg_write(pp, MVNETA_MAC_ADDR_HIGH, mac_h);
}
/* Accept frames of this address */
mvneta_set_ucast_addr(pp, addr[5], queue);
}
/* Set the number of packets that will be received before RX interrupt
* will be generated by HW.
*/
static void mvneta_rx_pkts_coal_set(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq, u32 value)
{
mvreg_write(pp, MVNETA_RXQ_THRESHOLD_REG(rxq->id),
value | MVNETA_RXQ_NON_OCCUPIED(0));
rxq->pkts_coal = value;
}
/* Set the time delay in usec before RX interrupt will be generated by
* HW.
*/
static void mvneta_rx_time_coal_set(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq, u32 value)
{
u32 val;
unsigned long clk_rate;
clk_rate = clk_get_rate(pp->clk);
val = (clk_rate / 1000000) * value;
mvreg_write(pp, MVNETA_RXQ_TIME_COAL_REG(rxq->id), val);
rxq->time_coal = value;
}
/* Set threshold for TX_DONE pkts coalescing */
static void mvneta_tx_done_pkts_coal_set(struct mvneta_port *pp,
struct mvneta_tx_queue *txq, u32 value)
{
u32 val;
val = mvreg_read(pp, MVNETA_TXQ_SIZE_REG(txq->id));
val &= ~MVNETA_TXQ_SENT_THRESH_ALL_MASK;
val |= MVNETA_TXQ_SENT_THRESH_MASK(value);
mvreg_write(pp, MVNETA_TXQ_SIZE_REG(txq->id), val);
txq->done_pkts_coal = value;
}
/* Handle rx descriptor fill by setting buf_cookie and buf_phys_addr */
static void mvneta_rx_desc_fill(struct mvneta_rx_desc *rx_desc,
u32 phys_addr, u32 cookie)
{
rx_desc->buf_cookie = cookie;
rx_desc->buf_phys_addr = phys_addr;
}
/* Decrement sent descriptors counter */
static void mvneta_txq_sent_desc_dec(struct mvneta_port *pp,
struct mvneta_tx_queue *txq,
int sent_desc)
{
u32 val;
/* Only 255 TX descriptors can be updated at once */
while (sent_desc > 0xff) {
val = 0xff << MVNETA_TXQ_DEC_SENT_SHIFT;
mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val);
sent_desc = sent_desc - 0xff;
}
val = sent_desc << MVNETA_TXQ_DEC_SENT_SHIFT;
mvreg_write(pp, MVNETA_TXQ_UPDATE_REG(txq->id), val);
}
/* Get number of TX descriptors already sent by HW */
static int mvneta_txq_sent_desc_num_get(struct mvneta_port *pp,
struct mvneta_tx_queue *txq)
{
u32 val;
int sent_desc;
val = mvreg_read(pp, MVNETA_TXQ_STATUS_REG(txq->id));
sent_desc = (val & MVNETA_TXQ_SENT_DESC_MASK) >>
MVNETA_TXQ_SENT_DESC_SHIFT;
return sent_desc;
}
/* Get number of sent descriptors and decrement counter.
* The number of sent descriptors is returned.
*/
static int mvneta_txq_sent_desc_proc(struct mvneta_port *pp,
struct mvneta_tx_queue *txq)
{
int sent_desc;
/* Get number of sent descriptors */
sent_desc = mvneta_txq_sent_desc_num_get(pp, txq);
/* Decrement sent descriptors counter */
if (sent_desc)
mvneta_txq_sent_desc_dec(pp, txq, sent_desc);
return sent_desc;
}
/* Set TXQ descriptors fields relevant for CSUM calculation */
static u32 mvneta_txq_desc_csum(int l3_offs, int l3_proto,
int ip_hdr_len, int l4_proto)
{
u32 command;
/* Fields: L3_offset, IP_hdrlen, L3_type, G_IPv4_chk,
* G_L4_chk, L4_type; required only for checksum
* calculation
*/
command = l3_offs << MVNETA_TX_L3_OFF_SHIFT;
command |= ip_hdr_len << MVNETA_TX_IP_HLEN_SHIFT;
if (l3_proto == htons(ETH_P_IP))
command |= MVNETA_TXD_IP_CSUM;
else
command |= MVNETA_TX_L3_IP6;
if (l4_proto == IPPROTO_TCP)
command |= MVNETA_TX_L4_CSUM_FULL;
else if (l4_proto == IPPROTO_UDP)
command |= MVNETA_TX_L4_UDP | MVNETA_TX_L4_CSUM_FULL;
else
command |= MVNETA_TX_L4_CSUM_NOT;
return command;
}
/* Display more error info */
static void mvneta_rx_error(struct mvneta_port *pp,
struct mvneta_rx_desc *rx_desc)
{
u32 status = rx_desc->status;
if (!mvneta_rxq_desc_is_first_last(status)) {
netdev_err(pp->dev,
"bad rx status %08x (buffer oversize), size=%d\n",
status, rx_desc->data_size);
return;
}
switch (status & MVNETA_RXD_ERR_CODE_MASK) {
case MVNETA_RXD_ERR_CRC:
netdev_err(pp->dev, "bad rx status %08x (crc error), size=%d\n",
status, rx_desc->data_size);
break;
case MVNETA_RXD_ERR_OVERRUN:
netdev_err(pp->dev, "bad rx status %08x (overrun error), size=%d\n",
status, rx_desc->data_size);
break;
case MVNETA_RXD_ERR_LEN:
netdev_err(pp->dev, "bad rx status %08x (max frame length error), size=%d\n",
status, rx_desc->data_size);
break;
case MVNETA_RXD_ERR_RESOURCE:
netdev_err(pp->dev, "bad rx status %08x (resource error), size=%d\n",
status, rx_desc->data_size);
break;
}
}
/* Handle RX checksum offload based on the descriptor's status */
static void mvneta_rx_csum(struct mvneta_port *pp, u32 status,
struct sk_buff *skb)
{
if ((status & MVNETA_RXD_L3_IP4) &&
(status & MVNETA_RXD_L4_CSUM_OK)) {
skb->csum = 0;
skb->ip_summed = CHECKSUM_UNNECESSARY;
return;
}
skb->ip_summed = CHECKSUM_NONE;
}
/* Return tx queue pointer (find last set bit) according to <cause> returned
* form tx_done reg. <cause> must not be null. The return value is always a
* valid queue for matching the first one found in <cause>.
*/
static struct mvneta_tx_queue *mvneta_tx_done_policy(struct mvneta_port *pp,
u32 cause)
{
int queue = fls(cause) - 1;
return &pp->txqs[queue];
}
/* Free tx queue skbuffs */
static void mvneta_txq_bufs_free(struct mvneta_port *pp,
struct mvneta_tx_queue *txq, int num)
{
int i;
for (i = 0; i < num; i++) {
struct mvneta_tx_desc *tx_desc = txq->descs +
txq->txq_get_index;
struct sk_buff *skb = txq->tx_skb[txq->txq_get_index];
mvneta_txq_inc_get(txq);
if (!IS_TSO_HEADER(txq, tx_desc->buf_phys_addr))
dma_unmap_single(pp->dev->dev.parent,
tx_desc->buf_phys_addr,
tx_desc->data_size, DMA_TO_DEVICE);
if (!skb)
continue;
dev_kfree_skb_any(skb);
}
}
/* Handle end of transmission */
static void mvneta_txq_done(struct mvneta_port *pp,
struct mvneta_tx_queue *txq)
{
struct netdev_queue *nq = netdev_get_tx_queue(pp->dev, txq->id);
int tx_done;
tx_done = mvneta_txq_sent_desc_proc(pp, txq);
if (!tx_done)
return;
mvneta_txq_bufs_free(pp, txq, tx_done);
txq->count -= tx_done;
if (netif_tx_queue_stopped(nq)) {
if (txq->count <= txq->tx_wake_threshold)
netif_tx_wake_queue(nq);
}
}
static void *mvneta_frag_alloc(const struct mvneta_port *pp)
{
if (likely(pp->frag_size <= PAGE_SIZE))
return netdev_alloc_frag(pp->frag_size);
else
return kmalloc(pp->frag_size, GFP_ATOMIC);
}
static void mvneta_frag_free(const struct mvneta_port *pp, void *data)
{
if (likely(pp->frag_size <= PAGE_SIZE))
put_page(virt_to_head_page(data));
else
kfree(data);
}
/* Refill processing */
static int mvneta_rx_refill(struct mvneta_port *pp,
struct mvneta_rx_desc *rx_desc)
{
dma_addr_t phys_addr;
void *data;
data = mvneta_frag_alloc(pp);
if (!data)
return -ENOMEM;
phys_addr = dma_map_single(pp->dev->dev.parent, data,
MVNETA_RX_BUF_SIZE(pp->pkt_size),
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(pp->dev->dev.parent, phys_addr))) {
mvneta_frag_free(pp, data);
return -ENOMEM;
}
mvneta_rx_desc_fill(rx_desc, phys_addr, (u32)data);
return 0;
}
/* Handle tx checksum */
static u32 mvneta_skb_tx_csum(struct mvneta_port *pp, struct sk_buff *skb)
{
if (skb->ip_summed == CHECKSUM_PARTIAL) {
int ip_hdr_len = 0;
__be16 l3_proto = vlan_get_protocol(skb);
u8 l4_proto;
if (l3_proto == htons(ETH_P_IP)) {
struct iphdr *ip4h = ip_hdr(skb);
/* Calculate IPv4 checksum and L4 checksum */
ip_hdr_len = ip4h->ihl;
l4_proto = ip4h->protocol;
} else if (l3_proto == htons(ETH_P_IPV6)) {
struct ipv6hdr *ip6h = ipv6_hdr(skb);
/* Read l4_protocol from one of IPv6 extra headers */
if (skb_network_header_len(skb) > 0)
ip_hdr_len = (skb_network_header_len(skb) >> 2);
l4_proto = ip6h->nexthdr;
} else
return MVNETA_TX_L4_CSUM_NOT;
return mvneta_txq_desc_csum(skb_network_offset(skb),
l3_proto, ip_hdr_len, l4_proto);
}
return MVNETA_TX_L4_CSUM_NOT;
}
/* Returns rx queue pointer (find last set bit) according to causeRxTx
* value
*/
static struct mvneta_rx_queue *mvneta_rx_policy(struct mvneta_port *pp,
u32 cause)
{
int queue = fls(cause >> 8) - 1;
return (queue < 0 || queue >= rxq_number) ? NULL : &pp->rxqs[queue];
}
/* Drop packets received by the RXQ and free buffers */
static void mvneta_rxq_drop_pkts(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq)
{
int rx_done, i;
rx_done = mvneta_rxq_busy_desc_num_get(pp, rxq);
for (i = 0; i < rxq->size; i++) {
struct mvneta_rx_desc *rx_desc = rxq->descs + i;
void *data = (void *)rx_desc->buf_cookie;
mvneta_frag_free(pp, data);
dma_unmap_single(pp->dev->dev.parent, rx_desc->buf_phys_addr,
MVNETA_RX_BUF_SIZE(pp->pkt_size), DMA_FROM_DEVICE);
}
if (rx_done)
mvneta_rxq_desc_num_update(pp, rxq, rx_done, rx_done);
}
/* Main rx processing */
static int mvneta_rx(struct mvneta_port *pp, int rx_todo,
struct mvneta_rx_queue *rxq)
{
struct net_device *dev = pp->dev;
int rx_done, rx_filled;
u32 rcvd_pkts = 0;
u32 rcvd_bytes = 0;
/* Get number of received packets */
rx_done = mvneta_rxq_busy_desc_num_get(pp, rxq);
if (rx_todo > rx_done)
rx_todo = rx_done;
rx_done = 0;
rx_filled = 0;
/* Fairness NAPI loop */
while (rx_done < rx_todo) {
struct mvneta_rx_desc *rx_desc = mvneta_rxq_next_desc_get(rxq);
struct sk_buff *skb;
unsigned char *data;
u32 rx_status;
int rx_bytes, err;
rx_done++;
rx_filled++;
rx_status = rx_desc->status;
rx_bytes = rx_desc->data_size - (ETH_FCS_LEN + MVNETA_MH_SIZE);
data = (unsigned char *)rx_desc->buf_cookie;
if (!mvneta_rxq_desc_is_first_last(rx_status) ||
(rx_status & MVNETA_RXD_ERR_SUMMARY)) {
err_drop_frame:
dev->stats.rx_errors++;
mvneta_rx_error(pp, rx_desc);
/* leave the descriptor untouched */
continue;
}
if (rx_bytes <= rx_copybreak) {
/* better copy a small frame and not unmap the DMA region */
skb = netdev_alloc_skb_ip_align(dev, rx_bytes);
if (unlikely(!skb))
goto err_drop_frame;
dma_sync_single_range_for_cpu(dev->dev.parent,
rx_desc->buf_phys_addr,
MVNETA_MH_SIZE + NET_SKB_PAD,
rx_bytes,
DMA_FROM_DEVICE);
memcpy(skb_put(skb, rx_bytes),
data + MVNETA_MH_SIZE + NET_SKB_PAD,
rx_bytes);
skb->protocol = eth_type_trans(skb, dev);
mvneta_rx_csum(pp, rx_status, skb);
napi_gro_receive(&pp->napi, skb);
rcvd_pkts++;
rcvd_bytes += rx_bytes;
/* leave the descriptor and buffer untouched */
continue;
}
skb = build_skb(data, pp->frag_size > PAGE_SIZE ? 0 : pp->frag_size);
if (!skb)
goto err_drop_frame;
dma_unmap_single(dev->dev.parent, rx_desc->buf_phys_addr,
MVNETA_RX_BUF_SIZE(pp->pkt_size), DMA_FROM_DEVICE);
rcvd_pkts++;
rcvd_bytes += rx_bytes;
/* Linux processing */
skb_reserve(skb, MVNETA_MH_SIZE + NET_SKB_PAD);
skb_put(skb, rx_bytes);
skb->protocol = eth_type_trans(skb, dev);
mvneta_rx_csum(pp, rx_status, skb);
napi_gro_receive(&pp->napi, skb);
/* Refill processing */
err = mvneta_rx_refill(pp, rx_desc);
if (err) {
netdev_err(dev, "Linux processing - Can't refill\n");
rxq->missed++;
rx_filled--;
}
}
if (rcvd_pkts) {
struct mvneta_pcpu_stats *stats = this_cpu_ptr(pp->stats);
u64_stats_update_begin(&stats->syncp);
stats->rx_packets += rcvd_pkts;
stats->rx_bytes += rcvd_bytes;
u64_stats_update_end(&stats->syncp);
}
/* Update rxq management counters */
mvneta_rxq_desc_num_update(pp, rxq, rx_done, rx_filled);
return rx_done;
}
static inline void
mvneta_tso_put_hdr(struct sk_buff *skb,
struct mvneta_port *pp, struct mvneta_tx_queue *txq)
{
struct mvneta_tx_desc *tx_desc;
int hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
txq->tx_skb[txq->txq_put_index] = NULL;
tx_desc = mvneta_txq_next_desc_get(txq);
tx_desc->data_size = hdr_len;
tx_desc->command = mvneta_skb_tx_csum(pp, skb);
tx_desc->command |= MVNETA_TXD_F_DESC;
tx_desc->buf_phys_addr = txq->tso_hdrs_phys +
txq->txq_put_index * TSO_HEADER_SIZE;
mvneta_txq_inc_put(txq);
}
static inline int
mvneta_tso_put_data(struct net_device *dev, struct mvneta_tx_queue *txq,
struct sk_buff *skb, char *data, int size,
bool last_tcp, bool is_last)
{
struct mvneta_tx_desc *tx_desc;
tx_desc = mvneta_txq_next_desc_get(txq);
tx_desc->data_size = size;
tx_desc->buf_phys_addr = dma_map_single(dev->dev.parent, data,
size, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(dev->dev.parent,
tx_desc->buf_phys_addr))) {
mvneta_txq_desc_put(txq);
return -ENOMEM;
}
tx_desc->command = 0;
txq->tx_skb[txq->txq_put_index] = NULL;
if (last_tcp) {
/* last descriptor in the TCP packet */
tx_desc->command = MVNETA_TXD_L_DESC;
/* last descriptor in SKB */
if (is_last)
txq->tx_skb[txq->txq_put_index] = skb;
}
mvneta_txq_inc_put(txq);
return 0;
}
static int mvneta_tx_tso(struct sk_buff *skb, struct net_device *dev,
struct mvneta_tx_queue *txq)
{
int total_len, data_left;
int desc_count = 0;
struct mvneta_port *pp = netdev_priv(dev);
struct tso_t tso;
int hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
int i;
/* Count needed descriptors */
if ((txq->count + tso_count_descs(skb)) >= txq->size)
return 0;
if (skb_headlen(skb) < (skb_transport_offset(skb) + tcp_hdrlen(skb))) {
pr_info("*** Is this even possible???!?!?\n");
return 0;
}
/* Initialize the TSO handler, and prepare the first payload */
tso_start(skb, &tso);
total_len = skb->len - hdr_len;
while (total_len > 0) {
char *hdr;
data_left = min_t(int, skb_shinfo(skb)->gso_size, total_len);
total_len -= data_left;
desc_count++;
/* prepare packet headers: MAC + IP + TCP */
hdr = txq->tso_hdrs + txq->txq_put_index * TSO_HEADER_SIZE;
tso_build_hdr(skb, hdr, &tso, data_left, total_len == 0);
mvneta_tso_put_hdr(skb, pp, txq);
while (data_left > 0) {
int size;
desc_count++;
size = min_t(int, tso.size, data_left);
if (mvneta_tso_put_data(dev, txq, skb,
tso.data, size,
size == data_left,
total_len == 0))
goto err_release;
data_left -= size;
tso_build_data(skb, &tso, size);
}
}
return desc_count;
err_release:
/* Release all used data descriptors; header descriptors must not
* be DMA-unmapped.
*/
for (i = desc_count - 1; i >= 0; i--) {
struct mvneta_tx_desc *tx_desc = txq->descs + i;
if (!IS_TSO_HEADER(txq, tx_desc->buf_phys_addr))
dma_unmap_single(pp->dev->dev.parent,
tx_desc->buf_phys_addr,
tx_desc->data_size,
DMA_TO_DEVICE);
mvneta_txq_desc_put(txq);
}
return 0;
}
/* Handle tx fragmentation processing */
static int mvneta_tx_frag_process(struct mvneta_port *pp, struct sk_buff *skb,
struct mvneta_tx_queue *txq)
{
struct mvneta_tx_desc *tx_desc;
int i, nr_frags = skb_shinfo(skb)->nr_frags;
for (i = 0; i < nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
void *addr = page_address(frag->page.p) + frag->page_offset;
tx_desc = mvneta_txq_next_desc_get(txq);
tx_desc->data_size = frag->size;
tx_desc->buf_phys_addr =
dma_map_single(pp->dev->dev.parent, addr,
tx_desc->data_size, DMA_TO_DEVICE);
if (dma_mapping_error(pp->dev->dev.parent,
tx_desc->buf_phys_addr)) {
mvneta_txq_desc_put(txq);
goto error;
}
if (i == nr_frags - 1) {
/* Last descriptor */
tx_desc->command = MVNETA_TXD_L_DESC | MVNETA_TXD_Z_PAD;
txq->tx_skb[txq->txq_put_index] = skb;
} else {
/* Descriptor in the middle: Not First, Not Last */
tx_desc->command = 0;
txq->tx_skb[txq->txq_put_index] = NULL;
}
mvneta_txq_inc_put(txq);
}
return 0;
error:
/* Release all descriptors that were used to map fragments of
* this packet, as well as the corresponding DMA mappings
*/
for (i = i - 1; i >= 0; i--) {
tx_desc = txq->descs + i;
dma_unmap_single(pp->dev->dev.parent,
tx_desc->buf_phys_addr,
tx_desc->data_size,
DMA_TO_DEVICE);
mvneta_txq_desc_put(txq);
}
return -ENOMEM;
}
/* Main tx processing */
static int mvneta_tx(struct sk_buff *skb, struct net_device *dev)
{
struct mvneta_port *pp = netdev_priv(dev);
u16 txq_id = skb_get_queue_mapping(skb);
struct mvneta_tx_queue *txq = &pp->txqs[txq_id];
struct mvneta_tx_desc *tx_desc;
int len = skb->len;
int frags = 0;
u32 tx_cmd;
if (!netif_running(dev))
goto out;
if (skb_is_gso(skb)) {
frags = mvneta_tx_tso(skb, dev, txq);
goto out;
}
frags = skb_shinfo(skb)->nr_frags + 1;
/* Get a descriptor for the first part of the packet */
tx_desc = mvneta_txq_next_desc_get(txq);
tx_cmd = mvneta_skb_tx_csum(pp, skb);
tx_desc->data_size = skb_headlen(skb);
tx_desc->buf_phys_addr = dma_map_single(dev->dev.parent, skb->data,
tx_desc->data_size,
DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(dev->dev.parent,
tx_desc->buf_phys_addr))) {
mvneta_txq_desc_put(txq);
frags = 0;
goto out;
}
if (frags == 1) {
/* First and Last descriptor */
tx_cmd |= MVNETA_TXD_FLZ_DESC;
tx_desc->command = tx_cmd;
txq->tx_skb[txq->txq_put_index] = skb;
mvneta_txq_inc_put(txq);
} else {
/* First but not Last */
tx_cmd |= MVNETA_TXD_F_DESC;
txq->tx_skb[txq->txq_put_index] = NULL;
mvneta_txq_inc_put(txq);
tx_desc->command = tx_cmd;
/* Continue with other skb fragments */
if (mvneta_tx_frag_process(pp, skb, txq)) {
dma_unmap_single(dev->dev.parent,
tx_desc->buf_phys_addr,
tx_desc->data_size,
DMA_TO_DEVICE);
mvneta_txq_desc_put(txq);
frags = 0;
goto out;
}
}
out:
if (frags > 0) {
struct mvneta_pcpu_stats *stats = this_cpu_ptr(pp->stats);
struct netdev_queue *nq = netdev_get_tx_queue(dev, txq_id);
txq->count += frags;
mvneta_txq_pend_desc_add(pp, txq, frags);
if (txq->count >= txq->tx_stop_threshold)
netif_tx_stop_queue(nq);
u64_stats_update_begin(&stats->syncp);
stats->tx_packets++;
stats->tx_bytes += len;
u64_stats_update_end(&stats->syncp);
} else {
dev->stats.tx_dropped++;
dev_kfree_skb_any(skb);
}
return NETDEV_TX_OK;
}
/* Free tx resources, when resetting a port */
static void mvneta_txq_done_force(struct mvneta_port *pp,
struct mvneta_tx_queue *txq)
{
int tx_done = txq->count;
mvneta_txq_bufs_free(pp, txq, tx_done);
/* reset txq */
txq->count = 0;
txq->txq_put_index = 0;
txq->txq_get_index = 0;
}
/* Handle tx done - called in softirq context. The <cause_tx_done> argument
* must be a valid cause according to MVNETA_TXQ_INTR_MASK_ALL.
*/
static void mvneta_tx_done_gbe(struct mvneta_port *pp, u32 cause_tx_done)
{
struct mvneta_tx_queue *txq;
struct netdev_queue *nq;
while (cause_tx_done) {
txq = mvneta_tx_done_policy(pp, cause_tx_done);
nq = netdev_get_tx_queue(pp->dev, txq->id);
__netif_tx_lock(nq, smp_processor_id());
if (txq->count)
mvneta_txq_done(pp, txq);
__netif_tx_unlock(nq);
cause_tx_done &= ~((1 << txq->id));
}
}
/* Compute crc8 of the specified address, using a unique algorithm ,
* according to hw spec, different than generic crc8 algorithm
*/
static int mvneta_addr_crc(unsigned char *addr)
{
int crc = 0;
int i;
for (i = 0; i < ETH_ALEN; i++) {
int j;
crc = (crc ^ addr[i]) << 8;
for (j = 7; j >= 0; j--) {
if (crc & (0x100 << j))
crc ^= 0x107 << j;
}
}
return crc;
}
/* This method controls the net device special MAC multicast support.
* The Special Multicast Table for MAC addresses supports MAC of the form
* 0x01-00-5E-00-00-XX (where XX is between 0x00 and 0xFF).
* The MAC DA[7:0] bits are used as a pointer to the Special Multicast
* Table entries in the DA-Filter table. This method set the Special
* Multicast Table appropriate entry.
*/
static void mvneta_set_special_mcast_addr(struct mvneta_port *pp,
unsigned char last_byte,
int queue)
{
unsigned int smc_table_reg;
unsigned int tbl_offset;
unsigned int reg_offset;
/* Register offset from SMC table base */
tbl_offset = (last_byte / 4);
/* Entry offset within the above reg */
reg_offset = last_byte % 4;
smc_table_reg = mvreg_read(pp, (MVNETA_DA_FILT_SPEC_MCAST
+ tbl_offset * 4));
if (queue == -1)
smc_table_reg &= ~(0xff << (8 * reg_offset));
else {
smc_table_reg &= ~(0xff << (8 * reg_offset));
smc_table_reg |= ((0x01 | (queue << 1)) << (8 * reg_offset));
}
mvreg_write(pp, MVNETA_DA_FILT_SPEC_MCAST + tbl_offset * 4,
smc_table_reg);
}
/* This method controls the network device Other MAC multicast support.
* The Other Multicast Table is used for multicast of another type.
* A CRC-8 is used as an index to the Other Multicast Table entries
* in the DA-Filter table.
* The method gets the CRC-8 value from the calling routine and
* sets the Other Multicast Table appropriate entry according to the
* specified CRC-8 .
*/
static void mvneta_set_other_mcast_addr(struct mvneta_port *pp,
unsigned char crc8,
int queue)
{
unsigned int omc_table_reg;
unsigned int tbl_offset;
unsigned int reg_offset;
tbl_offset = (crc8 / 4) * 4; /* Register offset from OMC table base */
reg_offset = crc8 % 4; /* Entry offset within the above reg */
omc_table_reg = mvreg_read(pp, MVNETA_DA_FILT_OTH_MCAST + tbl_offset);
if (queue == -1) {
/* Clear accepts frame bit at specified Other DA table entry */
omc_table_reg &= ~(0xff << (8 * reg_offset));
} else {
omc_table_reg &= ~(0xff << (8 * reg_offset));
omc_table_reg |= ((0x01 | (queue << 1)) << (8 * reg_offset));
}
mvreg_write(pp, MVNETA_DA_FILT_OTH_MCAST + tbl_offset, omc_table_reg);
}
/* The network device supports multicast using two tables:
* 1) Special Multicast Table for MAC addresses of the form
* 0x01-00-5E-00-00-XX (where XX is between 0x00 and 0xFF).
* The MAC DA[7:0] bits are used as a pointer to the Special Multicast
* Table entries in the DA-Filter table.
* 2) Other Multicast Table for multicast of another type. A CRC-8 value
* is used as an index to the Other Multicast Table entries in the
* DA-Filter table.
*/
static int mvneta_mcast_addr_set(struct mvneta_port *pp, unsigned char *p_addr,
int queue)
{
unsigned char crc_result = 0;
if (memcmp(p_addr, "\x01\x00\x5e\x00\x00", 5) == 0) {
mvneta_set_special_mcast_addr(pp, p_addr[5], queue);
return 0;
}
crc_result = mvneta_addr_crc(p_addr);
if (queue == -1) {
if (pp->mcast_count[crc_result] == 0) {
netdev_info(pp->dev, "No valid Mcast for crc8=0x%02x\n",
crc_result);
return -EINVAL;
}
pp->mcast_count[crc_result]--;
if (pp->mcast_count[crc_result] != 0) {
netdev_info(pp->dev,
"After delete there are %d valid Mcast for crc8=0x%02x\n",
pp->mcast_count[crc_result], crc_result);
return -EINVAL;
}
} else
pp->mcast_count[crc_result]++;
mvneta_set_other_mcast_addr(pp, crc_result, queue);
return 0;
}
/* Configure Fitering mode of Ethernet port */
static void mvneta_rx_unicast_promisc_set(struct mvneta_port *pp,
int is_promisc)
{
u32 port_cfg_reg, val;
port_cfg_reg = mvreg_read(pp, MVNETA_PORT_CONFIG);
val = mvreg_read(pp, MVNETA_TYPE_PRIO);
/* Set / Clear UPM bit in port configuration register */
if (is_promisc) {
/* Accept all Unicast addresses */
port_cfg_reg |= MVNETA_UNI_PROMISC_MODE;
val |= MVNETA_FORCE_UNI;
mvreg_write(pp, MVNETA_MAC_ADDR_LOW, 0xffff);
mvreg_write(pp, MVNETA_MAC_ADDR_HIGH, 0xffffffff);
} else {
/* Reject all Unicast addresses */
port_cfg_reg &= ~MVNETA_UNI_PROMISC_MODE;
val &= ~MVNETA_FORCE_UNI;
}
mvreg_write(pp, MVNETA_PORT_CONFIG, port_cfg_reg);
mvreg_write(pp, MVNETA_TYPE_PRIO, val);
}
/* register unicast and multicast addresses */
static void mvneta_set_rx_mode(struct net_device *dev)
{
struct mvneta_port *pp = netdev_priv(dev);
struct netdev_hw_addr *ha;
if (dev->flags & IFF_PROMISC) {
/* Accept all: Multicast + Unicast */
mvneta_rx_unicast_promisc_set(pp, 1);
mvneta_set_ucast_table(pp, rxq_def);
mvneta_set_special_mcast_table(pp, rxq_def);
mvneta_set_other_mcast_table(pp, rxq_def);
} else {
/* Accept single Unicast */
mvneta_rx_unicast_promisc_set(pp, 0);
mvneta_set_ucast_table(pp, -1);
mvneta_mac_addr_set(pp, dev->dev_addr, rxq_def);
if (dev->flags & IFF_ALLMULTI) {
/* Accept all multicast */
mvneta_set_special_mcast_table(pp, rxq_def);
mvneta_set_other_mcast_table(pp, rxq_def);
} else {
/* Accept only initialized multicast */
mvneta_set_special_mcast_table(pp, -1);
mvneta_set_other_mcast_table(pp, -1);
if (!netdev_mc_empty(dev)) {
netdev_for_each_mc_addr(ha, dev) {
mvneta_mcast_addr_set(pp, ha->addr,
rxq_def);
}
}
}
}
}
/* Interrupt handling - the callback for request_irq() */
static irqreturn_t mvneta_isr(int irq, void *dev_id)
{
struct mvneta_port *pp = (struct mvneta_port *)dev_id;
/* Mask all interrupts */
mvreg_write(pp, MVNETA_INTR_NEW_MASK, 0);
napi_schedule(&pp->napi);
return IRQ_HANDLED;
}
/* NAPI handler
* Bits 0 - 7 of the causeRxTx register indicate that are transmitted
* packets on the corresponding TXQ (Bit 0 is for TX queue 1).
* Bits 8 -15 of the cause Rx Tx register indicate that are received
* packets on the corresponding RXQ (Bit 8 is for RX queue 0).
* Each CPU has its own causeRxTx register
*/
static int mvneta_poll(struct napi_struct *napi, int budget)
{
int rx_done = 0;
u32 cause_rx_tx;
unsigned long flags;
struct mvneta_port *pp = netdev_priv(napi->dev);
if (!netif_running(pp->dev)) {
napi_complete(napi);
return rx_done;
}
/* Read cause register */
cause_rx_tx = mvreg_read(pp, MVNETA_INTR_NEW_CAUSE) &
(MVNETA_RX_INTR_MASK(rxq_number) | MVNETA_TX_INTR_MASK(txq_number));
/* Release Tx descriptors */
if (cause_rx_tx & MVNETA_TX_INTR_MASK_ALL) {
mvneta_tx_done_gbe(pp, (cause_rx_tx & MVNETA_TX_INTR_MASK_ALL));
cause_rx_tx &= ~MVNETA_TX_INTR_MASK_ALL;
}
/* For the case where the last mvneta_poll did not process all
* RX packets
*/
cause_rx_tx |= pp->cause_rx_tx;
if (rxq_number > 1) {
while ((cause_rx_tx & MVNETA_RX_INTR_MASK_ALL) && (budget > 0)) {
int count;
struct mvneta_rx_queue *rxq;
/* get rx queue number from cause_rx_tx */
rxq = mvneta_rx_policy(pp, cause_rx_tx);
if (!rxq)
break;
/* process the packet in that rx queue */
count = mvneta_rx(pp, budget, rxq);
rx_done += count;
budget -= count;
if (budget > 0) {
/* set off the rx bit of the
* corresponding bit in the cause rx
* tx register, so that next iteration
* will find the next rx queue where
* packets are received on
*/
cause_rx_tx &= ~((1 << rxq->id) << 8);
}
}
} else {
rx_done = mvneta_rx(pp, budget, &pp->rxqs[rxq_def]);
budget -= rx_done;
}
if (budget > 0) {
cause_rx_tx = 0;
napi_complete(napi);
local_irq_save(flags);
mvreg_write(pp, MVNETA_INTR_NEW_MASK,
MVNETA_RX_INTR_MASK(rxq_number) | MVNETA_TX_INTR_MASK(txq_number));
local_irq_restore(flags);
}
pp->cause_rx_tx = cause_rx_tx;
return rx_done;
}
/* Handle rxq fill: allocates rxq skbs; called when initializing a port */
static int mvneta_rxq_fill(struct mvneta_port *pp, struct mvneta_rx_queue *rxq,
int num)
{
int i;
for (i = 0; i < num; i++) {
memset(rxq->descs + i, 0, sizeof(struct mvneta_rx_desc));
if (mvneta_rx_refill(pp, rxq->descs + i) != 0) {
netdev_err(pp->dev, "%s:rxq %d, %d of %d buffs filled\n",
__func__, rxq->id, i, num);
break;
}
}
/* Add this number of RX descriptors as non occupied (ready to
* get packets)
*/
mvneta_rxq_non_occup_desc_add(pp, rxq, i);
return i;
}
/* Free all packets pending transmit from all TXQs and reset TX port */
static void mvneta_tx_reset(struct mvneta_port *pp)
{
int queue;
/* free the skb's in the tx ring */
for (queue = 0; queue < txq_number; queue++)
mvneta_txq_done_force(pp, &pp->txqs[queue]);
mvreg_write(pp, MVNETA_PORT_TX_RESET, MVNETA_PORT_TX_DMA_RESET);
mvreg_write(pp, MVNETA_PORT_TX_RESET, 0);
}
static void mvneta_rx_reset(struct mvneta_port *pp)
{
mvreg_write(pp, MVNETA_PORT_RX_RESET, MVNETA_PORT_RX_DMA_RESET);
mvreg_write(pp, MVNETA_PORT_RX_RESET, 0);
}
/* Rx/Tx queue initialization/cleanup methods */
/* Create a specified RX queue */
static int mvneta_rxq_init(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq)
{
rxq->size = pp->rx_ring_size;
/* Allocate memory for RX descriptors */
rxq->descs = dma_alloc_coherent(pp->dev->dev.parent,
rxq->size * MVNETA_DESC_ALIGNED_SIZE,
&rxq->descs_phys, GFP_KERNEL);
if (rxq->descs == NULL)
return -ENOMEM;
BUG_ON(rxq->descs !=
PTR_ALIGN(rxq->descs, MVNETA_CPU_D_CACHE_LINE_SIZE));
rxq->last_desc = rxq->size - 1;
/* Set Rx descriptors queue starting address */
mvreg_write(pp, MVNETA_RXQ_BASE_ADDR_REG(rxq->id), rxq->descs_phys);
mvreg_write(pp, MVNETA_RXQ_SIZE_REG(rxq->id), rxq->size);
/* Set Offset */
mvneta_rxq_offset_set(pp, rxq, NET_SKB_PAD);
/* Set coalescing pkts and time */
mvneta_rx_pkts_coal_set(pp, rxq, rxq->pkts_coal);
mvneta_rx_time_coal_set(pp, rxq, rxq->time_coal);
/* Fill RXQ with buffers from RX pool */
mvneta_rxq_buf_size_set(pp, rxq, MVNETA_RX_BUF_SIZE(pp->pkt_size));
mvneta_rxq_bm_disable(pp, rxq);
mvneta_rxq_fill(pp, rxq, rxq->size);
return 0;
}
/* Cleanup Rx queue */
static void mvneta_rxq_deinit(struct mvneta_port *pp,
struct mvneta_rx_queue *rxq)
{
mvneta_rxq_drop_pkts(pp, rxq);
if (rxq->descs)
dma_free_coherent(pp->dev->dev.parent,
rxq->size * MVNETA_DESC_ALIGNED_SIZE,
rxq->descs,
rxq->descs_phys);
rxq->descs = NULL;
rxq->last_desc = 0;
rxq->next_desc_to_proc = 0;
rxq->descs_phys = 0;
}
/* Create and initialize a tx queue */
static int mvneta_txq_init(struct mvneta_port *pp,
struct mvneta_tx_queue *txq)
{
txq->size = pp->tx_ring_size;
/* A queue must always have room for at least one skb.
* Therefore, stop the queue when the free entries reaches
* the maximum number of descriptors per skb.
*/
txq->tx_stop_threshold = txq->size - MVNETA_MAX_SKB_DESCS;
txq->tx_wake_threshold = txq->tx_stop_threshold / 2;
/* Allocate memory for TX descriptors */
txq->descs = dma_alloc_coherent(pp->dev->dev.parent,
txq->size * MVNETA_DESC_ALIGNED_SIZE,
&txq->descs_phys, GFP_KERNEL);
if (txq->descs == NULL)
return -ENOMEM;
/* Make sure descriptor address is cache line size aligned */
BUG_ON(txq->descs !=
PTR_ALIGN(txq->descs, MVNETA_CPU_D_CACHE_LINE_SIZE));
txq->last_desc = txq->size - 1;
/* Set maximum bandwidth for enabled TXQs */
mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(txq->id), 0x03ffffff);
mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(txq->id), 0x3fffffff);
/* Set Tx descriptors queue starting address */
mvreg_write(pp, MVNETA_TXQ_BASE_ADDR_REG(txq->id), txq->descs_phys);
mvreg_write(pp, MVNETA_TXQ_SIZE_REG(txq->id), txq->size);
txq->tx_skb = kmalloc(txq->size * sizeof(*txq->tx_skb), GFP_KERNEL);
if (txq->tx_skb == NULL) {
dma_free_coherent(pp->dev->dev.parent,
txq->size * MVNETA_DESC_ALIGNED_SIZE,
txq->descs, txq->descs_phys);
return -ENOMEM;
}
/* Allocate DMA buffers for TSO MAC/IP/TCP headers */
txq->tso_hdrs = dma_alloc_coherent(pp->dev->dev.parent,
txq->size * TSO_HEADER_SIZE,
&txq->tso_hdrs_phys, GFP_KERNEL);
if (txq->tso_hdrs == NULL) {
kfree(txq->tx_skb);
dma_free_coherent(pp->dev->dev.parent,
txq->size * MVNETA_DESC_ALIGNED_SIZE,
txq->descs, txq->descs_phys);
return -ENOMEM;
}
mvneta_tx_done_pkts_coal_set(pp, txq, txq->done_pkts_coal);
return 0;
}
/* Free allocated resources when mvneta_txq_init() fails to allocate memory*/
static void mvneta_txq_deinit(struct mvneta_port *pp,
struct mvneta_tx_queue *txq)
{
kfree(txq->tx_skb);
if (txq->tso_hdrs)
dma_free_coherent(pp->dev->dev.parent,
txq->size * TSO_HEADER_SIZE,
txq->tso_hdrs, txq->tso_hdrs_phys);
if (txq->descs)
dma_free_coherent(pp->dev->dev.parent,
txq->size * MVNETA_DESC_ALIGNED_SIZE,
txq->descs, txq->descs_phys);
txq->descs = NULL;
txq->last_desc = 0;
txq->next_desc_to_proc = 0;
txq->descs_phys = 0;
/* Set minimum bandwidth for disabled TXQs */
mvreg_write(pp, MVETH_TXQ_TOKEN_CFG_REG(txq->id), 0);
mvreg_write(pp, MVETH_TXQ_TOKEN_COUNT_REG(txq->id), 0);
/* Set Tx descriptors queue starting address and size */
mvreg_write(pp, MVNETA_TXQ_BASE_ADDR_REG(txq->id), 0);
mvreg_write(pp, MVNETA_TXQ_SIZE_REG(txq->id), 0);
}
/* Cleanup all Tx queues */
static void mvneta_cleanup_txqs(struct mvneta_port *pp)
{
int queue;
for (queue = 0; queue < txq_number; queue++)
mvneta_txq_deinit(pp, &pp->txqs[queue]);
}
/* Cleanup all Rx queues */
static void mvneta_cleanup_rxqs(struct mvneta_port *pp)
{
int queue;
for (queue = 0; queue < rxq_number; queue++)
mvneta_rxq_deinit(pp, &pp->rxqs[queue]);
}
/* Init all Rx queues */
static int mvneta_setup_rxqs(struct mvneta_port *pp)
{
int queue;
for (queue = 0; queue < rxq_number; queue++) {
int err = mvneta_rxq_init(pp, &pp->rxqs[queue]);
if (err) {
netdev_err(pp->dev, "%s: can't create rxq=%d\n",
__func__, queue);
mvneta_cleanup_rxqs(pp);
return err;
}
}
return 0;
}
/* Init all tx queues */
static int mvneta_setup_txqs(struct mvneta_port *pp)
{
int queue;
for (queue = 0; queue < txq_number; queue++) {
int err = mvneta_txq_init(pp, &pp->txqs[queue]);
if (err) {
netdev_err(pp->dev, "%s: can't create txq=%d\n",
__func__, queue);
mvneta_cleanup_txqs(pp);
return err;
}
}
return 0;
}
static void mvneta_start_dev(struct mvneta_port *pp)
{
mvneta_max_rx_size_set(pp, pp->pkt_size);
mvneta_txq_max_tx_size_set(pp, pp->pkt_size);
/* start the Rx/Tx activity */
mvneta_port_enable(pp);
/* Enable polling on the port */
napi_enable(&pp->napi);
/* Unmask interrupts */
mvreg_write(pp, MVNETA_INTR_NEW_MASK,
MVNETA_RX_INTR_MASK(rxq_number) | MVNETA_TX_INTR_MASK(txq_number));
phy_start(pp->phy_dev);
netif_tx_start_all_queues(pp->dev);
}
static void mvneta_stop_dev(struct mvneta_port *pp)
{
phy_stop(pp->phy_dev);
napi_disable(&pp->napi);
netif_carrier_off(pp->dev);
mvneta_port_down(pp);
netif_tx_stop_all_queues(pp->dev);
/* Stop the port activity */
mvneta_port_disable(pp);
/* Clear all ethernet port interrupts */
mvreg_write(pp, MVNETA_INTR_MISC_CAUSE, 0);
mvreg_write(pp, MVNETA_INTR_OLD_CAUSE, 0);
/* Mask all ethernet port interrupts */
mvreg_write(pp, MVNETA_INTR_NEW_MASK, 0);
mvreg_write(pp, MVNETA_INTR_OLD_MASK, 0);
mvreg_write(pp, MVNETA_INTR_MISC_MASK, 0);
mvneta_tx_reset(pp);
mvneta_rx_reset(pp);
}
/* Return positive if MTU is valid */
static int mvneta_check_mtu_valid(struct net_device *dev, int mtu)
{
if (mtu < 68) {
netdev_err(dev, "cannot change mtu to less than 68\n");
return -EINVAL;
}
/* 9676 == 9700 - 20 and rounding to 8 */
if (mtu > 9676) {
netdev_info(dev, "Illegal MTU value %d, round to 9676\n", mtu);
mtu = 9676;
}
if (!IS_ALIGNED(MVNETA_RX_PKT_SIZE(mtu), 8)) {
netdev_info(dev, "Illegal MTU value %d, rounding to %d\n",
mtu, ALIGN(MVNETA_RX_PKT_SIZE(mtu), 8));
mtu = ALIGN(MVNETA_RX_PKT_SIZE(mtu), 8);
}
return mtu;
}
/* Change the device mtu */
static int mvneta_change_mtu(struct net_device *dev, int mtu)
{
struct mvneta_port *pp = netdev_priv(dev);
int ret;
mtu = mvneta_check_mtu_valid(dev, mtu);
if (mtu < 0)
return -EINVAL;
dev->mtu = mtu;
if (!netif_running(dev)) {
netdev_update_features(dev);
return 0;
}
/* The interface is running, so we have to force a
* reallocation of the queues
*/
mvneta_stop_dev(pp);
mvneta_cleanup_txqs(pp);
mvneta_cleanup_rxqs(pp);
pp->pkt_size = MVNETA_RX_PKT_SIZE(dev->mtu);
pp->frag_size = SKB_DATA_ALIGN(MVNETA_RX_BUF_SIZE(pp->pkt_size)) +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
ret = mvneta_setup_rxqs(pp);
if (ret) {
netdev_err(dev, "unable to setup rxqs after MTU change\n");
return ret;
}
ret = mvneta_setup_txqs(pp);
if (ret) {
netdev_err(dev, "unable to setup txqs after MTU change\n");
return ret;
}
mvneta_start_dev(pp);
mvneta_port_up(pp);
netdev_update_features(dev);
return 0;
}
static netdev_features_t mvneta_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct mvneta_port *pp = netdev_priv(dev);
if (pp->tx_csum_limit && dev->mtu > pp->tx_csum_limit) {
features &= ~(NETIF_F_IP_CSUM | NETIF_F_TSO);
netdev_info(dev,
"Disable IP checksum for MTU greater than %dB\n",
pp->tx_csum_limit);
}
return features;
}
/* Get mac address */
static void mvneta_get_mac_addr(struct mvneta_port *pp, unsigned char *addr)
{
u32 mac_addr_l, mac_addr_h;
mac_addr_l = mvreg_read(pp, MVNETA_MAC_ADDR_LOW);
mac_addr_h = mvreg_read(pp, MVNETA_MAC_ADDR_HIGH);
addr[0] = (mac_addr_h >> 24) & 0xFF;
addr[1] = (mac_addr_h >> 16) & 0xFF;
addr[2] = (mac_addr_h >> 8) & 0xFF;
addr[3] = mac_addr_h & 0xFF;
addr[4] = (mac_addr_l >> 8) & 0xFF;
addr[5] = mac_addr_l & 0xFF;
}
/* Handle setting mac address */
static int mvneta_set_mac_addr(struct net_device *dev, void *addr)
{
struct mvneta_port *pp = netdev_priv(dev);
struct sockaddr *sockaddr = addr;
int ret;
ret = eth_prepare_mac_addr_change(dev, addr);
if (ret < 0)
return ret;
/* Remove previous address table entry */
mvneta_mac_addr_set(pp, dev->dev_addr, -1);
/* Set new addr in hw */
mvneta_mac_addr_set(pp, sockaddr->sa_data, rxq_def);
eth_commit_mac_addr_change(dev, addr);
return 0;
}
static void mvneta_adjust_link(struct net_device *ndev)
{
struct mvneta_port *pp = netdev_priv(ndev);
struct phy_device *phydev = pp->phy_dev;
int status_change = 0;
if (phydev->link) {
if ((pp->speed != phydev->speed) ||
(pp->duplex != phydev->duplex)) {
u32 val;
val = mvreg_read(pp, MVNETA_GMAC_AUTONEG_CONFIG);
val &= ~(MVNETA_GMAC_CONFIG_MII_SPEED |
MVNETA_GMAC_CONFIG_GMII_SPEED |
MVNETA_GMAC_CONFIG_FULL_DUPLEX |
MVNETA_GMAC_AN_SPEED_EN |
MVNETA_GMAC_AN_DUPLEX_EN);
if (phydev->duplex)
val |= MVNETA_GMAC_CONFIG_FULL_DUPLEX;
if (phydev->speed == SPEED_1000)
val |= MVNETA_GMAC_CONFIG_GMII_SPEED;
else if (phydev->speed == SPEED_100)
val |= MVNETA_GMAC_CONFIG_MII_SPEED;
mvreg_write(pp, MVNETA_GMAC_AUTONEG_CONFIG, val);
pp->duplex = phydev->duplex;
pp->speed = phydev->speed;
}
}
if (phydev->link != pp->link) {
if (!phydev->link) {
pp->duplex = -1;
pp->speed = 0;
}
pp->link = phydev->link;
status_change = 1;
}
if (status_change) {
if (phydev->link) {
u32 val = mvreg_read(pp, MVNETA_GMAC_AUTONEG_CONFIG);
val |= (MVNETA_GMAC_FORCE_LINK_PASS |
MVNETA_GMAC_FORCE_LINK_DOWN);
mvreg_write(pp, MVNETA_GMAC_AUTONEG_CONFIG, val);
mvneta_port_up(pp);
netdev_info(pp->dev, "link up\n");
} else {
mvneta_port_down(pp);
netdev_info(pp->dev, "link down\n");
}
}
}
static int mvneta_mdio_probe(struct mvneta_port *pp)
{
struct phy_device *phy_dev;
phy_dev = of_phy_connect(pp->dev, pp->phy_node, mvneta_adjust_link, 0,
pp->phy_interface);
if (!phy_dev) {
netdev_err(pp->dev, "could not find the PHY\n");
return -ENODEV;
}
phy_dev->supported &= PHY_GBIT_FEATURES;
phy_dev->advertising = phy_dev->supported;
pp->phy_dev = phy_dev;
pp->link = 0;
pp->duplex = 0;
pp->speed = 0;
return 0;
}
static void mvneta_mdio_remove(struct mvneta_port *pp)
{
phy_disconnect(pp->phy_dev);
pp->phy_dev = NULL;
}
static int mvneta_open(struct net_device *dev)
{
struct mvneta_port *pp = netdev_priv(dev);
int ret;
pp->pkt_size = MVNETA_RX_PKT_SIZE(pp->dev->mtu);
pp->frag_size = SKB_DATA_ALIGN(MVNETA_RX_BUF_SIZE(pp->pkt_size)) +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
ret = mvneta_setup_rxqs(pp);
if (ret)
return ret;
ret = mvneta_setup_txqs(pp);
if (ret)
goto err_cleanup_rxqs;
/* Connect to port interrupt line */
ret = request_irq(pp->dev->irq, mvneta_isr, 0,
MVNETA_DRIVER_NAME, pp);
if (ret) {
netdev_err(pp->dev, "cannot request irq %d\n", pp->dev->irq);
goto err_cleanup_txqs;
}
/* In default link is down */
netif_carrier_off(pp->dev);
ret = mvneta_mdio_probe(pp);
if (ret < 0) {
netdev_err(dev, "cannot probe MDIO bus\n");
goto err_free_irq;
}
mvneta_start_dev(pp);
return 0;
err_free_irq:
free_irq(pp->dev->irq, pp);
err_cleanup_txqs:
mvneta_cleanup_txqs(pp);
err_cleanup_rxqs:
mvneta_cleanup_rxqs(pp);
return ret;
}
/* Stop the port, free port interrupt line */
static int mvneta_stop(struct net_device *dev)
{
struct mvneta_port *pp = netdev_priv(dev);
mvneta_stop_dev(pp);
mvneta_mdio_remove(pp);
free_irq(dev->irq, pp);
mvneta_cleanup_rxqs(pp);
mvneta_cleanup_txqs(pp);
return 0;
}
static int mvneta_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct mvneta_port *pp = netdev_priv(dev);
int ret;
if (!pp->phy_dev)
return -ENOTSUPP;
ret = phy_mii_ioctl(pp->phy_dev, ifr, cmd);
if (!ret)
mvneta_adjust_link(dev);
return ret;
}
/* Ethtool methods */
/* Get settings (phy address, speed) for ethtools */
int mvneta_ethtool_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct mvneta_port *pp = netdev_priv(dev);
if (!pp->phy_dev)
return -ENODEV;
return phy_ethtool_gset(pp->phy_dev, cmd);
}
/* Set settings (phy address, speed) for ethtools */
int mvneta_ethtool_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct mvneta_port *pp = netdev_priv(dev);
if (!pp->phy_dev)
return -ENODEV;
return phy_ethtool_sset(pp->phy_dev, cmd);
}
/* Set interrupt coalescing for ethtools */
static int mvneta_ethtool_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *c)
{
struct mvneta_port *pp = netdev_priv(dev);
int queue;
for (queue = 0; queue < rxq_number; queue++) {
struct mvneta_rx_queue *rxq = &pp->rxqs[queue];
rxq->time_coal = c->rx_coalesce_usecs;
rxq->pkts_coal = c->rx_max_coalesced_frames;
mvneta_rx_pkts_coal_set(pp, rxq, rxq->pkts_coal);
mvneta_rx_time_coal_set(pp, rxq, rxq->time_coal);
}
for (queue = 0; queue < txq_number; queue++) {
struct mvneta_tx_queue *txq = &pp->txqs[queue];
txq->done_pkts_coal = c->tx_max_coalesced_frames;
mvneta_tx_done_pkts_coal_set(pp, txq, txq->done_pkts_coal);
}
return 0;
}
/* get coalescing for ethtools */
static int mvneta_ethtool_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *c)
{
struct mvneta_port *pp = netdev_priv(dev);
c->rx_coalesce_usecs = pp->rxqs[0].time_coal;
c->rx_max_coalesced_frames = pp->rxqs[0].pkts_coal;
c->tx_max_coalesced_frames = pp->txqs[0].done_pkts_coal;
return 0;
}
static void mvneta_ethtool_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *drvinfo)
{
strlcpy(drvinfo->driver, MVNETA_DRIVER_NAME,
sizeof(drvinfo->driver));
strlcpy(drvinfo->version, MVNETA_DRIVER_VERSION,
sizeof(drvinfo->version));
strlcpy(drvinfo->bus_info, dev_name(&dev->dev),
sizeof(drvinfo->bus_info));
}
static void mvneta_ethtool_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct mvneta_port *pp = netdev_priv(netdev);
ring->rx_max_pending = MVNETA_MAX_RXD;
ring->tx_max_pending = MVNETA_MAX_TXD;
ring->rx_pending = pp->rx_ring_size;
ring->tx_pending = pp->tx_ring_size;
}
static int mvneta_ethtool_set_ringparam(struct net_device *dev,
struct ethtool_ringparam *ring)
{
struct mvneta_port *pp = netdev_priv(dev);
if ((ring->rx_pending == 0) || (ring->tx_pending == 0))
return -EINVAL;
pp->rx_ring_size = ring->rx_pending < MVNETA_MAX_RXD ?
ring->rx_pending : MVNETA_MAX_RXD;
pp->tx_ring_size = clamp_t(u16, ring->tx_pending,
MVNETA_MAX_SKB_DESCS * 2, MVNETA_MAX_TXD);
if (pp->tx_ring_size != ring->tx_pending)
netdev_warn(dev, "TX queue size set to %u (requested %u)\n",
pp->tx_ring_size, ring->tx_pending);
if (netif_running(dev)) {
mvneta_stop(dev);
if (mvneta_open(dev)) {
netdev_err(dev,
"error on opening device after ring param change\n");
return -ENOMEM;
}
}
return 0;
}
static const struct net_device_ops mvneta_netdev_ops = {
.ndo_open = mvneta_open,
.ndo_stop = mvneta_stop,
.ndo_start_xmit = mvneta_tx,
.ndo_set_rx_mode = mvneta_set_rx_mode,
.ndo_set_mac_address = mvneta_set_mac_addr,
.ndo_change_mtu = mvneta_change_mtu,
.ndo_fix_features = mvneta_fix_features,
.ndo_get_stats64 = mvneta_get_stats64,
.ndo_do_ioctl = mvneta_ioctl,
};
const struct ethtool_ops mvneta_eth_tool_ops = {
.get_link = ethtool_op_get_link,
.get_settings = mvneta_ethtool_get_settings,
.set_settings = mvneta_ethtool_set_settings,
.set_coalesce = mvneta_ethtool_set_coalesce,
.get_coalesce = mvneta_ethtool_get_coalesce,
.get_drvinfo = mvneta_ethtool_get_drvinfo,
.get_ringparam = mvneta_ethtool_get_ringparam,
.set_ringparam = mvneta_ethtool_set_ringparam,
};
/* Initialize hw */
static int mvneta_init(struct device *dev, struct mvneta_port *pp)
{
int queue;
/* Disable port */
mvneta_port_disable(pp);
/* Set port default values */
mvneta_defaults_set(pp);
pp->txqs = devm_kcalloc(dev, txq_number, sizeof(struct mvneta_tx_queue),
GFP_KERNEL);
if (!pp->txqs)
return -ENOMEM;
/* Initialize TX descriptor rings */
for (queue = 0; queue < txq_number; queue++) {
struct mvneta_tx_queue *txq = &pp->txqs[queue];
txq->id = queue;
txq->size = pp->tx_ring_size;
txq->done_pkts_coal = MVNETA_TXDONE_COAL_PKTS;
}
pp->rxqs = devm_kcalloc(dev, rxq_number, sizeof(struct mvneta_rx_queue),
GFP_KERNEL);
if (!pp->rxqs)
return -ENOMEM;
/* Create Rx descriptor rings */
for (queue = 0; queue < rxq_number; queue++) {
struct mvneta_rx_queue *rxq = &pp->rxqs[queue];
rxq->id = queue;
rxq->size = pp->rx_ring_size;
rxq->pkts_coal = MVNETA_RX_COAL_PKTS;
rxq->time_coal = MVNETA_RX_COAL_USEC;
}
return 0;
}
/* platform glue : initialize decoding windows */
static void mvneta_conf_mbus_windows(struct mvneta_port *pp,
const struct mbus_dram_target_info *dram)
{
u32 win_enable;
u32 win_protect;
int i;
for (i = 0; i < 6; i++) {
mvreg_write(pp, MVNETA_WIN_BASE(i), 0);
mvreg_write(pp, MVNETA_WIN_SIZE(i), 0);
if (i < 4)
mvreg_write(pp, MVNETA_WIN_REMAP(i), 0);
}
win_enable = 0x3f;
win_protect = 0;
for (i = 0; i < dram->num_cs; i++) {
const struct mbus_dram_window *cs = dram->cs + i;
mvreg_write(pp, MVNETA_WIN_BASE(i), (cs->base & 0xffff0000) |
(cs->mbus_attr << 8) | dram->mbus_dram_target_id);
mvreg_write(pp, MVNETA_WIN_SIZE(i),
(cs->size - 1) & 0xffff0000);
win_enable &= ~(1 << i);
win_protect |= 3 << (2 * i);
}
mvreg_write(pp, MVNETA_BASE_ADDR_ENABLE, win_enable);
}
/* Power up the port */
static int mvneta_port_power_up(struct mvneta_port *pp, int phy_mode)
{
u32 ctrl;
/* MAC Cause register should be cleared */
mvreg_write(pp, MVNETA_UNIT_INTR_CAUSE, 0);
ctrl = mvreg_read(pp, MVNETA_GMAC_CTRL_2);
/* Even though it might look weird, when we're configured in
* SGMII or QSGMII mode, the RGMII bit needs to be set.
*/
switch(phy_mode) {
case PHY_INTERFACE_MODE_QSGMII:
mvreg_write(pp, MVNETA_SERDES_CFG, MVNETA_QSGMII_SERDES_PROTO);
ctrl |= MVNETA_GMAC2_PCS_ENABLE | MVNETA_GMAC2_PORT_RGMII;
break;
case PHY_INTERFACE_MODE_SGMII:
mvreg_write(pp, MVNETA_SERDES_CFG, MVNETA_SGMII_SERDES_PROTO);
ctrl |= MVNETA_GMAC2_PCS_ENABLE | MVNETA_GMAC2_PORT_RGMII;
break;
case PHY_INTERFACE_MODE_RGMII:
case PHY_INTERFACE_MODE_RGMII_ID:
ctrl |= MVNETA_GMAC2_PORT_RGMII;
break;
default:
return -EINVAL;
}
/* Cancel Port Reset */
ctrl &= ~MVNETA_GMAC2_PORT_RESET;
mvreg_write(pp, MVNETA_GMAC_CTRL_2, ctrl);
while ((mvreg_read(pp, MVNETA_GMAC_CTRL_2) &
MVNETA_GMAC2_PORT_RESET) != 0)
continue;
return 0;
}
/* Device initialization routine */
static int mvneta_probe(struct platform_device *pdev)
{
const struct mbus_dram_target_info *dram_target_info;
struct resource *res;
struct device_node *dn = pdev->dev.of_node;
struct device_node *phy_node;
struct mvneta_port *pp;
struct net_device *dev;
const char *dt_mac_addr;
char hw_mac_addr[ETH_ALEN];
const char *mac_from;
int phy_mode;
int err;
/* Our multiqueue support is not complete, so for now, only
* allow the usage of the first RX queue
*/
if (rxq_def != 0) {
dev_err(&pdev->dev, "Invalid rxq_def argument: %d\n", rxq_def);
return -EINVAL;
}
dev = alloc_etherdev_mqs(sizeof(struct mvneta_port), txq_number, rxq_number);
if (!dev)
return -ENOMEM;
dev->irq = irq_of_parse_and_map(dn, 0);
if (dev->irq == 0) {
err = -EINVAL;
goto err_free_netdev;
}
phy_node = of_parse_phandle(dn, "phy", 0);
if (!phy_node) {
if (!of_phy_is_fixed_link(dn)) {
dev_err(&pdev->dev, "no PHY specified\n");
err = -ENODEV;
goto err_free_irq;
}
err = of_phy_register_fixed_link(dn);
if (err < 0) {
dev_err(&pdev->dev, "cannot register fixed PHY\n");
goto err_free_irq;
}
/* In the case of a fixed PHY, the DT node associated
* to the PHY is the Ethernet MAC DT node.
*/
phy_node = of_node_get(dn);
}
phy_mode = of_get_phy_mode(dn);
if (phy_mode < 0) {
dev_err(&pdev->dev, "incorrect phy-mode\n");
err = -EINVAL;
goto err_put_phy_node;
}
dev->tx_queue_len = MVNETA_MAX_TXD;
dev->watchdog_timeo = 5 * HZ;
dev->netdev_ops = &mvneta_netdev_ops;
dev->ethtool_ops = &mvneta_eth_tool_ops;
pp = netdev_priv(dev);
pp->phy_node = phy_node;
pp->phy_interface = phy_mode;
pp->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(pp->clk)) {
err = PTR_ERR(pp->clk);
goto err_put_phy_node;
}
clk_prepare_enable(pp->clk);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
pp->base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(pp->base)) {
err = PTR_ERR(pp->base);
goto err_clk;
}
/* Alloc per-cpu stats */
pp->stats = netdev_alloc_pcpu_stats(struct mvneta_pcpu_stats);
if (!pp->stats) {
err = -ENOMEM;
goto err_clk;
}
dt_mac_addr = of_get_mac_address(dn);
if (dt_mac_addr) {
mac_from = "device tree";
memcpy(dev->dev_addr, dt_mac_addr, ETH_ALEN);
} else {
mvneta_get_mac_addr(pp, hw_mac_addr);
if (is_valid_ether_addr(hw_mac_addr)) {
mac_from = "hardware";
memcpy(dev->dev_addr, hw_mac_addr, ETH_ALEN);
} else {
mac_from = "random";
eth_hw_addr_random(dev);
}
}
if (of_device_is_compatible(dn, "marvell,armada-370-neta"))
pp->tx_csum_limit = 1600;
pp->tx_ring_size = MVNETA_MAX_TXD;
pp->rx_ring_size = MVNETA_MAX_RXD;
pp->dev = dev;
SET_NETDEV_DEV(dev, &pdev->dev);
err = mvneta_init(&pdev->dev, pp);
if (err < 0)
goto err_free_stats;
err = mvneta_port_power_up(pp, phy_mode);
if (err < 0) {
dev_err(&pdev->dev, "can't power up port\n");
goto err_free_stats;
}
dram_target_info = mv_mbus_dram_info();
if (dram_target_info)
mvneta_conf_mbus_windows(pp, dram_target_info);
netif_napi_add(dev, &pp->napi, mvneta_poll, NAPI_POLL_WEIGHT);
dev->features = NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_TSO;
dev->hw_features |= dev->features;
dev->vlan_features |= dev->features;
dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
dev->gso_max_segs = MVNETA_MAX_TSO_SEGS;
err = register_netdev(dev);
if (err < 0) {
dev_err(&pdev->dev, "failed to register\n");
goto err_free_stats;
}
netdev_info(dev, "Using %s mac address %pM\n", mac_from,
dev->dev_addr);
platform_set_drvdata(pdev, pp->dev);
return 0;
err_free_stats:
free_percpu(pp->stats);
err_clk:
clk_disable_unprepare(pp->clk);
err_put_phy_node:
of_node_put(phy_node);
err_free_irq:
irq_dispose_mapping(dev->irq);
err_free_netdev:
free_netdev(dev);
return err;
}
/* Device removal routine */
static int mvneta_remove(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct mvneta_port *pp = netdev_priv(dev);
unregister_netdev(dev);
clk_disable_unprepare(pp->clk);
free_percpu(pp->stats);
irq_dispose_mapping(dev->irq);
of_node_put(pp->phy_node);
free_netdev(dev);
return 0;
}
static const struct of_device_id mvneta_match[] = {
{ .compatible = "marvell,armada-370-neta" },
{ .compatible = "marvell,armada-xp-neta" },
{ }
};
MODULE_DEVICE_TABLE(of, mvneta_match);
static struct platform_driver mvneta_driver = {
.probe = mvneta_probe,
.remove = mvneta_remove,
.driver = {
.name = MVNETA_DRIVER_NAME,
.of_match_table = mvneta_match,
},
};
module_platform_driver(mvneta_driver);
MODULE_DESCRIPTION("Marvell NETA Ethernet Driver - www.marvell.com");
MODULE_AUTHOR("Rami Rosen <[email protected]>, Thomas Petazzoni <[email protected]>");
MODULE_LICENSE("GPL");
module_param(rxq_number, int, S_IRUGO);
module_param(txq_number, int, S_IRUGO);
module_param(rxq_def, int, S_IRUGO);
module_param(rx_copybreak, int, S_IRUGO | S_IWUSR);
| alvislin/openwrt | kernel/linux-3.18.45/drivers/net/ethernet/marvell/mvneta.c | C | gpl-2.0 | 86,890 |
/* This file contains code for unified image writing into many file formats */
/********************************************************************/
/* Copyright (c) 2001 Sasha Vasko <sasha at aftercode.net> */
/********************************************************************/
/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#undef LOCAL_DEBUG
#ifdef _WIN32
#include "win32/config.h"
#else
#include "config.h"
#endif
#ifdef HAVE_PNG
/* Include file for users of png library. */
# ifdef HAVE_BUILTIN_PNG
# include "libpng/png.h"
# else
# include <png.h>
# endif
#else
#include <setjmp.h>
# ifdef HAVE_JPEG
# ifdef HAVE_UNISTD_H
# include <unistd.h>
# endif
# include <stdio.h>
# endif
#endif
#ifdef HAVE_JPEG
/* Include file for users of jpg library. */
# undef HAVE_STDLIB_H
# ifndef X_DISPLAY_MISSING
# include <X11/Xmd.h>
# endif
# ifdef HAVE_BUILTIN_JPEG
# include "libjpeg/jpeglib.h"
# else
# include <jpeglib.h>
# endif
#endif
/*#define DO_CLOCKING*/
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#include <string.h>
#include <ctype.h>
/* <setjmp.h> is used for the optional error recovery mechanism */
#ifdef _WIN32
# include "win32/afterbase.h"
#else
# include "afterbase.h"
#endif
#ifdef HAVE_GIF
# ifdef HAVE_BUILTIN_UNGIF
# include "libungif/gif_lib.h"
# else
# include <gif_lib.h>
# endif
#endif
#ifdef HAVE_TIFF
#include <tiff.h>
#include <tiffio.h>
#endif
#ifdef HAVE_LIBXPM
#ifdef HAVE_LIBXPM_X11
#include <X11/xpm.h>
#else
#include <xpm.h>
#endif
#endif
#include "asimage.h"
#include "imencdec.h"
#include "xcf.h"
#include "xpm.h"
#include "ungif.h"
#include "import.h"
#include "export.h"
#include "ascmap.h"
//#include "bmp.h"
#ifdef jmpbuf
#undef jmpbuf
#endif
/***********************************************************************************/
/* High level interface : */
as_image_writer_func as_image_file_writers[ASIT_Unknown] =
{
ASImage2xpm ,
ASImage2xpm ,
ASImage2xpm ,
ASImage2png ,
ASImage2jpeg,
ASImage2xcf ,
ASImage2ppm ,
ASImage2ppm ,
ASImage2bmp ,
ASImage2ico ,
ASImage2ico ,
ASImage2gif ,
ASImage2tiff,
NULL,
NULL,
NULL
};
Bool
ASImage2file( ASImage *im, const char *dir, const char *file,
ASImageFileTypes type, ASImageExportParams *params )
{
int filename_len, dirname_len = 0 ;
char *realfilename = NULL ;
Bool res = False ;
int typei = (int) type;
if( im == NULL ) return False;
if( file )
{
filename_len = strlen(file);
if( dir != NULL )
dirname_len = strlen(dir)+1;
realfilename = safemalloc( dirname_len+filename_len+1 );
if( dir != NULL )
{
strcpy( realfilename, dir );
realfilename[dirname_len-1] = '/' ;
}
strcpy( realfilename+dirname_len, file );
#ifdef _WIN32
unix_path2dos_path( realfilename );
#endif
}
if( type >= ASIT_Unknown || typei < 0 )
show_error( "Hmm, I don't seem to know anything about format you trying to write file \"%s\" in\n.\tPlease check the manual", realfilename );
else if( as_image_file_writers[type] )
res = as_image_file_writers[type](im, realfilename, params);
else
show_error( "Support for the format of image file \"%s\" has not been implemented yet.", realfilename );
free( realfilename );
return res;
}
/* hmm do we need pixmap2file ???? */
/***********************************************************************************/
/* Some helper functions : */
FILE*
open_writable_image_file( const char *path )
{
FILE *fp = NULL;
if ( path )
{
if ((fp = fopen (path, "wb")) == NULL)
show_error("cannot open image file \"%s\" for writing. Please check permissions.", path);
}else
fp = stdout ;
return fp ;
}
void
scanline2raw( register CARD8 *row, ASScanline *buf, CARD8 *gamma_table, unsigned int width, Bool grayscale, Bool do_alpha )
{
register int x = width;
if( grayscale )
row += do_alpha? width<<1 : width ;
else
row += width*(do_alpha?4:3) ;
if( gamma_table )
{
if( !grayscale )
{
while ( --x >= 0 )
{
row -= 3 ;
if( do_alpha )
{
--row;
buf->alpha[x] = row[3];
}
buf->xc1[x] = gamma_table[row[0]];
buf->xc2[x]= gamma_table[row[1]];
buf->xc3[x] = gamma_table[row[2]];
}
}else /* greyscale */
while ( --x >= 0 )
{
if( do_alpha )
buf->alpha[x] = *(--row);
buf->xc1 [x] = buf->xc2[x] = buf->xc3[x] = gamma_table[*(--row)];
}
}else
{
if( !grayscale )
{
while ( --x >= 0 )
{
row -= 3 ;
if( do_alpha )
{
--row;
buf->alpha[x] = row[3];
}
buf->xc1[x] = row[0];
buf->xc2[x]= row[1];
buf->xc3[x] = row[2];
}
}else /* greyscale */
while ( --x >= 0 )
{
if( do_alpha )
buf->alpha[x] = *(--row);
buf->xc1 [x] = buf->xc2[x] = buf->xc3[x] = *(--row);
}
}
}
/***********************************************************************************/
#define SHOW_PENDING_IMPLEMENTATION_NOTE(f) \
show_error( "I'm sorry, but " f " image writing is pending implementation. Appreciate your patience" )
#define SHOW_UNSUPPORTED_NOTE(f,path) \
show_error( "unable to write file \"%s\" - " f " image format is not supported.\n", (path) )
#ifdef HAVE_XPM /* XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM */
#ifdef LOCAL_DEBUG
Bool print_component( CARD32*, int, unsigned int );
#endif
Bool
ASImage2xpm ( ASImage *im, const char *path, ASImageExportParams *params )
{
FILE *outfile;
unsigned int y, x ;
int *mapped_im, *row_pointer ;
ASColormap cmap = {0};
ASXpmCharmap xpm_cmap = {0};
int transp_idx = 0;
START_TIME(started);
static const ASXpmExportParams defaultsXPM = { ASIT_Xpm, EXPORT_ALPHA, 4, 127, 512 };
ASImageExportParams defaults;
register char *ptr ;
LOCAL_DEBUG_CALLER_OUT ("(\"%s\")", path);
if( params == NULL ) {
defaults.type = defaultsXPM.type;
defaults.xpm = defaultsXPM;
params = &defaults ;
}
if ((outfile = open_writable_image_file( path )) == NULL)
return False;
mapped_im = colormap_asimage( im, &cmap, params->xpm.max_colors, params->xpm.dither, params->xpm.opaque_threshold );
if( !get_flags( params->xpm.flags, EXPORT_ALPHA) )
cmap.has_opaque = False ;
else
transp_idx = cmap.count ;
LOCAL_DEBUG_OUT("building charmap%s","");
build_xpm_charmap( &cmap, cmap.has_opaque, &xpm_cmap );
SHOW_TIME("charmap calculation",started);
LOCAL_DEBUG_OUT("writing file%s","");
fprintf( outfile, "/* XPM */\nstatic char *asxpm[] = {\n/* columns rows colors chars-per-pixel */\n"
"\"%d %d %d %d\",\n", im->width, im->height, xpm_cmap.count, xpm_cmap.cpp );
ptr = &(xpm_cmap.char_code[0]);
for( y = 0 ; y < cmap.count ; y++ )
{
fprintf( outfile, "\"%s c #%2.2X%2.2X%2.2X\",\n", ptr, cmap.entries[y].red, cmap.entries[y].green, cmap.entries[y].blue );
ptr += xpm_cmap.cpp+1 ;
}
if( cmap.has_opaque && y < xpm_cmap.count )
fprintf( outfile, "\"%s c None\",\n", ptr );
SHOW_TIME("image header writing",started);
row_pointer = mapped_im ;
for( y = 0 ; y < im->height ; y++ )
{
fputc( '"', outfile );
for( x = 0; x < im->width ; x++ )
{
register int idx = (row_pointer[x] >= 0)? row_pointer[x] : transp_idx ;
register char *ptr = &(xpm_cmap.char_code[idx*(xpm_cmap.cpp+1)]) ;
LOCAL_DEBUG_OUT( "(%d,%d)->%d (row_pointer %d )", x, y, idx, row_pointer[x] );
if( idx > (int)cmap.count )
show_error("bad XPM color index :(%d,%d) -> %d, %d: %s", x, y, idx, row_pointer[x], ptr );
while( *ptr )
fputc( *(ptr++), outfile );
}
row_pointer += im->width ;
fputc( '"', outfile );
if( y < im->height-1 )
fputc( ',', outfile );
fputc( '\n', outfile );
}
fprintf( outfile, "};\n" );
if (outfile != stdout)
fclose( outfile );
SHOW_TIME("image writing",started);
destroy_xpm_charmap( &xpm_cmap, True );
free( mapped_im );
destroy_colormap( &cmap, True );
SHOW_TIME("total",started);
return True;
}
/****** VO ******/
Bool
ASImage2xpmRawBuff ( ASImage *im, CARD8 **buffer, int *size, ASImageExportParams *params )
{
unsigned int y, x ;
int *mapped_im, *row_pointer ;
ASColormap cmap = {0};
ASXpmCharmap xpm_cmap = {0} ;
int transp_idx = 0;
START_TIME(started);
static const ASXpmExportParams defaultsXPM = { ASIT_Xpm, EXPORT_ALPHA, 4, 127, 512 };
ASImageExportParams defaults;
register char *ptr ;
char *curr;
if( params == NULL ) {
defaults.type = defaultsXPM.type;
defaults.xpm = defaultsXPM;
params = &defaults ;
}
mapped_im = colormap_asimage( im, &cmap, params->xpm.max_colors, params->xpm.dither, params->xpm.opaque_threshold );
if (mapped_im == NULL)
return False;
if( !get_flags( params->xpm.flags, EXPORT_ALPHA) )
cmap.has_opaque = False ;
else
transp_idx = cmap.count ;
LOCAL_DEBUG_OUT("building charmap%s","");
build_xpm_charmap( &cmap, cmap.has_opaque, &xpm_cmap );
SHOW_TIME("charmap calculation",started);
*size = 0;
*buffer = 0;
/* crazy check against buffer overflow */
if ((im->width > 100000) || (im->height > 1000000) ||
(xpm_cmap.count > 100000) || (xpm_cmap.cpp > 100000)) {
destroy_xpm_charmap( &xpm_cmap, True );
free( mapped_im );
destroy_colormap( &cmap, True );
return False;
}
/* estimate size*/
*size = (im->width + 4)*im->height*xpm_cmap.cpp;
*size += cmap.count*(20 + xpm_cmap.cpp);
*size += 200;
curr = calloc(*size, 1);
*buffer = (CARD8*)curr;
sprintf(curr, "/* XPM */\nstatic char *asxpm[] = {\n/* columns rows colors chars-per-pixel */\n"
"\"%d %d %d %d\",\n", im->width, im->height, xpm_cmap.count, xpm_cmap.cpp );
curr += strlen(curr);
ptr = &(xpm_cmap.char_code[0]);
for( y = 0 ; y < cmap.count ; y++ )
{
sprintf(curr, "\"%s c #%2.2X%2.2X%2.2X\",\n", ptr, cmap.entries[y].red, cmap.entries[y].green, cmap.entries[y].blue );
ptr += xpm_cmap.cpp+1 ;
curr += strlen(curr);
}
if( cmap.has_opaque && y < xpm_cmap.count ) {
sprintf(curr, "\"%s c None\",\n", ptr );
curr += strlen(curr);
}
SHOW_TIME("image header writing",started);
row_pointer = mapped_im ;
for( y = 0 ; y < im->height ; y++ )
{
*curr = '"';
curr++;
for( x = 0; x < im->width ; x++ )
{
register int idx = (row_pointer[x] >= 0)? row_pointer[x] : transp_idx ;
register char *ptr = &(xpm_cmap.char_code[idx*(xpm_cmap.cpp+1)]) ;
int len = strlen(ptr);
if( idx > (int)cmap.count )
show_error("bad XPM color index :(%d,%d) -> %d, %d: %s", x, y, idx, row_pointer[x], ptr );
memcpy(curr, ptr, len);
curr += len;
}
row_pointer += im->width ;
*curr = '"';
curr++;
if( y < im->height-1 ) {
*curr = ',';
curr++;
}
*curr = '\n';
curr++;
}
sprintf( curr, "};\n" );
destroy_xpm_charmap( &xpm_cmap, True );
free( mapped_im );
destroy_colormap( &cmap, True );
*size = strlen((char*)*buffer);
SHOW_TIME("total",started);
return True;
}
#else /* XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM */
Bool
ASImage2xpm ( ASImage *im, const char *path, ASImageExportParams *params )
{
SHOW_UNSUPPORTED_NOTE("XPM",path);
return False ;
}
#endif /* XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM XPM */
/***********************************************************************************/
/***********************************************************************************/
#ifdef HAVE_PNG /* PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG */
static Bool
ASImage2png_int ( ASImage *im, void *data, png_rw_ptr write_fn, png_flush_ptr flush_fn, register ASImageExportParams *params )
{
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
png_byte *row_pointer;
int y ;
Bool has_alpha;
Bool grayscale;
int compression;
ASImageDecoder *imdec ;
CARD32 *r, *g, *b, *a ;
png_color_16 back_color ;
START_TIME(started);
static const ASPngExportParams defaults = { ASIT_Png, EXPORT_ALPHA, -1 };
png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
if ( png_ptr != NULL )
if( (info_ptr = png_create_info_struct(png_ptr)) != NULL )
if( setjmp(png_jmpbuf(png_ptr)) )
{
png_destroy_info_struct(png_ptr, (png_infopp) &info_ptr);
info_ptr = NULL ;
}
if( params == NULL )
{
compression = defaults.compression ;
grayscale = get_flags(defaults.flags, EXPORT_GRAYSCALE );
has_alpha = get_flags(defaults.flags, EXPORT_ALPHA );
}else
{
compression = params->png.compression ;
grayscale = get_flags(params->png.flags, EXPORT_GRAYSCALE );
has_alpha = get_flags(params->png.flags, EXPORT_ALPHA );
}
/* lets see if we have alpha channel indeed : */
if( has_alpha )
{
if( !get_flags( get_asimage_chanmask(im), SCL_DO_ALPHA) )
has_alpha = False ;
}
if((imdec = start_image_decoding( NULL /* default visual */ , im,
has_alpha?SCL_DO_ALL:(SCL_DO_GREEN|SCL_DO_BLUE|SCL_DO_RED),
0, 0, im->width, 0, NULL)) == NULL )
{
LOCAL_DEBUG_OUT( "failed to start image decoding%s", "");
png_destroy_write_struct(&png_ptr, &info_ptr);
return False;
}
if( !info_ptr)
{
if( png_ptr )
png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
stop_image_decoding( &imdec );
return False;
}
if( write_fn == NULL && flush_fn == NULL )
{
png_init_io(png_ptr, (FILE*)data);
}else
{
png_set_write_fn(png_ptr,data,(png_rw_ptr) write_fn, flush_fn );
}
if( compression > 0 )
png_set_compression_level(png_ptr,MIN(compression,99)/10);
png_set_IHDR(png_ptr, info_ptr, im->width, im->height, 8,
grayscale ? (has_alpha?PNG_COLOR_TYPE_GRAY_ALPHA:PNG_COLOR_TYPE_GRAY):
(has_alpha?PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB),
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT );
/* better set background color as some web browsers can't seem to work without it ( IE in particular ) */
memset( &back_color, 0x00, sizeof(png_color_16));
back_color.red = ARGB32_RED16( im->back_color );
back_color.green = ARGB32_GREEN16( im->back_color );
back_color.blue = ARGB32_BLUE16( im->back_color );
png_set_bKGD(png_ptr, info_ptr, &back_color);
/* PNG treats alpha s alevel of opacity,
* and so do we - there is no need to reverse it : */
/* png_set_invert_alpha(png_ptr); */
/* starting writing the file : writing info first */
png_write_info(png_ptr, info_ptr);
r = imdec->buffer.red ;
g = imdec->buffer.green ;
b = imdec->buffer.blue ;
a = imdec->buffer.alpha ;
if( grayscale )
{
row_pointer = safemalloc( im->width*(has_alpha?2:1));
for ( y = 0 ; y < (int)im->height ; y++ )
{
register int i = im->width;
CARD8 *ptr = (CARD8*)row_pointer;
imdec->decode_image_scanline( imdec );
if( has_alpha )
{
while( --i >= 0 ) /* normalized graylevel computing : */
{
ptr[(i<<1)] = (57*r[i]+181*g[i]+18*b[i])/256 ;
ptr[(i<<1)+1] = a[i] ;
}
}else
while( --i >= 0 ) /* normalized graylevel computing : */
ptr[i] = (57*r[i]+181*g[i]+18*b[i])/256 ;
png_write_rows(png_ptr, &row_pointer, 1);
}
}else
{
/* fprintf( stderr, "saving : %s\n", path );*/
row_pointer = safecalloc( im->width * (has_alpha?4:3), 1 );
for (y = 0; y < (int)im->height; y++)
{
register int i = im->width;
CARD8 *ptr = (CARD8*)(row_pointer+(i-1)*(has_alpha?4:3)) ;
imdec->decode_image_scanline( imdec );
if( has_alpha )
{
while( --i >= 0 )
{
/* 0 is red, 1 is green, 2 is blue, 3 is alpha */
ptr[0] = r[i] ;
ptr[1] = g[i] ;
ptr[2] = b[i] ;
ptr[3] = a[i] ;
ptr-=4;
/*fprintf( stderr, "#%2.2X%2.2X%2.2X%2.2X ", imbuf.alpha[i], imbuf.red[i], imbuf.green[i], imbuf.blue[i] );*/
}
}else
while( --i >= 0 )
{
ptr[0] = r[i] ;
ptr[1] = g[i] ;
ptr[2] = b[i] ;
ptr-=3;
/*fprintf( stderr, "#%FFX%2.2X%2.2X%2.2X ", imbuf.red[i], imbuf.green[i], imbuf.blue[i] );*/
}
/*fprintf( stderr, "\n");*/
png_write_rows(png_ptr, &row_pointer, 1);
}
}
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
free( row_pointer );
stop_image_decoding( &imdec );
SHOW_TIME("image writing", started);
return True ;
}
Bool
ASImage2png ( ASImage *im, const char *path, register ASImageExportParams *params )
{
FILE *outfile;
Bool res ;
if( im == NULL )
return False;
if ((outfile = open_writable_image_file( path )) == NULL)
return False;
res = ASImage2png_int ( im, outfile, NULL, NULL, params );
if (outfile != stdout)
fclose(outfile);
return res;
}
typedef struct ASImPNGBuffer
{
CARD8 *buffer ;
int used_size, allocated_size ;
}ASImPNGBuffer;
void asim_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
ASImPNGBuffer *buff = (ASImPNGBuffer*) png_get_io_ptr(png_ptr);
if( buff && length > 0 )
{
if( buff->used_size + length > (unsigned int)buff->allocated_size )
{ /* allocating in 2048 byte increements : */
buff->allocated_size = (buff->used_size + length + 2048)&0xFFFFF800 ;
buff->buffer = realloc( buff->buffer, buff->allocated_size );
}
memcpy( &(buff->buffer[buff->used_size]), data, length );
buff->used_size += length ;
}
}
void asim_png_flush_data(png_structp png_ptr)
{
/* nothing to do really, but PNG requires it */
}
Bool
ASImage2PNGBuff( ASImage *im, CARD8 **buffer, int *size, ASImageExportParams *params )
{
ASImPNGBuffer int_buff ;
if( im == NULL || buffer == NULL || size == NULL )
return False;
memset( &int_buff, 0x00, sizeof(ASImPNGBuffer) );
if( ASImage2png_int ( im, &int_buff, (png_rw_ptr)asim_png_write_data, (png_flush_ptr)asim_png_flush_data, params ) )
{
*buffer = int_buff.buffer ;
*size = int_buff.used_size ;
return True;
}
if( int_buff.buffer )
free( int_buff.buffer );
*buffer = NULL ;
*size = 0 ;
return False;
}
#else /* PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG */
Bool
ASImage2png ( ASImage *im, const char *path, ASImageExportParams *params )
{
SHOW_UNSUPPORTED_NOTE( "PNG", path );
return False;
}
Bool
ASImage2PNGBuff( ASImage *im, CARD8 **buffer, int *size, ASImageExportParams *params )
{
if( buffer )
*buffer = NULL ;
if( size )
*size = 0 ;
return False;
}
#endif /* PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG PNG */
/***********************************************************************************/
/***********************************************************************************/
#ifdef HAVE_JPEG /* JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG */
Bool
ASImage2jpeg( ASImage *im, const char *path, ASImageExportParams *params )
{
/* This struct contains the JPEG decompression parameters and pointers to
* working space (which is allocated as needed by the JPEG library).
*/
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
/* More stuff */
FILE *outfile; /* target file */
JSAMPROW row_pointer[1];/* pointer to JSAMPLE row[s] */
int y;
static const ASJpegExportParams defaultsJpeg = { ASIT_Jpeg, 0, -1 };
ASImageExportParams defaults;
Bool grayscale;
ASImageDecoder *imdec ;
CARD32 *r, *g, *b ;
START_TIME(started);
if( im == NULL )
return False;
if( params == NULL ) {
defaults.type = defaultsJpeg.type;
defaults.jpeg = defaultsJpeg;
params = &defaults ;
}
if ((outfile = open_writable_image_file( path )) == NULL)
return False;
if((imdec = start_image_decoding( NULL /* default visual */ , im,
(SCL_DO_GREEN|SCL_DO_BLUE|SCL_DO_RED),
0, 0, im->width, 0, NULL)) == NULL )
{
LOCAL_DEBUG_OUT( "failed to start image decoding%s", "");
if (outfile != stdout)
fclose(outfile);
return False;
}
grayscale = get_flags(params->jpeg.flags, EXPORT_GRAYSCALE );
/* Step 1: allocate and initialize JPEG compression object */
/* We have to set up the error handler first, in case the initialization
* step fails. (Unlikely, but it could happen if you are out of memory.)
* This routine fills in the contents of struct jerr, and returns jerr's
* address which we place into the link field in cinfo.
*/
cinfo.err = jpeg_std_error(&jerr);
/* Now we can initialize the JPEG compression object. */
jpeg_create_compress(&cinfo);
/* Step 2: specify data destination (eg, a file) */
/* Note: steps 2 and 3 can be done in either order. */
/* Here we use the library-supplied code to send compressed data to a
* stdio stream. You can also write your own code to do something else.
* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
* requires it in order to write binary files.
*/
jpeg_stdio_dest(&cinfo, outfile);
/* Step 3: set parameters for compression */
cinfo.image_width = im->width; /* image width and height, in pixels */
cinfo.image_height = im->height;
cinfo.input_components = (grayscale)?1:3; /* # of color components per pixel */
cinfo.in_color_space = (grayscale)?JCS_GRAYSCALE:JCS_RGB; /* colorspace of input image */
/* Now use the library's routine to set default compression parameters.
* (You must set at least cinfo.in_color_space before calling this)*/
jpeg_set_defaults(&cinfo);
if( params->jpeg.quality > 0 )
jpeg_set_quality(&cinfo, MIN(params->jpeg.quality,100), TRUE /* limit to baseline-JPEG values */);
/* Step 4: Start compressor */
/* TRUE ensures that we will write a complete interchange-JPEG file.*/
jpeg_start_compress(&cinfo, TRUE);
/* Step 5: while (scan lines remain to be written) */
/* jpeg_write_scanlines(...); */
/* Here we use the library's state variable cinfo.next_scanline as the
* loop counter, so that we don't have to keep track ourselves.
* To keep things simple, we pass one scanline per call; you can pass
* more if you wish, though.
*/
r = imdec->buffer.red ;
g = imdec->buffer.green ;
b = imdec->buffer.blue ;
if( grayscale )
{
row_pointer[0] = safemalloc( im->width );
for (y = 0; y < (int)im->height; y++)
{
register int i = im->width;
CARD8 *ptr = (CARD8*)row_pointer[0];
imdec->decode_image_scanline( imdec );
while( --i >= 0 ) /* normalized graylevel computing : */
ptr[i] = (54*r[i]+183*g[i]+19*b[i])/256 ;
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
}else
{
row_pointer[0] = safemalloc( im->width * 3 );
for (y = 0; y < (int)im->height; y++)
{
register int i = (int)im->width;
CARD8 *ptr = (CARD8*)(row_pointer[0]+(i-1)*3) ;
LOCAL_DEBUG_OUT( "decoding row %d", y );
imdec->decode_image_scanline( imdec );
LOCAL_DEBUG_OUT( "building row %d", y );
while( --i >= 0 )
{
ptr[0] = r[i] ;
ptr[1] = g[i] ;
ptr[2] = b[i] ;
ptr-=3;
}
LOCAL_DEBUG_OUT( "writing row %d", y );
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
}
LOCAL_DEBUG_OUT( "done writing image%s","" );
/* free(buffer); */
/* Step 6: Finish compression and release JPEG compression object*/
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
free( row_pointer[0] );
stop_image_decoding( &imdec );
if (outfile != stdout)
fclose(outfile);
SHOW_TIME("image export",started);
LOCAL_DEBUG_OUT("done writing JPEG image \"%s\"", path);
return True ;
}
#else /* JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG */
Bool
ASImage2jpeg( ASImage *im, const char *path, ASImageExportParams *params )
{
SHOW_UNSUPPORTED_NOTE( "JPEG", path );
return False;
}
#endif /* JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG JPEG */
/***********************************************************************************/
/***********************************************************************************/
/* XCF - GIMP's native file format : */
Bool
ASImage2xcf ( ASImage *im, const char *path, ASImageExportParams *params )
{
/* More stuff */
XcfImage *xcf_im = NULL;
START_TIME(started);
SHOW_PENDING_IMPLEMENTATION_NOTE("XCF");
if( xcf_im == NULL )
return False;
#ifdef LOCAL_DEBUG
print_xcf_image( xcf_im );
#endif
/* Make a one-row-high sample array that will go away when done with image */
SHOW_TIME("write initialization",started);
free_xcf_image(xcf_im);
SHOW_TIME("image export",started);
return False ;
}
/***********************************************************************************/
/* PPM/PNM file format : */
Bool
ASImage2ppm ( ASImage *im, const char *path, ASImageExportParams *params )
{
START_TIME(started);
SHOW_PENDING_IMPLEMENTATION_NOTE("PPM");
SHOW_TIME("image export",started);
return False;
}
/***********************************************************************************/
/* Windows BMP file format : see bmp.c */
/***********************************************************************************/
/* Windows ICO/CUR file format : */
Bool
ASImage2ico ( ASImage *im, const char *path, ASImageExportParams *params )
{
START_TIME(started);
SHOW_PENDING_IMPLEMENTATION_NOTE("ICO");
SHOW_TIME("image export",started);
return False;
}
/***********************************************************************************/
#ifdef HAVE_GIF /* GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF */
Bool ASImage2gif( ASImage *im, const char *path, ASImageExportParams *params )
{
FILE *outfile = NULL, *infile = NULL;
GifFileType *gif = NULL ;
ColorMapObject *gif_cmap ;
Bool dont_save_cmap = False ;
static const ASGifExportParams defaultsGif = { ASIT_Gif,EXPORT_ALPHA|EXPORT_APPEND, 3, 127, 10 };
ASImageExportParams defaults;
ASColormap cmap;
int *mapped_im ;
int y ;
GifPixelType *row_pointer ;
Bool new_image = True ;
START_TIME(started);
int cmap_size = 1;
#if (GIFLIB_MAJOR>=5)
int errcode;
#endif
#define GIF_NETSCAPE_EXT_BYTES 3
unsigned char netscape_ext_bytes[GIF_NETSCAPE_EXT_BYTES] = { 0x1, 0x0, 0x0};
#define GIF_GCE_BYTES 4
unsigned char gce_bytes[GIF_GCE_BYTES] = {0x01, 0x0, 0x0, 0x0 }; /* Graphic Control Extension bytes :
* first byte - flags (0x01 for transparency )
* second and third bytes - animation delay
* forth byte - transoparent pixel value.
*/
LOCAL_DEBUG_CALLER_OUT ("(\"%s\")", path);
if( params == NULL ) {
defaults.type = defaultsGif.type;
defaults.gif = defaultsGif;
params = &defaults ;
}
mapped_im = colormap_asimage( im, &cmap, 255, params->gif.dither, params->gif.opaque_threshold );
if( get_flags( params->gif.flags, EXPORT_ALPHA) &&
get_flags( get_asimage_chanmask(im), SCL_DO_ALPHA) )
gce_bytes[GIF_GCE_TRANSPARENCY_BYTE] = cmap.count ;
else
gce_bytes[0] = 0 ;
#ifdef DEBUG_TRANSP_GIF
fprintf( stderr, "***> cmap.count = %d, transp_byte = %X, flags = %d, chanmask = %d\n", cmap.count, gce_bytes[GIF_GCE_TRANSPARENCY_BYTE],
get_flags( params->gif.flags, EXPORT_ALPHA), get_flags( get_asimage_chanmask(im), SCL_DO_ALPHA) );
#endif
gce_bytes[GIF_GCE_DELAY_BYTE_HIGH] = (params->gif.animate_delay>>8)&0x00FF;
gce_bytes[GIF_GCE_DELAY_BYTE_LOW] = params->gif.animate_delay&0x00FF;
if( get_flags( params->gif.flags, EXPORT_ANIMATION_REPEATS ) )
{
netscape_ext_bytes[GIF_NETSCAPE_REPEAT_BYTE_HIGH] = (params->gif.animate_repeats>>8)&0x00FF;
netscape_ext_bytes[GIF_NETSCAPE_REPEAT_BYTE_LOW] = params->gif.animate_repeats&0x00FF;
}
while( cmap_size < 256 && cmap_size < (int)cmap.count+(gce_bytes[0]&0x01) )
cmap_size = cmap_size<<1 ;
#if (GIFLIB_MAJOR>=5)
if( (gif_cmap = GifMakeMapObject(cmap_size, NULL )) == NULL )
#else
if( (gif_cmap = MakeMapObject(cmap_size, NULL )) == NULL )
#endif
{
free( mapped_im );
#if (GIFLIB_MAJOR>=5)
ASIM_PrintGifError(E_GIF_ERR_NOT_ENOUGH_MEM);
#else
ASIM_PrintGifError();
#endif
return False;
}
memcpy( &(gif_cmap->Colors[0]), &(cmap.entries[0]), MIN(cmap.count,(unsigned int)cmap_size)*3 );
if( get_flags(params->gif.flags, EXPORT_APPEND) && path != NULL)
infile = fopen( path, "rb" );
if( infile != NULL )
{
SavedImage *images = NULL ;
int count = 0 ;
/* TODO: do something about multiimage files !!! */
#if (GIFLIB_MAJOR>=5)
gif = open_gif_read(infile, &errcode);
#else
gif = open_gif_read(infile);
#endif
if( gif == NULL || get_gif_saved_images(gif, -1, &images, &count) == GIF_ERROR)
{
#if (GIFLIB_MAJOR>=5)
ASIM_PrintGifError(errcode);
#else
ASIM_PrintGifError();
#endif
if( gif )
{
#if (GIFLIB_MAJOR>=5)
DGifCloseFile(gif, &errcode);
#else
DGifCloseFile(gif);
#endif
gif = NULL ;
}
if (infile)
{
fclose( infile );
infile = NULL;
}
}else
{
GifFileType gif_src ;
new_image = False ;
gif_src = *gif ;
gif->SColorMap = NULL ;
gif->Image.ColorMap = NULL ;
#if (GIFLIB_MAJOR>=5)
DGifCloseFile(gif, &errcode);
#else
DGifCloseFile(gif);
#endif
gif = NULL;
fclose (infile);
infile = NULL;
outfile = open_writable_image_file( path );
if (outfile)
#if (GIFLIB_MAJOR>=5)
gif = EGifOpenFileHandle(fileno(outfile), &errcode);
#else
gif = EGifOpenFileHandle(fileno(outfile));
#endif
if (gif)
{
int status;
if( ( status = EGifPutScreenDesc(gif, gif_src.SWidth, gif_src.SHeight,
gif_src.SColorResolution,
gif_src.SBackGroundColor,
gif_src.SColorMap )) == GIF_OK )
status = write_gif_saved_images( gif, images, count );
if( status != GIF_OK )
#if (GIFLIB_MAJOR>=5)
ASIM_PrintGifError(status);
#else
ASIM_PrintGifError();
#endif
}
if (gif_src.SColorMap)
{ /* we only want to save private colormap if it is any different from
* screen colormap ( saves us 768 bytes per image ) */
if( gif_cmap->ColorCount == gif_src.SColorMap->ColorCount )
dont_save_cmap = ( memcmp( gif_cmap->Colors, gif_src.SColorMap->Colors, gif_cmap->ColorCount*sizeof(GifColorType)) == 0 );
#if (GIFLIB_MAJOR>=5)
GifFreeMapObject(gif_src.SColorMap);
#else
FreeMapObject(gif_src.SColorMap);
#endif
}
if (gif)
{
EGifPutExtension(gif, GRAPHICS_EXT_FUNC_CODE, GIF_GCE_BYTES, &(gce_bytes[0]));
if( get_flags( params->gif.flags, EXPORT_ANIMATION_REPEATS ) )
{
#if (GIFLIB_MAJOR>=5)
EGifPutExtensionLeader(gif, APPLICATION_EXT_FUNC_CODE);
EGifPutExtensionBlock(gif, 11, "NETSCAPE2.0");
EGifPutExtensionBlock(gif, GIF_NETSCAPE_EXT_BYTES, &(netscape_ext_bytes[0]));
EGifPutExtensionTrailer(gif);
#else
EGifPutExtensionFirst(gif, APPLICATION_EXT_FUNC_CODE, 11, "NETSCAPE2.0");
EGifPutExtensionLast(gif, 0, GIF_NETSCAPE_EXT_BYTES, &(netscape_ext_bytes[0]));
#endif
}
#if (GIFLIB_MAJOR>=5)
if( (errcode = EGifPutImageDesc(gif, 0, 0, im->width, im->height, false, (dont_save_cmap)?NULL:gif_cmap )) == GIF_ERROR )
ASIM_PrintGifError(errcode);
#else
if( EGifPutImageDesc(gif, 0, 0, im->width, im->height, FALSE, (dont_save_cmap)?NULL:gif_cmap ) == GIF_ERROR )
ASIM_PrintGifError();
#endif
}
}
free_gif_saved_images( images, count );
}
if (gif == NULL)
{
if (outfile == NULL)
outfile = open_writable_image_file(path);
if (outfile)
{
#if (GIFLIB_MAJOR>=5)
gif = EGifOpenFileHandle(fileno(outfile), &errcode);
if (errcode != E_GIF_SUCCEEDED)
ASIM_PrintGifError(errcode);
#else
if ((gif = EGifOpenFileHandle(fileno(outfile))) == NULL)
ASIM_PrintGifError();
#endif
}
}
if( new_image && gif )
{
#if (GIFLIB_MAJOR>=5)
if( (errcode = EGifPutScreenDesc(gif, im->width, im->height, cmap_size, 0, gif_cmap )) == GIF_ERROR )
ASIM_PrintGifError(errcode);
#else
if( EGifPutScreenDesc(gif, im->width, im->height, cmap_size, 0, gif_cmap ) == GIF_ERROR )
ASIM_PrintGifError();
#endif
EGifPutExtension(gif, 0xf9, GIF_GCE_BYTES, &(gce_bytes[0]));
#if (GIFLIB_MAJOR>=5)
if( (errcode = EGifPutImageDesc(gif, 0, 0, im->width, im->height, false, NULL )) == GIF_ERROR )
ASIM_PrintGifError(errcode);
#else
if( EGifPutImageDesc(gif, 0, 0, im->width, im->height, FALSE, NULL ) == GIF_ERROR )
ASIM_PrintGifError();
#endif
}
if( gif_cmap )
{
#if (GIFLIB_MAJOR>=5)
GifFreeMapObject(gif_cmap);
#else
FreeMapObject(gif_cmap);
#endif
gif_cmap = NULL ;
}
if( gif )
{
row_pointer = safemalloc( im->width*sizeof(GifPixelType));
/* it appears to be much faster to write image out in line by line fashion */
for( y = 0 ; y < (int)im->height ; y++ )
{
register int x = im->width ;
register int *src = mapped_im + x*y;
while( --x >= 0 )
row_pointer[x] = src[x] ;
#if (GIFLIB_MAJOR>=5)
if( (errcode = EGifPutLine(gif, row_pointer, im->width)) == GIF_ERROR)
ASIM_PrintGifError(errcode);
#else
if( EGifPutLine(gif, row_pointer, im->width) == GIF_ERROR)
ASIM_PrintGifError();
#endif
}
free( row_pointer );
#if (GIFLIB_MAJOR>=5)
EGifCloseFile(gif, &errcode);
if (errcode != E_GIF_SUCCEEDED)
ASIM_PrintGifError(errcode);
#else
if (EGifCloseFile(gif) == GIF_ERROR)
ASIM_PrintGifError();
#endif
gif = NULL;
}
free( mapped_im );
destroy_colormap( &cmap, True );
if (outfile
#ifdef NO_DOUBLE_FCLOSE_AFTER_FDOPEN
&& gif /* can't do double fclose in MS CRT after VC2005 */
#endif
&& outfile != stdout)
{
fclose (outfile);
}
SHOW_TIME("image export",started);
return True ;
}
#else /* GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF */
Bool
ASImage2gif( ASImage *im, const char *path, ASImageExportParams *params )
{
SHOW_UNSUPPORTED_NOTE("GIF",path);
return False ;
}
#endif /* GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF GIF */
#ifdef HAVE_TIFF/* TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF */
Bool
ASImage2tiff( ASImage *im, const char *path, ASImageExportParams *params)
{
TIFF *out;
static const ASTiffExportParams defaultsTiff = { ASIT_Tiff, 0, (CARD32)-1, TIFF_COMPRESSION_NONE, 100, 0 };
ASImageExportParams defaults;
uint16 photometric = PHOTOMETRIC_RGB;
tsize_t linebytes, scanline;
ASImageDecoder *imdec ;
CARD32 *r, *g, *b, *a ;
unsigned char* buf;
CARD32 row ;
Bool has_alpha ;
int nsamples = 3 ;
START_TIME(started);
if( params == NULL ) {
defaults.type = defaultsTiff.type;
defaults.tiff = defaultsTiff;
params = &defaults ;
}
if( path == NULL )
{
SHOW_UNSUPPORTED_NOTE("TIFF streamed into stdout",path);
return False ;
}
out = TIFFOpen(path, "w");
if (out == NULL)
return False;
/* I don't really know why by grayscale images in Tiff does not work :(
* still here is the code :*/
if( get_flags( params->tiff.flags, EXPORT_GRAYSCALE ) )
nsamples = 1 ;
has_alpha = get_flags( params->tiff.flags, EXPORT_ALPHA );
if( has_alpha )
{
if( !get_flags( get_asimage_chanmask(im), SCL_DO_ALPHA) )
has_alpha = False ;
else
++nsamples ;
}
if((imdec = start_image_decoding( NULL /* default visual */ , im,
has_alpha?SCL_DO_ALL:(SCL_DO_GREEN|SCL_DO_BLUE|SCL_DO_RED),
0, 0, im->width, 0, NULL)) == NULL )
{
LOCAL_DEBUG_OUT( "failed to start image decoding%s", "");
TIFFClose(out);
return False;
}
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, (uint32) im->width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, (uint32) im->height);
TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nsamples);
if (has_alpha)
{
uint16 v[1];
v[0] = EXTRASAMPLE_UNASSALPHA;
TIFFSetField(out, TIFFTAG_EXTRASAMPLES, 1, v);
}
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
if( params->tiff.compression_type == -1 )
params->tiff.compression_type = defaultsTiff.compression_type ;
TIFFSetField(out, TIFFTAG_COMPRESSION, params->tiff.compression_type);
switch (params->tiff.compression_type )
{
case COMPRESSION_JPEG:
photometric = PHOTOMETRIC_YCBCR;
if( params->tiff.jpeg_quality > 0 )
TIFFSetField(out, TIFFTAG_JPEGQUALITY, params->tiff.jpeg_quality );
TIFFSetField( out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB );
break;
}
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
linebytes = im->width*nsamples;
scanline = TIFFScanlineSize(out);
if (scanline > linebytes)
{
buf = (unsigned char *)_TIFFmalloc(scanline);
_TIFFmemset(buf+linebytes, 0, scanline-linebytes);
} else
buf = (unsigned char *)_TIFFmalloc(linebytes);
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
TIFFDefaultStripSize(out, params->tiff.rows_per_strip));
r = imdec->buffer.red ;
g = imdec->buffer.green ;
b = imdec->buffer.blue ;
a = imdec->buffer.alpha ;
for (row = 0; row < im->height; ++row)
{
register int i = im->width, k = (im->width-1)*nsamples ;
imdec->decode_image_scanline( imdec );
if( has_alpha )
{
if( nsamples == 2 )
while ( --i >= 0 )
{
buf[k+1] = a[i] ;
buf[k] = (54*r[i]+183*g[i]+19*b[i])/256 ;
k-= 2;
}
else
while ( --i >= 0 )
{
buf[k+3] = a[i] ;
buf[k+2] = b[i] ;
buf[k+1] = g[i] ;
buf[k] = r[i] ;
k-= 4;
}
}else if( nsamples == 1 )
while ( --i >= 0 )
buf[k--] = (54*r[i]+183*g[i]+19*b[i])/256 ;
else
while ( --i >= 0 )
{
buf[k+2] = b[i] ;
buf[k+1] = g[i] ;
buf[k] = r[i] ;
k-= 3;
}
if (TIFFWriteScanline(out, buf, row, 0) < 0)
break;
}
stop_image_decoding( &imdec );
TIFFClose(out);
SHOW_TIME("image export",started);
return True;
}
#else /* TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF */
Bool
ASImage2tiff( ASImage *im, const char *path, ASImageExportParams *params )
{
SHOW_UNSUPPORTED_NOTE("TIFF",path);
return False ;
}
#endif /* TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF TIFF */
| mhuwiler/rootauto | graf2d/asimage/src/libAfterImage/export.c | C | lgpl-2.1 | 38,902 |
define("dojox/mobile/bidi/Button", ["dojo/_base/declare", "./common"], function(declare, common){
// module:
// mobile/bidi/Button
return declare(null, {
// summary:
// Support for control over text direction for mobile Button widget, using Unicode Control Characters to control text direction.
// description:
// Implementation for text direction support for Label.
// This class should not be used directly.
// Mobile Button widget loads this module when user sets "has: {'dojo-bidi': true }" in data-dojo-config.
_setLabelAttr: function(/*String*/ content){
this.inherited(arguments, [this._cv ? this._cv(content) : content]);
this.focusNode.innerHTML = common.enforceTextDirWithUcc(this.focusNode.innerHTML, this.textDir);
},
_setTextDirAttr: function(/*String*/ textDir){
if(!this._created || this.textDir !== textDir){
this._set("textDir", textDir);
this.focusNode.innerHTML = common.enforceTextDirWithUcc(common.removeUCCFromText(this.focusNode.innerHTML), this.textDir);
}
}
});
});
| Caspar12/zh.sw | zh.web.site.admin/src/main/resources/static/js/dojo/dojox/mobile/bidi/Button.js.uncompressed.js | JavaScript | apache-2.0 | 1,044 |
package com.jakewharton.u2020;
import java.lang.annotation.Retention;
import javax.inject.Qualifier;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Qualifier @Retention(RUNTIME)
public @interface IsInstrumentationTest {
}
| friederbluemle/u2020 | src/internalDebug/java/com/jakewharton/u2020/IsInstrumentationTest.java | Java | apache-2.0 | 239 |
package ad
import (
"errors"
"fmt"
"reflect"
"testing"
"gopkg.in/ldap.v2"
"github.com/openshift/origin/pkg/auth/ldaputil"
"github.com/openshift/origin/pkg/auth/ldaputil/testclient"
)
func newTestAugmentedADLDAPInterface(client ldap.Client) *AugmentedADLDAPInterface {
// below are common test implementations of LDAPInterface fields
userQuery := ldaputil.LDAPQuery{
BaseDN: "ou=users,dc=example,dc=com",
Scope: ldaputil.ScopeWholeSubtree,
DerefAliases: ldaputil.DerefAliasesAlways,
TimeLimit: 0,
Filter: "objectClass=inetOrgPerson",
}
groupMembershipAttributes := []string{"memberOf"}
userNameAttributes := []string{"cn"}
groupQuery := ldaputil.LDAPQueryOnAttribute{
LDAPQuery: ldaputil.LDAPQuery{
BaseDN: "ou=groups,dc=example,dc=com",
Scope: ldaputil.ScopeWholeSubtree,
DerefAliases: ldaputil.DerefAliasesAlways,
TimeLimit: 0,
Filter: "objectClass=groupOfNames",
},
QueryAttribute: "dn",
}
groupNameAttributes := []string{"cn"}
return NewAugmentedADLDAPInterface(testclient.NewConfig(client),
userQuery,
groupMembershipAttributes,
userNameAttributes,
groupQuery,
groupNameAttributes)
}
// newDefaultTestGroup returns a new LDAP entry with the given CN
func newTestGroup(CN string) *ldap.Entry {
return ldap.NewEntry(fmt.Sprintf("cn=%s,ou=groups,dc=example,dc=com", CN), map[string][]string{"cn": {CN}})
}
func TestGroupEntryFor(t *testing.T) {
var testCases = []struct {
name string
cacheSeed map[string]*ldap.Entry
client ldap.Client
baseDNOverride string
expectedError error
expectedEntry *ldap.Entry
}{
{
name: "cached entries",
cacheSeed: map[string]*ldap.Entry{
"cn=testGroup,ou=groups,dc=example,dc=com": newTestGroup("testGroup"),
},
expectedError: nil,
expectedEntry: newTestGroup("testGroup"),
},
{
name: "search request error",
baseDNOverride: "otherBaseDN",
expectedError: ldaputil.NewQueryOutOfBoundsError("cn=testGroup,ou=groups,dc=example,dc=com", "otherBaseDN"),
expectedEntry: nil,
},
{
name: "search error",
client: testclient.NewMatchingSearchErrorClient(testclient.New(), "cn=testGroup,ou=groups,dc=example,dc=com", errors.New("generic search error")),
expectedError: errors.New("generic search error"),
expectedEntry: nil,
},
{
name: "no error",
client: testclient.NewDNMappingClient(
testclient.New(),
map[string][]*ldap.Entry{
"cn=testGroup,ou=groups,dc=example,dc=com": {newTestGroup("testGroup")},
},
),
expectedError: nil,
expectedEntry: newTestGroup("testGroup"),
},
}
for _, testCase := range testCases {
ldapInterface := newTestAugmentedADLDAPInterface(testCase.client)
if len(testCase.cacheSeed) > 0 {
ldapInterface.cachedGroups = testCase.cacheSeed
}
if len(testCase.baseDNOverride) > 0 {
ldapInterface.groupQuery.BaseDN = testCase.baseDNOverride
}
entry, err := ldapInterface.GroupEntryFor("cn=testGroup,ou=groups,dc=example,dc=com")
if !reflect.DeepEqual(err, testCase.expectedError) {
t.Errorf("%s: incorrect error returned:\n\texpected:\n\t%v\n\tgot:\n\t%v\n", testCase.name, testCase.expectedError, err)
}
if !reflect.DeepEqual(entry, testCase.expectedEntry) {
t.Errorf("%s: incorrect members returned:\n\texpected:\n\t%v\n\tgot:\n\t%v\n", testCase.name, testCase.expectedEntry, entry)
}
}
}
| rhuss/gofabric8 | vendor/github.com/openshift/origin/pkg/cmd/admin/groups/sync/ad/augmented_ldapinterface_test.go | GO | apache-2.0 | 3,431 |
# Security Policy
## Reporting a Vulnerability
To report security issues send an email to [email protected] (not for support).
The following keys may be used to communicate sensitive information to developers:
| Name | Fingerprint |
|------|-------------|
| Pieter Wuille | 133E AC17 9436 F14A 5CF1 B794 860F EB80 4E66 9320 |
| Andrew Poelstra | 699A 63EF C17A D3A9 A34C FFC0 7AD0 A91C 40BD 0091 |
| Tim Ruffing | 09E0 3F87 1092 E40E 106E 902B 33BC 86AB 80FF 5516 |
You can import a key by running the following command with that individual’s fingerprint: `gpg --recv-keys "<fingerprint>"` Ensure that you put quotes around fingerprints containing spaces.
| rnicoll/dogecoin | src/secp256k1/SECURITY.md | Markdown | mit | 683 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 University of Washington
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Leonard Tracy <[email protected]>
* Andrea Sacco <[email protected]>
*/
#ifndef UAN_PHY_H
#define UAN_PHY_H
#include "ns3/object.h"
#include "ns3/uan-mac.h"
#include "ns3/uan-tx-mode.h"
#include "ns3/uan-prop-model.h"
#include "ns3/uan-transducer.h"
#include "ns3/device-energy-model.h"
namespace ns3 {
/**
* \class UanPhyCalcSinr
*
* Class used for calculating SINR of packet in UanPhy.
* Can be set to any derived class using attributes of UanPhy
* to implement different models.
*/
class UanPhyCalcSinr : public Object
{
public:
static TypeId GetTypeId (void);
/**
* \param pkt Packet to calculate SINR for
* \param arrTime Arrival time of pkt
* \param rxPowerDb The received signal strength of the packet in dB re 1 uPa
* \param ambNoiseDb Ambient channel noise in dB re 1 uPa
* \param mode TX Mode of pkt
* \param pdp Power delay profile of pkt
* \param arrivalList List of interfering arrivals given from Transducer.
*/
virtual double CalcSinrDb (Ptr<Packet> pkt,
Time arrTime,
double rxPowerDb,
double ambNoiseDb,
UanTxMode mode,
UanPdp pdp,
const UanTransducer::ArrivalList &arrivalList
) const = 0;
/**
* Clears all pointer references
*/
virtual void Clear (void);
virtual void DoDispose (void);
/**
* \param db dB value
* \returns kilopascals
* \brief Converts dB re 1 uPa to kilopascals
*/
inline double DbToKp (double db) const
{
return std::pow (10, db / 10.0);
}
/**
* \param kp value in kilopascals
* \returns dB re 1 uPa
* \brief Converts kilopascals to dB re 1 uPa
*/
inline double KpToDb (double kp) const
{
return 10 * std::log10 (kp);
}
};
/**
* \class UanPhyPer
* Used in UanPhy for determining probability of packet error based on received SINR and
* modulation (mode). Can be set in UanPhy via attributes
*/
class UanPhyPer : public Object
{
public:
static TypeId GetTypeId (void);
/**
* Calculates the prob. of packet error based on
* SINR at the receiver and a tx mode.
* \param pkt Packet which is under consideration
* \param sinrDb SINR at receiver
* \param mode TX mode used to transmit packet
* \returns Probability of packet error
*/
virtual double CalcPer (Ptr<Packet> pkt, double sinrDb, UanTxMode mode) = 0;
/**
* Clears all pointer references
*/
virtual void Clear (void);
virtual void DoDispose (void);
};
/**
* \class UanPhyListener
*
* \brief Interface for PHY event listener
* A class which implements this interface may register with Phy object
* to receive notification of TX/RX/CCA events
*/
class UanPhyListener
{
public:
virtual ~UanPhyListener ()
{
}
/**
* \brief Function called when Phy object begins receiving packet
*/
virtual void NotifyRxStart (void) = 0;
/**
* \brief Function called when Phy object finishes receiving packet without error
*/
virtual void NotifyRxEndOk (void) = 0;
/**
* \brief Function called when Phy object finishes receiving packet in error
*/
virtual void NotifyRxEndError (void) = 0;
/**
* \brief Function called when Phy object begins sensing channel is busy
*/
virtual void NotifyCcaStart (void) = 0;
/**
* \brief Function called when Phy object stops sensing channel is busy
*/
virtual void NotifyCcaEnd (void) = 0;
/**
* \param duration Duration of transmission
* \brief Function called when transmission starts from Phy object
*/
virtual void NotifyTxStart (Time duration) = 0;
};
/**
* \class UanPhy
*
* \brief Base class for UAN Phy models
*/
class UanPhy : public Object
{
public:
static TypeId GetTypeId (void);
/// Enum defining possible Phy states
enum State
{
IDLE, CCABUSY, RX, TX, SLEEP
};
/**
* arg1: packet received successfully
* arg2: snr of packet
* arg3: mode of packet
*/
typedef Callback<void, Ptr<Packet>, double, UanTxMode> RxOkCallback;
/**
* arg1: packet received successfully
* arg2: snr of packet
*/
typedef Callback<void, Ptr<Packet>, double > RxErrCallback;
/**
* \param callback DeviceEnergyModel change state callback.
*
* This function sets the DeviceEnergyModel callback for UanPhy device. Must
* be implemented by UanPhy child classes.
*/
virtual void SetEnergyModelCallback (DeviceEnergyModel::ChangeStateCallback callback) = 0;
/**
* This function handles the energy depletion event. Must
* be implemented by UanPhy child classes.
*/
virtual void EnergyDepletionHandler (void) = 0;
/**
* \param pkt Packet to transmit
* \param modeNum Index of mode in SupportedModes list to use for transmission
*/
virtual void SendPacket (Ptr<Packet> pkt, uint32_t modeNum) = 0;
/**
* \param listener New listener to register
*
* Register an object to be notified of common Phy events
*/
virtual void RegisterListener (UanPhyListener *listener) = 0;
/**
* \brief Packet arriving from channel: i.e. leading bit of packet has arrived.
* \param pkt Packet which is arriving
* \param rxPowerDb Signal power of incoming packet in dB
* \param txMode Transmission mode defining modulation of incoming packet
* \param pdp Power delay profile of incoming packet
*/
virtual void StartRxPacket (Ptr<Packet> pkt, double rxPowerDb, UanTxMode txMode, UanPdp pdp) = 0;
/**
* \param cb Callback to be enabled when packet is received without error
*/
virtual void SetReceiveOkCallback (RxOkCallback cb) = 0;
/**
* \param cb Callback to be enabled when a packet is received with errors
*/
virtual void SetReceiveErrorCallback (RxErrCallback cb) = 0;
/**
* \param gain Gain added at receiver
*/
virtual void SetRxGainDb (double gain) = 0;
/**
* \param txpwr Final output transmission power in dB
*/
virtual void SetTxPowerDb (double txpwr) = 0;
/**
* \param thresh Threshold SINR for propper reception in dB
*/
virtual void SetRxThresholdDb (double thresh) = 0;
/**
* \param thresh Signal power at receiver required for CCA busy state
*
*/
virtual void SetCcaThresholdDb (double thresh) = 0;
/**
* \returns Gain added to signal at receiver in dB
*/
virtual double GetRxGainDb (void) = 0;
/**
* \returns Current TX power output
*/
virtual double GetTxPowerDb (void) = 0;
/**
* \returns Required signal strength, in dB, to begin receiving packet
*/
virtual double GetRxThresholdDb (void) = 0;
/**
* \returns Threshold signal strength in dB to enter CCA busy mode
*/
virtual double GetCcaThresholdDb (void) = 0;
/**
*
* \returns True if Phy is SLEEP
*/
virtual bool IsStateSleep (void) = 0;
/**
*
* \returns True if Phy is IDLE
*/
virtual bool IsStateIdle (void) = 0;
/**
*
* \returns True if Phy is not IDLE
*/
virtual bool IsStateBusy (void) = 0;
/**
*
* \returns True if Phy is currently in receive mode
*/
virtual bool IsStateRx (void) = 0;
/**
*
* \returns True if Phy is busy transmitting
*/
virtual bool IsStateTx (void) = 0;
/**
*
* \returns True if Phy is not TX or RX but the channel is sensed busy
*/
virtual bool IsStateCcaBusy (void) = 0;
/**
* \returns Channel this phy is attached to
*/
virtual Ptr<UanChannel> GetChannel (void) const = 0;
/**
* \returns the Net Device that this Phy is a part of
*/
virtual Ptr<UanNetDevice> GetDevice (void) = 0;
/**
* \param channel The channel this Phy is attached to
*/
virtual void SetChannel (Ptr<UanChannel> channel) = 0;
/**
* \param device The Net Device this Phy is a part of
*/
virtual void SetDevice (Ptr<UanNetDevice> device) = 0;
/**
* \param mac The MAC forwarding messages to this Phy
*/
virtual void SetMac (Ptr<UanMac> mac) = 0;
/**
* \param packet Packet that is beginning transmission
* \param txPowerDb Transmit power of packet
* \param txMode Transmission mode of packet
*
* Notification that there is a transmission beginning
* on the transducer that this Phy is attached to.
*/
virtual void NotifyTransStartTx (Ptr<Packet> packet, double txPowerDb, UanTxMode txMode) = 0;
/**
*
* Function called when there has been a change in the
* ammount of interference this node is experiencing
* from other transmissions
*/
virtual void NotifyIntChange (void) = 0;
/**
*
* \param trans Transducer this Phy outputs to / receives from
*/
virtual void SetTransducer (Ptr<UanTransducer> trans) = 0;
/**
* \returns Transducer this Phy outputs to / receives from
*/
virtual Ptr<UanTransducer> GetTransducer (void) = 0;
/**
* \returns Number of TX modes supported by this PHY
*/
virtual uint32_t GetNModes (void) = 0;
/**
* \param n Mode number of mode to return (place in Modeslist)
* \returns Mode n
*/
virtual UanTxMode GetMode (uint32_t n) = 0;
/**
* \warning Returns non-valid pointer if IsStateRx == false
* \returns Packet currently being received in PHY
*/
virtual Ptr<Packet> GetPacketRx (void) const = 0;
/**
* Clears all pointer references
*/
virtual void Clear (void) = 0;
virtual void SetSleepMode (bool sleep) = 0;
/**
* Public method used to fire a PhyTxBegin trace. Implemented for encapsulation
* purposes.
*/
void NotifyTxBegin (Ptr<const Packet> packet);
/**
* Public method used to fire a PhyTxEnd trace. Implemented for encapsulation
* purposes.
*/
void NotifyTxEnd (Ptr<const Packet> packet);
/**
* Public method used to fire a PhyTxDrop trace. Implemented for encapsulation
* purposes.
*/
void NotifyTxDrop (Ptr<const Packet> packet);
/**
* Public method used to fire a PhyRxBegin trace. Implemented for encapsulation
* purposes.
*/
void NotifyRxBegin (Ptr<const Packet> packet);
/**
* Public method used to fire a PhyRxEnd trace. Implemented for encapsulation
* purposes.
*/
void NotifyRxEnd (Ptr<const Packet> packet);
/**
* Public method used to fire a PhyRxDrop trace. Implemented for encapsulation
* purposes.
*/
void NotifyRxDrop (Ptr<const Packet> packet);
/**
* Assign a fixed random variable stream number to the random variables
* used by this model. Return the number of streams (possibly zero) that
* have been assigned.
*
* \param stream first stream index to use
* \return the number of stream indices assigned by this model
*/
virtual int64_t AssignStreams (int64_t stream) = 0;
private:
/**
* The trace source fired when a packet begins the transmission process on
* the medium.
*
* \see class CallBackTraceSource
*/
TracedCallback<Ptr<const Packet> > m_phyTxBeginTrace;
/**
* The trace source fired when a packet ends the transmission process on
* the medium.
*
* \see class CallBackTraceSource
*/
TracedCallback<Ptr<const Packet> > m_phyTxEndTrace;
/**
* The trace source fired when the phy layer drops a packet as it tries
* to transmit it.
*
* \see class CallBackTraceSource
*/
TracedCallback<Ptr<const Packet> > m_phyTxDropTrace;
/**
* The trace source fired when a packet begins the reception process from
* the medium.
*
* \see class CallBackTraceSource
*/
TracedCallback<Ptr<const Packet> > m_phyRxBeginTrace;
/**
* The trace source fired when a packet ends the reception process from
* the medium.
*
* \see class CallBackTraceSource
*/
TracedCallback<Ptr<const Packet> > m_phyRxEndTrace;
/**
* The trace source fired when the phy layer drops a packet it has received.
*
* \see class CallBackTraceSource
*/
TracedCallback<Ptr<const Packet> > m_phyRxDropTrace;
};
}
#endif /* UAN_PHY_H */
| thehajime/ns-3-dev | src/uan/model/uan-phy.h | C | gpl-2.0 | 12,743 |
c
c dpoco factors a double precision symmetric positive definite
c matrix and estimates the condition of the matrix.
c
c if rcond is not needed, dpofa is slightly faster.
c to solve a*x = b , follow dpoco by dposl.
c to compute inverse(a)*c , follow dpoco by dposl.
c to compute determinant(a) , follow dpoco by dpodi.
c to compute inverse(a) , follow dpoco by dpodi.
c
c on entry
c
c a double precision(lda, n)
c the symmetric matrix to be factored. only the
c diagonal and upper triangle are used.
c
c lda integer
c the leading dimension of the array a .
c
c n integer
c the order of the matrix a .
c
c on return
c
c a an upper triangular matrix r so that a = trans(r)*r
c where trans(r) is the transpose.
c the strict lower triangle is unaltered.
c if info .ne. 0 , the factorization is not complete.
c
c rcond double precision
c an estimate of the reciprocal condition of a .
c for the system a*x = b , relative perturbations
c in a and b of size epsilon may cause
c relative perturbations in x of size epsilon/rcond .
c if rcond is so small that the logical expression
c 1.0 + rcond .eq. 1.0
c is true, then a may be singular to working
c precision. in particular, rcond is zero if
c exact singularity is detected or the estimate
c underflows. if info .ne. 0 , rcond is unchanged.
c
c z double precision(n)
c a work vector whose contents are usually unimportant.
c if a is close to a singular matrix, then z is
c an approximate null vector in the sense that
c norm(a*z) = rcond*norm(a)*norm(z) .
c if info .ne. 0 , z is unchanged.
c
c info integer
c = 0 for normal return.
c = k signals an error condition. the leading minor
c of order k is not positive definite.
c
c linpack. this version dated 08/14/78 .
c cleve moler, university of new mexico, argonne national lab.
c
c subroutines and functions
c
c linpack dpofa
c blas daxpy,ddot,dscal,dasum
c fortran dabs,dmax1,dreal,dsign
c
subroutine dpoco(a,lda,n,rcond,z,info)
integer lda,n,info
double precision a(lda,*),z(*)
double precision rcond
c
c internal variables
c
double precision ddot,ek,t,wk,wkm
double precision anorm,s,dasum,sm,ynorm
integer i,j,jm1,k,kb,kp1
c
c
c find norm of a using only upper half
c
do 30 j = 1, n
z(j) = dasum(j,a(1,j),1)
jm1 = j - 1
if (jm1 .lt. 1) go to 20
do 10 i = 1, jm1
z(i) = z(i) + dabs(a(i,j))
10 continue
20 continue
30 continue
anorm = 0.0d0
do 40 j = 1, n
anorm = dmax1(anorm,z(j))
40 continue
c
c factor
c
call dpofa(a,lda,n,info)
if (info .ne. 0) go to 180
c
c rcond = 1/(norm(a)*(estimate of norm(inverse(a)))) .
c estimate = norm(z)/norm(y) where a*z = y and a*y = e .
c the components of e are chosen to cause maximum local
c growth in the elements of w where trans(r)*w = e .
c the vectors are frequently rescaled to avoid overflow.
c
c solve trans(r)*w = e
c
ek = 1.0d0
do 50 j = 1, n
z(j) = 0.0d0
50 continue
do 110 k = 1, n
if (z(k) .ne. 0.0d0) ek = dsign(ek,-z(k))
if (dabs(ek-z(k)) .le. a(k,k)) go to 60
s = a(k,k)/dabs(ek-z(k))
call dscal(n,s,z,1)
ek = s*ek
60 continue
wk = ek - z(k)
wkm = -ek - z(k)
s = dabs(wk)
sm = dabs(wkm)
wk = wk/a(k,k)
wkm = wkm/a(k,k)
kp1 = k + 1
if (kp1 .gt. n) go to 100
do 70 j = kp1, n
sm = sm + dabs(z(j)+wkm*a(k,j))
z(j) = z(j) + wk*a(k,j)
s = s + dabs(z(j))
70 continue
if (s .ge. sm) go to 90
t = wkm - wk
wk = wkm
do 80 j = kp1, n
z(j) = z(j) + t*a(k,j)
80 continue
90 continue
100 continue
z(k) = wk
110 continue
s = 1.0d0/dasum(n,z,1)
call dscal(n,s,z,1)
c
c solve r*y = w
c
do 130 kb = 1, n
k = n + 1 - kb
if (dabs(z(k)) .le. a(k,k)) go to 120
s = a(k,k)/dabs(z(k))
call dscal(n,s,z,1)
120 continue
z(k) = z(k)/a(k,k)
t = -z(k)
call daxpy(k-1,t,a(1,k),1,z(1),1)
130 continue
s = 1.0d0/dasum(n,z,1)
call dscal(n,s,z,1)
c
ynorm = 1.0d0
c
c solve trans(r)*v = y
c
do 150 k = 1, n
z(k) = z(k) - ddot(k-1,a(1,k),1,z(1),1)
if (dabs(z(k)) .le. a(k,k)) go to 140
s = a(k,k)/dabs(z(k))
call dscal(n,s,z,1)
ynorm = s*ynorm
140 continue
z(k) = z(k)/a(k,k)
150 continue
s = 1.0d0/dasum(n,z,1)
call dscal(n,s,z,1)
ynorm = s*ynorm
c
c solve r*z = v
c
do 170 kb = 1, n
k = n + 1 - kb
if (dabs(z(k)) .le. a(k,k)) go to 160
s = a(k,k)/dabs(z(k))
call dscal(n,s,z,1)
ynorm = s*ynorm
160 continue
z(k) = z(k)/a(k,k)
t = -z(k)
call daxpy(k-1,t,a(1,k),1,z(1),1)
170 continue
c make znorm = 1.0
s = 1.0d0/dasum(n,z,1)
call dscal(n,s,z,1)
ynorm = s*ynorm
c
if (anorm .ne. 0.0d0) rcond = ynorm/anorm
if (anorm .eq. 0.0d0) rcond = 0.0d0
180 continue
return
end
| jimhester/r-source | src/appl/dpoco.f | FORTRAN | gpl-2.0 | 6,117 |
do
function run(msg, matches)
if msg.to.id == our_id or is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat = "chat#id"..matches[2]
local user = "user#id"..msg.from.id
chat_add_user(chat, user, ok_cb, false)
end
end
end
return {
patterns = {
"^[/!](join) (.*)$"
"^[Jj](oin) (.*)$"
},
run = run,
}
end
| mramir8274/botman | plugins/inpm.lua | Lua | gpl-2.0 | 779 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Navigation Panel - jQuery EasyUI Mobile Demo</title>
<link rel="stylesheet" type="text/css" href="../../themes/metro/easyui.css">
<link rel="stylesheet" type="text/css" href="../../themes/mobile.css">
<link rel="stylesheet" type="text/css" href="../../themes/icon.css">
<script type="text/javascript" src="../../jquery.min.js"></script>
<script type="text/javascript" src="../../jquery.easyui.min.js"></script>
<script type="text/javascript" src="../../jquery.easyui.mobile.js"></script>
</head>
<body>
<div class="easyui-navpanel">
<header>
<div class="m-toolbar">
<div class="m-title">Navigation</div>
</div>
</header>
<div style="margin:50px 0 0;text-align:center">
<a href="javascript:void(0)" class="easyui-linkbutton" style="width:100px;height:30px" onclick="$.mobile.go('#p2')">Goto Panel2</a>
</div>
</div>
<div id="p2" class="easyui-navpanel">
<header>
<div class="m-toolbar">
<div class="m-title">Panel2</div>
<div class="m-left">
<a href="#" class="easyui-linkbutton m-back" data-options="plain:true,outline:true,back:true">Back</a>
</div>
</div>
</header>
<div style="margin:50px 0 0;text-align:center">
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="$.mobile.back()">Go Back</a>
</div>
</div>
</body>
</html> | mulyadigunawan02/pas | web-app/js/jquery-easyui/demo-mobile/panel/nav.html | HTML | gpl-3.0 | 1,637 |
<!--
This file is auto-generated from builtinprecision_test_generator.py
DO NOT EDIT!
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebGL Builtin Precision Conformance Tests</title>
<link rel="stylesheet" href="../../../../resources/js-test-style.css"/>
<script src=/resources/testharness.js></script>
<script src=/resources/testharnessreport.js></script>
<script src="../../../../js/js-test-pre.js"></script>
<script src="../../../../js/webgl-test-utils.js"></script>
<script src="../../../../closure-library/closure/goog/base.js"></script>
<script src="../../../deqp-deps.js"></script>
<script>goog.require('functional.gles3.es3fBuiltinPrecisionTests');</script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<canvas id="canvas" width="200" height="100"> </canvas>
<script>
var canvas = document.getElementById('canvas');
var wtu = WebGLTestUtils;
var gl = wtu.create3DContext('canvas', null, 2);
functional.gles3.es3fBuiltinPrecisionTests.run(gl, 24);
</script>
</body>
</html>
| UK992/servo | tests/wpt/webgl/tests/deqp/functional/gles3/builtinprecision/sqrt.html | HTML | mpl-2.0 | 1,056 |
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package storage
import "sort"
// SortBlockDevices sorts block devices by device name.
func SortBlockDevices(devices []BlockDevice) {
sort.Sort(byDeviceName(devices))
}
type byDeviceName []BlockDevice
func (b byDeviceName) Len() int {
return len(b)
}
func (b byDeviceName) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
func (b byDeviceName) Less(i, j int) bool {
return b[i].DeviceName < b[j].DeviceName
}
| mjs/juju | storage/sort.go | GO | agpl-3.0 | 506 |
// RUN: %clang_cc1 -fsyntax-only -fdelayed-template-parsing -Wunused-private-field -Wused-but-marked-unused -Wno-uninitialized -verify -std=c++11 %s
// expected-no-diagnostics
class EverythingMayBeUsed {
int x;
public:
template <class T>
void f() {
x = 0;
}
};
| cd80/UtilizedLLVM | tools/clang/test/SemaCXX/warn-unused-private-field-delayed-template.cpp | C++ | unlicense | 274 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.tools.nodetool;
import io.airlift.airline.Arguments;
import io.airlift.airline.Command;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.cassandra.tools.NodeProbe;
import org.apache.cassandra.tools.NodeTool.NodeToolCmd;
@Command(name = "enableautocompaction", description = "Enable autocompaction for the given keyspace and table")
public class EnableAutoCompaction extends NodeToolCmd
{
@Arguments(usage = "[<keyspace> <tables>...]", description = "The keyspace followed by one or many tables")
private List<String> args = new ArrayList<>();
@Override
public void execute(NodeProbe probe)
{
List<String> keyspaces = parseOptionalKeyspace(args, probe);
String[] tableNames = parseOptionalTables(args);
for (String keyspace : keyspaces)
{
try
{
probe.enableAutoCompaction(keyspace, tableNames);
} catch (IOException e)
{
throw new RuntimeException("Error occurred during enabling auto-compaction", e);
}
}
}
} | jeromatron/cassandra | src/java/org/apache/cassandra/tools/nodetool/EnableAutoCompaction.java | Java | apache-2.0 | 1,953 |
// @target: ES5
// @module: commonjs
// @declaration: true
// @Filename: privacyCannotNameAccessorDeclFile_GlobalWidgets.ts
declare module "GlobalWidgets" {
export class Widget3 {
name: string;
}
export function createWidget3(): Widget3;
export module SpecializedGlobalWidget {
export class Widget4 {
name: string;
}
function createWidget4(): Widget4;
}
}
// @Filename: privacyCannotNameAccessorDeclFile_Widgets.ts
export class Widget1 {
name = 'one';
}
export function createWidget1() {
return new Widget1();
}
export module SpecializedWidget {
export class Widget2 {
name = 'one';
}
export function createWidget2() {
return new Widget2();
}
}
// @Filename:privacyCannotNameAccessorDeclFile_exporter.ts
///<reference path='privacyCannotNameAccessorDeclFile_GlobalWidgets.ts'/>
import Widgets = require("privacyCannotNameAccessorDeclFile_Widgets");
import Widgets1 = require("GlobalWidgets");
export function createExportedWidget1() {
return Widgets.createWidget1();
}
export function createExportedWidget2() {
return Widgets.SpecializedWidget.createWidget2();
}
export function createExportedWidget3() {
return Widgets1.createWidget3();
}
export function createExportedWidget4() {
return Widgets1.SpecializedGlobalWidget.createWidget4();
}
// @Filename:privacyCannotNameAccessorDeclFile_consumer.ts
import exporter = require("privacyCannotNameAccessorDeclFile_exporter");
export class publicClassWithWithPrivateGetAccessorTypes {
static get myPublicStaticMethod() { // Error
return exporter.createExportedWidget1();
}
private static get myPrivateStaticMethod() {
return exporter.createExportedWidget1();
}
get myPublicMethod() { // Error
return exporter.createExportedWidget1();
}
private get myPrivateMethod() {
return exporter.createExportedWidget1();
}
static get myPublicStaticMethod1() { // Error
return exporter.createExportedWidget3();
}
private static get myPrivateStaticMethod1() {
return exporter.createExportedWidget3();
}
get myPublicMethod1() { // Error
return exporter.createExportedWidget3();
}
private get myPrivateMethod1() {
return exporter.createExportedWidget3();
}
}
class privateClassWithWithPrivateGetAccessorTypes {
static get myPublicStaticMethod() {
return exporter.createExportedWidget1();
}
private static get myPrivateStaticMethod() {
return exporter.createExportedWidget1();
}
get myPublicMethod() {
return exporter.createExportedWidget1();
}
private get myPrivateMethod() {
return exporter.createExportedWidget1();
}
static get myPublicStaticMethod1() {
return exporter.createExportedWidget3();
}
private static get myPrivateStaticMethod1() {
return exporter.createExportedWidget3();
}
get myPublicMethod1() {
return exporter.createExportedWidget3();
}
private get myPrivateMethod1() {
return exporter.createExportedWidget3();
}
}
export class publicClassWithPrivateModuleGetAccessorTypes {
static get myPublicStaticMethod() { // Error
return exporter.createExportedWidget2();
}
get myPublicMethod() { // Error
return exporter.createExportedWidget2();
}
static get myPublicStaticMethod1() { // Error
return exporter.createExportedWidget4();
}
get myPublicMethod1() { // Error
return exporter.createExportedWidget4();
}
}
class privateClassWithPrivateModuleGetAccessorTypes {
static get myPublicStaticMethod() {
return exporter.createExportedWidget2();
}
get myPublicMethod() {
return exporter.createExportedWidget2();
}
static get myPublicStaticMethod1() {
return exporter.createExportedWidget4();
}
get myPublicMethod1() {
return exporter.createExportedWidget4();
}
} | progre/TypeScript | tests/cases/compiler/privacyCannotNameAccessorDeclFile.ts | TypeScript | apache-2.0 | 4,158 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Animation of rotate property</title>
<style type="text/css" media="screen">
div {
-webkit-box-sizing: border-box;
}
.column {
margin: 10px;
display: inline-block;
vertical-align: top;
}
.container {
position: relative;
height: 200px;
width: 200px;
margin: 10px;
background-color: silver;
border: 1px solid black;
}
.box {
position: absolute;
top: 0;
left: 0;
height: 60px;
width: 60px;
border: 1px dotted black;
-webkit-transform-origin: top left; /* to match SVG */
}
.final {
border: 1px solid blue;
}
#target, #ref {
-webkit-animation-name: bounce;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: alternate;
-webkit-animation-timing-function: ease-in-out;
}
@-webkit-keyframes bounce {
from {
transform: translate(0px, 0px) scale(1) rotate(0deg);
}
to {
transform: translate(75px, 25px) scale(2) rotate(45deg);
}
}
</style>
</head>
<body>
<h1>CSS Animation of 'webkit-transform:' property for SVG</h1>
<p>The SVG animation should be identical with the CSS one</p>
<div class="column">
<h2>SVG compound</h2>
<div class="container">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
viewBox="0 0 200 200" style="width:200px; height:200px;">
<rect id="target" x="0" y="0" width="60" height="60" stroke="blue" fill="none">
</rect>
</svg>
</div>
<h2>CSS compound</h2>
<div class="container">
<div class="final box" id="ref">
</div>
</div>
</div>
</body>
</html> | guorendong/iridium-browser-ubuntu | third_party/WebKit/ManualTests/svg-css-animate-compound.html | HTML | bsd-3-clause | 1,886 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"am",
"pm"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "dd-MMM-y h:mm:ss a",
"mediumDate": "dd-MMM-y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/yy h:mm a",
"shortDate": "dd/MM/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 2,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 2,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "en-in",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| marcoR80/simple-app-mobile | www/vendor/angular-1.3.9/i18n/angular-locale_en-in.js | JavaScript | mit | 2,299 |
#ifndef _SCSI_IOCTL_H
#define _SCSI_IOCTL_H
#define SCSI_IOCTL_SEND_COMMAND 1
#define SCSI_IOCTL_TEST_UNIT_READY 2
#define SCSI_IOCTL_BENCHMARK_COMMAND 3
#define SCSI_IOCTL_SYNC 4
#define SCSI_IOCTL_START_UNIT 5
#define SCSI_IOCTL_STOP_UNIT 6
#define SCSI_IOCTL_DOORLOCK 0x5380
#define SCSI_IOCTL_DOORUNLOCK 0x5381
#endif
| zichiban/UnixHubLinux | tools/include/scsi/scsi_ioctl.h | C | mit | 322 |
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
i8259.c
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Forrest Yu, 2005
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#include "type.h"
#include "stdio.h"
#include "const.h"
#include "protect.h"
#include "proc.h"
#include "fs.h"
#include "tty.h"
#include "console.h"
#include "global.h"
#include "proto.h"
/*======================================================================*
init_8259A
*======================================================================*/
PUBLIC void init_8259A()
{
out_byte(INT_M_CTL, 0x11); /* Master 8259, ICW1. */
out_byte(INT_S_CTL, 0x11); /* Slave 8259, ICW1. */
out_byte(INT_M_CTLMASK, INT_VECTOR_IRQ0); /* Master 8259, ICW2. 设置 '主8259' 的中断入口地址为 0x20. */
out_byte(INT_S_CTLMASK, INT_VECTOR_IRQ8); /* Slave 8259, ICW2. 设置 '从8259' 的中断入口地址为 0x28. */
out_byte(INT_M_CTLMASK, 0x4); /* Master 8259, ICW3. IR2 对应 '从8259'. */
out_byte(INT_S_CTLMASK, 0x2); /* Slave 8259, ICW3. 对应 '主8259' 的 IR2. */
out_byte(INT_M_CTLMASK, 0x1); /* Master 8259, ICW4. */
out_byte(INT_S_CTLMASK, 0x1); /* Slave 8259, ICW4. */
out_byte(INT_M_CTLMASK, 0xFF); /* Master 8259, OCW1. */
out_byte(INT_S_CTLMASK, 0xFF); /* Slave 8259, OCW1. */
int i;
for (i = 0; i < NR_IRQ; i++) {
irq_table[i] = spurious_irq;
}
}
/*======================================================================*
spurious_irq
*======================================================================*/
PUBLIC void spurious_irq(int irq)
{
disp_str("spurious_irq: ");
disp_int(irq);
disp_str("\n");
}
/*======================================================================*
put_irq_handler
*======================================================================*/
PUBLIC void put_irq_handler(int irq, irq_handler handler)
{
disable_irq(irq);
irq_table[irq] = handler;
}
| RongbinZhuang/simpleOS | ver0/reference/chapter9/j/kernel/i8259.c | C | mit | 2,131 |
#productscategory_list .product-name {
margin-bottom: 5px; }
#productscategory_list .product-name a {
font-size: 15px;
line-height: 18px;
color: #3a3939; }
#productscategory_list .product-name a:hover {
color: #515151; }
#productscategory_list .exclusive span {
font-size: 13px;
line-height: 18px;
padding: 2px 8px 3px;
text-decoration: none; }
#productscategory_list .exclusive span:focus, #productscategory_list .exclusive span:active {
text-decoration: none; }
/*# sourceMappingURL=productscategory.css.map */
| fernandaos12/ateliebambolina | themes/thema-bambolina/css/modules/productscategory/css/productscategory.css | CSS | gpl-2.0 | 554 |
// { dg-require-namedlocale "en_US" }
// { dg-require-namedlocale "is_IS" }
// { dg-require-namedlocale "de_DE" }
// 2001-01-17 Benjamin Kosnik <[email protected]>
// Copyright (C) 2001-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 22.2.3.1.1 nunpunct members
#include <locale>
#include <testsuite_hooks.h>
void test02()
{
using namespace std;
bool test __attribute__((unused)) = true;
// basic construction
locale loc_c = locale::classic();
locale loc_us = locale("en_US");
locale loc_is = locale("is_IS");
locale loc_de = locale("de_DE");
VERIFY( loc_c != loc_de );
VERIFY( loc_us != loc_is );
VERIFY( loc_us != loc_de );
VERIFY( loc_de != loc_is );
// cache the numpunct facets
const numpunct<wchar_t>& nump_c = use_facet<numpunct<wchar_t> >(loc_c);
const numpunct<wchar_t>& nump_us = use_facet<numpunct<wchar_t> >(loc_us);
const numpunct<wchar_t>& nump_is = use_facet<numpunct<wchar_t> >(loc_is);
const numpunct<wchar_t>& nump_de = use_facet<numpunct<wchar_t> >(loc_de);
// sanity check the data is correct.
string g1 = nump_c.grouping();
wstring t1 = nump_c.truename();
wstring f1 = nump_c.falsename();
wchar_t dp2 = nump_us.decimal_point();
wchar_t th2 = nump_us.thousands_sep();
string g2 = nump_us.grouping();
wstring t2 = nump_us.truename();
wstring f2 = nump_us.falsename();
wchar_t dp3 = nump_is.decimal_point();
wchar_t th3 = nump_is.thousands_sep();
string g3 = nump_is.grouping();
wstring t3 = nump_is.truename();
wstring f3 = nump_is.falsename();
wchar_t dp4 = nump_de.decimal_point();
wchar_t th4 = nump_de.thousands_sep();
string g4 = nump_de.grouping();
wstring t4 = nump_de.truename();
wstring f4 = nump_de.falsename();
VERIFY( dp2 != dp3 );
VERIFY( th2 != th3 );
VERIFY( dp2 != dp4 );
VERIFY( th2 != th4 );
// XXX This isn't actually supported right now.
// VERIFY( t2 != t3 );
// VERIFY( f2 != f3 );
}
int main()
{
test02();
return 0;
}
| jagleeso/gcc | libstdc++-v3/testsuite/22_locale/numpunct/members/wchar_t/2.cc | C++ | gpl-2.0 | 2,664 |
module.exports = {
FUNCTION_BODY: 'functionBody',
FUNCTION_DECLARATION: 'functionDeclaration',
PARAMS: 'params',
PROGRAM: 'program',
SPACE: 'space',
TEXT: 'text'
};
| markredballoon/clivemizen | wp-content/themes/redballoon/bootstrap/node_modules/grunt-csscomb/node_modules/csscomb/node_modules/gonzales-pe/lib/js/node-types.js | JavaScript | gpl-2.0 | 189 |
import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types";
export const definition: IconDefinition;
export const faArrowAltCircleRight: IconDefinition;
export const prefix: IconPrefix;
export const iconName: IconName;
export const width: number;
export const height: number;
export const ligatures: string[];
export const unicode: string;
export const svgPathData: string; | taudinpurkauspeli/taudinpurkauspeli | vendor/assets/bower_components/font-awesome/js-packages/@fortawesome/free-solid-svg-icons/faArrowAltCircleRight.d.ts | TypeScript | gpl-3.0 | 407 |
/* { dg-do compile } */
/* { dg-options "-O2 -fdump-tree-lim2-details" } */
int x; int y;
struct { int x; int y; } global;
int foo() {
int i;
for ( i=0; i<10; i++)
y += x*x;
for ( i=0; i<10; i++)
global.y += global.x*global.x;
}
/* { dg-final { scan-tree-dump-times "Executing store motion of global.y" 1 "lim2" } } */
/* XXX: We should also check for the load motion of global.x, but there is no easy way to do this. */
| selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/gcc.dg/tree-ssa/structopt-1.c | C | gpl-3.0 | 430 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/render_messages.h"
#include "chrome/common/content_settings_pattern_serializer.h"
namespace IPC {
void ParamTraits<ContentSettingsPattern>::Write(
Message* m, const ContentSettingsPattern& pattern) {
ContentSettingsPatternSerializer::WriteToMessage(pattern, m);
}
bool ParamTraits<ContentSettingsPattern>::Read(
const Message* m, PickleIterator* iter, ContentSettingsPattern* pattern) {
return ContentSettingsPatternSerializer::ReadFromMessage(m, iter, pattern);
}
void ParamTraits<ContentSettingsPattern>::Log(
const ContentSettingsPattern& p, std::string* l) {
l->append("<ContentSettingsPattern: ");
l->append(p.ToString());
l->append(">");
}
} // namespace IPC
| s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/common/render_messages.cc | C++ | gpl-3.0 | 888 |
//
// daemon.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <ctime>
#include <iostream>
#include <syslog.h>
#include <unistd.h>
using boost::asio::ip::udp;
class udp_daytime_server
{
public:
udp_daytime_server(boost::asio::io_service& io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_daytime_server::handle_receive, this, _1));
}
void handle_receive(const boost::system::error_code& ec)
{
if (!ec || ec == boost::asio::error::message_size)
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
std::string message = ctime(&now);
boost::system::error_code ignored_ec;
socket_.send_to(boost::asio::buffer(message),
remote_endpoint_, 0, ignored_ec);
}
start_receive();
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array<char, 1> recv_buffer_;
};
int main()
{
try
{
boost::asio::io_service io_service;
// Initialise the server before becoming a daemon. If the process is
// started from a shell, this means any errors will be reported back to the
// user.
udp_daytime_server server(io_service);
// Register signal handlers so that the daemon may be shut down. You may
// also want to register for other signals, such as SIGHUP to trigger a
// re-read of a configuration file.
boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
signals.async_wait(
boost::bind(&boost::asio::io_service::stop, &io_service));
// Inform the io_service that we are about to become a daemon. The
// io_service cleans up any internal resources, such as threads, that may
// interfere with forking.
io_service.notify_fork(boost::asio::io_service::fork_prepare);
// Fork the process and have the parent exit. If the process was started
// from a shell, this returns control to the user. Forking a new process is
// also a prerequisite for the subsequent call to setsid().
if (pid_t pid = fork())
{
if (pid > 0)
{
// We're in the parent process and need to exit.
//
// When the exit() function is used, the program terminates without
// invoking local variables' destructors. Only global variables are
// destroyed. As the io_service object is a local variable, this means
// we do not have to call:
//
// io_service.notify_fork(boost::asio::io_service::fork_parent);
//
// However, this line should be added before each call to exit() if
// using a global io_service object. An additional call:
//
// io_service.notify_fork(boost::asio::io_service::fork_prepare);
//
// should also precede the second fork().
exit(0);
}
else
{
syslog(LOG_ERR | LOG_USER, "First fork failed: %m");
return 1;
}
}
// Make the process a new session leader. This detaches it from the
// terminal.
setsid();
// A process inherits its working directory from its parent. This could be
// on a mounted filesystem, which means that the running daemon would
// prevent this filesystem from being unmounted. Changing to the root
// directory avoids this problem.
chdir("/");
// The file mode creation mask is also inherited from the parent process.
// We don't want to restrict the permissions on files created by the
// daemon, so the mask is cleared.
umask(0);
// A second fork ensures the process cannot acquire a controlling terminal.
if (pid_t pid = fork())
{
if (pid > 0)
{
exit(0);
}
else
{
syslog(LOG_ERR | LOG_USER, "Second fork failed: %m");
return 1;
}
}
// Close the standard streams. This decouples the daemon from the terminal
// that started it.
close(0);
close(1);
close(2);
// We don't want the daemon to have any standard input.
if (open("/dev/null", O_RDONLY) < 0)
{
syslog(LOG_ERR | LOG_USER, "Unable to open /dev/null: %m");
return 1;
}
// Send standard output to a log file.
const char* output = "/tmp/asio.daemon.out";
const int flags = O_WRONLY | O_CREAT | O_APPEND;
const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
if (open(output, flags, mode) < 0)
{
syslog(LOG_ERR | LOG_USER, "Unable to open output file %s: %m", output);
return 1;
}
// Also send standard error to the same log file.
if (dup(1) < 0)
{
syslog(LOG_ERR | LOG_USER, "Unable to dup output descriptor: %m");
return 1;
}
// Inform the io_service that we have finished becoming a daemon. The
// io_service uses this opportunity to create any internal file descriptors
// that need to be private to the new process.
io_service.notify_fork(boost::asio::io_service::fork_child);
// The io_service can now be used normally.
syslog(LOG_INFO | LOG_USER, "Daemon started");
io_service.run();
syslog(LOG_INFO | LOG_USER, "Daemon stopped");
}
catch (std::exception& e)
{
syslog(LOG_ERR | LOG_USER, "Exception: %s", e.what());
std::cerr << "Exception: " << e.what() << std::endl;
}
}
| gwq5210/litlib | thirdparty/sources/boost_1_60_0/libs/asio/example/cpp03/fork/daemon.cpp | C++ | gpl-3.0 | 5,804 |
@import Foundation;
typedef NSString MyString __attribute__((swift_wrapper(struct)));
extern MyString * const MyStringOne;
| apple/swift | test/ClangImporter/Inputs/bad-ns-extensible-string-enum.h | C | apache-2.0 | 124 |
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.67
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// Low-level file input and output for OpenEXR
// based on C++ standard iostreams.
//
//-----------------------------------------------------------------------------
#include <ImfStdIO.h>
#include "Iex.h"
#include <errno.h>
using namespace std;
#include "ImfNamespace.h"
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
namespace {
void
clearError ()
{
errno = 0;
}
bool
checkError (istream &is, streamsize expected = 0)
{
if (!is)
{
if (errno)
IEX_NAMESPACE::throwErrnoExc();
if (is.gcount() < expected)
{
THROW (IEX_NAMESPACE::InputExc, "Early end of file: read " << is.gcount()
<< " out of " << expected << " requested bytes.");
}
return false;
}
return true;
}
void
checkError (ostream &os)
{
if (!os)
{
if (errno)
IEX_NAMESPACE::throwErrnoExc();
throw IEX_NAMESPACE::ErrnoExc ("File output failed.");
}
}
} // namespace
StdIFStream::StdIFStream (const char fileName[]):
OPENEXR_IMF_INTERNAL_NAMESPACE::IStream (fileName),
_is (new ifstream (fileName, ios_base::binary)),
_deleteStream (true)
{
if (!*_is)
{
delete _is;
IEX_NAMESPACE::throwErrnoExc();
}
}
StdIFStream::StdIFStream (ifstream &is, const char fileName[]):
OPENEXR_IMF_INTERNAL_NAMESPACE::IStream (fileName),
_is (&is),
_deleteStream (false)
{
// empty
}
StdIFStream::~StdIFStream ()
{
if (_deleteStream)
delete _is;
}
bool
StdIFStream::read (char c[/*n*/], int n)
{
if (!*_is)
throw IEX_NAMESPACE::InputExc ("Unexpected end of file.");
clearError();
_is->read (c, n);
return checkError (*_is, n);
}
Int64
StdIFStream::tellg ()
{
return std::streamoff (_is->tellg());
}
void
StdIFStream::seekg (Int64 pos)
{
_is->seekg (pos);
checkError (*_is);
}
void
StdIFStream::clear ()
{
_is->clear();
}
StdOFStream::StdOFStream (const char fileName[]):
OPENEXR_IMF_INTERNAL_NAMESPACE::OStream (fileName),
_os (new ofstream (fileName, ios_base::binary)),
_deleteStream (true)
{
if (!*_os)
{
delete _os;
IEX_NAMESPACE::throwErrnoExc();
}
}
StdOFStream::StdOFStream (ofstream &os, const char fileName[]):
OPENEXR_IMF_INTERNAL_NAMESPACE::OStream (fileName),
_os (&os),
_deleteStream (false)
{
// empty
}
StdOFStream::~StdOFStream ()
{
if (_deleteStream)
delete _os;
}
void
StdOFStream::write (const char c[/*n*/], int n)
{
clearError();
_os->write (c, n);
checkError (*_os);
}
Int64
StdOFStream::tellp ()
{
return std::streamoff (_os->tellp());
}
void
StdOFStream::seekp (Int64 pos)
{
_os->seekp (pos);
checkError (*_os);
}
StdOSStream::StdOSStream (): OPENEXR_IMF_INTERNAL_NAMESPACE::OStream ("(string)")
{
// empty
}
void
StdOSStream::write (const char c[/*n*/], int n)
{
clearError();
_os.write (c, n);
checkError (_os);
}
Int64
StdOSStream::tellp ()
{
return std::streamoff (_os.tellp());
}
void
StdOSStream::seekp (Int64 pos)
{
_os.seekp (pos);
checkError (_os);
}
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
| Ghosttje/VSMegaSDK | third_party/freeimage/Source/OpenEXR/IlmImf/ImfStdIO.cpp | C++ | bsd-2-clause | 4,938 |
#include <string.h>
#include <stdlib.h>
#include "msvcint.h"
#include "lua.h"
#include "lauxlib.h"
#include "sproto.h"
#define MAX_GLOBALSPROTO 16
#define ENCODE_BUFFERSIZE 2050
#define ENCODE_MAXSIZE 0x1000000
#define ENCODE_DEEPLEVEL 64
#ifndef luaL_newlib /* using LuaJIT */
/*
** set functions from list 'l' into table at top - 'nup'; each
** function gets the 'nup' elements at the top as upvalues.
** Returns with only the table at the stack.
*/
LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
#ifdef luaL_checkversion
luaL_checkversion(L);
#endif
luaL_checkstack(L, nup, "too many upvalues");
for (; l->name != NULL; l++) { /* fill the table with given functions */
int i;
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -nup);
lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
lua_setfield(L, -(nup + 2), l->name);
}
lua_pop(L, nup); /* remove upvalues */
}
#define luaL_newlibtable(L,l) \
lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)
#define luaL_newlib(L,l) (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
#endif
#if LUA_VERSION_NUM < 503
// lua_isinteger is lua 5.3 api
#define lua_isinteger lua_isnumber
// work around , use push & lua_gettable may be better
#define lua_geti lua_rawgeti
#define lua_seti lua_rawseti
#endif
static int
lnewproto(lua_State *L) {
struct sproto * sp;
size_t sz;
void * buffer = (void *)luaL_checklstring(L,1,&sz);
sp = sproto_create(buffer, sz);
if (sp) {
lua_pushlightuserdata(L, sp);
return 1;
}
return 0;
}
static int
ldeleteproto(lua_State *L) {
struct sproto * sp = lua_touserdata(L,1);
if (sp == NULL) {
return luaL_argerror(L, 1, "Need a sproto object");
}
sproto_release(sp);
return 0;
}
static int
lquerytype(lua_State *L) {
const char * type_name;
struct sproto *sp = lua_touserdata(L,1);
struct sproto_type *st;
if (sp == NULL) {
return luaL_argerror(L, 1, "Need a sproto object");
}
type_name = luaL_checkstring(L,2);
st = sproto_type(sp, type_name);
if (st) {
lua_pushlightuserdata(L, st);
return 1;
}
return luaL_error(L, "type %s not found", type_name);
}
struct encode_ud {
lua_State *L;
struct sproto_type *st;
int tbl_index;
const char * array_tag;
int array_index;
int deep;
int iter_index;
};
static int
encode(const struct sproto_arg *args) {
struct encode_ud *self = args->ud;
lua_State *L = self->L;
if (self->deep >= ENCODE_DEEPLEVEL)
return luaL_error(L, "The table is too deep");
if (args->index > 0) {
if (args->tagname != self->array_tag) {
// a new array
self->array_tag = args->tagname;
lua_getfield(L, self->tbl_index, args->tagname);
if (lua_isnil(L, -1)) {
if (self->array_index) {
lua_replace(L, self->array_index);
}
self->array_index = 0;
return 0;
}
if (!lua_istable(L, -1)) {
return luaL_error(L, ".*%s(%d) should be a table (Is a %s)",
args->tagname, args->index, lua_typename(L, lua_type(L, -1)));
}
if (self->array_index) {
lua_replace(L, self->array_index);
} else {
self->array_index = lua_gettop(L);
}
}
if (args->mainindex >= 0) {
// use lua_next to iterate the table
// todo: check the key is equal to mainindex value
lua_pushvalue(L,self->iter_index);
if (!lua_next(L, self->array_index)) {
// iterate end
lua_pushnil(L);
lua_replace(L, self->iter_index);
return 0;
}
lua_insert(L, -2);
lua_replace(L, self->iter_index);
} else {
lua_geti(L, self->array_index, args->index);
}
} else {
lua_getfield(L, self->tbl_index, args->tagname);
}
if (lua_isnil(L, -1)) {
lua_pop(L,1);
return 0;
}
switch (args->type) {
case SPROTO_TINTEGER: {
lua_Integer v;
lua_Integer vh;
if (!lua_isinteger(L, -1)) {
return luaL_error(L, ".%s[%d] is not an integer (Is a %s)",
args->tagname, args->index, lua_typename(L, lua_type(L, -1)));
} else {
v = lua_tointeger(L, -1);
}
lua_pop(L,1);
// notice: in lua 5.2, lua_Integer maybe 52bit
vh = v >> 31;
if (vh == 0 || vh == -1) {
*(uint32_t *)args->value = (uint32_t)v;
return 4;
}
else {
*(uint64_t *)args->value = (uint64_t)v;
return 8;
}
}
case SPROTO_TBOOLEAN: {
int v = lua_toboolean(L, -1);
if (!lua_isboolean(L,-1)) {
return luaL_error(L, ".%s[%d] is not a boolean (Is a %s)",
args->tagname, args->index, lua_typename(L, lua_type(L, -1)));
}
*(int *)args->value = v;
lua_pop(L,1);
return 4;
}
case SPROTO_TSTRING: {
size_t sz = 0;
const char * str;
if (!lua_isstring(L, -1)) {
return luaL_error(L, ".%s[%d] is not a string (Is a %s)",
args->tagname, args->index, lua_typename(L, lua_type(L, -1)));
} else {
str = lua_tolstring(L, -1, &sz);
}
if (sz > args->length)
return -1;
memcpy(args->value, str, sz);
lua_pop(L,1);
return sz + 1; // The length of empty string is 1.
}
case SPROTO_TSTRUCT: {
struct encode_ud sub;
int r;
int top = lua_gettop(L);
if (!lua_istable(L, top)) {
return luaL_error(L, ".%s[%d] is not a table (Is a %s)",
args->tagname, args->index, lua_typename(L, lua_type(L, -1)));
}
sub.L = L;
sub.st = args->subtype;
sub.tbl_index = top;
sub.array_tag = NULL;
sub.array_index = 0;
sub.deep = self->deep + 1;
lua_pushnil(L); // prepare an iterator slot
sub.iter_index = sub.tbl_index + 1;
r = sproto_encode(args->subtype, args->value, args->length, encode, &sub);
lua_settop(L, top-1); // pop the value
return r;
}
default:
return luaL_error(L, "Invalid field type %d", args->type);
}
}
static void *
expand_buffer(lua_State *L, int osz, int nsz) {
void *output;
do {
osz *= 2;
} while (osz < nsz);
if (osz > ENCODE_MAXSIZE) {
luaL_error(L, "object is too large (>%d)", ENCODE_MAXSIZE);
return NULL;
}
output = lua_newuserdata(L, osz);
lua_replace(L, lua_upvalueindex(1));
lua_pushinteger(L, osz);
lua_replace(L, lua_upvalueindex(2));
return output;
}
/*
lightuserdata sproto_type
table source
return string
*/
static int
lencode(lua_State *L) {
struct encode_ud self;
void * buffer = lua_touserdata(L, lua_upvalueindex(1));
int sz = lua_tointeger(L, lua_upvalueindex(2));
int tbl_index = 2;
struct sproto_type * st = lua_touserdata(L, 1);
if (st == NULL) {
return luaL_argerror(L, 1, "Need a sproto_type object");
}
luaL_checktype(L, tbl_index, LUA_TTABLE);
luaL_checkstack(L, ENCODE_DEEPLEVEL*2 + 8, NULL);
self.L = L;
self.st = st;
self.tbl_index = tbl_index;
for (;;) {
int r;
self.array_tag = NULL;
self.array_index = 0;
self.deep = 0;
lua_settop(L, tbl_index);
lua_pushnil(L); // for iterator (stack slot 3)
self.iter_index = tbl_index+1;
r = sproto_encode(st, buffer, sz, encode, &self);
if (r<0) {
buffer = expand_buffer(L, sz, sz*2);
sz *= 2;
} else {
lua_pushlstring(L, buffer, r);
return 1;
}
}
}
struct decode_ud {
lua_State *L;
const char * array_tag;
int array_index;
int result_index;
int deep;
int mainindex_tag;
int key_index;
};
static int
decode(const struct sproto_arg *args) {
struct decode_ud * self = args->ud;
lua_State *L = self->L;
if (self->deep >= ENCODE_DEEPLEVEL)
return luaL_error(L, "The table is too deep");
if (args->index > 0) {
// It's array
if (args->tagname != self->array_tag) {
self->array_tag = args->tagname;
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setfield(L, self->result_index, args->tagname);
if (self->array_index) {
lua_replace(L, self->array_index);
} else {
self->array_index = lua_gettop(L);
}
}
}
switch (args->type) {
case SPROTO_TINTEGER: {
// notice: in lua 5.2, 52bit integer support (not 64)
lua_Integer v = *(uint64_t*)args->value;
lua_pushinteger(L, v);
break;
}
case SPROTO_TBOOLEAN: {
int v = *(uint64_t*)args->value;
lua_pushboolean(L,v);
break;
}
case SPROTO_TSTRING: {
lua_pushlstring(L, args->value, args->length);
break;
}
case SPROTO_TSTRUCT: {
struct decode_ud sub;
int r;
lua_newtable(L);
sub.L = L;
sub.result_index = lua_gettop(L);
sub.deep = self->deep + 1;
sub.array_index = 0;
sub.array_tag = NULL;
if (args->mainindex >= 0) {
// This struct will set into a map, so mark the main index tag.
sub.mainindex_tag = args->mainindex;
lua_pushnil(L);
sub.key_index = lua_gettop(L);
r = sproto_decode(args->subtype, args->value, args->length, decode, &sub);
if (r < 0 || r != args->length)
return r;
// assert(args->index > 0);
lua_pushvalue(L, sub.key_index);
if (lua_isnil(L, -1)) {
luaL_error(L, "Can't find main index (tag=%d) in [%s]", args->mainindex, args->tagname);
}
lua_pushvalue(L, sub.result_index);
lua_settable(L, self->array_index);
lua_settop(L, sub.result_index-1);
return 0;
} else {
sub.mainindex_tag = -1;
sub.key_index = 0;
r = sproto_decode(args->subtype, args->value, args->length, decode, &sub);
if (r < 0 || r != args->length)
return r;
lua_settop(L, sub.result_index);
break;
}
}
default:
luaL_error(L, "Invalid type");
}
if (args->index > 0) {
lua_seti(L, self->array_index, args->index);
} else {
if (self->mainindex_tag == args->tagid) {
// This tag is marked, save the value to key_index
// assert(self->key_index > 0);
lua_pushvalue(L,-1);
lua_replace(L, self->key_index);
}
lua_setfield(L, self->result_index, args->tagname);
}
return 0;
}
static const void *
getbuffer(lua_State *L, int index, size_t *sz) {
const void * buffer = NULL;
int t = lua_type(L, index);
if (t == LUA_TSTRING) {
buffer = lua_tolstring(L, index, sz);
} else {
if (t != LUA_TUSERDATA && t != LUA_TLIGHTUSERDATA) {
luaL_argerror(L, index, "Need a string or userdata");
return NULL;
}
buffer = lua_touserdata(L, index);
*sz = luaL_checkinteger(L, index+1);
}
return buffer;
}
/*
lightuserdata sproto_type
string source / (lightuserdata , integer)
return table
*/
static int
ldecode(lua_State *L) {
struct sproto_type * st = lua_touserdata(L, 1);
const void * buffer;
struct decode_ud self;
size_t sz;
int r;
if (st == NULL) {
return luaL_argerror(L, 1, "Need a sproto_type object");
}
sz = 0;
buffer = getbuffer(L, 2, &sz);
if (!lua_istable(L, -1)) {
lua_newtable(L);
}
luaL_checkstack(L, ENCODE_DEEPLEVEL*3 + 8, NULL);
self.L = L;
self.result_index = lua_gettop(L);
self.array_index = 0;
self.array_tag = NULL;
self.deep = 0;
self.mainindex_tag = -1;
self.key_index = 0;
r = sproto_decode(st, buffer, (int)sz, decode, &self);
if (r < 0) {
return luaL_error(L, "decode error");
}
lua_settop(L, self.result_index);
lua_pushinteger(L, r);
return 2;
}
static int
ldumpproto(lua_State *L) {
struct sproto * sp = lua_touserdata(L, 1);
if (sp == NULL) {
return luaL_argerror(L, 1, "Need a sproto_type object");
}
sproto_dump(sp);
return 0;
}
/*
string source / (lightuserdata , integer)
return string
*/
static int
lpack(lua_State *L) {
size_t sz=0;
const void * buffer = getbuffer(L, 1, &sz);
// the worst-case space overhead of packing is 2 bytes per 2 KiB of input (256 words = 2KiB).
size_t maxsz = (sz + 2047) / 2048 * 2 + sz;
void * output = lua_touserdata(L, lua_upvalueindex(1));
int bytes;
int osz = lua_tointeger(L, lua_upvalueindex(2));
if (osz < maxsz) {
output = expand_buffer(L, osz, maxsz);
}
bytes = sproto_pack(buffer, sz, output, maxsz);
if (bytes > maxsz) {
return luaL_error(L, "packing error, return size = %d", bytes);
}
lua_pushlstring(L, output, bytes);
return 1;
}
static int
lunpack(lua_State *L) {
size_t sz=0;
const void * buffer = getbuffer(L, 1, &sz);
void * output = lua_touserdata(L, lua_upvalueindex(1));
int osz = lua_tointeger(L, lua_upvalueindex(2));
int r = sproto_unpack(buffer, sz, output, osz);
if (r < 0)
return luaL_error(L, "Invalid unpack stream");
if (r > osz) {
output = expand_buffer(L, osz, r);
r = sproto_unpack(buffer, sz, output, r);
if (r < 0)
return luaL_error(L, "Invalid unpack stream");
}
lua_pushlstring(L, output, r);
return 1;
}
static void
pushfunction_withbuffer(lua_State *L, const char * name, lua_CFunction func) {
lua_newuserdata(L, ENCODE_BUFFERSIZE);
lua_pushinteger(L, ENCODE_BUFFERSIZE);
lua_pushcclosure(L, func, 2);
lua_setfield(L, -2, name);
}
static int
lprotocol(lua_State *L) {
struct sproto * sp = lua_touserdata(L, 1);
struct sproto_type * request;
struct sproto_type * response;
int t;
int tag;
if (sp == NULL) {
return luaL_argerror(L, 1, "Need a sproto_type object");
}
t = lua_type(L,2);
if (t == LUA_TNUMBER) {
const char * name;
tag = lua_tointeger(L, 2);
name = sproto_protoname(sp, tag);
if (name == NULL)
return 0;
lua_pushstring(L, name);
} else {
const char * name = lua_tostring(L, 2);
tag = sproto_prototag(sp, name);
if (tag < 0)
return 0;
lua_pushinteger(L, tag);
}
request = sproto_protoquery(sp, tag, SPROTO_REQUEST);
if (request == NULL) {
lua_pushnil(L);
} else {
lua_pushlightuserdata(L, request);
}
response = sproto_protoquery(sp, tag, SPROTO_RESPONSE);
if (response == NULL) {
lua_pushnil(L);
} else {
lua_pushlightuserdata(L, response);
}
return 3;
}
/* global sproto pointer for multi states
NOTICE : It is not thread safe
*/
static struct sproto * G_sproto[MAX_GLOBALSPROTO];
static int
lsaveproto(lua_State *L) {
struct sproto * sp = lua_touserdata(L, 1);
int index = luaL_optinteger(L, 2, 0);
if (index < 0 || index >= MAX_GLOBALSPROTO) {
return luaL_error(L, "Invalid global slot index %d", index);
}
/* TODO : release old object (memory leak now, but thread safe)*/
G_sproto[index] = sp;
return 0;
}
static int
lloadproto(lua_State *L) {
int index = luaL_optinteger(L, 1, 0);
struct sproto * sp;
if (index < 0 || index >= MAX_GLOBALSPROTO) {
return luaL_error(L, "Invalid global slot index %d", index);
}
sp = G_sproto[index];
if (sp == NULL) {
return luaL_error(L, "nil sproto at index %d", index);
}
lua_pushlightuserdata(L, sp);
return 1;
}
static int
encode_default(const struct sproto_arg *args) {
lua_State *L = args->ud;
lua_pushstring(L, args->tagname);
if (args->index > 0) {
lua_newtable(L);
} else {
switch(args->type) {
case SPROTO_TINTEGER:
lua_pushinteger(L, 0);
break;
case SPROTO_TBOOLEAN:
lua_pushboolean(L, 0);
break;
case SPROTO_TSTRING:
lua_pushliteral(L, "");
break;
case SPROTO_TSTRUCT:
lua_createtable(L, 0, 1);
lua_pushstring(L, sproto_name(args->subtype));
lua_setfield(L, -2, "__type");
break;
}
}
lua_rawset(L, -3);
return 0;
}
/*
lightuserdata sproto_type
return default table
*/
static int
ldefault(lua_State *L) {
int ret;
// 64 is always enough for dummy buffer, except the type has many fields ( > 27).
char dummy[64];
struct sproto_type * st = lua_touserdata(L, 1);
if (st == NULL) {
return luaL_argerror(L, 1, "Need a sproto_type object");
}
lua_newtable(L);
ret = sproto_encode(st, dummy, sizeof(dummy), encode_default, L);
if (ret<0) {
// try again
int sz = sizeof(dummy) * 2;
void * tmp = lua_newuserdata(L, sz);
lua_insert(L, -2);
for (;;) {
ret = sproto_encode(st, tmp, sz, encode_default, L);
if (ret >= 0)
break;
sz *= 2;
tmp = lua_newuserdata(L, sz);
lua_replace(L, -3);
}
}
return 1;
}
int
luaopen_sproto_core(lua_State *L) {
#ifdef luaL_checkversion
luaL_checkversion(L);
#endif
luaL_Reg l[] = {
{ "newproto", lnewproto },
{ "deleteproto", ldeleteproto },
{ "dumpproto", ldumpproto },
{ "querytype", lquerytype },
{ "decode", ldecode },
{ "protocol", lprotocol },
{ "loadproto", lloadproto },
{ "saveproto", lsaveproto },
{ "default", ldefault },
{ NULL, NULL },
};
luaL_newlib(L,l);
pushfunction_withbuffer(L, "encode", lencode);
pushfunction_withbuffer(L, "pack", lpack);
pushfunction_withbuffer(L, "unpack", lunpack);
return 1;
}
| kebo/skynet | lualib-src/sproto/lsproto.c | C | mit | 15,847 |
<?php
/**
* Part of the Fuel framework.
*
* @package Fuel
* @version 1.7
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2014 Fuel Development Team
* @link http://fuelphp.com
*/
namespace Fuel\Core;
abstract class Cache_Storage_Driver
{
/**
* @var array defines which class properties are gettable with get_... in the __call() method
*/
protected static $_gettable = array('created', 'expiration', 'dependencies', 'identifier');
/**
* @var array defines which class properties are settable with set_... in the __call() method
*/
protected static $_settable = array('expiration', 'dependencies', 'identifier');
/**
* @var string name of the content handler driver
*/
protected $content_handler = null;
/**
* @var Cache_Handler_Driver handles and formats the cache's contents
*/
protected $handler_object = null;
/**
* @var string the cache's name, either string or md5'd serialization of something else
*/
protected $identifier = null;
/**
* @var int timestamp of creation of the cache
*/
protected $created = null;
/**
* @var int timestamp when this cache will expire
*/
protected $expiration = null;
/**
* @var array contains identifiers of other caches this one depends on
*/
protected $dependencies = array();
/**
* @var mixed the contents of this
*/
protected $contents = null;
/**
* @var string loaded driver
*/
protected $driver = null;
/**
* Abstract method that should take care of the storage engine specific reading. Needs to set the object properties:
* - created
* - expiration
* - dependencies
* - contents
* - content_handler
*
* @return bool success of the operation
*/
abstract protected function _get();
/**
* Abstract method that should take care of the storage engine specific writing. Needs to write the object properties:
* - created
* - expiration
* - dependencies
* - contents
* - content_handler
*/
abstract protected function _set();
/**
* Should delete this cache instance, should also run reset() afterwards
*/
abstract public function delete();
/**
* Flushes the whole cache for a specific storage type or just a part of it when $section is set
* (might not work with all storage drivers), defaults to the default storage type
*
* @param string
*/
abstract public function delete_all($section);
/**
* Should check all dependencies against the creation timestamp.
* This is static to make it possible in the future to check dependencies from other storages then the current one,
* though I don't have a clue yet how to make that possible.
*
* @return bool either true or false on any failure
*/
abstract public function check_dependencies(array $dependencies);
/**
* Default constructor, any extension should either load this first or act similar
*
* @param string the identifier for this cache
* @param array additional config values
*/
public function __construct($identifier, $config)
{
$this->identifier = $identifier;
// fetch options from config and set them
$this->expiration = array_key_exists('expiration', $config) ? $config['expiration'] : \Config::get('cache.expiration', null);
$this->dependencies = array_key_exists('dependencies', $config) ? $config['dependencies'] : array();
$this->content_handler = array_key_exists('content_handler', $config) ? new $config['content_handler']() : null;
$this->driver = array_key_exists('driver', $config) ? $config['driver'] : 'file';
}
/**
* Allows for default getting and setting
*
* @param string
* @param array
* @return void|mixed
*/
public function __call($method, $args = array())
{
// Allow getting any properties set in static::$_gettable
if (substr($method, 0, 3) == 'get')
{
$name = substr($method, 4);
if (in_array($name, static::$_gettable))
{
return $this->{$name};
}
else
{
throw new \BadMethodCallException('This property doesn\'t exist or can\'t be read.');
}
}
// Allow setting any properties set in static::$_settable
elseif (substr($method, 0, 3) == 'set')
{
$name = substr($method, 4);
if (in_array($name, static::$_settable))
{
$this->{$name} = @$args[0];
}
else
{
throw new \BadMethodCallException('This property doesn\'t exist or can\'t be set.');
}
return $this;
}
else
{
throw new \BadMethodCallException('Illegal method call: ' . $method);
}
}
/**
* Converts the identifier to a string when necessary:
* A int is just converted to a string, all others are serialized and then md5'd
*
* @param mixed
* @return string
*/
public static function stringify_identifier($identifier)
{
// Identifier may not be empty, but can be false or 0
if ($identifier === '' || $identifier === null)
{
throw new \FuelException('The identifier cannot be empty, must contain a value of any kind other than null or an empty string.');
}
// In case of string or int just return it as a string
if (is_string($identifier) || is_int($identifier))
{
// cleanup to only allow alphanum chars, dashes, dots & underscores
if (preg_match('/^([a-z0-9_\.\-]*)$/iuD', $identifier) === 0)
{
throw new \FuelException('Cache identifier can only contain alphanumeric characters, underscores, dashes & dots.');
}
return (string) $identifier;
}
// In case of array, bool or object return the md5 of the $identifier's serialization
else
{
return '_hashes.'.md5(serialize($identifier));
}
}
/**
* Resets all properties except for the identifier, should be run by default when a delete() is triggered
*/
public function reset()
{
$this->contents = null;
$this->created = null;
$this->expiration = null;
$this->dependencies = array();
$this->content_handler = null;
$this->handler_object = null;
}
/**
* Front for writing the cache, ensures interchangeability of storage engines. Actual writing
* is being done by the _set() method which needs to be extended.
*
* @param mixed The content to be cached
* @param int The time in seconds until the cache will expire, =< 0 or null means no expiration
* @param array array of names on which this cache depends for
* @return Cache_Storage_Driver The new request
*/
final public function set($contents = null, $expiration = false, $dependencies = array())
{
$contents = \Fuel::value($contents);
// save the current expiration
$current_expiration = $this->expiration;
// Use either the given value or the class property
if ( ! is_null($contents)) $this->set_contents($contents);
$this->expiration = ($expiration !== false) ? $expiration : $this->expiration;
$this->dependencies = ( ! empty($dependencies)) ? $dependencies : $this->dependencies;
$this->created = time();
// Create expiration timestamp when other then null
if ( ! is_null($this->expiration))
{
if ( ! is_numeric($this->expiration))
{
throw new \InvalidArgumentException('Expiration must be a valid number.');
}
$this->expiration = $this->created + intval($this->expiration);
}
// Convert dependency identifiers to string when set
$this->dependencies = ( ! is_array($this->dependencies)) ? array($this->dependencies) : $this->dependencies;
if ( ! empty( $this->dependencies ) )
{
foreach($this->dependencies as $key => $id)
{
$this->dependencies[$key] = $this->stringify_identifier($id);
}
}
// Turn everything over to the storage specific method
$this->_set();
// restore the expiration
$this->expiration = $current_expiration;
}
/**
* Front for reading the cache, ensures interchangeability of storage engines. Actual reading
* is being done by the _get() method which needs to be extended.
*
* @param bool
* @return Cache_Storage_Driver
*/
final public function get($use_expiration = true)
{
if ( ! $this->_get())
{
throw new \CacheNotFoundException('not found');
}
if ($use_expiration)
{
if ( ! is_null($this->expiration) and $this->expiration < 0)
{
$this->delete();
throw new \CacheExpiredException('expired');
}
// Check dependencies and handle as expired on failure
if ( ! $this->check_dependencies($this->dependencies))
{
$this->delete();
throw new \CacheExpiredException('expired');
}
}
return $this->get_contents();
}
/**
* Does get() & set() in one call that takes a callback and it's arguments to generate the contents
*
* @param string|array Valid PHP callback
* @param array Arguments for the above function/method
* @param int|null Cache expiration in seconds
* @param array Contains the identifiers of caches this one will depend on
* @return mixed
*/
final public function call($callback, $args = array(), $expiration = null, $dependencies = array())
{
try
{
$this->get();
}
catch (\CacheNotFoundException $e)
{
// Create the contents
$contents = call_fuel_func_array($callback, $args);
$this->set($contents, $expiration, $dependencies);
}
return $this->get_contents();
}
/**
* Set the contents with optional handler instead of the default
*
* @param mixed
* @param string
* @return Cache_Storage_Driver
*/
public function set_contents($contents, $handler = NULL)
{
$this->contents = $contents;
$this->set_content_handler($handler);
$this->contents = $this->handle_writing($contents);
return $this;
}
/**
* Fetches contents
*
* @return mixed
*/
public function get_contents()
{
return $this->handle_reading($this->contents);
}
/**
* Decides a content handler that makes it possible to write non-strings to a file
*
* @param string
* @return Cache_Storage_Driver
*/
protected function set_content_handler($handler)
{
$this->handler_object = null;
$this->content_handler = (string) $handler;
return $this;
}
/**
* Gets a specific content handler
*
* @param string
* @return Cache_Handler_Driver
*/
public function get_content_handler($handler = null)
{
if ( ! empty($this->handler_object))
{
return $this->handler_object;
}
// When not yet set, use $handler or detect the preferred handler (string = string, otherwise serialize)
if (empty($this->content_handler) && empty($handler))
{
if ( ! empty($handler))
{
$this->content_handler = $handler;
}
if (is_string($this->contents))
{
$this->content_handler = \Config::get('cache.string_handler', 'string');
}
else
{
$type = is_object($this->contents) ? get_class($this->contents) : gettype($this->contents);
$this->content_handler = \Config::get('cache.'.$type.'_handler', 'serialized');
}
}
$class = '\\Cache_Handler_'.ucfirst($this->content_handler);
$this->handler_object = new $class();
return $this->handler_object;
}
/**
* Converts the contents the cachable format
*
* @return string
*/
protected function handle_writing($contents)
{
return $this->get_content_handler()->writable($contents);
}
/**
* Converts the cachable format to the original value
*
* @return mixed
*/
protected function handle_reading($contents)
{
return $this->get_content_handler()->readable($contents);
}
}
| indigophp-archive/codeception-fuel-module | fuel/fuel/core/classes/cache/storage/driver.php | PHP | mit | 11,405 |
/**
******************************************************************************
* @file stm32f0xx_ll_rtc.h
* @author MCD Application Team
* @brief Header file of RTC LL module.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F0xx_LL_RTC_H
#define __STM32F0xx_LL_RTC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx.h"
/** @addtogroup STM32F0xx_LL_Driver
* @{
*/
#if defined(RTC)
/** @defgroup RTC_LL RTC
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup RTC_LL_Private_Constants RTC Private Constants
* @{
*/
/* Masks Definition */
#define RTC_INIT_MASK 0xFFFFFFFFU
#define RTC_RSF_MASK 0xFFFFFF5FU
/* Write protection defines */
#define RTC_WRITE_PROTECTION_DISABLE ((uint8_t)0xFFU)
#define RTC_WRITE_PROTECTION_ENABLE_1 ((uint8_t)0xCAU)
#define RTC_WRITE_PROTECTION_ENABLE_2 ((uint8_t)0x53U)
/* Defines used to combine date & time */
#define RTC_OFFSET_WEEKDAY 24U
#define RTC_OFFSET_DAY 16U
#define RTC_OFFSET_MONTH 8U
#define RTC_OFFSET_HOUR 16U
#define RTC_OFFSET_MINUTE 8U
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup RTC_LL_Private_Macros RTC Private Macros
* @{
*/
/**
* @}
*/
#endif /*USE_FULL_LL_DRIVER*/
/* Exported types ------------------------------------------------------------*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup RTC_LL_ES_INIT RTC Exported Init structure
* @{
*/
/**
* @brief RTC Init structures definition
*/
typedef struct
{
uint32_t HourFormat; /*!< Specifies the RTC Hours Format.
This parameter can be a value of @ref RTC_LL_EC_HOURFORMAT
This feature can be modified afterwards using unitary function
@ref LL_RTC_SetHourFormat(). */
uint32_t AsynchPrescaler; /*!< Specifies the RTC Asynchronous Predivider value.
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F
This feature can be modified afterwards using unitary function
@ref LL_RTC_SetAsynchPrescaler(). */
uint32_t SynchPrescaler; /*!< Specifies the RTC Synchronous Predivider value.
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7FFF
This feature can be modified afterwards using unitary function
@ref LL_RTC_SetSynchPrescaler(). */
} LL_RTC_InitTypeDef;
/**
* @brief RTC Time structure definition
*/
typedef struct
{
uint32_t TimeFormat; /*!< Specifies the RTC AM/PM Time.
This parameter can be a value of @ref RTC_LL_EC_TIME_FORMAT
This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetFormat(). */
uint8_t Hours; /*!< Specifies the RTC Time Hours.
This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the @ref LL_RTC_TIME_FORMAT_PM is selected.
This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the @ref LL_RTC_TIME_FORMAT_AM_OR_24 is selected.
This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetHour(). */
uint8_t Minutes; /*!< Specifies the RTC Time Minutes.
This parameter must be a number between Min_Data = 0 and Max_Data = 59
This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetMinute(). */
uint8_t Seconds; /*!< Specifies the RTC Time Seconds.
This parameter must be a number between Min_Data = 0 and Max_Data = 59
This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetSecond(). */
} LL_RTC_TimeTypeDef;
/**
* @brief RTC Date structure definition
*/
typedef struct
{
uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay.
This parameter can be a value of @ref RTC_LL_EC_WEEKDAY
This feature can be modified afterwards using unitary function @ref LL_RTC_DATE_SetWeekDay(). */
uint8_t Month; /*!< Specifies the RTC Date Month.
This parameter can be a value of @ref RTC_LL_EC_MONTH
This feature can be modified afterwards using unitary function @ref LL_RTC_DATE_SetMonth(). */
uint8_t Day; /*!< Specifies the RTC Date Day.
This parameter must be a number between Min_Data = 1 and Max_Data = 31
This feature can be modified afterwards using unitary function @ref LL_RTC_DATE_SetDay(). */
uint8_t Year; /*!< Specifies the RTC Date Year.
This parameter must be a number between Min_Data = 0 and Max_Data = 99
This feature can be modified afterwards using unitary function @ref LL_RTC_DATE_SetYear(). */
} LL_RTC_DateTypeDef;
/**
* @brief RTC Alarm structure definition
*/
typedef struct
{
LL_RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members. */
uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks.
This parameter can be a value of @ref RTC_LL_EC_ALMA_MASK
This feature can be modified afterwards using unitary function @ref LL_RTC_ALMA_SetMask() for ALARM A.
*/
uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on day or WeekDay.
This parameter can be a value of @ref RTC_LL_EC_ALMA_WEEKDAY_SELECTION
This feature can be modified afterwards using unitary function @ref LL_RTC_ALMA_EnableWeekday() or @ref LL_RTC_ALMA_DisableWeekday()
*/
uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Day/WeekDay.
If AlarmDateWeekDaySel set to day, this parameter must be a number between Min_Data = 1 and Max_Data = 31.
This feature can be modified afterwards using unitary function @ref LL_RTC_ALMA_SetDay()
If AlarmDateWeekDaySel set to Weekday, this parameter can be a value of @ref RTC_LL_EC_WEEKDAY.
This feature can be modified afterwards using unitary function @ref LL_RTC_ALMA_SetWeekDay()
*/
} LL_RTC_AlarmTypeDef;
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/* Exported constants --------------------------------------------------------*/
/** @defgroup RTC_LL_Exported_Constants RTC Exported Constants
* @{
*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup RTC_LL_EC_FORMAT FORMAT
* @{
*/
#define LL_RTC_FORMAT_BIN 0x000000000U /*!< Binary data format */
#define LL_RTC_FORMAT_BCD 0x000000001U /*!< BCD data format */
/**
* @}
*/
/** @defgroup RTC_LL_EC_ALMA_WEEKDAY_SELECTION RTC Alarm A Date WeekDay
* @{
*/
#define LL_RTC_ALMA_DATEWEEKDAYSEL_DATE 0x00000000U /*!< Alarm A Date is selected */
#define LL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY RTC_ALRMAR_WDSEL /*!< Alarm A WeekDay is selected */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/** @defgroup RTC_LL_EC_GET_FLAG Get Flags Defines
* @brief Flags defines which can be used with LL_RTC_ReadReg function
* @{
*/
#define LL_RTC_ISR_RECALPF RTC_ISR_RECALPF
#define LL_RTC_ISR_TAMP3F RTC_ISR_TAMP3F
#define LL_RTC_ISR_TAMP2F RTC_ISR_TAMP2F
#define LL_RTC_ISR_TAMP1F RTC_ISR_TAMP1F
#define LL_RTC_ISR_TSOVF RTC_ISR_TSOVF
#define LL_RTC_ISR_TSF RTC_ISR_TSF
#define LL_RTC_ISR_WUTF RTC_ISR_WUTF
#define LL_RTC_ISR_ALRAF RTC_ISR_ALRAF
#define LL_RTC_ISR_INITF RTC_ISR_INITF
#define LL_RTC_ISR_RSF RTC_ISR_RSF
#define LL_RTC_ISR_INITS RTC_ISR_INITS
#define LL_RTC_ISR_SHPF RTC_ISR_SHPF
#define LL_RTC_ISR_WUTWF RTC_ISR_WUTWF
#define LL_RTC_ISR_ALRAWF RTC_ISR_ALRAWF
/**
* @}
*/
/** @defgroup RTC_LL_EC_IT IT Defines
* @brief IT defines which can be used with LL_RTC_ReadReg and LL_RTC_WriteReg functions
* @{
*/
#define LL_RTC_CR_TSIE RTC_CR_TSIE
#define LL_RTC_CR_WUTIE RTC_CR_WUTIE
#define LL_RTC_CR_ALRAIE RTC_CR_ALRAIE
#define LL_RTC_TAFCR_TAMPIE RTC_TAFCR_TAMPIE
/**
* @}
*/
/** @defgroup RTC_LL_EC_WEEKDAY WEEK DAY
* @{
*/
#define LL_RTC_WEEKDAY_MONDAY ((uint8_t)0x01U) /*!< Monday */
#define LL_RTC_WEEKDAY_TUESDAY ((uint8_t)0x02U) /*!< Tuesday */
#define LL_RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03U) /*!< Wednesday */
#define LL_RTC_WEEKDAY_THURSDAY ((uint8_t)0x04U) /*!< Thrusday */
#define LL_RTC_WEEKDAY_FRIDAY ((uint8_t)0x05U) /*!< Friday */
#define LL_RTC_WEEKDAY_SATURDAY ((uint8_t)0x06U) /*!< Saturday */
#define LL_RTC_WEEKDAY_SUNDAY ((uint8_t)0x07U) /*!< Sunday */
/**
* @}
*/
/** @defgroup RTC_LL_EC_MONTH MONTH
* @{
*/
#define LL_RTC_MONTH_JANUARY ((uint8_t)0x01U) /*!< January */
#define LL_RTC_MONTH_FEBRUARY ((uint8_t)0x02U) /*!< February */
#define LL_RTC_MONTH_MARCH ((uint8_t)0x03U) /*!< March */
#define LL_RTC_MONTH_APRIL ((uint8_t)0x04U) /*!< April */
#define LL_RTC_MONTH_MAY ((uint8_t)0x05U) /*!< May */
#define LL_RTC_MONTH_JUNE ((uint8_t)0x06U) /*!< June */
#define LL_RTC_MONTH_JULY ((uint8_t)0x07U) /*!< July */
#define LL_RTC_MONTH_AUGUST ((uint8_t)0x08U) /*!< August */
#define LL_RTC_MONTH_SEPTEMBER ((uint8_t)0x09U) /*!< September */
#define LL_RTC_MONTH_OCTOBER ((uint8_t)0x10U) /*!< October */
#define LL_RTC_MONTH_NOVEMBER ((uint8_t)0x11U) /*!< November */
#define LL_RTC_MONTH_DECEMBER ((uint8_t)0x12U) /*!< December */
/**
* @}
*/
/** @defgroup RTC_LL_EC_HOURFORMAT HOUR FORMAT
* @{
*/
#define LL_RTC_HOURFORMAT_24HOUR 0x00000000U /*!< 24 hour/day format */
#define LL_RTC_HOURFORMAT_AMPM RTC_CR_FMT /*!< AM/PM hour format */
/**
* @}
*/
/** @defgroup RTC_LL_EC_ALARMOUT ALARM OUTPUT
* @{
*/
#define LL_RTC_ALARMOUT_DISABLE 0x00000000U /*!< Output disabled */
#define LL_RTC_ALARMOUT_ALMA RTC_CR_OSEL_0 /*!< Alarm A output enabled */
#define LL_RTC_ALARMOUT_ALMB RTC_CR_OSEL_1 /*!< Alarm B output enabled */
#define LL_RTC_ALARMOUT_WAKEUP RTC_CR_OSEL /*!< Wakeup output enabled */
/**
* @}
*/
/** @defgroup RTC_LL_EC_ALARM_OUTPUTTYPE ALARM OUTPUT TYPE
* @{
*/
#define LL_RTC_ALARM_OUTPUTTYPE_OPENDRAIN 0x00000000U /*!< RTC_ALARM, when mapped on PC13, is open-drain output */
#define LL_RTC_ALARM_OUTPUTTYPE_PUSHPULL RTC_TAFCR_ALARMOUTTYPE /*!< RTC_ALARM, when mapped on PC13, is push-pull output */
/**
* @}
*/
/** @defgroup RTC_LL_EC_PIN PIN
* @{
*/
#define LL_RTC_PIN_PC13 RTC_TAFCR_PC13MODE /*!< PC13 is forced to push-pull output if all RTC alternate functions are disabled */
#define LL_RTC_PIN_PC14 RTC_TAFCR_PC14MODE /*!< PC14 is forced to push-pull output if LSE is disabled */
#define LL_RTC_PIN_PC15 RTC_TAFCR_PC15MODE /*!< PC15 is forced to push-pull output if LSE is disabled */
/**
* @}
*/
/** @defgroup RTC_LL_EC_OUTPUTPOLARITY_PIN OUTPUT POLARITY PIN
* @{
*/
#define LL_RTC_OUTPUTPOLARITY_PIN_HIGH 0x00000000U /*!< Pin is high when ALRAF/ALRBF/WUTF is asserted (depending on OSEL)*/
#define LL_RTC_OUTPUTPOLARITY_PIN_LOW RTC_CR_POL /*!< Pin is low when ALRAF/ALRBF/WUTF is asserted (depending on OSEL) */
/**
* @}
*/
/** @defgroup RTC_LL_EC_TIME_FORMAT TIME FORMAT
* @{
*/
#define LL_RTC_TIME_FORMAT_AM_OR_24 0x00000000U /*!< AM or 24-hour format */
#define LL_RTC_TIME_FORMAT_PM RTC_TR_PM /*!< PM */
/**
* @}
*/
/** @defgroup RTC_LL_EC_SHIFT_SECOND SHIFT SECOND
* @{
*/
#define LL_RTC_SHIFT_SECOND_DELAY 0x00000000U /* Delay (seconds) = SUBFS / (PREDIV_S + 1) */
#define LL_RTC_SHIFT_SECOND_ADVANCE RTC_SHIFTR_ADD1S /* Advance (seconds) = (1 - (SUBFS / (PREDIV_S + 1))) */
/**
* @}
*/
/** @defgroup RTC_LL_EC_ALMA_MASK ALARMA MASK
* @{
*/
#define LL_RTC_ALMA_MASK_NONE 0x00000000U /*!< No masks applied on Alarm A*/
#define LL_RTC_ALMA_MASK_DATEWEEKDAY RTC_ALRMAR_MSK4 /*!< Date/day do not care in Alarm A comparison */
#define LL_RTC_ALMA_MASK_HOURS RTC_ALRMAR_MSK3 /*!< Hours do not care in Alarm A comparison */
#define LL_RTC_ALMA_MASK_MINUTES RTC_ALRMAR_MSK2 /*!< Minutes do not care in Alarm A comparison */
#define LL_RTC_ALMA_MASK_SECONDS RTC_ALRMAR_MSK1 /*!< Seconds do not care in Alarm A comparison */
#define LL_RTC_ALMA_MASK_ALL (RTC_ALRMAR_MSK4 | RTC_ALRMAR_MSK3 | RTC_ALRMAR_MSK2 | RTC_ALRMAR_MSK1) /*!< Masks all */
/**
* @}
*/
/** @defgroup RTC_LL_EC_ALMA_TIME_FORMAT ALARMA TIME FORMAT
* @{
*/
#define LL_RTC_ALMA_TIME_FORMAT_AM 0x00000000U /*!< AM or 24-hour format */
#define LL_RTC_ALMA_TIME_FORMAT_PM RTC_ALRMAR_PM /*!< PM */
/**
* @}
*/
/** @defgroup RTC_LL_EC_TIMESTAMP_EDGE TIMESTAMP EDGE
* @{
*/
#define LL_RTC_TIMESTAMP_EDGE_RISING 0x00000000U /*!< RTC_TS input rising edge generates a time-stamp event */
#define LL_RTC_TIMESTAMP_EDGE_FALLING RTC_CR_TSEDGE /*!< RTC_TS input falling edge generates a time-stamp even */
/**
* @}
*/
/** @defgroup RTC_LL_EC_TS_TIME_FORMAT TIMESTAMP TIME FORMAT
* @{
*/
#define LL_RTC_TS_TIME_FORMAT_AM 0x00000000U /*!< AM or 24-hour format */
#define LL_RTC_TS_TIME_FORMAT_PM RTC_TSTR_PM /*!< PM */
/**
* @}
*/
/** @defgroup RTC_LL_EC_TAMPER TAMPER
* @{
*/
#if defined(RTC_TAMPER1_SUPPORT)
#define LL_RTC_TAMPER_1 RTC_TAFCR_TAMP1E /*!< RTC_TAMP1 input detection */
#endif /* RTC_TAMPER1_SUPPORT */
#if defined(RTC_TAMPER2_SUPPORT)
#define LL_RTC_TAMPER_2 RTC_TAFCR_TAMP2E /*!< RTC_TAMP2 input detection */
#endif /* RTC_TAMPER2_SUPPORT */
#if defined(RTC_TAMPER3_SUPPORT)
#define LL_RTC_TAMPER_3 RTC_TAFCR_TAMP3E /*!< RTC_TAMP3 input detection */
#endif /* RTC_TAMPER3_SUPPORT */
/**
* @}
*/
/** @defgroup RTC_LL_EC_TAMPER_MASK TAMPER MASK
* @{
*/
#if defined(RTC_TAMPER1_SUPPORT)
#define LL_RTC_TAMPER_MASK_TAMPER1 RTC_TAFCR_TAMP1MF /*!< Tamper 1 event generates a trigger event. TAMP1F is masked and internally cleared by hardware.The backup registers are not erased */
#endif /* RTC_TAMPER1_SUPPORT */
#if defined(RTC_TAMPER2_SUPPORT)
#define LL_RTC_TAMPER_MASK_TAMPER2 RTC_TAFCR_TAMP2MF /*!< Tamper 2 event generates a trigger event. TAMP2F is masked and internally cleared by hardware. The backup registers are not erased. */
#endif /* RTC_TAMPER2_SUPPORT */
#if defined(RTC_TAMPER3_SUPPORT)
#define LL_RTC_TAMPER_MASK_TAMPER3 RTC_TAFCR_TAMP3MF /*!< Tamper 3 event generates a trigger event. TAMP3F is masked and internally cleared by hardware. The backup registers are not erased */
#endif /* RTC_TAMPER3_SUPPORT */
/**
* @}
*/
/** @defgroup RTC_LL_EC_TAMPER_NOERASE TAMPER NO ERASE
* @{
*/
#if defined(RTC_TAMPER1_SUPPORT)
#define LL_RTC_TAMPER_NOERASE_TAMPER1 RTC_TAFCR_TAMP1NOERASE /*!< Tamper 1 event does not erase the backup registers. */
#endif /* RTC_TAMPER1_SUPPORT */
#if defined(RTC_TAMPER2_SUPPORT)
#define LL_RTC_TAMPER_NOERASE_TAMPER2 RTC_TAFCR_TAMP2NOERASE /*!< Tamper 2 event does not erase the backup registers. */
#endif /* RTC_TAMPER2_SUPPORT */
#if defined(RTC_TAMPER3_SUPPORT)
#define LL_RTC_TAMPER_NOERASE_TAMPER3 RTC_TAFCR_TAMP3NOERASE /*!< Tamper 3 event does not erase the backup registers. */
#endif /* RTC_TAMPER3_SUPPORT */
/**
* @}
*/
#if defined(RTC_TAFCR_TAMPPRCH)
/** @defgroup RTC_LL_EC_TAMPER_DURATION TAMPER DURATION
* @{
*/
#define LL_RTC_TAMPER_DURATION_1RTCCLK 0x00000000U /*!< Tamper pins are pre-charged before sampling during 1 RTCCLK cycle */
#define LL_RTC_TAMPER_DURATION_2RTCCLK RTC_TAFCR_TAMPPRCH_0 /*!< Tamper pins are pre-charged before sampling during 2 RTCCLK cycles */
#define LL_RTC_TAMPER_DURATION_4RTCCLK RTC_TAFCR_TAMPPRCH_1 /*!< Tamper pins are pre-charged before sampling during 4 RTCCLK cycles */
#define LL_RTC_TAMPER_DURATION_8RTCCLK RTC_TAFCR_TAMPPRCH /*!< Tamper pins are pre-charged before sampling during 8 RTCCLK cycles */
/**
* @}
*/
#endif /* RTC_TAFCR_TAMPPRCH */
#if defined(RTC_TAFCR_TAMPFLT)
/** @defgroup RTC_LL_EC_TAMPER_FILTER TAMPER FILTER
* @{
*/
#define LL_RTC_TAMPER_FILTER_DISABLE 0x00000000U /*!< Tamper filter is disabled */
#define LL_RTC_TAMPER_FILTER_2SAMPLE RTC_TAFCR_TAMPFLT_0 /*!< Tamper is activated after 2 consecutive samples at the active level */
#define LL_RTC_TAMPER_FILTER_4SAMPLE RTC_TAFCR_TAMPFLT_1 /*!< Tamper is activated after 4 consecutive samples at the active level */
#define LL_RTC_TAMPER_FILTER_8SAMPLE RTC_TAFCR_TAMPFLT /*!< Tamper is activated after 8 consecutive samples at the active level. */
/**
* @}
*/
#endif /* RTC_TAFCR_TAMPFLT */
#if defined(RTC_TAFCR_TAMPFREQ)
/** @defgroup RTC_LL_EC_TAMPER_SAMPLFREQDIV TAMPER SAMPLING FREQUENCY DIVIDER
* @{
*/
#define LL_RTC_TAMPER_SAMPLFREQDIV_32768 0x00000000U /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 32768 */
#define LL_RTC_TAMPER_SAMPLFREQDIV_16384 RTC_TAFCR_TAMPFREQ_0 /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 16384 */
#define LL_RTC_TAMPER_SAMPLFREQDIV_8192 RTC_TAFCR_TAMPFREQ_1 /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 8192 */
#define LL_RTC_TAMPER_SAMPLFREQDIV_4096 (RTC_TAFCR_TAMPFREQ_1 | RTC_TAFCR_TAMPFREQ_0) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 4096 */
#define LL_RTC_TAMPER_SAMPLFREQDIV_2048 RTC_TAFCR_TAMPFREQ_2 /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 2048 */
#define LL_RTC_TAMPER_SAMPLFREQDIV_1024 (RTC_TAFCR_TAMPFREQ_2 | RTC_TAFCR_TAMPFREQ_0) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 1024 */
#define LL_RTC_TAMPER_SAMPLFREQDIV_512 (RTC_TAFCR_TAMPFREQ_2 | RTC_TAFCR_TAMPFREQ_1) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 512 */
#define LL_RTC_TAMPER_SAMPLFREQDIV_256 RTC_TAFCR_TAMPFREQ /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 256 */
/**
* @}
*/
#endif /* RTC_TAFCR_TAMPFREQ */
/** @defgroup RTC_LL_EC_TAMPER_ACTIVELEVEL TAMPER ACTIVE LEVEL
* @{
*/
#if defined(RTC_TAMPER1_SUPPORT)
#define LL_RTC_TAMPER_ACTIVELEVEL_TAMP1 RTC_TAFCR_TAMP1TRG /*!< RTC_TAMP1 input falling edge (if TAMPFLT = 00) or staying high (if TAMPFLT != 00) triggers a tamper detection event*/
#endif /* RTC_TAMPER1_SUPPORT */
#if defined(RTC_TAMPER2_SUPPORT)
#define LL_RTC_TAMPER_ACTIVELEVEL_TAMP2 RTC_TAFCR_TAMP2TRG /*!< RTC_TAMP2 input falling edge (if TAMPFLT = 00) or staying high (if TAMPFLT != 00) triggers a tamper detection event*/
#endif /* RTC_TAMPER2_SUPPORT */
#if defined(RTC_TAMPER3_SUPPORT)
#define LL_RTC_TAMPER_ACTIVELEVEL_TAMP3 RTC_TAFCR_TAMP3TRG /*!< RTC_TAMP3 input falling edge (if TAMPFLT = 00) or staying high (if TAMPFLT != 00) triggers a tamper detection event*/
#endif /* RTC_TAMPER3_SUPPORT */
/**
* @}
*/
/** @defgroup RTC_LL_EC_WAKEUPCLOCK_DIV WAKEUP CLOCK DIV
* @{
*/
#define LL_RTC_WAKEUPCLOCK_DIV_16 0x00000000U /*!< RTC/16 clock is selected */
#define LL_RTC_WAKEUPCLOCK_DIV_8 (RTC_CR_WUCKSEL_0) /*!< RTC/8 clock is selected */
#define LL_RTC_WAKEUPCLOCK_DIV_4 (RTC_CR_WUCKSEL_1) /*!< RTC/4 clock is selected */
#define LL_RTC_WAKEUPCLOCK_DIV_2 (RTC_CR_WUCKSEL_1 | RTC_CR_WUCKSEL_0) /*!< RTC/2 clock is selected */
#define LL_RTC_WAKEUPCLOCK_CKSPRE (RTC_CR_WUCKSEL_2) /*!< ck_spre (usually 1 Hz) clock is selected */
#define LL_RTC_WAKEUPCLOCK_CKSPRE_WUT (RTC_CR_WUCKSEL_2 | RTC_CR_WUCKSEL_1) /*!< ck_spre (usually 1 Hz) clock is selected and 2exp16 is added to the WUT counter value*/
/**
* @}
*/
#if defined(RTC_BACKUP_SUPPORT)
/** @defgroup RTC_LL_EC_BKP BACKUP
* @{
*/
#define LL_RTC_BKP_DR0 0x00000000U
#define LL_RTC_BKP_DR1 0x00000001U
#define LL_RTC_BKP_DR2 0x00000002U
#define LL_RTC_BKP_DR3 0x00000003U
#define LL_RTC_BKP_DR4 0x00000004U
/**
* @}
*/
#endif /* RTC_BACKUP_SUPPORT */
/** @defgroup RTC_LL_EC_CALIB_OUTPUT Calibration output
* @{
*/
#define LL_RTC_CALIB_OUTPUT_NONE 0x00000000U /*!< Calibration output disabled */
#define LL_RTC_CALIB_OUTPUT_1HZ (RTC_CR_COE | RTC_CR_COSEL) /*!< Calibration output is 1 Hz */
#define LL_RTC_CALIB_OUTPUT_512HZ (RTC_CR_COE) /*!< Calibration output is 512 Hz */
/**
* @}
*/
/** @defgroup RTC_LL_EC_CALIB_INSERTPULSE Calibration pulse insertion
* @{
*/
#define LL_RTC_CALIB_INSERTPULSE_NONE 0x00000000U /*!< No RTCCLK pulses are added */
#define LL_RTC_CALIB_INSERTPULSE_SET RTC_CALR_CALP /*!< One RTCCLK pulse is effectively inserted every 2exp11 pulses (frequency increased by 488.5 ppm) */
/**
* @}
*/
/** @defgroup RTC_LL_EC_CALIB_PERIOD Calibration period
* @{
*/
#define LL_RTC_CALIB_PERIOD_32SEC 0x00000000U /*!< Use a 32-second calibration cycle period */
#define LL_RTC_CALIB_PERIOD_16SEC RTC_CALR_CALW16 /*!< Use a 16-second calibration cycle period */
#define LL_RTC_CALIB_PERIOD_8SEC RTC_CALR_CALW8 /*!< Use a 8-second calibration cycle period */
/**
* @}
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/** @defgroup RTC_LL_Exported_Macros RTC Exported Macros
* @{
*/
/** @defgroup RTC_LL_EM_WRITE_READ Common Write and read registers Macros
* @{
*/
/**
* @brief Write a value in RTC register
* @param __INSTANCE__ RTC Instance
* @param __REG__ Register to be written
* @param __VALUE__ Value to be written in the register
* @retval None
*/
#define LL_RTC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__))
/**
* @brief Read a value in RTC register
* @param __INSTANCE__ RTC Instance
* @param __REG__ Register to be read
* @retval Register value
*/
#define LL_RTC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__)
/**
* @}
*/
/** @defgroup RTC_LL_EM_Convert Convert helper Macros
* @{
*/
/**
* @brief Helper macro to convert a value from 2 digit decimal format to BCD format
* @param __VALUE__ Byte to be converted
* @retval Converted byte
*/
#define __LL_RTC_CONVERT_BIN2BCD(__VALUE__) (uint8_t)((((__VALUE__) / 10U) << 4U) | ((__VALUE__) % 10U))
/**
* @brief Helper macro to convert a value from BCD format to 2 digit decimal format
* @param __VALUE__ BCD value to be converted
* @retval Converted byte
*/
#define __LL_RTC_CONVERT_BCD2BIN(__VALUE__) (uint8_t)(((uint8_t)((__VALUE__) & (uint8_t)0xF0U) >> (uint8_t)0x4U) * 10U + ((__VALUE__) & (uint8_t)0x0FU))
/**
* @}
*/
/** @defgroup RTC_LL_EM_Date Date helper Macros
* @{
*/
/**
* @brief Helper macro to retrieve weekday.
* @param __RTC_DATE__ Date returned by @ref LL_RTC_DATE_Get function.
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_WEEKDAY_MONDAY
* @arg @ref LL_RTC_WEEKDAY_TUESDAY
* @arg @ref LL_RTC_WEEKDAY_WEDNESDAY
* @arg @ref LL_RTC_WEEKDAY_THURSDAY
* @arg @ref LL_RTC_WEEKDAY_FRIDAY
* @arg @ref LL_RTC_WEEKDAY_SATURDAY
* @arg @ref LL_RTC_WEEKDAY_SUNDAY
*/
#define __LL_RTC_GET_WEEKDAY(__RTC_DATE__) (((__RTC_DATE__) >> RTC_OFFSET_WEEKDAY) & 0x000000FFU)
/**
* @brief Helper macro to retrieve Year in BCD format
* @param __RTC_DATE__ Value returned by @ref LL_RTC_DATE_Get
* @retval Year in BCD format (0x00 . . . 0x99)
*/
#define __LL_RTC_GET_YEAR(__RTC_DATE__) ((__RTC_DATE__) & 0x000000FFU)
/**
* @brief Helper macro to retrieve Month in BCD format
* @param __RTC_DATE__ Value returned by @ref LL_RTC_DATE_Get
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_MONTH_JANUARY
* @arg @ref LL_RTC_MONTH_FEBRUARY
* @arg @ref LL_RTC_MONTH_MARCH
* @arg @ref LL_RTC_MONTH_APRIL
* @arg @ref LL_RTC_MONTH_MAY
* @arg @ref LL_RTC_MONTH_JUNE
* @arg @ref LL_RTC_MONTH_JULY
* @arg @ref LL_RTC_MONTH_AUGUST
* @arg @ref LL_RTC_MONTH_SEPTEMBER
* @arg @ref LL_RTC_MONTH_OCTOBER
* @arg @ref LL_RTC_MONTH_NOVEMBER
* @arg @ref LL_RTC_MONTH_DECEMBER
*/
#define __LL_RTC_GET_MONTH(__RTC_DATE__) (((__RTC_DATE__) >>RTC_OFFSET_MONTH) & 0x000000FFU)
/**
* @brief Helper macro to retrieve Day in BCD format
* @param __RTC_DATE__ Value returned by @ref LL_RTC_DATE_Get
* @retval Day in BCD format (0x01 . . . 0x31)
*/
#define __LL_RTC_GET_DAY(__RTC_DATE__) (((__RTC_DATE__) >>RTC_OFFSET_DAY) & 0x000000FFU)
/**
* @}
*/
/** @defgroup RTC_LL_EM_Time Time helper Macros
* @{
*/
/**
* @brief Helper macro to retrieve hour in BCD format
* @param __RTC_TIME__ RTC time returned by @ref LL_RTC_TIME_Get function
* @retval Hours in BCD format (0x01. . .0x12 or between Min_Data=0x00 and Max_Data=0x23)
*/
#define __LL_RTC_GET_HOUR(__RTC_TIME__) (((__RTC_TIME__) >> RTC_OFFSET_HOUR) & 0x000000FFU)
/**
* @brief Helper macro to retrieve minute in BCD format
* @param __RTC_TIME__ RTC time returned by @ref LL_RTC_TIME_Get function
* @retval Minutes in BCD format (0x00. . .0x59)
*/
#define __LL_RTC_GET_MINUTE(__RTC_TIME__) (((__RTC_TIME__) >> RTC_OFFSET_MINUTE) & 0x000000FFU)
/**
* @brief Helper macro to retrieve second in BCD format
* @param __RTC_TIME__ RTC time returned by @ref LL_RTC_TIME_Get function
* @retval Seconds in format (0x00. . .0x59)
*/
#define __LL_RTC_GET_SECOND(__RTC_TIME__) ((__RTC_TIME__) & 0x000000FFU)
/**
* @}
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup RTC_LL_Exported_Functions RTC Exported Functions
* @{
*/
/** @defgroup RTC_LL_EF_Configuration Configuration
* @{
*/
/**
* @brief Set Hours format (24 hour/day or AM/PM hour format)
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note It can be written in initialization mode only (@ref LL_RTC_EnableInitMode function)
* @rmtoll CR FMT LL_RTC_SetHourFormat
* @param RTCx RTC Instance
* @param HourFormat This parameter can be one of the following values:
* @arg @ref LL_RTC_HOURFORMAT_24HOUR
* @arg @ref LL_RTC_HOURFORMAT_AMPM
* @retval None
*/
__STATIC_INLINE void LL_RTC_SetHourFormat(RTC_TypeDef *RTCx, uint32_t HourFormat)
{
MODIFY_REG(RTCx->CR, RTC_CR_FMT, HourFormat);
}
/**
* @brief Get Hours format (24 hour/day or AM/PM hour format)
* @rmtoll CR FMT LL_RTC_GetHourFormat
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_HOURFORMAT_24HOUR
* @arg @ref LL_RTC_HOURFORMAT_AMPM
*/
__STATIC_INLINE uint32_t LL_RTC_GetHourFormat(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_FMT));
}
/**
* @brief Select the flag to be routed to RTC_ALARM output
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR OSEL LL_RTC_SetAlarmOutEvent
* @param RTCx RTC Instance
* @param AlarmOutput This parameter can be one of the following values:
* @arg @ref LL_RTC_ALARMOUT_DISABLE
* @arg @ref LL_RTC_ALARMOUT_ALMA
* @arg @ref LL_RTC_ALARMOUT_ALMB
* @arg @ref LL_RTC_ALARMOUT_WAKEUP
* @retval None
*/
__STATIC_INLINE void LL_RTC_SetAlarmOutEvent(RTC_TypeDef *RTCx, uint32_t AlarmOutput)
{
MODIFY_REG(RTCx->CR, RTC_CR_OSEL, AlarmOutput);
}
/**
* @brief Get the flag to be routed to RTC_ALARM output
* @rmtoll CR OSEL LL_RTC_GetAlarmOutEvent
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_ALARMOUT_DISABLE
* @arg @ref LL_RTC_ALARMOUT_ALMA
* @arg @ref LL_RTC_ALARMOUT_ALMB
* @arg @ref LL_RTC_ALARMOUT_WAKEUP
*/
__STATIC_INLINE uint32_t LL_RTC_GetAlarmOutEvent(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_OSEL));
}
/**
* @brief Set RTC_ALARM output type (ALARM in push-pull or open-drain output)
* @note Used only when RTC_ALARM is mapped on PC13
* @note If all RTC alternate functions are disabled and PC13MODE = 1, PC13VALUE configures the
* PC13 output data
* @rmtoll TAFCR ALARMOUTTYPE LL_RTC_SetAlarmOutputType
* @param RTCx RTC Instance
* @param Output This parameter can be one of the following values:
* @arg @ref LL_RTC_ALARM_OUTPUTTYPE_OPENDRAIN
* @arg @ref LL_RTC_ALARM_OUTPUTTYPE_PUSHPULL
* @retval None
*/
__STATIC_INLINE void LL_RTC_SetAlarmOutputType(RTC_TypeDef *RTCx, uint32_t Output)
{
MODIFY_REG(RTCx->TAFCR, RTC_TAFCR_ALARMOUTTYPE, Output);
}
/**
* @brief Get RTC_ALARM output type (ALARM in push-pull or open-drain output)
* @note used only when RTC_ALARM is mapped on PC13
* @note If all RTC alternate functions are disabled and PC13MODE = 1, PC13VALUE configures the
* PC13 output data
* @rmtoll TAFCR ALARMOUTTYPE LL_RTC_GetAlarmOutputType
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_ALARM_OUTPUTTYPE_OPENDRAIN
* @arg @ref LL_RTC_ALARM_OUTPUTTYPE_PUSHPULL
*/
__STATIC_INLINE uint32_t LL_RTC_GetAlarmOutputType(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TAFCR, RTC_TAFCR_ALARMOUTTYPE));
}
/**
* @brief Enable push-pull output on PC13, PC14 and/or PC15
* @note PC13 forced to push-pull output if all RTC alternate functions are disabled
* @note PC14 and PC15 forced to push-pull output if LSE is disabled
* @rmtoll TAFCR PC13MODE LL_RTC_EnablePushPullMode\n
* @rmtoll TAFCR PC14MODE LL_RTC_EnablePushPullMode\n
* @rmtoll TAFCR PC15MODE LL_RTC_EnablePushPullMode
* @param RTCx RTC Instance
* @param PinMask This parameter can be a combination of the following values:
* @arg @ref LL_RTC_PIN_PC13
* @arg @ref LL_RTC_PIN_PC14
* @arg @ref LL_RTC_PIN_PC15
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnablePushPullMode(RTC_TypeDef *RTCx, uint32_t PinMask)
{
SET_BIT(RTCx->TAFCR, PinMask);
}
/**
* @brief Disable push-pull output on PC13, PC14 and/or PC15
* @note PC13, PC14 and/or PC15 are controlled by the GPIO configuration registers.
* Consequently PC13, PC14 and/or PC15 are floating in Standby mode.
* @rmtoll TAFCR PC13MODE LL_RTC_DisablePushPullMode\n
* TAFCR PC14MODE LL_RTC_DisablePushPullMode\n
* TAFCR PC15MODE LL_RTC_DisablePushPullMode
* @param RTCx RTC Instance
* @param PinMask This parameter can be a combination of the following values:
* @arg @ref LL_RTC_PIN_PC13
* @arg @ref LL_RTC_PIN_PC14
* @arg @ref LL_RTC_PIN_PC15
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisablePushPullMode(RTC_TypeDef* RTCx, uint32_t PinMask)
{
CLEAR_BIT(RTCx->TAFCR, PinMask);
}
/**
* @brief Set PC14 and/or PC15 to high level.
* @note Output data configuration is possible if the LSE is disabled and PushPull output is enabled (through @ref LL_RTC_EnablePushPullMode)
* @rmtoll TAFCR PC14VALUE LL_RTC_SetOutputPin\n
* TAFCR PC15VALUE LL_RTC_SetOutputPin
* @param RTCx RTC Instance
* @param PinMask This parameter can be a combination of the following values:
* @arg @ref LL_RTC_PIN_PC14
* @arg @ref LL_RTC_PIN_PC15
* @retval None
*/
__STATIC_INLINE void LL_RTC_SetOutputPin(RTC_TypeDef* RTCx, uint32_t PinMask)
{
SET_BIT(RTCx->TAFCR, (PinMask >> 1));
}
/**
* @brief Set PC14 and/or PC15 to low level.
* @note Output data configuration is possible if the LSE is disabled and PushPull output is enabled (through @ref LL_RTC_EnablePushPullMode)
* @rmtoll TAFCR PC14VALUE LL_RTC_ResetOutputPin\n
* TAFCR PC15VALUE LL_RTC_ResetOutputPin
* @param RTCx RTC Instance
* @param PinMask This parameter can be a combination of the following values:
* @arg @ref LL_RTC_PIN_PC14
* @arg @ref LL_RTC_PIN_PC15
* @retval None
*/
__STATIC_INLINE void LL_RTC_ResetOutputPin(RTC_TypeDef* RTCx, uint32_t PinMask)
{
CLEAR_BIT(RTCx->TAFCR, (PinMask >> 1));
}
/**
* @brief Enable initialization mode
* @note Initialization mode is used to program time and date register (RTC_TR and RTC_DR)
* and prescaler register (RTC_PRER).
* Counters are stopped and start counting from the new value when INIT is reset.
* @rmtoll ISR INIT LL_RTC_EnableInitMode
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnableInitMode(RTC_TypeDef *RTCx)
{
/* Set the Initialization mode */
WRITE_REG(RTCx->ISR, RTC_INIT_MASK);
}
/**
* @brief Disable initialization mode (Free running mode)
* @rmtoll ISR INIT LL_RTC_DisableInitMode
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisableInitMode(RTC_TypeDef *RTCx)
{
/* Exit Initialization mode */
WRITE_REG(RTCx->ISR, (uint32_t)~RTC_ISR_INIT);
}
/**
* @brief Set Output polarity (pin is low when ALRAF/ALRBF/WUTF is asserted)
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR POL LL_RTC_SetOutputPolarity
* @param RTCx RTC Instance
* @param Polarity This parameter can be one of the following values:
* @arg @ref LL_RTC_OUTPUTPOLARITY_PIN_HIGH
* @arg @ref LL_RTC_OUTPUTPOLARITY_PIN_LOW
* @retval None
*/
__STATIC_INLINE void LL_RTC_SetOutputPolarity(RTC_TypeDef *RTCx, uint32_t Polarity)
{
MODIFY_REG(RTCx->CR, RTC_CR_POL, Polarity);
}
/**
* @brief Get Output polarity
* @rmtoll CR POL LL_RTC_GetOutputPolarity
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_OUTPUTPOLARITY_PIN_HIGH
* @arg @ref LL_RTC_OUTPUTPOLARITY_PIN_LOW
*/
__STATIC_INLINE uint32_t LL_RTC_GetOutputPolarity(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_POL));
}
/**
* @brief Enable Bypass the shadow registers
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR BYPSHAD LL_RTC_EnableShadowRegBypass
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnableShadowRegBypass(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_BYPSHAD);
}
/**
* @brief Disable Bypass the shadow registers
* @rmtoll CR BYPSHAD LL_RTC_DisableShadowRegBypass
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisableShadowRegBypass(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_BYPSHAD);
}
/**
* @brief Check if Shadow registers bypass is enabled or not.
* @rmtoll CR BYPSHAD LL_RTC_IsShadowRegBypassEnabled
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsShadowRegBypassEnabled(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->CR, RTC_CR_BYPSHAD) == (RTC_CR_BYPSHAD));
}
/**
* @brief Enable RTC_REFIN reference clock detection (50 or 60 Hz)
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note It can be written in initialization mode only (@ref LL_RTC_EnableInitMode function)
* @rmtoll CR REFCKON LL_RTC_EnableRefClock
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnableRefClock(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_REFCKON);
}
/**
* @brief Disable RTC_REFIN reference clock detection (50 or 60 Hz)
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note It can be written in initialization mode only (@ref LL_RTC_EnableInitMode function)
* @rmtoll CR REFCKON LL_RTC_DisableRefClock
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisableRefClock(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_REFCKON);
}
/**
* @brief Set Asynchronous prescaler factor
* @rmtoll PRER PREDIV_A LL_RTC_SetAsynchPrescaler
* @param RTCx RTC Instance
* @param AsynchPrescaler Value between Min_Data = 0 and Max_Data = 0x7F
* @retval None
*/
__STATIC_INLINE void LL_RTC_SetAsynchPrescaler(RTC_TypeDef *RTCx, uint32_t AsynchPrescaler)
{
MODIFY_REG(RTCx->PRER, RTC_PRER_PREDIV_A, AsynchPrescaler << RTC_PRER_PREDIV_A_Pos);
}
/**
* @brief Set Synchronous prescaler factor
* @rmtoll PRER PREDIV_S LL_RTC_SetSynchPrescaler
* @param RTCx RTC Instance
* @param SynchPrescaler Value between Min_Data = 0 and Max_Data = 0x7FFF
* @retval None
*/
__STATIC_INLINE void LL_RTC_SetSynchPrescaler(RTC_TypeDef *RTCx, uint32_t SynchPrescaler)
{
MODIFY_REG(RTCx->PRER, RTC_PRER_PREDIV_S, SynchPrescaler);
}
/**
* @brief Get Asynchronous prescaler factor
* @rmtoll PRER PREDIV_A LL_RTC_GetAsynchPrescaler
* @param RTCx RTC Instance
* @retval Value between Min_Data = 0 and Max_Data = 0x7F
*/
__STATIC_INLINE uint32_t LL_RTC_GetAsynchPrescaler(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->PRER, RTC_PRER_PREDIV_A) >> RTC_PRER_PREDIV_A_Pos);
}
/**
* @brief Get Synchronous prescaler factor
* @rmtoll PRER PREDIV_S LL_RTC_GetSynchPrescaler
* @param RTCx RTC Instance
* @retval Value between Min_Data = 0 and Max_Data = 0x7FFF
*/
__STATIC_INLINE uint32_t LL_RTC_GetSynchPrescaler(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->PRER, RTC_PRER_PREDIV_S));
}
/**
* @brief Enable the write protection for RTC registers.
* @rmtoll WPR KEY LL_RTC_EnableWriteProtection
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnableWriteProtection(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->WPR, RTC_WRITE_PROTECTION_DISABLE);
}
/**
* @brief Disable the write protection for RTC registers.
* @rmtoll WPR KEY LL_RTC_DisableWriteProtection
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisableWriteProtection(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->WPR, RTC_WRITE_PROTECTION_ENABLE_1);
WRITE_REG(RTCx->WPR, RTC_WRITE_PROTECTION_ENABLE_2);
}
/**
* @}
*/
/** @defgroup RTC_LL_EF_Time Time
* @{
*/
/**
* @brief Set time format (AM/24-hour or PM notation)
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note It can be written in initialization mode only (@ref LL_RTC_EnableInitMode function)
* @rmtoll TR PM LL_RTC_TIME_SetFormat
* @param RTCx RTC Instance
* @param TimeFormat This parameter can be one of the following values:
* @arg @ref LL_RTC_TIME_FORMAT_AM_OR_24
* @arg @ref LL_RTC_TIME_FORMAT_PM
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_SetFormat(RTC_TypeDef *RTCx, uint32_t TimeFormat)
{
MODIFY_REG(RTCx->TR, RTC_TR_PM, TimeFormat);
}
/**
* @brief Get time format (AM or PM notation)
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar
* shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)).
* @rmtoll TR PM LL_RTC_TIME_GetFormat
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_TIME_FORMAT_AM_OR_24
* @arg @ref LL_RTC_TIME_FORMAT_PM
*/
__STATIC_INLINE uint32_t LL_RTC_TIME_GetFormat(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TR, RTC_TR_PM));
}
/**
* @brief Set Hours in BCD format
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note It can be written in initialization mode only (@ref LL_RTC_EnableInitMode function)
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert hour from binary to BCD format
* @rmtoll TR HT LL_RTC_TIME_SetHour\n
* TR HU LL_RTC_TIME_SetHour
* @param RTCx RTC Instance
* @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_SetHour(RTC_TypeDef *RTCx, uint32_t Hours)
{
MODIFY_REG(RTCx->TR, (RTC_TR_HT | RTC_TR_HU),
(((Hours & 0xF0U) << (RTC_TR_HT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_TR_HU_Pos)));
}
/**
* @brief Get Hours in BCD format
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar
* shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)).
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert hour from BCD to
* Binary format
* @rmtoll TR HT LL_RTC_TIME_GetHour\n
* TR HU LL_RTC_TIME_GetHour
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23
*/
__STATIC_INLINE uint32_t LL_RTC_TIME_GetHour(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->TR, (RTC_TR_HT | RTC_TR_HU));
return (uint32_t)((((temp & RTC_TR_HT) >> RTC_TR_HT_Pos) << 4U) | ((temp & RTC_TR_HU) >> RTC_TR_HU_Pos));
}
/**
* @brief Set Minutes in BCD format
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note It can be written in initialization mode only (@ref LL_RTC_EnableInitMode function)
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Minutes from binary to BCD format
* @rmtoll TR MNT LL_RTC_TIME_SetMinute\n
* TR MNU LL_RTC_TIME_SetMinute
* @param RTCx RTC Instance
* @param Minutes Value between Min_Data=0x00 and Max_Data=0x59
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes)
{
MODIFY_REG(RTCx->TR, (RTC_TR_MNT | RTC_TR_MNU),
(((Minutes & 0xF0U) << (RTC_TR_MNT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_TR_MNU_Pos)));
}
/**
* @brief Get Minutes in BCD format
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar
* shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)).
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert minute from BCD
* to Binary format
* @rmtoll TR MNT LL_RTC_TIME_GetMinute\n
* TR MNU LL_RTC_TIME_GetMinute
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0x59
*/
__STATIC_INLINE uint32_t LL_RTC_TIME_GetMinute(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->TR, (RTC_TR_MNT | RTC_TR_MNU));
return (uint32_t)((((temp & RTC_TR_MNT) >> RTC_TR_MNT_Pos) << 4U) | ((temp & RTC_TR_MNU) >> RTC_TR_MNU_Pos));
}
/**
* @brief Set Seconds in BCD format
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note It can be written in initialization mode only (@ref LL_RTC_EnableInitMode function)
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Seconds from binary to BCD format
* @rmtoll TR ST LL_RTC_TIME_SetSecond\n
* TR SU LL_RTC_TIME_SetSecond
* @param RTCx RTC Instance
* @param Seconds Value between Min_Data=0x00 and Max_Data=0x59
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds)
{
MODIFY_REG(RTCx->TR, (RTC_TR_ST | RTC_TR_SU),
(((Seconds & 0xF0U) << (RTC_TR_ST_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_TR_SU_Pos)));
}
/**
* @brief Get Seconds in BCD format
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar
* shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)).
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Seconds from BCD
* to Binary format
* @rmtoll TR ST LL_RTC_TIME_GetSecond\n
* TR SU LL_RTC_TIME_GetSecond
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0x59
*/
__STATIC_INLINE uint32_t LL_RTC_TIME_GetSecond(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->TR, (RTC_TR_ST | RTC_TR_SU));
return (uint32_t)((((temp & RTC_TR_ST) >> RTC_TR_ST_Pos) << 4U) | ((temp & RTC_TR_SU) >> RTC_TR_SU_Pos));
}
/**
* @brief Set time (hour, minute and second) in BCD format
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note It can be written in initialization mode only (@ref LL_RTC_EnableInitMode function)
* @note TimeFormat and Hours should follow the same format
* @rmtoll TR PM LL_RTC_TIME_Config\n
* TR HT LL_RTC_TIME_Config\n
* TR HU LL_RTC_TIME_Config\n
* TR MNT LL_RTC_TIME_Config\n
* TR MNU LL_RTC_TIME_Config\n
* TR ST LL_RTC_TIME_Config\n
* TR SU LL_RTC_TIME_Config
* @param RTCx RTC Instance
* @param Format12_24 This parameter can be one of the following values:
* @arg @ref LL_RTC_TIME_FORMAT_AM_OR_24
* @arg @ref LL_RTC_TIME_FORMAT_PM
* @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23
* @param Minutes Value between Min_Data=0x00 and Max_Data=0x59
* @param Seconds Value between Min_Data=0x00 and Max_Data=0x59
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_Config(RTC_TypeDef *RTCx, uint32_t Format12_24, uint32_t Hours, uint32_t Minutes, uint32_t Seconds)
{
register uint32_t temp = 0U;
temp = Format12_24 | \
(((Hours & 0xF0U) << (RTC_TR_HT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_TR_HU_Pos)) | \
(((Minutes & 0xF0U) << (RTC_TR_MNT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_TR_MNU_Pos)) | \
(((Seconds & 0xF0U) << (RTC_TR_ST_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_TR_SU_Pos));
MODIFY_REG(RTCx->TR, (RTC_TR_PM | RTC_TR_HT | RTC_TR_HU | RTC_TR_MNT | RTC_TR_MNU | RTC_TR_ST | RTC_TR_SU), temp);
}
/**
* @brief Get time (hour, minute and second) in BCD format
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar
* shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)).
* @note helper macros __LL_RTC_GET_HOUR, __LL_RTC_GET_MINUTE and __LL_RTC_GET_SECOND
* are available to get independently each parameter.
* @rmtoll TR HT LL_RTC_TIME_Get\n
* TR HU LL_RTC_TIME_Get\n
* TR MNT LL_RTC_TIME_Get\n
* TR MNU LL_RTC_TIME_Get\n
* TR ST LL_RTC_TIME_Get\n
* TR SU LL_RTC_TIME_Get
* @param RTCx RTC Instance
* @retval Combination of hours, minutes and seconds (Format: 0x00HHMMSS).
*/
__STATIC_INLINE uint32_t LL_RTC_TIME_Get(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->TR, (RTC_TR_HT | RTC_TR_HU | RTC_TR_MNT | RTC_TR_MNU | RTC_TR_ST | RTC_TR_SU));
return (uint32_t)((((((temp & RTC_TR_HT) >> RTC_TR_HT_Pos) << 4U) | ((temp & RTC_TR_HU) >> RTC_TR_HU_Pos)) << RTC_OFFSET_HOUR) | \
(((((temp & RTC_TR_MNT) >> RTC_TR_MNT_Pos) << 4U) | ((temp & RTC_TR_MNU) >> RTC_TR_MNU_Pos)) << RTC_OFFSET_MINUTE) | \
((((temp & RTC_TR_ST) >> RTC_TR_ST_Pos) << 4U) | ((temp & RTC_TR_SU) >> RTC_TR_SU_Pos)));
}
/**
* @brief Memorize whether the daylight saving time change has been performed
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR BKP LL_RTC_TIME_EnableDayLightStore
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_EnableDayLightStore(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_BKP);
}
/**
* @brief Disable memorization whether the daylight saving time change has been performed.
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR BKP LL_RTC_TIME_DisableDayLightStore
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_DisableDayLightStore(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_BKP);
}
/**
* @brief Check if RTC Day Light Saving stored operation has been enabled or not
* @rmtoll CR BKP LL_RTC_TIME_IsDayLightStoreEnabled
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_TIME_IsDayLightStoreEnabled(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->CR, RTC_CR_BKP) == (RTC_CR_BKP));
}
/**
* @brief Subtract 1 hour (winter time change)
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR SUB1H LL_RTC_TIME_DecHour
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_DecHour(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_SUB1H);
}
/**
* @brief Add 1 hour (summer time change)
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR ADD1H LL_RTC_TIME_IncHour
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_IncHour(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_ADD1H);
}
/**
* @brief Get Sub second value in the synchronous prescaler counter.
* @note You can use both SubSeconds value and SecondFraction (PREDIV_S through
* LL_RTC_GetSynchPrescaler function) terms returned to convert Calendar
* SubSeconds value in second fraction ratio with time unit following
* generic formula:
* ==> Seconds fraction ratio * time_unit= [(SecondFraction-SubSeconds)/(SecondFraction+1)] * time_unit
* This conversion can be performed only if no shift operation is pending
* (ie. SHFP=0) when PREDIV_S >= SS.
* @rmtoll SSR SS LL_RTC_TIME_GetSubSecond
* @param RTCx RTC Instance
* @retval Sub second value (number between 0 and 65535)
*/
__STATIC_INLINE uint32_t LL_RTC_TIME_GetSubSecond(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->SSR, RTC_SSR_SS));
}
/**
* @brief Synchronize to a remote clock with a high degree of precision.
* @note This operation effectively subtracts from (delays) or advance the clock of a fraction of a second.
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note When REFCKON is set, firmware must not write to Shift control register.
* @rmtoll SHIFTR ADD1S LL_RTC_TIME_Synchronize\n
* SHIFTR SUBFS LL_RTC_TIME_Synchronize
* @param RTCx RTC Instance
* @param ShiftSecond This parameter can be one of the following values:
* @arg @ref LL_RTC_SHIFT_SECOND_DELAY
* @arg @ref LL_RTC_SHIFT_SECOND_ADVANCE
* @param Fraction Number of Seconds Fractions (any value from 0 to 0x7FFF)
* @retval None
*/
__STATIC_INLINE void LL_RTC_TIME_Synchronize(RTC_TypeDef *RTCx, uint32_t ShiftSecond, uint32_t Fraction)
{
WRITE_REG(RTCx->SHIFTR, ShiftSecond | Fraction);
}
/**
* @}
*/
/** @defgroup RTC_LL_EF_Date Date
* @{
*/
/**
* @brief Set Year in BCD format
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Year from binary to BCD format
* @rmtoll DR YT LL_RTC_DATE_SetYear\n
* DR YU LL_RTC_DATE_SetYear
* @param RTCx RTC Instance
* @param Year Value between Min_Data=0x00 and Max_Data=0x99
* @retval None
*/
__STATIC_INLINE void LL_RTC_DATE_SetYear(RTC_TypeDef *RTCx, uint32_t Year)
{
MODIFY_REG(RTCx->DR, (RTC_DR_YT | RTC_DR_YU),
(((Year & 0xF0U) << (RTC_DR_YT_Pos - 4U)) | ((Year & 0x0FU) << RTC_DR_YU_Pos)));
}
/**
* @brief Get Year in BCD format
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Year from BCD to Binary format
* @rmtoll DR YT LL_RTC_DATE_GetYear\n
* DR YU LL_RTC_DATE_GetYear
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0x99
*/
__STATIC_INLINE uint32_t LL_RTC_DATE_GetYear(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->DR, (RTC_DR_YT | RTC_DR_YU));
return (uint32_t)((((temp & RTC_DR_YT) >> RTC_DR_YT_Pos) << 4U) | ((temp & RTC_DR_YU) >> RTC_DR_YU_Pos));
}
/**
* @brief Set Week day
* @rmtoll DR WDU LL_RTC_DATE_SetWeekDay
* @param RTCx RTC Instance
* @param WeekDay This parameter can be one of the following values:
* @arg @ref LL_RTC_WEEKDAY_MONDAY
* @arg @ref LL_RTC_WEEKDAY_TUESDAY
* @arg @ref LL_RTC_WEEKDAY_WEDNESDAY
* @arg @ref LL_RTC_WEEKDAY_THURSDAY
* @arg @ref LL_RTC_WEEKDAY_FRIDAY
* @arg @ref LL_RTC_WEEKDAY_SATURDAY
* @arg @ref LL_RTC_WEEKDAY_SUNDAY
* @retval None
*/
__STATIC_INLINE void LL_RTC_DATE_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay)
{
MODIFY_REG(RTCx->DR, RTC_DR_WDU, WeekDay << RTC_DR_WDU_Pos);
}
/**
* @brief Get Week day
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @rmtoll DR WDU LL_RTC_DATE_GetWeekDay
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_WEEKDAY_MONDAY
* @arg @ref LL_RTC_WEEKDAY_TUESDAY
* @arg @ref LL_RTC_WEEKDAY_WEDNESDAY
* @arg @ref LL_RTC_WEEKDAY_THURSDAY
* @arg @ref LL_RTC_WEEKDAY_FRIDAY
* @arg @ref LL_RTC_WEEKDAY_SATURDAY
* @arg @ref LL_RTC_WEEKDAY_SUNDAY
*/
__STATIC_INLINE uint32_t LL_RTC_DATE_GetWeekDay(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->DR, RTC_DR_WDU) >> RTC_DR_WDU_Pos);
}
/**
* @brief Set Month in BCD format
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Month from binary to BCD format
* @rmtoll DR MT LL_RTC_DATE_SetMonth\n
* DR MU LL_RTC_DATE_SetMonth
* @param RTCx RTC Instance
* @param Month This parameter can be one of the following values:
* @arg @ref LL_RTC_MONTH_JANUARY
* @arg @ref LL_RTC_MONTH_FEBRUARY
* @arg @ref LL_RTC_MONTH_MARCH
* @arg @ref LL_RTC_MONTH_APRIL
* @arg @ref LL_RTC_MONTH_MAY
* @arg @ref LL_RTC_MONTH_JUNE
* @arg @ref LL_RTC_MONTH_JULY
* @arg @ref LL_RTC_MONTH_AUGUST
* @arg @ref LL_RTC_MONTH_SEPTEMBER
* @arg @ref LL_RTC_MONTH_OCTOBER
* @arg @ref LL_RTC_MONTH_NOVEMBER
* @arg @ref LL_RTC_MONTH_DECEMBER
* @retval None
*/
__STATIC_INLINE void LL_RTC_DATE_SetMonth(RTC_TypeDef *RTCx, uint32_t Month)
{
MODIFY_REG(RTCx->DR, (RTC_DR_MT | RTC_DR_MU),
(((Month & 0xF0U) << (RTC_DR_MT_Pos - 4U)) | ((Month & 0x0FU) << RTC_DR_MU_Pos)));
}
/**
* @brief Get Month in BCD format
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Month from BCD to Binary format
* @rmtoll DR MT LL_RTC_DATE_GetMonth\n
* DR MU LL_RTC_DATE_GetMonth
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_MONTH_JANUARY
* @arg @ref LL_RTC_MONTH_FEBRUARY
* @arg @ref LL_RTC_MONTH_MARCH
* @arg @ref LL_RTC_MONTH_APRIL
* @arg @ref LL_RTC_MONTH_MAY
* @arg @ref LL_RTC_MONTH_JUNE
* @arg @ref LL_RTC_MONTH_JULY
* @arg @ref LL_RTC_MONTH_AUGUST
* @arg @ref LL_RTC_MONTH_SEPTEMBER
* @arg @ref LL_RTC_MONTH_OCTOBER
* @arg @ref LL_RTC_MONTH_NOVEMBER
* @arg @ref LL_RTC_MONTH_DECEMBER
*/
__STATIC_INLINE uint32_t LL_RTC_DATE_GetMonth(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->DR, (RTC_DR_MT | RTC_DR_MU));
return (uint32_t)((((temp & RTC_DR_MT) >> RTC_DR_MT_Pos) << 4U) | ((temp & RTC_DR_MU) >> RTC_DR_MU_Pos));
}
/**
* @brief Set Day in BCD format
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Day from binary to BCD format
* @rmtoll DR DT LL_RTC_DATE_SetDay\n
* DR DU LL_RTC_DATE_SetDay
* @param RTCx RTC Instance
* @param Day Value between Min_Data=0x01 and Max_Data=0x31
* @retval None
*/
__STATIC_INLINE void LL_RTC_DATE_SetDay(RTC_TypeDef *RTCx, uint32_t Day)
{
MODIFY_REG(RTCx->DR, (RTC_DR_DT | RTC_DR_DU),
(((Day & 0xF0U) << (RTC_DR_DT_Pos - 4U)) | ((Day & 0x0FU) << RTC_DR_DU_Pos)));
}
/**
* @brief Get Day in BCD format
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format
* @rmtoll DR DT LL_RTC_DATE_GetDay\n
* DR DU LL_RTC_DATE_GetDay
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x01 and Max_Data=0x31
*/
__STATIC_INLINE uint32_t LL_RTC_DATE_GetDay(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->DR, (RTC_DR_DT | RTC_DR_DU));
return (uint32_t)((((temp & RTC_DR_DT) >> RTC_DR_DT_Pos) << 4U) | ((temp & RTC_DR_DU) >> RTC_DR_DU_Pos));
}
/**
* @brief Set date (WeekDay, Day, Month and Year) in BCD format
* @rmtoll DR WDU LL_RTC_DATE_Config\n
* DR MT LL_RTC_DATE_Config\n
* DR MU LL_RTC_DATE_Config\n
* DR DT LL_RTC_DATE_Config\n
* DR DU LL_RTC_DATE_Config\n
* DR YT LL_RTC_DATE_Config\n
* DR YU LL_RTC_DATE_Config
* @param RTCx RTC Instance
* @param WeekDay This parameter can be one of the following values:
* @arg @ref LL_RTC_WEEKDAY_MONDAY
* @arg @ref LL_RTC_WEEKDAY_TUESDAY
* @arg @ref LL_RTC_WEEKDAY_WEDNESDAY
* @arg @ref LL_RTC_WEEKDAY_THURSDAY
* @arg @ref LL_RTC_WEEKDAY_FRIDAY
* @arg @ref LL_RTC_WEEKDAY_SATURDAY
* @arg @ref LL_RTC_WEEKDAY_SUNDAY
* @param Day Value between Min_Data=0x01 and Max_Data=0x31
* @param Month This parameter can be one of the following values:
* @arg @ref LL_RTC_MONTH_JANUARY
* @arg @ref LL_RTC_MONTH_FEBRUARY
* @arg @ref LL_RTC_MONTH_MARCH
* @arg @ref LL_RTC_MONTH_APRIL
* @arg @ref LL_RTC_MONTH_MAY
* @arg @ref LL_RTC_MONTH_JUNE
* @arg @ref LL_RTC_MONTH_JULY
* @arg @ref LL_RTC_MONTH_AUGUST
* @arg @ref LL_RTC_MONTH_SEPTEMBER
* @arg @ref LL_RTC_MONTH_OCTOBER
* @arg @ref LL_RTC_MONTH_NOVEMBER
* @arg @ref LL_RTC_MONTH_DECEMBER
* @param Year Value between Min_Data=0x00 and Max_Data=0x99
* @retval None
*/
__STATIC_INLINE void LL_RTC_DATE_Config(RTC_TypeDef *RTCx, uint32_t WeekDay, uint32_t Day, uint32_t Month, uint32_t Year)
{
register uint32_t temp = 0U;
temp = (WeekDay << RTC_DR_WDU_Pos) | \
(((Year & 0xF0U) << (RTC_DR_YT_Pos - 4U)) | ((Year & 0x0FU) << RTC_DR_YU_Pos)) | \
(((Month & 0xF0U) << (RTC_DR_MT_Pos - 4U)) | ((Month & 0x0FU) << RTC_DR_MU_Pos)) | \
(((Day & 0xF0U) << (RTC_DR_DT_Pos - 4U)) | ((Day & 0x0FU) << RTC_DR_DU_Pos));
MODIFY_REG(RTCx->DR, (RTC_DR_WDU | RTC_DR_MT | RTC_DR_MU | RTC_DR_DT | RTC_DR_DU | RTC_DR_YT | RTC_DR_YU), temp);
}
/**
* @brief Get date (WeekDay, Day, Month and Year) in BCD format
* @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set
* before reading this bit
* @note helper macros __LL_RTC_GET_WEEKDAY, __LL_RTC_GET_YEAR, __LL_RTC_GET_MONTH,
* and __LL_RTC_GET_DAY are available to get independently each parameter.
* @rmtoll DR WDU LL_RTC_DATE_Get\n
* DR MT LL_RTC_DATE_Get\n
* DR MU LL_RTC_DATE_Get\n
* DR DT LL_RTC_DATE_Get\n
* DR DU LL_RTC_DATE_Get\n
* DR YT LL_RTC_DATE_Get\n
* DR YU LL_RTC_DATE_Get
* @param RTCx RTC Instance
* @retval Combination of WeekDay, Day, Month and Year (Format: 0xWWDDMMYY).
*/
__STATIC_INLINE uint32_t LL_RTC_DATE_Get(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->DR, (RTC_DR_WDU | RTC_DR_MT | RTC_DR_MU | RTC_DR_DT | RTC_DR_DU | RTC_DR_YT | RTC_DR_YU));
return (uint32_t)((((temp & RTC_DR_WDU) >> RTC_DR_WDU_Pos) << RTC_OFFSET_WEEKDAY) | \
(((((temp & RTC_DR_DT) >> RTC_DR_DT_Pos) << 4U) | ((temp & RTC_DR_DU) >> RTC_DR_DU_Pos)) << RTC_OFFSET_DAY) | \
(((((temp & RTC_DR_MT) >> RTC_DR_MT_Pos) << 4U) | ((temp & RTC_DR_MU) >> RTC_DR_MU_Pos)) << RTC_OFFSET_MONTH) | \
((((temp & RTC_DR_YT) >> RTC_DR_YT_Pos) << 4U) | ((temp & RTC_DR_YU) >> RTC_DR_YU_Pos)));
}
/**
* @}
*/
/** @defgroup RTC_LL_EF_ALARMA ALARMA
* @{
*/
/**
* @brief Enable Alarm A
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR ALRAE LL_RTC_ALMA_Enable
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_Enable(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_ALRAE);
}
/**
* @brief Disable Alarm A
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR ALRAE LL_RTC_ALMA_Disable
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_Disable(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_ALRAE);
}
/**
* @brief Specify the Alarm A masks.
* @rmtoll ALRMAR MSK4 LL_RTC_ALMA_SetMask\n
* ALRMAR MSK3 LL_RTC_ALMA_SetMask\n
* ALRMAR MSK2 LL_RTC_ALMA_SetMask\n
* ALRMAR MSK1 LL_RTC_ALMA_SetMask
* @param RTCx RTC Instance
* @param Mask This parameter can be a combination of the following values:
* @arg @ref LL_RTC_ALMA_MASK_NONE
* @arg @ref LL_RTC_ALMA_MASK_DATEWEEKDAY
* @arg @ref LL_RTC_ALMA_MASK_HOURS
* @arg @ref LL_RTC_ALMA_MASK_MINUTES
* @arg @ref LL_RTC_ALMA_MASK_SECONDS
* @arg @ref LL_RTC_ALMA_MASK_ALL
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetMask(RTC_TypeDef *RTCx, uint32_t Mask)
{
MODIFY_REG(RTCx->ALRMAR, RTC_ALRMAR_MSK4 | RTC_ALRMAR_MSK3 | RTC_ALRMAR_MSK2 | RTC_ALRMAR_MSK1, Mask);
}
/**
* @brief Get the Alarm A masks.
* @rmtoll ALRMAR MSK4 LL_RTC_ALMA_GetMask\n
* ALRMAR MSK3 LL_RTC_ALMA_GetMask\n
* ALRMAR MSK2 LL_RTC_ALMA_GetMask\n
* ALRMAR MSK1 LL_RTC_ALMA_GetMask
* @param RTCx RTC Instance
* @retval Returned value can be can be a combination of the following values:
* @arg @ref LL_RTC_ALMA_MASK_NONE
* @arg @ref LL_RTC_ALMA_MASK_DATEWEEKDAY
* @arg @ref LL_RTC_ALMA_MASK_HOURS
* @arg @ref LL_RTC_ALMA_MASK_MINUTES
* @arg @ref LL_RTC_ALMA_MASK_SECONDS
* @arg @ref LL_RTC_ALMA_MASK_ALL
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetMask(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->ALRMAR, RTC_ALRMAR_MSK4 | RTC_ALRMAR_MSK3 | RTC_ALRMAR_MSK2 | RTC_ALRMAR_MSK1));
}
/**
* @brief Enable AlarmA Week day selection (DU[3:0] represents the week day. DT[1:0] is do not care)
* @rmtoll ALRMAR WDSEL LL_RTC_ALMA_EnableWeekday
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_EnableWeekday(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->ALRMAR, RTC_ALRMAR_WDSEL);
}
/**
* @brief Disable AlarmA Week day selection (DU[3:0] represents the date )
* @rmtoll ALRMAR WDSEL LL_RTC_ALMA_DisableWeekday
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_DisableWeekday(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->ALRMAR, RTC_ALRMAR_WDSEL);
}
/**
* @brief Set ALARM A Day in BCD format
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Day from binary to BCD format
* @rmtoll ALRMAR DT LL_RTC_ALMA_SetDay\n
* ALRMAR DU LL_RTC_ALMA_SetDay
* @param RTCx RTC Instance
* @param Day Value between Min_Data=0x01 and Max_Data=0x31
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetDay(RTC_TypeDef *RTCx, uint32_t Day)
{
MODIFY_REG(RTCx->ALRMAR, (RTC_ALRMAR_DT | RTC_ALRMAR_DU),
(((Day & 0xF0U) << (RTC_ALRMAR_DT_Pos - 4U)) | ((Day & 0x0FU) << RTC_ALRMAR_DU_Pos)));
}
/**
* @brief Get ALARM A Day in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format
* @rmtoll ALRMAR DT LL_RTC_ALMA_GetDay\n
* ALRMAR DU LL_RTC_ALMA_GetDay
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x01 and Max_Data=0x31
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetDay(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->ALRMAR, (RTC_ALRMAR_DT | RTC_ALRMAR_DU));
return (uint32_t)((((temp & RTC_ALRMAR_DT) >> RTC_ALRMAR_DT_Pos) << 4U) | ((temp & RTC_ALRMAR_DU) >> RTC_ALRMAR_DU_Pos));
}
/**
* @brief Set ALARM A Weekday
* @rmtoll ALRMAR DU LL_RTC_ALMA_SetWeekDay
* @param RTCx RTC Instance
* @param WeekDay This parameter can be one of the following values:
* @arg @ref LL_RTC_WEEKDAY_MONDAY
* @arg @ref LL_RTC_WEEKDAY_TUESDAY
* @arg @ref LL_RTC_WEEKDAY_WEDNESDAY
* @arg @ref LL_RTC_WEEKDAY_THURSDAY
* @arg @ref LL_RTC_WEEKDAY_FRIDAY
* @arg @ref LL_RTC_WEEKDAY_SATURDAY
* @arg @ref LL_RTC_WEEKDAY_SUNDAY
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay)
{
MODIFY_REG(RTCx->ALRMAR, RTC_ALRMAR_DU, WeekDay << RTC_ALRMAR_DU_Pos);
}
/**
* @brief Get ALARM A Weekday
* @rmtoll ALRMAR DU LL_RTC_ALMA_GetWeekDay
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_WEEKDAY_MONDAY
* @arg @ref LL_RTC_WEEKDAY_TUESDAY
* @arg @ref LL_RTC_WEEKDAY_WEDNESDAY
* @arg @ref LL_RTC_WEEKDAY_THURSDAY
* @arg @ref LL_RTC_WEEKDAY_FRIDAY
* @arg @ref LL_RTC_WEEKDAY_SATURDAY
* @arg @ref LL_RTC_WEEKDAY_SUNDAY
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetWeekDay(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->ALRMAR, RTC_ALRMAR_DU) >> RTC_ALRMAR_DU_Pos);
}
/**
* @brief Set Alarm A time format (AM/24-hour or PM notation)
* @rmtoll ALRMAR PM LL_RTC_ALMA_SetTimeFormat
* @param RTCx RTC Instance
* @param TimeFormat This parameter can be one of the following values:
* @arg @ref LL_RTC_ALMA_TIME_FORMAT_AM
* @arg @ref LL_RTC_ALMA_TIME_FORMAT_PM
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetTimeFormat(RTC_TypeDef *RTCx, uint32_t TimeFormat)
{
MODIFY_REG(RTCx->ALRMAR, RTC_ALRMAR_PM, TimeFormat);
}
/**
* @brief Get Alarm A time format (AM or PM notation)
* @rmtoll ALRMAR PM LL_RTC_ALMA_GetTimeFormat
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_ALMA_TIME_FORMAT_AM
* @arg @ref LL_RTC_ALMA_TIME_FORMAT_PM
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetTimeFormat(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->ALRMAR, RTC_ALRMAR_PM));
}
/**
* @brief Set ALARM A Hours in BCD format
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Hours from binary to BCD format
* @rmtoll ALRMAR HT LL_RTC_ALMA_SetHour\n
* ALRMAR HU LL_RTC_ALMA_SetHour
* @param RTCx RTC Instance
* @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetHour(RTC_TypeDef *RTCx, uint32_t Hours)
{
MODIFY_REG(RTCx->ALRMAR, (RTC_ALRMAR_HT | RTC_ALRMAR_HU),
(((Hours & 0xF0U) << (RTC_ALRMAR_HT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_ALRMAR_HU_Pos)));
}
/**
* @brief Get ALARM A Hours in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Hours from BCD to Binary format
* @rmtoll ALRMAR HT LL_RTC_ALMA_GetHour\n
* ALRMAR HU LL_RTC_ALMA_GetHour
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetHour(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->ALRMAR, (RTC_ALRMAR_HT | RTC_ALRMAR_HU));
return (uint32_t)((((temp & RTC_ALRMAR_HT) >> RTC_ALRMAR_HT_Pos) << 4U) | ((temp & RTC_ALRMAR_HU) >> RTC_ALRMAR_HU_Pos));
}
/**
* @brief Set ALARM A Minutes in BCD format
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Minutes from binary to BCD format
* @rmtoll ALRMAR MNT LL_RTC_ALMA_SetMinute\n
* ALRMAR MNU LL_RTC_ALMA_SetMinute
* @param RTCx RTC Instance
* @param Minutes Value between Min_Data=0x00 and Max_Data=0x59
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes)
{
MODIFY_REG(RTCx->ALRMAR, (RTC_ALRMAR_MNT | RTC_ALRMAR_MNU),
(((Minutes & 0xF0U) << (RTC_ALRMAR_MNT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_ALRMAR_MNU_Pos)));
}
/**
* @brief Get ALARM A Minutes in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Minutes from BCD to Binary format
* @rmtoll ALRMAR MNT LL_RTC_ALMA_GetMinute\n
* ALRMAR MNU LL_RTC_ALMA_GetMinute
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0x59
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetMinute(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->ALRMAR, (RTC_ALRMAR_MNT | RTC_ALRMAR_MNU));
return (uint32_t)((((temp & RTC_ALRMAR_MNT) >> RTC_ALRMAR_MNT_Pos) << 4U) | ((temp & RTC_ALRMAR_MNU) >> RTC_ALRMAR_MNU_Pos));
}
/**
* @brief Set ALARM A Seconds in BCD format
* @note helper macro __LL_RTC_CONVERT_BIN2BCD is available to convert Seconds from binary to BCD format
* @rmtoll ALRMAR ST LL_RTC_ALMA_SetSecond\n
* ALRMAR SU LL_RTC_ALMA_SetSecond
* @param RTCx RTC Instance
* @param Seconds Value between Min_Data=0x00 and Max_Data=0x59
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds)
{
MODIFY_REG(RTCx->ALRMAR, (RTC_ALRMAR_ST | RTC_ALRMAR_SU),
(((Seconds & 0xF0U) << (RTC_ALRMAR_ST_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_ALRMAR_SU_Pos)));
}
/**
* @brief Get ALARM A Seconds in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Seconds from BCD to Binary format
* @rmtoll ALRMAR ST LL_RTC_ALMA_GetSecond\n
* ALRMAR SU LL_RTC_ALMA_GetSecond
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0x59
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSecond(RTC_TypeDef *RTCx)
{
register uint32_t temp = 0U;
temp = READ_BIT(RTCx->ALRMAR, (RTC_ALRMAR_ST | RTC_ALRMAR_SU));
return (uint32_t)((((temp & RTC_ALRMAR_ST) >> RTC_ALRMAR_ST_Pos) << 4U) | ((temp & RTC_ALRMAR_SU) >> RTC_ALRMAR_SU_Pos));
}
/**
* @brief Set Alarm A Time (hour, minute and second) in BCD format
* @rmtoll ALRMAR PM LL_RTC_ALMA_ConfigTime\n
* ALRMAR HT LL_RTC_ALMA_ConfigTime\n
* ALRMAR HU LL_RTC_ALMA_ConfigTime\n
* ALRMAR MNT LL_RTC_ALMA_ConfigTime\n
* ALRMAR MNU LL_RTC_ALMA_ConfigTime\n
* ALRMAR ST LL_RTC_ALMA_ConfigTime\n
* ALRMAR SU LL_RTC_ALMA_ConfigTime
* @param RTCx RTC Instance
* @param Format12_24 This parameter can be one of the following values:
* @arg @ref LL_RTC_ALMA_TIME_FORMAT_AM
* @arg @ref LL_RTC_ALMA_TIME_FORMAT_PM
* @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23
* @param Minutes Value between Min_Data=0x00 and Max_Data=0x59
* @param Seconds Value between Min_Data=0x00 and Max_Data=0x59
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_ConfigTime(RTC_TypeDef *RTCx, uint32_t Format12_24, uint32_t Hours, uint32_t Minutes, uint32_t Seconds)
{
register uint32_t temp = 0U;
temp = Format12_24 | (((Hours & 0xF0U) << (RTC_ALRMAR_HT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_ALRMAR_HU_Pos)) | \
(((Minutes & 0xF0U) << (RTC_ALRMAR_MNT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_ALRMAR_MNU_Pos)) | \
(((Seconds & 0xF0U) << (RTC_ALRMAR_ST_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_ALRMAR_SU_Pos));
MODIFY_REG(RTCx->ALRMAR, RTC_ALRMAR_PM | RTC_ALRMAR_HT | RTC_ALRMAR_HU | RTC_ALRMAR_MNT | RTC_ALRMAR_MNU | RTC_ALRMAR_ST | RTC_ALRMAR_SU, temp);
}
/**
* @brief Get Alarm B Time (hour, minute and second) in BCD format
* @note helper macros __LL_RTC_GET_HOUR, __LL_RTC_GET_MINUTE and __LL_RTC_GET_SECOND
* are available to get independently each parameter.
* @rmtoll ALRMAR HT LL_RTC_ALMA_GetTime\n
* ALRMAR HU LL_RTC_ALMA_GetTime\n
* ALRMAR MNT LL_RTC_ALMA_GetTime\n
* ALRMAR MNU LL_RTC_ALMA_GetTime\n
* ALRMAR ST LL_RTC_ALMA_GetTime\n
* ALRMAR SU LL_RTC_ALMA_GetTime
* @param RTCx RTC Instance
* @retval Combination of hours, minutes and seconds.
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetTime(RTC_TypeDef *RTCx)
{
return (uint32_t)((LL_RTC_ALMA_GetHour(RTCx) << RTC_OFFSET_HOUR) | (LL_RTC_ALMA_GetMinute(RTCx) << RTC_OFFSET_MINUTE) | LL_RTC_ALMA_GetSecond(RTCx));
}
/**
* @brief Set Alarm A Mask the most-significant bits starting at this bit
* @note This register can be written only when ALRAE is reset in RTC_CR register,
* or in initialization mode.
* @rmtoll ALRMASSR MASKSS LL_RTC_ALMA_SetSubSecondMask
* @param RTCx RTC Instance
* @param Mask Value between Min_Data=0x00 and Max_Data=0xF
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetSubSecondMask(RTC_TypeDef *RTCx, uint32_t Mask)
{
MODIFY_REG(RTCx->ALRMASSR, RTC_ALRMASSR_MASKSS, Mask << RTC_ALRMASSR_MASKSS_Pos);
}
/**
* @brief Get Alarm A Mask the most-significant bits starting at this bit
* @rmtoll ALRMASSR MASKSS LL_RTC_ALMA_GetSubSecondMask
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0xF
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSubSecondMask(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->ALRMASSR, RTC_ALRMASSR_MASKSS) >> RTC_ALRMASSR_MASKSS_Pos);
}
/**
* @brief Set Alarm A Sub seconds value
* @rmtoll ALRMASSR SS LL_RTC_ALMA_SetSubSecond
* @param RTCx RTC Instance
* @param Subsecond Value between Min_Data=0x00 and Max_Data=0x7FFF
* @retval None
*/
__STATIC_INLINE void LL_RTC_ALMA_SetSubSecond(RTC_TypeDef *RTCx, uint32_t Subsecond)
{
MODIFY_REG(RTCx->ALRMASSR, RTC_ALRMASSR_SS, Subsecond);
}
/**
* @brief Get Alarm A Sub seconds value
* @rmtoll ALRMASSR SS LL_RTC_ALMA_GetSubSecond
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0x7FFF
*/
__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSubSecond(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->ALRMASSR, RTC_ALRMASSR_SS));
}
/**
* @}
*/
/** @defgroup RTC_LL_EF_Timestamp Timestamp
* @{
*/
/**
* @brief Enable Timestamp
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR TSE LL_RTC_TS_Enable
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TS_Enable(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_TSE);
}
/**
* @brief Disable Timestamp
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR TSE LL_RTC_TS_Disable
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TS_Disable(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_TSE);
}
/**
* @brief Set Time-stamp event active edge
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note TSE must be reset when TSEDGE is changed to avoid unwanted TSF setting
* @rmtoll CR TSEDGE LL_RTC_TS_SetActiveEdge
* @param RTCx RTC Instance
* @param Edge This parameter can be one of the following values:
* @arg @ref LL_RTC_TIMESTAMP_EDGE_RISING
* @arg @ref LL_RTC_TIMESTAMP_EDGE_FALLING
* @retval None
*/
__STATIC_INLINE void LL_RTC_TS_SetActiveEdge(RTC_TypeDef *RTCx, uint32_t Edge)
{
MODIFY_REG(RTCx->CR, RTC_CR_TSEDGE, Edge);
}
/**
* @brief Get Time-stamp event active edge
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR TSEDGE LL_RTC_TS_GetActiveEdge
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_TIMESTAMP_EDGE_RISING
* @arg @ref LL_RTC_TIMESTAMP_EDGE_FALLING
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetActiveEdge(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_TSEDGE));
}
/**
* @brief Get Timestamp AM/PM notation (AM or 24-hour format)
* @rmtoll TSTR PM LL_RTC_TS_GetTimeFormat
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_TS_TIME_FORMAT_AM
* @arg @ref LL_RTC_TS_TIME_FORMAT_PM
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetTimeFormat(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_PM));
}
/**
* @brief Get Timestamp Hours in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Hours from BCD to Binary format
* @rmtoll TSTR HT LL_RTC_TS_GetHour\n
* TSTR HU LL_RTC_TS_GetHour
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetHour(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_HT | RTC_TSTR_HU) >> RTC_TSTR_HU_Pos);
}
/**
* @brief Get Timestamp Minutes in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Minutes from BCD to Binary format
* @rmtoll TSTR MNT LL_RTC_TS_GetMinute\n
* TSTR MNU LL_RTC_TS_GetMinute
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0x59
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetMinute(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_MNT | RTC_TSTR_MNU) >> RTC_TSTR_MNU_Pos);
}
/**
* @brief Get Timestamp Seconds in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Seconds from BCD to Binary format
* @rmtoll TSTR ST LL_RTC_TS_GetSecond\n
* TSTR SU LL_RTC_TS_GetSecond
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0x59
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetSecond(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_ST | RTC_TSTR_SU));
}
/**
* @brief Get Timestamp time (hour, minute and second) in BCD format
* @note helper macros __LL_RTC_GET_HOUR, __LL_RTC_GET_MINUTE and __LL_RTC_GET_SECOND
* are available to get independently each parameter.
* @rmtoll TSTR HT LL_RTC_TS_GetTime\n
* TSTR HU LL_RTC_TS_GetTime\n
* TSTR MNT LL_RTC_TS_GetTime\n
* TSTR MNU LL_RTC_TS_GetTime\n
* TSTR ST LL_RTC_TS_GetTime\n
* TSTR SU LL_RTC_TS_GetTime
* @param RTCx RTC Instance
* @retval Combination of hours, minutes and seconds.
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetTime(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSTR,
RTC_TSTR_HT | RTC_TSTR_HU | RTC_TSTR_MNT | RTC_TSTR_MNU | RTC_TSTR_ST | RTC_TSTR_SU));
}
/**
* @brief Get Timestamp Week day
* @rmtoll TSDR WDU LL_RTC_TS_GetWeekDay
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_WEEKDAY_MONDAY
* @arg @ref LL_RTC_WEEKDAY_TUESDAY
* @arg @ref LL_RTC_WEEKDAY_WEDNESDAY
* @arg @ref LL_RTC_WEEKDAY_THURSDAY
* @arg @ref LL_RTC_WEEKDAY_FRIDAY
* @arg @ref LL_RTC_WEEKDAY_SATURDAY
* @arg @ref LL_RTC_WEEKDAY_SUNDAY
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetWeekDay(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSDR, RTC_TSDR_WDU) >> RTC_TSDR_WDU_Pos);
}
/**
* @brief Get Timestamp Month in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Month from BCD to Binary format
* @rmtoll TSDR MT LL_RTC_TS_GetMonth\n
* TSDR MU LL_RTC_TS_GetMonth
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_MONTH_JANUARY
* @arg @ref LL_RTC_MONTH_FEBRUARY
* @arg @ref LL_RTC_MONTH_MARCH
* @arg @ref LL_RTC_MONTH_APRIL
* @arg @ref LL_RTC_MONTH_MAY
* @arg @ref LL_RTC_MONTH_JUNE
* @arg @ref LL_RTC_MONTH_JULY
* @arg @ref LL_RTC_MONTH_AUGUST
* @arg @ref LL_RTC_MONTH_SEPTEMBER
* @arg @ref LL_RTC_MONTH_OCTOBER
* @arg @ref LL_RTC_MONTH_NOVEMBER
* @arg @ref LL_RTC_MONTH_DECEMBER
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetMonth(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSDR, RTC_TSDR_MT | RTC_TSDR_MU) >> RTC_TSDR_MU_Pos);
}
/**
* @brief Get Timestamp Day in BCD format
* @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format
* @rmtoll TSDR DT LL_RTC_TS_GetDay\n
* TSDR DU LL_RTC_TS_GetDay
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x01 and Max_Data=0x31
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetDay(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSDR, RTC_TSDR_DT | RTC_TSDR_DU));
}
/**
* @brief Get Timestamp date (WeekDay, Day and Month) in BCD format
* @note helper macros __LL_RTC_GET_WEEKDAY, __LL_RTC_GET_MONTH,
* and __LL_RTC_GET_DAY are available to get independently each parameter.
* @rmtoll TSDR WDU LL_RTC_TS_GetDate\n
* TSDR MT LL_RTC_TS_GetDate\n
* TSDR MU LL_RTC_TS_GetDate\n
* TSDR DT LL_RTC_TS_GetDate\n
* TSDR DU LL_RTC_TS_GetDate
* @param RTCx RTC Instance
* @retval Combination of Weekday, Day and Month
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetDate(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSDR, RTC_TSDR_WDU | RTC_TSDR_MT | RTC_TSDR_MU | RTC_TSDR_DT | RTC_TSDR_DU));
}
/**
* @brief Get time-stamp sub second value
* @rmtoll TSSSR SS LL_RTC_TS_GetSubSecond
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0xFFFF
*/
__STATIC_INLINE uint32_t LL_RTC_TS_GetSubSecond(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TSSSR, RTC_TSSSR_SS));
}
#if defined(RTC_TAFCR_TAMPTS)
/**
* @brief Activate timestamp on tamper detection event
* @rmtoll TAFCR TAMPTS LL_RTC_TS_EnableOnTamper
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TS_EnableOnTamper(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPTS);
}
/**
* @brief Disable timestamp on tamper detection event
* @rmtoll TAFCR TAMPTS LL_RTC_TS_DisableOnTamper
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TS_DisableOnTamper(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPTS);
}
#endif /* RTC_TAFCR_TAMPTS */
/**
* @}
*/
/** @defgroup RTC_LL_EF_Tamper Tamper
* @{
*/
/**
* @brief Enable RTC_TAMPx input detection
* @rmtoll TAFCR TAMP1E LL_RTC_TAMPER_Enable\n
* TAFCR TAMP2E LL_RTC_TAMPER_Enable\n
* TAFCR TAMP3E LL_RTC_TAMPER_Enable
* @param RTCx RTC Instance
* @param Tamper This parameter can be a combination of the following values:
* @arg @ref LL_RTC_TAMPER_1
* @arg @ref LL_RTC_TAMPER_2
* @arg @ref LL_RTC_TAMPER_3 (*)
*
* (*) value not defined in all devices.
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_Enable(RTC_TypeDef *RTCx, uint32_t Tamper)
{
SET_BIT(RTCx->TAFCR, Tamper);
}
/**
* @brief Clear RTC_TAMPx input detection
* @rmtoll TAFCR TAMP1E LL_RTC_TAMPER_Disable\n
* TAFCR TAMP2E LL_RTC_TAMPER_Disable\n
* TAFCR TAMP3E LL_RTC_TAMPER_Disable
* @param RTCx RTC Instance
* @param Tamper This parameter can be a combination of the following values:
* @arg @ref LL_RTC_TAMPER_1
* @arg @ref LL_RTC_TAMPER_2
* @arg @ref LL_RTC_TAMPER_3 (*)
*
* (*) value not defined in all devices.
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_Disable(RTC_TypeDef *RTCx, uint32_t Tamper)
{
CLEAR_BIT(RTCx->TAFCR, Tamper);
}
#if defined(RTC_TAFCR_TAMPPUDIS)
/**
* @brief Disable RTC_TAMPx pull-up disable (Disable precharge of RTC_TAMPx pins)
* @rmtoll TAFCR TAMPPUDIS LL_RTC_TAMPER_DisablePullUp
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_DisablePullUp(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPPUDIS);
}
/**
* @brief Enable RTC_TAMPx pull-up disable ( Precharge RTC_TAMPx pins before sampling)
* @rmtoll TAFCR TAMPPUDIS LL_RTC_TAMPER_EnablePullUp
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_EnablePullUp(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPPUDIS);
}
#endif /* RTC_TAFCR_TAMPPUDIS */
#if defined(RTC_TAFCR_TAMPPRCH)
/**
* @brief Set RTC_TAMPx precharge duration
* @rmtoll TAFCR TAMPPRCH LL_RTC_TAMPER_SetPrecharge
* @param RTCx RTC Instance
* @param Duration This parameter can be one of the following values:
* @arg @ref LL_RTC_TAMPER_DURATION_1RTCCLK
* @arg @ref LL_RTC_TAMPER_DURATION_2RTCCLK
* @arg @ref LL_RTC_TAMPER_DURATION_4RTCCLK
* @arg @ref LL_RTC_TAMPER_DURATION_8RTCCLK
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_SetPrecharge(RTC_TypeDef *RTCx, uint32_t Duration)
{
MODIFY_REG(RTCx->TAFCR, RTC_TAFCR_TAMPPRCH, Duration);
}
/**
* @brief Get RTC_TAMPx precharge duration
* @rmtoll TAFCR TAMPPRCH LL_RTC_TAMPER_GetPrecharge
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_TAMPER_DURATION_1RTCCLK
* @arg @ref LL_RTC_TAMPER_DURATION_2RTCCLK
* @arg @ref LL_RTC_TAMPER_DURATION_4RTCCLK
* @arg @ref LL_RTC_TAMPER_DURATION_8RTCCLK
*/
__STATIC_INLINE uint32_t LL_RTC_TAMPER_GetPrecharge(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPPRCH));
}
#endif /* RTC_TAFCR_TAMPPRCH */
#if defined(RTC_TAFCR_TAMPFLT)
/**
* @brief Set RTC_TAMPx filter count
* @rmtoll TAFCR TAMPFLT LL_RTC_TAMPER_SetFilterCount
* @param RTCx RTC Instance
* @param FilterCount This parameter can be one of the following values:
* @arg @ref LL_RTC_TAMPER_FILTER_DISABLE
* @arg @ref LL_RTC_TAMPER_FILTER_2SAMPLE
* @arg @ref LL_RTC_TAMPER_FILTER_4SAMPLE
* @arg @ref LL_RTC_TAMPER_FILTER_8SAMPLE
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_SetFilterCount(RTC_TypeDef *RTCx, uint32_t FilterCount)
{
MODIFY_REG(RTCx->TAFCR, RTC_TAFCR_TAMPFLT, FilterCount);
}
/**
* @brief Get RTC_TAMPx filter count
* @rmtoll TAFCR TAMPFLT LL_RTC_TAMPER_GetFilterCount
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_TAMPER_FILTER_DISABLE
* @arg @ref LL_RTC_TAMPER_FILTER_2SAMPLE
* @arg @ref LL_RTC_TAMPER_FILTER_4SAMPLE
* @arg @ref LL_RTC_TAMPER_FILTER_8SAMPLE
*/
__STATIC_INLINE uint32_t LL_RTC_TAMPER_GetFilterCount(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPFLT));
}
#endif /* RTC_TAFCR_TAMPFLT */
#if defined(RTC_TAFCR_TAMPFREQ)
/**
* @brief Set Tamper sampling frequency
* @rmtoll TAFCR TAMPFREQ LL_RTC_TAMPER_SetSamplingFreq
* @param RTCx RTC Instance
* @param SamplingFreq This parameter can be one of the following values:
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_32768
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_16384
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_8192
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_4096
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_2048
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_1024
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_512
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_256
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_SetSamplingFreq(RTC_TypeDef *RTCx, uint32_t SamplingFreq)
{
MODIFY_REG(RTCx->TAFCR, RTC_TAFCR_TAMPFREQ, SamplingFreq);
}
/**
* @brief Get Tamper sampling frequency
* @rmtoll TAFCR TAMPFREQ LL_RTC_TAMPER_GetSamplingFreq
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_32768
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_16384
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_8192
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_4096
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_2048
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_1024
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_512
* @arg @ref LL_RTC_TAMPER_SAMPLFREQDIV_256
*/
__STATIC_INLINE uint32_t LL_RTC_TAMPER_GetSamplingFreq(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPFREQ));
}
#endif /* RTC_TAFCR_TAMPFREQ */
/**
* @brief Enable Active level for Tamper input
* @rmtoll TAFCR TAMP1TRG LL_RTC_TAMPER_EnableActiveLevel\n
* TAFCR TAMP2TRG LL_RTC_TAMPER_EnableActiveLevel\n
* TAFCR TAMP3TRG LL_RTC_TAMPER_EnableActiveLevel
* @param RTCx RTC Instance
* @param Tamper This parameter can be a combination of the following values:
* @arg @ref LL_RTC_TAMPER_ACTIVELEVEL_TAMP1
* @arg @ref LL_RTC_TAMPER_ACTIVELEVEL_TAMP2
* @arg @ref LL_RTC_TAMPER_ACTIVELEVEL_TAMP3 (*)
*
* (*) value not defined in all devices.
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_EnableActiveLevel(RTC_TypeDef *RTCx, uint32_t Tamper)
{
SET_BIT(RTCx->TAFCR, Tamper);
}
/**
* @brief Disable Active level for Tamper input
* @rmtoll TAFCR TAMP1TRG LL_RTC_TAMPER_DisableActiveLevel\n
* TAFCR TAMP2TRG LL_RTC_TAMPER_DisableActiveLevel\n
* TAFCR TAMP3TRG LL_RTC_TAMPER_DisableActiveLevel
* @param RTCx RTC Instance
* @param Tamper This parameter can be a combination of the following values:
* @arg @ref LL_RTC_TAMPER_ACTIVELEVEL_TAMP1
* @arg @ref LL_RTC_TAMPER_ACTIVELEVEL_TAMP2
* @arg @ref LL_RTC_TAMPER_ACTIVELEVEL_TAMP3 (*)
*
* (*) value not defined in all devices.
* @retval None
*/
__STATIC_INLINE void LL_RTC_TAMPER_DisableActiveLevel(RTC_TypeDef *RTCx, uint32_t Tamper)
{
CLEAR_BIT(RTCx->TAFCR, Tamper);
}
/**
* @}
*/
#if defined(RTC_WAKEUP_SUPPORT)
/** @defgroup RTC_LL_EF_Wakeup Wakeup
* @{
*/
/**
* @brief Enable Wakeup timer
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR WUTE LL_RTC_WAKEUP_Enable
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_WAKEUP_Enable(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_WUTE);
}
/**
* @brief Disable Wakeup timer
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR WUTE LL_RTC_WAKEUP_Disable
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_WAKEUP_Disable(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_WUTE);
}
/**
* @brief Check if Wakeup timer is enabled or not
* @rmtoll CR WUTE LL_RTC_WAKEUP_IsEnabled
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_WAKEUP_IsEnabled(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->CR, RTC_CR_WUTE) == (RTC_CR_WUTE));
}
/**
* @brief Select Wakeup clock
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note Bit can be written only when RTC_CR WUTE bit = 0 and RTC_ISR WUTWF bit = 1
* @rmtoll CR WUCKSEL LL_RTC_WAKEUP_SetClock
* @param RTCx RTC Instance
* @param WakeupClock This parameter can be one of the following values:
* @arg @ref LL_RTC_WAKEUPCLOCK_DIV_16
* @arg @ref LL_RTC_WAKEUPCLOCK_DIV_8
* @arg @ref LL_RTC_WAKEUPCLOCK_DIV_4
* @arg @ref LL_RTC_WAKEUPCLOCK_DIV_2
* @arg @ref LL_RTC_WAKEUPCLOCK_CKSPRE
* @arg @ref LL_RTC_WAKEUPCLOCK_CKSPRE_WUT
* @retval None
*/
__STATIC_INLINE void LL_RTC_WAKEUP_SetClock(RTC_TypeDef *RTCx, uint32_t WakeupClock)
{
MODIFY_REG(RTCx->CR, RTC_CR_WUCKSEL, WakeupClock);
}
/**
* @brief Get Wakeup clock
* @rmtoll CR WUCKSEL LL_RTC_WAKEUP_GetClock
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_WAKEUPCLOCK_DIV_16
* @arg @ref LL_RTC_WAKEUPCLOCK_DIV_8
* @arg @ref LL_RTC_WAKEUPCLOCK_DIV_4
* @arg @ref LL_RTC_WAKEUPCLOCK_DIV_2
* @arg @ref LL_RTC_WAKEUPCLOCK_CKSPRE
* @arg @ref LL_RTC_WAKEUPCLOCK_CKSPRE_WUT
*/
__STATIC_INLINE uint32_t LL_RTC_WAKEUP_GetClock(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_WUCKSEL));
}
/**
* @brief Set Wakeup auto-reload value
* @note Bit can be written only when WUTWF is set to 1 in RTC_ISR
* @rmtoll WUTR WUT LL_RTC_WAKEUP_SetAutoReload
* @param RTCx RTC Instance
* @param Value Value between Min_Data=0x00 and Max_Data=0xFFFF
* @retval None
*/
__STATIC_INLINE void LL_RTC_WAKEUP_SetAutoReload(RTC_TypeDef *RTCx, uint32_t Value)
{
MODIFY_REG(RTCx->WUTR, RTC_WUTR_WUT, Value);
}
/**
* @brief Get Wakeup auto-reload value
* @rmtoll WUTR WUT LL_RTC_WAKEUP_GetAutoReload
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data=0xFFFF
*/
__STATIC_INLINE uint32_t LL_RTC_WAKEUP_GetAutoReload(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->WUTR, RTC_WUTR_WUT));
}
/**
* @}
*/
#endif /* RTC_WAKEUP_SUPPORT */
#if defined(RTC_BACKUP_SUPPORT)
/** @defgroup RTC_LL_EF_Backup_Registers Backup_Registers
* @{
*/
/**
* @brief Writes a data in a specified RTC Backup data register.
* @rmtoll BKPxR BKP LL_RTC_BAK_SetRegister
* @param RTCx RTC Instance
* @param BackupRegister This parameter can be one of the following values:
* @arg @ref LL_RTC_BKP_DR0
* @arg @ref LL_RTC_BKP_DR1
* @arg @ref LL_RTC_BKP_DR2
* @arg @ref LL_RTC_BKP_DR3
* @arg @ref LL_RTC_BKP_DR4
* @param Data Value between Min_Data=0x00 and Max_Data=0xFFFFFFFF
* @retval None
*/
__STATIC_INLINE void LL_RTC_BAK_SetRegister(RTC_TypeDef *RTCx, uint32_t BackupRegister, uint32_t Data)
{
register uint32_t tmp = 0U;
tmp = (uint32_t)(&(RTCx->BKP0R));
tmp += (BackupRegister * 4U);
/* Write the specified register */
*(__IO uint32_t *)tmp = (uint32_t)Data;
}
/**
* @brief Reads data from the specified RTC Backup data Register.
* @rmtoll BKPxR BKP LL_RTC_BAK_GetRegister
* @param RTCx RTC Instance
* @param BackupRegister This parameter can be one of the following values:
* @arg @ref LL_RTC_BKP_DR0
* @arg @ref LL_RTC_BKP_DR1
* @arg @ref LL_RTC_BKP_DR2
* @arg @ref LL_RTC_BKP_DR3
* @arg @ref LL_RTC_BKP_DR4
* @retval Value between Min_Data=0x00 and Max_Data=0xFFFFFFFF
*/
__STATIC_INLINE uint32_t LL_RTC_BAK_GetRegister(RTC_TypeDef *RTCx, uint32_t BackupRegister)
{
register uint32_t tmp = 0U;
tmp = (uint32_t)(&(RTCx->BKP0R));
tmp += (BackupRegister * 4U);
/* Read the specified register */
return (*(__IO uint32_t *)tmp);
}
/**
* @}
*/
#endif /* RTC_BACKUP_SUPPORT */
/** @defgroup RTC_LL_EF_Calibration Calibration
* @{
*/
/**
* @brief Set Calibration output frequency (1 Hz or 512 Hz)
* @note Bits are write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR COE LL_RTC_CAL_SetOutputFreq\n
* CR COSEL LL_RTC_CAL_SetOutputFreq
* @param RTCx RTC Instance
* @param Frequency This parameter can be one of the following values:
* @arg @ref LL_RTC_CALIB_OUTPUT_NONE
* @arg @ref LL_RTC_CALIB_OUTPUT_1HZ
* @arg @ref LL_RTC_CALIB_OUTPUT_512HZ
* @retval None
*/
__STATIC_INLINE void LL_RTC_CAL_SetOutputFreq(RTC_TypeDef *RTCx, uint32_t Frequency)
{
MODIFY_REG(RTCx->CR, RTC_CR_COE | RTC_CR_COSEL, Frequency);
}
/**
* @brief Get Calibration output frequency (1 Hz or 512 Hz)
* @rmtoll CR COE LL_RTC_CAL_GetOutputFreq\n
* CR COSEL LL_RTC_CAL_GetOutputFreq
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_CALIB_OUTPUT_NONE
* @arg @ref LL_RTC_CALIB_OUTPUT_1HZ
* @arg @ref LL_RTC_CALIB_OUTPUT_512HZ
*/
__STATIC_INLINE uint32_t LL_RTC_CAL_GetOutputFreq(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_COE | RTC_CR_COSEL));
}
/**
* @brief Insert or not One RTCCLK pulse every 2exp11 pulses (frequency increased by 488.5 ppm)
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note Bit can be written only when RECALPF is set to 0 in RTC_ISR
* @rmtoll CALR CALP LL_RTC_CAL_SetPulse
* @param RTCx RTC Instance
* @param Pulse This parameter can be one of the following values:
* @arg @ref LL_RTC_CALIB_INSERTPULSE_NONE
* @arg @ref LL_RTC_CALIB_INSERTPULSE_SET
* @retval None
*/
__STATIC_INLINE void LL_RTC_CAL_SetPulse(RTC_TypeDef *RTCx, uint32_t Pulse)
{
MODIFY_REG(RTCx->CALR, RTC_CALR_CALP, Pulse);
}
/**
* @brief Check if one RTCCLK has been inserted or not every 2exp11 pulses (frequency increased by 488.5 ppm)
* @rmtoll CALR CALP LL_RTC_CAL_IsPulseInserted
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_CAL_IsPulseInserted(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->CALR, RTC_CALR_CALP) == (RTC_CALR_CALP));
}
/**
* @brief Set the calibration cycle period
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note Bit can be written only when RECALPF is set to 0 in RTC_ISR
* @rmtoll CALR CALW8 LL_RTC_CAL_SetPeriod\n
* CALR CALW16 LL_RTC_CAL_SetPeriod
* @param RTCx RTC Instance
* @param Period This parameter can be one of the following values:
* @arg @ref LL_RTC_CALIB_PERIOD_32SEC
* @arg @ref LL_RTC_CALIB_PERIOD_16SEC
* @arg @ref LL_RTC_CALIB_PERIOD_8SEC
* @retval None
*/
__STATIC_INLINE void LL_RTC_CAL_SetPeriod(RTC_TypeDef *RTCx, uint32_t Period)
{
MODIFY_REG(RTCx->CALR, RTC_CALR_CALW8 | RTC_CALR_CALW16, Period);
}
/**
* @brief Get the calibration cycle period
* @rmtoll CALR CALW8 LL_RTC_CAL_GetPeriod\n
* CALR CALW16 LL_RTC_CAL_GetPeriod
* @param RTCx RTC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_RTC_CALIB_PERIOD_32SEC
* @arg @ref LL_RTC_CALIB_PERIOD_16SEC
* @arg @ref LL_RTC_CALIB_PERIOD_8SEC
*/
__STATIC_INLINE uint32_t LL_RTC_CAL_GetPeriod(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->CALR, RTC_CALR_CALW8 | RTC_CALR_CALW16));
}
/**
* @brief Set Calibration minus
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @note Bit can be written only when RECALPF is set to 0 in RTC_ISR
* @rmtoll CALR CALM LL_RTC_CAL_SetMinus
* @param RTCx RTC Instance
* @param CalibMinus Value between Min_Data=0x00 and Max_Data=0x1FF
* @retval None
*/
__STATIC_INLINE void LL_RTC_CAL_SetMinus(RTC_TypeDef *RTCx, uint32_t CalibMinus)
{
MODIFY_REG(RTCx->CALR, RTC_CALR_CALM, CalibMinus);
}
/**
* @brief Get Calibration minus
* @rmtoll CALR CALM LL_RTC_CAL_GetMinus
* @param RTCx RTC Instance
* @retval Value between Min_Data=0x00 and Max_Data= 0x1FF
*/
__STATIC_INLINE uint32_t LL_RTC_CAL_GetMinus(RTC_TypeDef *RTCx)
{
return (uint32_t)(READ_BIT(RTCx->CALR, RTC_CALR_CALM));
}
/**
* @}
*/
/** @defgroup RTC_LL_EF_FLAG_Management FLAG_Management
* @{
*/
/**
* @brief Get Recalibration pending Flag
* @rmtoll ISR RECALPF LL_RTC_IsActiveFlag_RECALP
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RECALP(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_RECALPF) == (RTC_ISR_RECALPF));
}
#if defined(RTC_TAMPER3_SUPPORT)
/**
* @brief Get RTC_TAMP3 detection flag
* @rmtoll ISR TAMP3F LL_RTC_IsActiveFlag_TAMP3
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TAMP3(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_TAMP3F) == (RTC_ISR_TAMP3F));
}
#endif /* RTC_TAMPER3_SUPPORT */
#if defined(RTC_TAMPER2_SUPPORT)
/**
* @brief Get RTC_TAMP2 detection flag
* @rmtoll ISR TAMP2F LL_RTC_IsActiveFlag_TAMP2
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TAMP2(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_TAMP2F) == (RTC_ISR_TAMP2F));
}
#endif /* RTC_TAMPER2_SUPPORT */
#if defined(RTC_TAMPER1_SUPPORT)
/**
* @brief Get RTC_TAMP1 detection flag
* @rmtoll ISR TAMP1F LL_RTC_IsActiveFlag_TAMP1
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TAMP1(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_TAMP1F) == (RTC_ISR_TAMP1F));
}
#endif /* RTC_TAMPER1_SUPPORT */
/**
* @brief Get Time-stamp overflow flag
* @rmtoll ISR TSOVF LL_RTC_IsActiveFlag_TSOV
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSOV(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_TSOVF) == (RTC_ISR_TSOVF));
}
/**
* @brief Get Time-stamp flag
* @rmtoll ISR TSF LL_RTC_IsActiveFlag_TS
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TS(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_TSF) == (RTC_ISR_TSF));
}
#if defined(RTC_WAKEUP_SUPPORT)
/**
* @brief Get Wakeup timer flag
* @rmtoll ISR WUTF LL_RTC_IsActiveFlag_WUT
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_WUT(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_WUTF) == (RTC_ISR_WUTF));
}
#endif /* RTC_WAKEUP_SUPPORT */
/**
* @brief Get Alarm A flag
* @rmtoll ISR ALRAF LL_RTC_IsActiveFlag_ALRA
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRA(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_ALRAF) == (RTC_ISR_ALRAF));
}
#if defined(RTC_TAMPER3_SUPPORT)
/**
* @brief Clear RTC_TAMP3 detection flag
* @rmtoll ISR TAMP3F LL_RTC_ClearFlag_TAMP3
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ClearFlag_TAMP3(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->ISR, (~((RTC_ISR_TAMP3F | RTC_ISR_INIT) & 0x0000FFFFU) | (RTCx->ISR & RTC_ISR_INIT)));
}
#endif /* RTC_TAMPER3_SUPPORT */
#if defined(RTC_TAMPER2_SUPPORT)
/**
* @brief Clear RTC_TAMP2 detection flag
* @rmtoll ISR TAMP2F LL_RTC_ClearFlag_TAMP2
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ClearFlag_TAMP2(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->ISR, (~((RTC_ISR_TAMP2F | RTC_ISR_INIT) & 0x0000FFFFU) | (RTCx->ISR & RTC_ISR_INIT)));
}
#endif /* RTC_TAMPER2_SUPPORT */
#if defined(RTC_TAMPER1_SUPPORT)
/**
* @brief Clear RTC_TAMP1 detection flag
* @rmtoll ISR TAMP1F LL_RTC_ClearFlag_TAMP1
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ClearFlag_TAMP1(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->ISR, (~((RTC_ISR_TAMP1F | RTC_ISR_INIT) & 0x0000FFFFU) | (RTCx->ISR & RTC_ISR_INIT)));
}
#endif /* RTC_TAMPER1_SUPPORT */
/**
* @brief Clear Time-stamp overflow flag
* @rmtoll ISR TSOVF LL_RTC_ClearFlag_TSOV
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ClearFlag_TSOV(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->ISR, (~((RTC_ISR_TSOVF | RTC_ISR_INIT) & 0x0000FFFFU) | (RTCx->ISR & RTC_ISR_INIT)));
}
/**
* @brief Clear Time-stamp flag
* @rmtoll ISR TSF LL_RTC_ClearFlag_TS
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ClearFlag_TS(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->ISR, (~((RTC_ISR_TSF | RTC_ISR_INIT) & 0x0000FFFFU) | (RTCx->ISR & RTC_ISR_INIT)));
}
#if defined(RTC_WAKEUP_SUPPORT)
/**
* @brief Clear Wakeup timer flag
* @rmtoll ISR WUTF LL_RTC_ClearFlag_WUT
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ClearFlag_WUT(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->ISR, (~((RTC_ISR_WUTF | RTC_ISR_INIT) & 0x0000FFFFU) | (RTCx->ISR & RTC_ISR_INIT)));
}
#endif /* RTC_WAKEUP_SUPPORT */
/**
* @brief Clear Alarm A flag
* @rmtoll ISR ALRAF LL_RTC_ClearFlag_ALRA
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ClearFlag_ALRA(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->ISR, (~((RTC_ISR_ALRAF | RTC_ISR_INIT) & 0x0000FFFFU) | (RTCx->ISR & RTC_ISR_INIT)));
}
/**
* @brief Get Initialization flag
* @rmtoll ISR INITF LL_RTC_IsActiveFlag_INIT
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_INIT(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_INITF) == (RTC_ISR_INITF));
}
/**
* @brief Get Registers synchronization flag
* @rmtoll ISR RSF LL_RTC_IsActiveFlag_RS
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RS(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_RSF) == (RTC_ISR_RSF));
}
/**
* @brief Clear Registers synchronization flag
* @rmtoll ISR RSF LL_RTC_ClearFlag_RS
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_ClearFlag_RS(RTC_TypeDef *RTCx)
{
WRITE_REG(RTCx->ISR, (~((RTC_ISR_RSF | RTC_ISR_INIT) & 0x0000FFFFU) | (RTCx->ISR & RTC_ISR_INIT)));
}
/**
* @brief Get Initialization status flag
* @rmtoll ISR INITS LL_RTC_IsActiveFlag_INITS
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_INITS(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_INITS) == (RTC_ISR_INITS));
}
/**
* @brief Get Shift operation pending flag
* @rmtoll ISR SHPF LL_RTC_IsActiveFlag_SHP
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_SHP(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_SHPF) == (RTC_ISR_SHPF));
}
#if defined(RTC_WAKEUP_SUPPORT)
/**
* @brief Get Wakeup timer write flag
* @rmtoll ISR WUTWF LL_RTC_IsActiveFlag_WUTW
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_WUTW(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_WUTWF) == (RTC_ISR_WUTWF));
}
#endif /* RTC_WAKEUP_SUPPORT */
/**
* @brief Get Alarm A write flag
* @rmtoll ISR ALRAWF LL_RTC_IsActiveFlag_ALRAW
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRAW(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->ISR, RTC_ISR_ALRAWF) == (RTC_ISR_ALRAWF));
}
/**
* @}
*/
/** @defgroup RTC_LL_EF_IT_Management IT_Management
* @{
*/
/**
* @brief Enable Time-stamp interrupt
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR TSIE LL_RTC_EnableIT_TS
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnableIT_TS(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_TSIE);
}
/**
* @brief Disable Time-stamp interrupt
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR TSIE LL_RTC_DisableIT_TS
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisableIT_TS(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_TSIE);
}
#if defined(RTC_WAKEUP_SUPPORT)
/**
* @brief Enable Wakeup timer interrupt
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR WUTIE LL_RTC_EnableIT_WUT
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnableIT_WUT(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_WUTIE);
}
/**
* @brief Disable Wakeup timer interrupt
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR WUTIE LL_RTC_DisableIT_WUT
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisableIT_WUT(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_WUTIE);
}
#endif /* RTC_WAKEUP_SUPPORT */
/**
* @brief Enable Alarm A interrupt
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR ALRAIE LL_RTC_EnableIT_ALRA
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnableIT_ALRA(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->CR, RTC_CR_ALRAIE);
}
/**
* @brief Disable Alarm A interrupt
* @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before.
* @rmtoll CR ALRAIE LL_RTC_DisableIT_ALRA
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisableIT_ALRA(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->CR, RTC_CR_ALRAIE);
}
/**
* @brief Enable all Tamper Interrupt
* @rmtoll TAFCR TAMPIE LL_RTC_EnableIT_TAMP
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_EnableIT_TAMP(RTC_TypeDef *RTCx)
{
SET_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPIE);
}
/**
* @brief Disable all Tamper Interrupt
* @rmtoll TAFCR TAMPIE LL_RTC_DisableIT_TAMP
* @param RTCx RTC Instance
* @retval None
*/
__STATIC_INLINE void LL_RTC_DisableIT_TAMP(RTC_TypeDef *RTCx)
{
CLEAR_BIT(RTCx->TAFCR, RTC_TAFCR_TAMPIE);
}
/**
* @brief Check if Time-stamp interrupt is enabled or not
* @rmtoll CR TSIE LL_RTC_IsEnabledIT_TS
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_TS(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->CR, RTC_CR_TSIE) == (RTC_CR_TSIE));
}
#if defined(RTC_WAKEUP_SUPPORT)
/**
* @brief Check if Wakeup timer interrupt is enabled or not
* @rmtoll CR WUTIE LL_RTC_IsEnabledIT_WUT
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_WUT(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->CR, RTC_CR_WUTIE) == (RTC_CR_WUTIE));
}
#endif /* RTC_WAKEUP_SUPPORT */
/**
* @brief Check if Alarm A interrupt is enabled or not
* @rmtoll CR ALRAIE LL_RTC_IsEnabledIT_ALRA
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_ALRA(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->CR, RTC_CR_ALRAIE) == (RTC_CR_ALRAIE));
}
/**
* @brief Check if all the TAMPER interrupts are enabled or not
* @rmtoll TAFCR TAMPIE LL_RTC_IsEnabledIT_TAMP
* @param RTCx RTC Instance
* @retval State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_TAMP(RTC_TypeDef *RTCx)
{
return (READ_BIT(RTCx->TAFCR,
RTC_TAFCR_TAMPIE) == (RTC_TAFCR_TAMPIE));
}
/**
* @}
*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup RTC_LL_EF_Init Initialization and de-initialization functions
* @{
*/
ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx);
ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct);
void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct);
ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct);
void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct);
ErrorStatus LL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_DateTypeDef *RTC_DateStruct);
void LL_RTC_DATE_StructInit(LL_RTC_DateTypeDef *RTC_DateStruct);
ErrorStatus LL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct);
void LL_RTC_ALMA_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct);
ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx);
ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx);
ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx);
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/**
* @}
*/
/**
* @}
*/
#endif /* defined(RTC) */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32F0xx_LL_RTC_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| betzw/mbed-os | targets/TARGET_STM/TARGET_STM32F0/device/stm32f0xx_ll_rtc.h | C | apache-2.0 | 121,645 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.transport;
import org.elasticsearch.client.support.Headers;
import org.elasticsearch.client.transport.support.InternalTransportAdminClient;
import org.elasticsearch.client.transport.support.InternalTransportClient;
import org.elasticsearch.client.transport.support.InternalTransportClusterAdminClient;
import org.elasticsearch.client.transport.support.InternalTransportIndicesAdminClient;
import org.elasticsearch.common.inject.AbstractModule;
/**
*
*/
public class ClientTransportModule extends AbstractModule {
@Override
protected void configure() {
bind(Headers.class).asEagerSingleton();
bind(InternalTransportClient.class).asEagerSingleton();
bind(InternalTransportAdminClient.class).asEagerSingleton();
bind(InternalTransportIndicesAdminClient.class).asEagerSingleton();
bind(InternalTransportClusterAdminClient.class).asEagerSingleton();
bind(TransportClientNodesService.class).asEagerSingleton();
}
}
| dmiszkiewicz/elasticsearch | src/main/java/org/elasticsearch/client/transport/ClientTransportModule.java | Java | apache-2.0 | 1,797 |
//go:build !linux && !windows
// +build !linux,!windows
/*
Copyright 2018 The Kubernetes Authors.
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.
*/
package kuberuntime
import (
"k8s.io/api/core/v1"
runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
)
// applyPlatformSpecificContainerConfig applies platform specific configurations to runtimeapi.ContainerConfig.
func (m *kubeGenericRuntimeManager) applyPlatformSpecificContainerConfig(config *runtimeapi.ContainerConfig, container *v1.Container, pod *v1.Pod, uid *int64, username string, nsTarget *kubecontainer.ContainerID) error {
return nil
}
| deads2k/origin | vendor/k8s.io/kubernetes/pkg/kubelet/kuberuntime/kuberuntime_container_unsupported.go | GO | apache-2.0 | 1,136 |
var gulp = require('gulp'),
gulpLoadPlugins = require('gulp-load-plugins'),
karma = require('karma').server;
var plugins = gulpLoadPlugins();
var defaultTasks = ['env:test', 'karma:unit', 'mochaTest'];
gulp.task('env:test', function () {
process.env.NODE_ENV = 'test';
});
gulp.task('karma:unit', function (done) {
karma.start({
configFile: __dirname + '/../karma.conf.js',
singleRun: true
}, function () {
done();
});
});
gulp.task('loadTestSchema', function () {
require('../server.js');
require('../node_modules/meanio/lib/core_modules/module/util').preload('../packages/**/server', 'model');
});
gulp.task('mochaTest', ['loadTestSchema'], function () {
return gulp.src('../packages/**/server/tests/**/*.js', {read: false})
.pipe(plugins.mocha({
reporter: 'spec'
}));
});
gulp.task('test', defaultTasks);
| tjboudreaux/RecruitTracker | gulp/test.js | JavaScript | mit | 857 |
<!doctype html>
<html lang="en" data-framework="troopjs">
<head>
<meta charset="utf-8">
<title>TroopJS • TodoMVC</title>
<link rel="stylesheet" href="bower_components/todomvc-common/base.css">
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<section id="todoapp">
<header id="header">
<h1>todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus data-weave="troopjs-todos/widget/create">
</header>
<section id="main" data-weave="troopjs-todos/widget/display">
<input id="toggle-all" type="checkbox" data-weave="troopjs-todos/widget/mark">
<label for="toggle-all">Mark all as complete</label>
<ul id="todo-list" data-weave="troopjs-todos/widget/list"></ul>
</section>
<footer id="footer" data-weave="troopjs-todos/widget/display">
<span id="todo-count" data-weave="troopjs-todos/widget/count"><strong>1</strong> item left</span>
<ul id="filters" data-weave="troopjs-todos/widget/filters">
<li>
<a class="selected" href="#/">All</a>
</li>
<li>
<a href="#/active">Active</a>
</li>
<li>
<a href="#/completed">Completed</a>
</li>
</ul>
<button id="clear-completed" data-weave="troopjs-todos/widget/clear">Clear completed (1)</button>
</footer>
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="https://github.com/mikaelkaron">Mikael Karon</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
<script src="bower_components/todomvc-common/base.js"></script>
<script>
'use strict';
var require = {
packages: [{
name: 'jquery',
location: 'bower_components/jquery',
main: 'jquery'
}, {
name: 'troopjs-bundle',
location: 'bower_components/troopjs-bundle',
main: 'maxi'
}, {
name: 'troopjs-todos',
location: 'js'
}],
map: {
'*': {
template: 'troopjs-requirejs/template'
}
},
deps: [ 'require', 'jquery', 'troopjs-bundle' ],
callback: function Boot (contextRequire, jQuery) {
contextRequire([ 'troopjs-browser/application/widget', 'troopjs-browser/route/widget' ], function Strap (Application, RouteWidget) {
jQuery(function ($) {
Application($('html'), 'bootstrap', RouteWidget($(window), 'route')).start();
});
});
}
};
</script>
<script src="bower_components/requirejs/require.js" async="async"></script>
</body>
</html>
| ericelliott/todomvc | labs/dependency-examples/troopjs_require/index.html | HTML | mit | 2,413 |
/*
* bag.js - js/css/other loader + kv storage
*
* Copyright 2013-2016 Vitaly Puzrin
* https://github.com/nodeca/bag.js
*
* License MIT
*/
/*global define*/
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
root.Bag = factory();
}
} (this, function () {
'use strict';
var head = document.head || document.getElementsByTagName('head')[0];
//////////////////////////////////////////////////////////////////////////////
// helpers
function _class(obj) { return Object.prototype.toString.call(obj); }
function _isString(obj) { return _class(obj) === '[object String]'; }
function _isFunction(obj) { return _class(obj) === '[object Function]'; }
var _isArray = Array.isArray || function isArray(obj) {
return _class(obj) === '[object Array]';
};
function _each(obj, iterator) {
if (_isArray(obj)) {
if (obj.forEach) return obj.forEach(iterator);
for (var i = 0; i < obj.length; i++) iterator(obj[i], i, obj);
} else {
for (var k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) iterator(obj[k], k);
}
}
}
function _default(obj, src) {
// extend obj with src properties if not exists;
_each(src, function (val, key) {
if (!obj[key]) obj[key] = src[key];
});
return obj;
}
function promiseOrCallback(promise, cb) {
if (!cb) return promise;
var called = false;
promise.then(
function (data) {
setTimeout(function () {
if (!called) {
called = true;
cb(null, data);
}
}, 0);
},
function (err) {
setTimeout(function () {
if (!called) {
called = true;
cb(err);
}
}, 0);
}
);
}
//////////////////////////////////////////////////////////////////////////////
// Simple thenable implementation. Originally by @medikoo
// https://github.com/medikoo/plain-promise
// Modified to use ES3 only :)
/*eslint-disable func-style*/
var PP = function (executor) {
var self = this;
this._callbacks = [];
executor(
function (v) { self._resolve(v); },
function (v) { self._reject(v); }
);
};
PP.resolve = function (value) {
return new PP(function (resolve) { resolve(value); });
};
PP.reject = function (error) {
return new PP(function (resolve, reject) { reject(error); });
};
PP.cast = function (value) {
if (value instanceof PP) return value;
return PP.resolve(value);
};
PP.prototype = {
constructor: PP,
// Private properties and methods:
_failed: false,
_resolved: false,
_settled: false,
_release: function (onSuccess, onFail) {
/*eslint-disable no-lonely-if*/
if (this._failed) {
if (typeof onFail === 'function') onFail(this._value);
else throw this._value;
} else {
if (typeof onSuccess === 'function') onSuccess(this._value);
}
},
_resolve: function (value) {
if (this._resolved) return;
this._resolved = true;
var self = this;
if (value instanceof PP) {
value.done(function (v) {
self._settle(v);
}, function (error) {
self._failed = true;
self._settle(error);
});
} else {
this._settle(value);
}
},
_reject: function (value) {
if (this._resolved) return;
this._resolved = true;
this._failed = true;
this._settle(value);
},
_settle: function (value) {
this._settled = true;
this._value = value;
var self = this;
// Do not release before `resolve` or `reject` returns
setTimeout(function () {
_each(self._callbacks, function (data) {
self._release(data.onSuccess, data.onFail);
});
}, 0);
},
// Public API:
// Warning: Some implementations do not provide `done`
done: function (onSuccess, onFail) {
var self = this;
if (this._settled) {
// Do not release before `done` returns
setTimeout(function () { self._release(onSuccess, onFail); }, 0);
} else {
this._callbacks.push({ onSuccess: onSuccess, onFail: onFail });
}
},
then: function (onSuccess, onFail) {
var self = this;
return new PP(function (resolve, reject) {
self.done(function (value) {
if (typeof onSuccess === 'function') {
try {
value = onSuccess(value);
} catch (e) {
reject(e);
return;
}
}
resolve(value);
}, function (value) {
if (typeof onFail === 'function') {
try {
value = onFail(value);
} catch (e) {
reject(e);
return;
}
resolve(value);
} else {
reject(value);
}
});
});
},
'catch': function (onFail) {
return this.then(null, onFail);
}
};
var P = window.Promise || PP;
//////////////////////////////////////////////////////////////////////////////
// Adapters for Store class
function DomStorage(namespace) {
var self = this;
var _ns = namespace + '__';
this.init = function () { return P.resolve(); };
this.remove = function (key) {
localStorage.removeItem(_ns + key);
return P.resolve();
};
this.set = function (key, value, expire) {
var obj = {
value: value,
expire: expire
};
return new P(function (resolve, reject) {
try {
localStorage.setItem(_ns + key, JSON.stringify(obj));
resolve();
} catch (e) {
// On quota error try to reset storage & try again.
// Just remove all keys, without conditions, no optimizations needed.
if (e.name.toUpperCase().indexOf('QUOTA') >= 0) {
try {
_each(localStorage, function (val, name) {
var k = name.split(_ns)[1];
if (k) { self.remove(k); }
});
localStorage.setItem(_ns + key, JSON.stringify(obj));
resolve();
} catch (e2) {
reject(e2);
}
} else {
reject(e);
}
}
});
};
this.get = function (key, raw) {
return new P(function (resolve, reject) {
try {
var data = localStorage.getItem(_ns + key);
// return `undefined` for missed keys
if (data === null) return resolve();
data = JSON.parse(localStorage.getItem(_ns + key));
resolve(data = raw ? data : data.value);
} catch (e) {
reject(new Error("Can't read key: " + key));
}
});
};
this.clear = function (expiredOnly) {
var now = +new Date();
var p = P.resolve();
_each(localStorage, function (val, name) {
var key = name.split(_ns)[1];
if (!key) return;
if (!expiredOnly) {
p = p.then(function () { self.remove(key); });
return;
}
p = p.then(function () {
return self.get(key, true)
.then(function (raw) {
if (raw && (raw.expire > 0) && ((raw.expire - now) < 0)) {
// no need to chain promise, because operation is sync
self.remove(key);
}
});
});
});
return p;
};
}
DomStorage.exists = function () {
try {
localStorage.setItem('__ls_test__', '__ls_test__');
localStorage.removeItem('__ls_test__');
return true;
} catch (e) {
return false;
}
};
function WebSql(namespace) {
var db;
this.init = function () {
return new P(function (resolve, reject) {
db = window.openDatabase(namespace, '1.0', 'bag.js db', 2e5);
if (!db) {
reject("Can't open websql database");
return;
}
db.transaction(function (tx) {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT, expire INTEGER KEY)',
[],
function () { resolve(); },
function (tx, err) { reject(err); }
);
});
});
};
this.remove = function (key) {
return new P(function (resolve, reject) {
db.transaction(function (tx) {
tx.executeSql(
'DELETE FROM kv WHERE key = ?',
[ key ],
function () { resolve(); },
function (tx, err) { reject(err); }
);
});
});
};
this.set = function (key, value, expire) {
return new P(function (resolve, reject) {
db.transaction(function (tx) {
tx.executeSql(
'INSERT OR REPLACE INTO kv (key, value, expire) VALUES (?, ?, ?)',
[ key, JSON.stringify(value), expire ],
function () { resolve(); },
function (tx, err) { reject(err); }
);
});
});
};
this.get = function (key) {
return new P(function (resolve, reject) {
db.readTransaction(function (tx) {
tx.executeSql(
'SELECT value FROM kv WHERE key = ?',
[ key ],
function (tx, result) {
// return `undefined` for missed keys
if (result.rows.length === 0) return resolve();
var value = result.rows.item(0).value;
try {
resolve(JSON.parse(value));
} catch (e) {
reject(new Error("Can't unserialise data: " + value));
}
},
function (tx, err) { reject(err); }
);
});
});
};
this.clear = function (expiredOnly) {
return new P(function (resolve, reject) {
db.transaction(function (tx) {
tx.executeSql(
expiredOnly ?
'DELETE FROM kv WHERE expire > 0 AND expire < ?'
:
'DELETE FROM kv',
expiredOnly ? [ +new Date() ] : [],
function () { resolve(); },
function (tx, err) { reject(err); }
);
});
});
};
}
WebSql.exists = function () { return (!!window.openDatabase); };
function Idb(namespace) {
var db;
this.init = function () {
return new P(function (resolve, reject) {
var idb = window.indexedDB;
var req = idb.open(namespace, 2 /*version*/);
req.onsuccess = function (e) {
db = e.target.result;
resolve();
};
req.onblocked = function (e) {
reject(new Error('IndexedDB blocked. ' + e.target.errorCode));
};
req.onerror = function (e) {
reject(new Error('IndexedDB opening error. ' + e.target.errorCode));
};
req.onupgradeneeded = function (e) {
db = e.target.result;
if (db.objectStoreNames.contains('kv')) db.deleteObjectStore('kv');
var store = db.createObjectStore('kv', { keyPath: 'key' });
store.createIndex('expire', 'expire', { unique: false });
};
});
};
this.remove = function (key) {
return new P(function (resolve, reject) {
var tx = db.transaction('kv', 'readwrite');
tx.oncomplete = function () { resolve(); };
tx.onerror = tx.onabort = function (e) { reject(e.target); };
// IE 8 not allow to use reserved keywords as functions. More info:
// http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/
tx.objectStore('kv')['delete'](key).onerror = function () {
tx.abort();
};
});
};
this.set = function (key, value, expire) {
return new P(function (resolve, reject) {
var tx = db.transaction('kv', 'readwrite');
tx.oncomplete = function () { resolve(); };
tx.onerror = tx.onabort = function (e) { reject(e.target); };
tx.objectStore('kv').put({
key: key,
value: value,
expire: expire
}).onerror = function () { tx.abort(); };
});
};
this.get = function (key) {
return new P(function (resolve, reject) {
var tx = db.transaction('kv');
// tx.oncomplete = function () { resolve(result); };
tx.onerror = tx.onabort = function (e) {
reject(new Error('Key get error: ' + e.target));
};
tx.objectStore('kv').get(key).onsuccess = function (e) {
if (e.target.result) resolve(e.target.result.value);
else resolve();
};
});
};
this.clear = function (expiredOnly) {
return new P(function (resolve, reject) {
var keyrange = window.IDBKeyRange,
tx = db.transaction('kv', 'readwrite'),
store = tx.objectStore('kv');
tx = db.transaction('kv', 'readwrite');
store = tx.objectStore('kv');
tx.oncomplete = function () { resolve(); };
tx.onerror = tx.onabort = function (e) {
reject(new Error('Clear error: ', e.target));
};
if (expiredOnly) {
var cursor = store.index('expire').openCursor(keyrange.bound(1, +new Date()));
cursor.onsuccess = function (e) {
var _cursor = e.target.result;
if (_cursor) {
// IE 8 not allow to use reserved keywords as functions (`delete` and `continue`). More info:
// http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/
store['delete'](_cursor.primaryKey).onerror = function () {
tx.abort();
};
_cursor['continue']();
}
};
return;
}
// Just clear everything
tx.objectStore('kv').clear().onerror = function () { tx.abort(); };
});
};
}
Idb.exists = function () {
var db = window.indexedDB;
if (!db) return false;
// Check outdated idb implementations, where `onupgradeneede` event doesn't work,
// see https://github.com/pouchdb/pouchdb/issues/1207 for more details
var dbName = '__idb_test__';
var result = db.open(dbName, 1).onupgradeneeded === null;
if (db.deleteDatabase) db.deleteDatabase(dbName);
return result;
};
/////////////////////////////////////////////////////////////////////////////
// key/value storage with expiration
var storeAdapters = {
indexeddb: Idb,
websql: WebSql,
localstorage: DomStorage
};
// namespace - db name or similar
// storesList - array of allowed adapter names to use
//
function Storage(namespace, storesList) {
var self = this;
var db = null;
var init_done = false;
_each(storesList, function (name) {
// do storage names case insensitive
name = name.toLowerCase();
if (!storeAdapters[name]) {
throw new Error('Wrong storage adapter name: ' + name, storesList);
}
if (storeAdapters[name].exists() && !db) {
db = new storeAdapters[name](namespace);
return false; // terminate search on first success
}
});
if (!db) {
/* eslint-disable no-console */
// If no adaprets - don't make error for correct fallback.
// Just log that we continue work without storing results.
if (typeof console !== 'undefined' && console.log) {
console.log('None of requested storages available: ' + storesList);
}
/* eslint-enable no-console */
}
function createInit() {
return P.resolve()
.then(function () {
if (!db) throw new Error('No available db');
return db.init().then(function () {
init_done = true;
db.clear(true); // clear expired
});
});
}
var _waitInit;
this.init = function () {
if (!_waitInit) _waitInit = createInit();
return _waitInit;
};
function run() { // (method, ...params)
var args = Array.prototype.slice.call(arguments, 1),
method = arguments[0];
return init_done ? db[method].apply(db, args) :
self.init().then(function () {
return db[method].apply(db, args);
});
}
this.set = function (key, value, expire, callback) {
if (_isFunction(expire)) {
callback = expire;
expire = null;
}
expire = expire ? +(new Date()) + (expire * 1000) : 0;
return promiseOrCallback(run('set', key, value, expire), callback);
};
this.get = function (key, callback) {
return promiseOrCallback(run('get', key), callback);
};
this.remove = function (key, callback) {
return promiseOrCallback(run('remove', key), callback);
};
this.clear = function (expiredOnly, callback) {
if (_isFunction(expiredOnly)) {
callback = expiredOnly;
expiredOnly = null;
}
return promiseOrCallback(run('clear', expiredOnly), callback);
};
}
//////////////////////////////////////////////////////////////////////////////
// Bag class implementation
function Bag(options) {
if (!(this instanceof Bag)) return new Bag(options);
var self = this;
options = options || {};
this.prefix = options.prefix || 'bag';
this.timeout = options.timeout || 20; // 20 seconds
this.expire = options.expire || 30 * 24; // 30 days
this.isValidItem = options.isValidItem || null;
this.stores = _isArray(options.stores) ? options.stores : [ 'indexeddb', 'websql', 'localstorage' ];
var storage = null;
function createStorage() {
if (!storage) storage = new Storage(self.prefix, self.stores);
}
function getUrl(url) {
return new P(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve({
content: xhr.responseText,
type: xhr.getResponseHeader('content-type')
});
} else {
reject(new Error("Can't open url " + url +
(xhr.status ? xhr.statusText + ' (' + xhr.status + ')' : '')));
}
}
};
setTimeout(function () {
if (xhr.readyState < 4) {
xhr.abort();
reject(new Error('Timeout'));
}
}, self.timeout * 1000);
try {
xhr.send();
} catch (err) {
reject(err);
}
});
}
function createCacheObj(obj, response) {
var cacheObj = {};
_each([ 'url', 'key', 'unique' ], function (key) {
if (obj[key]) cacheObj[key] = obj[key];
});
var now = +new Date();
cacheObj.data = response.content;
cacheObj.originalType = response.type;
cacheObj.type = obj.type || response.type;
cacheObj.stamp = now;
return cacheObj;
}
function saveUrl(obj) {
return getUrl(obj.url_real)
.then(function (result) {
var delay = (obj.expire || self.expire) * 60 * 60; // in seconds
var cached = createCacheObj(obj, result);
return storage.set(obj.key, cached, delay)
// Suppress error - have to return data anyway
.then(
function () { return _default(obj, cached); },
function () { return _default(obj, cached); }
);
});
}
function isCacheInvalid(cached, obj) {
return !cached ||
cached.expire - +new Date() < 0 ||
obj.unique !== cached.unique ||
obj.url !== cached.url ||
(self.isValidItem && !self.isValidItem(cached, obj));
}
function fetch(obj) {
if (!obj.url) return P.resolve();
obj.key = (obj.key || obj.url);
return storage.get(obj.key)
// Suppress error, we can get it in private mode (Firefox)
.then(function (data) { return data; }, function () { return null; })
.then(function (cached) {
if (!cached && obj.cached) throw new Error('Cache not exists');
// if can't get object from store, then just load it from web.
obj.execute = (obj.execute !== false);
var shouldFetch = !cached || isCacheInvalid(cached, obj);
// If don't have to load new date - return one from cache
if (!obj.live && !shouldFetch) {
obj.type = obj.type || cached.originalType;
return _default(obj, cached);
}
// calculate loading url
obj.url_real = obj.url;
if (obj.unique) {
// set parameter to prevent browser cache
obj.url_real = obj.url + ((obj.url.indexOf('?') > 0) ? '&' : '?') + 'bag-unique=' + obj.unique;
}
return saveUrl(obj)
.then(
function () { return obj; },
function (err) {
if (!cached) throw err;
obj.type = obj.type || cached.originalType;
return _default(obj, cached);
}
);
});
}
////////////////////////////////////////////////////////////////////////////
// helpers to set absolute sourcemap url
/* eslint-disable max-len */
var sourceMappingRe = /(?:^([ \t]*\/\/[@|#][ \t]+sourceMappingURL=)(.+?)([ \t]*)$)|(?:^([ \t]*\/\*[@#][ \t]+sourceMappingURL=)(.+?)([ \t]*\*\/[ \t])*$)/mg;
/* eslint-enable max-len */
function parse_url(url) {
var pattern = new RegExp('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?');
var matches = url.match(pattern);
return {
scheme: matches[2],
authority: matches[4],
path: matches[5],
query: matches[7],
fragment: matches[9]
};
}
function patchMappingUrl(obj) {
var refUrl = parse_url(obj.url);
var done = false;
var res = obj.data.replace(sourceMappingRe, function (match, p1, p2, p3, p4, p5, p6) {
if (!match) return null;
done = true;
// select matched group of params
if (!p1) { p1 = p4; p2 = p5; p3 = p6; }
var mapUrl = parse_url(p2);
var scheme = (mapUrl.scheme ? mapUrl.scheme : refUrl.scheme) || window.location.protocol.slice(0, -1);
var authority = (mapUrl.authority ? mapUrl.authority : refUrl.authority) || window.location.host;
/* eslint-disable max-len */
var path = mapUrl.path[0] === '/' ? mapUrl.path : refUrl.path.split('/').slice(0, -1).join('/') + '/' + mapUrl.path;
/* eslint-enable max-len */
return p1 + (scheme + '://' + authority + path) + p3;
});
return done ? res : '';
}
////////////////////////////////////////////////////////////////////////////
var handlers = {
'application/javascript': function injectScript(obj) {
var script = document.createElement('script'), txt;
// try to change sourcemap address to absolute
txt = patchMappingUrl(obj);
if (!txt) {
// or add script name for dev tools
txt = obj.data + '\n//# sourceURL=' + obj.url;
}
// Have to use .text, since we support IE8,
// which won't allow appending to a script
script.text = txt;
head.appendChild(script);
return;
},
'text/css': function injectStyle(obj) {
var style = document.createElement('style'), txt;
// try to change sourcemap address to absolute
txt = patchMappingUrl(obj);
if (!txt) {
// or add stylesheet script name for dev tools
txt = obj.data + '\n/*# sourceURL=' + obj.url + ' */';
}
// Needed to enable `style.styleSheet` in IE
style.setAttribute('type', 'text/css');
if (style.styleSheet) {
// We should append style element to DOM before assign css text to
// workaround IE bugs with `@import` and `@font-face`.
// https://github.com/andrewwakeling/ie-css-bugs
head.appendChild(style);
style.styleSheet.cssText = txt; // IE method
} else {
style.appendChild(document.createTextNode(txt)); // others
head.appendChild(style);
}
return;
}
};
function execute(obj) {
if (!obj.type) return;
// Cut off encoding if exists:
// application/javascript; charset=UTF-8
var handlerName = obj.type.split(';')[0];
// Fix outdated mime types if needed, to use single handler
if (handlerName === 'application/x-javascript' || handlerName === 'text/javascript') {
handlerName = 'application/javascript';
}
if (handlers[handlerName]) handlers[handlerName](obj);
return;
}
////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
this.require = function (resources, callback) {
createStorage();
return promiseOrCallback(new P(function (resolve, reject) {
var result = [], exec_pos = 0,
res = _isArray(resources) ? resources : [ resources ];
if (!resources) {
resolve();
return;
}
_each(res, function (r, i) { result[i] = false; });
_each(res, function (r, i) {
if (_isString(r)) res[i] = { url: r };
fetch(res[i]).then(function () {
// return content only, if one need full info -
// check input object, that will be extended.
result[i] = res[i].data;
var k;
for (k = exec_pos; k < result.length; k++) {
if (result[k] === false) break;
if (res[k].execute) execute(res[k]);
}
exec_pos = k;
if (exec_pos >= res.length) {
resolve(_isArray(resources) ? result : result[0]);
}
}, function (err) {
reject(err);
});
});
}), callback);
};
// Create proxy methods (init store then subcall)
_each([ 'remove', 'get', 'set', 'clear' ], function (method) {
self[method] = function () {
createStorage();
return storage[method].apply(storage, arguments);
};
});
this.addHandler = function (types, handler) {
types = _isArray(types) ? types : [ types ];
_each(types, function (type) { handlers[type] = handler; });
};
this.removeHandler = function (types) {
self.addHandler(types/*, undefined*/);
};
}
return Bag;
}));
| kennynaoh/cdnjs | ajax/libs/bagjs/2.0.2/bag.js | JavaScript | mit | 26,956 |
<p>
Some documentation on how to construct a file to import. <!-- TODO -->
</p>
<h3>How to create a file to import</h3>
<p>
TODO
</p>
<h3>Column content</h3>
<p>
Some content fields can be preprocessed specially for the convience
of the user. For example it is more portable to specify a user by
name or e-mail address than by internal UID.
</p>
<a name="allowed-values"></a>
<h4>Allowed values</h4>
<p>
If you can select a value with a set of radio buttons, you can use
either <strong>the key</strong> or <strong>the value</strong> of the
set of options. For example, if the radio buttons read <em>One</em>
(with internal key <em>1</em>), <em>Two</em> (with internal key
<em>2</em>) and <em>Three</em> (with internal key <em>3</em>) you
can use any of following values to select <em>Two</em>:
</p>
<pre>
2
Two
two
</pre>
<a name="book-reference"></a>
<h4>Book reference</h4>
<p>
Just like a <a href="#node-reference">Node reference</a>, a <em>Book
reference</em>, such as the <em>Book</em> of a <em>Book outline</em>,
can be specified by <strong>NID</strong> or <strong>Title</strong>
(case insensitive).
</p>
<p>
To specify that a page should not be added to a <em>Book outline</em>
you can specify <strong><none></strong>. To create a new
toplevel book specify <strong><new></strong>.
</p>
<a name="book-page-reference"></a>
<h4>Book page reference</h4>
<p>
Just like a <a href="#node-reference">Node reference</a>, a <em>Book
page reference</em>, such as the <em>Parent item</em> of a
<em>Book outline</em>, can be specified by <strong>NID</strong>
or <strong>Title</strong> (case insensitive).
</p>
<p class="warning">
You can not have a book page inside the same book with the same
title.
</p>
<a name="boolean"></a>
<h4>Boolean</h4>
<p>
A <em>Boolean</em> content field, for example <em>Published</em>, can
be specified by following <strong>True</strong> values (case insensitive):
</p>
<pre>
1
on
yes
true
On - translated
Yes - translated
True - translated
</pre>
<p>
or by following <strong>False</strong> values (case insensitive):
</p>
<pre>
0
off
no
false
Off - translated
No - translated
False - translated
</pre>
<a name="date"></a>
<h4>Date</h4>
<p>
If you map a <em>Date</em> content field, such as <em>Authored on</em>,
you will be presented with the option on how to interpret the data in
the file column.
</p>
<p>
For example, if you specify the <strong>Custom date format</strong> as
<em>m/d/Y</em>, dates need to be in the <em>12/23/2008</em> format,
while if you specify <em>d/m/Y</em> they need to be in the
<em>23/12/2008</em> format.
</p>
<p>
Dates in <strong>UNIX timestamp</strong> or the <strong>ISO format</strong>
(2008-12-23) will always be accepted.
</p>
<a name="filepath"></a>
<h4>File path</h4>
<p>
A field that reference a <em>File</em>, such as the <em>CCK FileField</em>,
<em>CCK ImageField</em> or <em>Core attachments</em> (of the <em>Upload</em>
module), need to contain a <strong>filepath</strong> relative to the
directory in which the files are stored.
</p>
<p>
You need to manually move the files to the correct location prior doing
the import.
</p>
<p>
For example, if you have an image <code>butterfly.jpg</code> that is
used in a <em>CCK ImageField</em> field which stores its files in a
configured directory <code>sites/default/files/butterflies</code> your
CSV file needs to contain <code>butterfly.jpg</code> as value and you
need to manually copy or FTP the image file to
<code>sites/default/files/butterflies/butterfly.jpg</code>.
</p>
<a name="input-format"></a>
<h4>Input format</h4>
<p>
An <em>Input format</em> field, for example of the <em>Body</em>, can
be specified by <strong>ID</strong> or <strong>Name</strong> (case
insensitive). For example, on a default Drupal installation, following
values will be accepted for <em>Filtered HTML</em>:
</p>
<pre>
Filtered HTML
filtered html
1
</pre>
<a name="node-reference"></a>
<h4>Node reference</h4>
<p>
A <em>Node reference</em>, such as the fields defined by the <em>Node
reference</em> module, can be specified by <strong>NID</strong> or
<strong>Title</strong> (case insensitive). For example, a node
<em>Hello world!</em> with NID <em>574</em> can be specified as:
</p>
<pre>
Hello world!
hello world!
574
</pre>
<a name="user-reference"></a>
<h4>User reference</h4>
<p>
A <em>User reference</em>, such as <em>Authored by</em>, can be specified
by <strong>UID</strong>, <strong>Username</strong> (case insensitive) or
<strong>E-mail address</strong> (case insensitive). For example, a user
<em>Joe Doe</em> with e-mail address <em>[email protected]</em> and UID
<em>42</em> can be specified as:
</p>
<pre>
Joe Doe
joe doe
[email protected]
[email protected]
42
</pre>
<a name="weight"></a>
<h4>Weight</h4>
<p>
A <em>Weight</em>, such as for <em>Book outline</em>, can be specified
as an <strong>Integer</strong> only. The following are all valid
weights:
</p>
<pre>
-5
0
9
</pre>
| 404pnf/4u2u | sites/t.2u4u.com.cn/modules/standard/node_import/help/input-format.html | HTML | gpl-2.0 | 4,993 |
/************************************************************************
*
* IONSP.H Definitions for I/O Networks Serial Protocol
*
* Copyright (C) 1997-1998 Inside Out Networks, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* These definitions are used by both kernel-mode driver and the
* peripheral firmware and MUST be kept in sync.
*
************************************************************************/
/************************************************************************
The data to and from all ports on the peripheral is multiplexed
through a single endpoint pair (EP1 since it supports 64-byte
MaxPacketSize). Therefore, the data, commands, and status for
each port must be preceded by a short header identifying the
destination port. The header also identifies the bytes that follow
as data or as command/status info.
Header format, first byte:
CLLLLPPP
--------
| | |------ Port Number: 0-7
| |--------- Length: MSB bits of length
|----------- Data/Command: 0 = Data header
1 = Cmd / Status (Cmd if OUT, Status if IN)
This gives 2 possible formats:
Data header: 0LLLLPPP LLLLLLLL
============
Where (LLLL,LLLLLLL) is 12-bit length of data that follows for
port number (PPP). The length is 0-based (0-FFF means 0-4095
bytes). The ~4K limit allows the host driver (which deals in
transfer requests instead of individual packets) to write a
large chunk of data in a single request. Note, however, that
the length must always be <= the current TxCredits for a given
port due to buffering limitations on the peripheral.
Cmd/Status header: 1ccccPPP [ CCCCCCCC, Params ]...
==================
Where (cccc) or (cccc,CCCCCCCC) is the cmd or status identifier.
Frequently-used values are encoded as (cccc), longer ones using
(cccc,CCCCCCCC). Subsequent bytes are optional parameters and are
specific to the cmd or status code. This may include a length
for command and status codes that need variable-length parameters.
In addition, we use another interrupt pipe (endpoint) which the host polls
periodically for flow control information. The peripheral, when there has
been a change, sends the following 10-byte packet:
RRRRRRRRRRRRRRRR
T0T0T0T0T0T0T0T0
T1T1T1T1T1T1T1T1
T2T2T2T2T2T2T2T2
T3T3T3T3T3T3T3T3
The first field is the 16-bit RxBytesAvail field, which indicates the
number of bytes which may be read by the host from EP1. This is necessary:
(a) because OSR2.1 has a bug which causes data loss if the peripheral returns
fewer bytes than the host expects to read, and (b) because, on Microsoft
platforms at least, an outstanding read posted on EP1 consumes about 35% of
the CPU just polling the device for data.
The next 4 fields are the 16-bit TxCredits for each port, which indicate how
many bytes the host is allowed to send on EP1 for transmit to a given port.
After an OPEN_PORT command, the Edgeport sends the initial TxCredits for that
port.
All 16-bit fields are sent in little-endian (Intel) format.
************************************************************************/
//
// Define format of InterruptStatus packet returned from the
// Interrupt pipe
//
struct int_status_pkt {
__u16 RxBytesAvail; // Additional bytes available to
// be read from Bulk IN pipe
__u16 TxCredits[MAX_RS232_PORTS]; // Additional space available in
// given port's TxBuffer
};
#define GET_INT_STATUS_SIZE(NumPorts) (sizeof(__u16) + (sizeof(__u16) * (NumPorts)))
//
// Define cmd/status header values and macros to extract them.
//
// Data: 0LLLLPPP LLLLLLLL
// Cmd/Stat: 1ccccPPP CCCCCCCC
#define IOSP_DATA_HDR_SIZE 2
#define IOSP_CMD_HDR_SIZE 2
#define IOSP_MAX_DATA_LENGTH 0x0FFF // 12 bits -> 4K
#define IOSP_PORT_MASK 0x07 // Mask to isolate port number
#define IOSP_CMD_STAT_BIT 0x80 // If set, this is command/status header
#define IS_CMD_STAT_HDR(Byte1) ((Byte1) & IOSP_CMD_STAT_BIT)
#define IS_DATA_HDR(Byte1) (!IS_CMD_STAT_HDR(Byte1))
#define IOSP_GET_HDR_PORT(Byte1) ((__u8) ((Byte1) & IOSP_PORT_MASK))
#define IOSP_GET_HDR_DATA_LEN(Byte1, Byte2) ((__u16) (((__u16)((Byte1) & 0x78)) << 5) | (Byte2))
#define IOSP_GET_STATUS_CODE(Byte1) ((__u8) (((Byte1) & 0x78) >> 3))
//
// These macros build the 1st and 2nd bytes for a data header
//
#define IOSP_BUILD_DATA_HDR1(Port, Len) ((__u8) (((Port) | ((__u8) (((__u16) (Len)) >> 5) & 0x78))))
#define IOSP_BUILD_DATA_HDR2(Port, Len) ((__u8) (Len))
//
// These macros build the 1st and 2nd bytes for a command header
//
#define IOSP_BUILD_CMD_HDR1(Port, Cmd) ((__u8) (IOSP_CMD_STAT_BIT | (Port) | ((__u8) ((Cmd) << 3))))
//--------------------------------------------------------------
//
// Define values for commands and command parameters
// (sent from Host to Edgeport)
//
// 1ccccPPP P1P1P1P1 [ P2P2P2P2P2 ]...
//
// cccc: 00-07 2-byte commands. Write UART register 0-7 with
// value in P1. See 16650.H for definitions of
// UART register numbers and contents.
//
// 08-0B 3-byte commands: ==== P1 ==== ==== P2 ====
// 08 available for expansion
// 09 1-param commands Command Code Param
// 0A available for expansion
// 0B available for expansion
//
// 0C-0D 4-byte commands. P1 = extended cmd and P2,P3 = params
// Currently unimplemented.
//
// 0E-0F N-byte commands: P1 = num bytes after P1 (ie, TotalLen - 2)
// P2 = extended cmd, P3..Pn = parameters.
// Currently unimplemented.
//
#define IOSP_WRITE_UART_REG(n) ((n) & 0x07) // UartReg[ n ] := P1
// Register numbers and contents
// defined in 16554.H.
// 0x08 // Available for expansion.
#define IOSP_EXT_CMD 0x09 // P1 = Command code (defined below)
// P2 = Parameter
//
// Extended Command values, used with IOSP_EXT_CMD, may
// or may not use parameter P2.
//
#define IOSP_CMD_OPEN_PORT 0x00 // Enable ints, init UART. (NO PARAM)
#define IOSP_CMD_CLOSE_PORT 0x01 // Disable ints, flush buffers. (NO PARAM)
#define IOSP_CMD_CHASE_PORT 0x02 // Wait for Edgeport TX buffers to empty. (NO PARAM)
#define IOSP_CMD_SET_RX_FLOW 0x03 // Set Rx Flow Control in Edgeport
#define IOSP_CMD_SET_TX_FLOW 0x04 // Set Tx Flow Control in Edgeport
#define IOSP_CMD_SET_XON_CHAR 0x05 // Set XON Character in Edgeport
#define IOSP_CMD_SET_XOFF_CHAR 0x06 // Set XOFF Character in Edgeport
#define IOSP_CMD_RX_CHECK_REQ 0x07 // Request Edgeport to insert a Checkpoint into
// the receive data stream (Parameter = 1 byte sequence number)
#define IOSP_CMD_SET_BREAK 0x08 // Turn on the BREAK (LCR bit 6)
#define IOSP_CMD_CLEAR_BREAK 0x09 // Turn off the BREAK (LCR bit 6)
//
// Define macros to simplify building of IOSP cmds
//
#define MAKE_CMD_WRITE_REG(ppBuf, pLen, Port, Reg, Val) \
do { \
(*(ppBuf))[0] = IOSP_BUILD_CMD_HDR1((Port), \
IOSP_WRITE_UART_REG(Reg)); \
(*(ppBuf))[1] = (Val); \
\
*ppBuf += 2; \
*pLen += 2; \
} while (0)
#define MAKE_CMD_EXT_CMD(ppBuf, pLen, Port, ExtCmd, Param) \
do { \
(*(ppBuf))[0] = IOSP_BUILD_CMD_HDR1((Port), IOSP_EXT_CMD); \
(*(ppBuf))[1] = (ExtCmd); \
(*(ppBuf))[2] = (Param); \
\
*ppBuf += 3; \
*pLen += 3; \
} while (0)
//--------------------------------------------------------------
//
// Define format of flow control commands
// (sent from Host to Edgeport)
//
// 11001PPP FlowCmd FlowTypes
//
// Note that the 'FlowTypes' parameter is a bit mask; that is,
// more than one flow control type can be active at the same time.
// FlowTypes = 0 means 'no flow control'.
//
//
// IOSP_CMD_SET_RX_FLOW
//
// Tells Edgeport how it can stop incoming UART data
//
// Example for Port 0
// P0 = 11001000
// P1 = IOSP_CMD_SET_RX_FLOW
// P2 = Bit mask as follows:
#define IOSP_RX_FLOW_RTS 0x01 // Edgeport drops RTS to stop incoming data
#define IOSP_RX_FLOW_DTR 0x02 // Edgeport drops DTR to stop incoming data
#define IOSP_RX_FLOW_DSR_SENSITIVITY 0x04 // Ignores Rx data unless DSR high
// Not currently implemented by firmware.
#define IOSP_RX_FLOW_XON_XOFF 0x08 // Edgeport sends XOFF char to stop incoming data.
// Host must have previously programmed the
// XON/XOFF values with SET_XON/SET_XOFF
// before enabling this bit.
//
// IOSP_CMD_SET_TX_FLOW
//
// Tells Edgeport what signal(s) will stop it from transmitting UART data
//
// Example for Port 0
// P0 = 11001000
// P1 = IOSP_CMD_SET_TX_FLOW
// P2 = Bit mask as follows:
#define IOSP_TX_FLOW_CTS 0x01 // Edgeport stops Tx if CTS low
#define IOSP_TX_FLOW_DSR 0x02 // Edgeport stops Tx if DSR low
#define IOSP_TX_FLOW_DCD 0x04 // Edgeport stops Tx if DCD low
#define IOSP_TX_FLOW_XON_XOFF 0x08 // Edgeport stops Tx upon receiving XOFF char.
// Host must have previously programmed the
// XON/XOFF values with SET_XON/SET_XOFF
// before enabling this bit.
#define IOSP_TX_FLOW_XOFF_CONTINUE 0x10 // If not set, Edgeport stops Tx when
// sending XOFF in order to fix broken
// systems that interpret the next
// received char as XON.
// If set, Edgeport continues Tx
// normally after transmitting XOFF.
// Not currently implemented by firmware.
#define IOSP_TX_TOGGLE_RTS 0x20 // Edgeport drives RTS as a true half-duplex
// Request-to-Send signal: it is raised before
// beginning transmission and lowered after
// the last Tx char leaves the UART.
// Not currently implemented by firmware.
//
// IOSP_CMD_SET_XON_CHAR
//
// Sets the character which Edgeport transmits/interprets as XON.
// Note: This command MUST be sent before sending a SET_RX_FLOW or
// SET_TX_FLOW with the XON_XOFF bit set.
//
// Example for Port 0
// P0 = 11001000
// P1 = IOSP_CMD_SET_XON_CHAR
// P2 = 0x11
//
// IOSP_CMD_SET_XOFF_CHAR
//
// Sets the character which Edgeport transmits/interprets as XOFF.
// Note: This command must be sent before sending a SET_RX_FLOW or
// SET_TX_FLOW with the XON_XOFF bit set.
//
// Example for Port 0
// P0 = 11001000
// P1 = IOSP_CMD_SET_XOFF_CHAR
// P2 = 0x13
//
// IOSP_CMD_RX_CHECK_REQ
//
// This command is used to assist in the implementation of the
// IOCTL_SERIAL_PURGE Windows IOCTL.
// This IOSP command tries to place a marker at the end of the RX
// queue in the Edgeport. If the Edgeport RX queue is full then
// the Check will be discarded.
// It is up to the device driver to timeout waiting for the
// RX_CHECK_RSP. If a RX_CHECK_RSP is received, the driver is
// sure that all data has been received from the edgeport and
// may now purge any internal RX buffers.
// Note tat the sequence numbers may be used to detect lost
// CHECK_REQs.
// Example for Port 0
// P0 = 11001000
// P1 = IOSP_CMD_RX_CHECK_REQ
// P2 = Sequence number
// Response will be:
// P1 = IOSP_EXT_RX_CHECK_RSP
// P2 = Request Sequence number
//--------------------------------------------------------------
//
// Define values for status and status parameters
// (received by Host from Edgeport)
//
// 1ssssPPP P1P1P1P1 [ P2P2P2P2P2 ]...
//
// ssss: 00-07 2-byte status. ssss identifies which UART register
// has changed value, and the new value is in P1.
// Note that the ssss values do not correspond to the
// 16554 register numbers given in 16554.H. Instead,
// see below for definitions of the ssss numbers
// used in this status message.
//
// 08-0B 3-byte status: ==== P1 ==== ==== P2 ====
// 08 LSR_DATA: New LSR Errored byte
// 09 1-param responses Response Code Param
// 0A OPEN_RSP: InitialMsr TxBufferSize
// 0B available for expansion
//
// 0C-0D 4-byte status. P1 = extended status code and P2,P3 = params
// Not currently implemented.
//
// 0E-0F N-byte status: P1 = num bytes after P1 (ie, TotalLen - 2)
// P2 = extended status, P3..Pn = parameters.
// Not currently implemented.
//
/****************************************************
* SSSS values for 2-byte status messages (0-8)
****************************************************/
#define IOSP_STATUS_LSR 0x00 // P1 is new value of LSR register.
// Bits defined in 16554.H. Edgeport
// returns this in order to report
// line status errors (overrun,
// parity, framing, break). This form
// is used when a errored receive data
// character was NOT present in the
// UART when the LSR error occurred
// (ie, when LSR bit 0 = 0).
#define IOSP_STATUS_MSR 0x01 // P1 is new value of MSR register.
// Bits defined in 16554.H. Edgeport
// returns this in order to report
// changes in modem status lines
// (CTS, DSR, RI, CD)
//
// 0x02 // Available for future expansion
// 0x03 //
// 0x04 //
// 0x05 //
// 0x06 //
// 0x07 //
/****************************************************
* SSSS values for 3-byte status messages (8-A)
****************************************************/
#define IOSP_STATUS_LSR_DATA 0x08 // P1 is new value of LSR register (same as STATUS_LSR)
// P2 is errored character read from
// RxFIFO after LSR reported an error.
#define IOSP_EXT_STATUS 0x09 // P1 is status/response code, param in P2.
// Response Codes (P1 values) for 3-byte status messages
#define IOSP_EXT_STATUS_CHASE_RSP 0 // Reply to CHASE_PORT cmd. P2 is outcome:
#define IOSP_EXT_STATUS_CHASE_PASS 0 // P2 = 0: All Tx data drained successfully
#define IOSP_EXT_STATUS_CHASE_FAIL 1 // P2 = 1: Timed out (stuck due to flow
// control from remote device).
#define IOSP_EXT_STATUS_RX_CHECK_RSP 1 // Reply to RX_CHECK cmd. P2 is sequence number
#define IOSP_STATUS_OPEN_RSP 0x0A // Reply to OPEN_PORT cmd.
// P1 is Initial MSR value
// P2 is encoded TxBuffer Size:
// TxBufferSize = (P2 + 1) * 64
// 0x0B // Available for future expansion
#define GET_TX_BUFFER_SIZE(P2) (((P2) + 1) * 64)
/****************************************************
* SSSS values for 4-byte status messages
****************************************************/
#define IOSP_EXT4_STATUS 0x0C // Extended status code in P1,
// Params in P2, P3
// Currently unimplemented.
// 0x0D // Currently unused, available.
//
// Macros to parse status messages
//
#define IOSP_GET_STATUS_LEN(code) ((code) < 8 ? 2 : ((code) < 0x0A ? 3 : 4))
#define IOSP_STATUS_IS_2BYTE(code) ((code) < 0x08)
#define IOSP_STATUS_IS_3BYTE(code) (((code) >= 0x08) && ((code) <= 0x0B))
#define IOSP_STATUS_IS_4BYTE(code) (((code) >= 0x0C) && ((code) <= 0x0D))
| sigma-random/asuswrt-merlin | release/src-rt-7.x.main/src/linux/linux-2.6.36/drivers/usb/serial/io_ionsp.h | C | gpl-2.0 | 14,546 |
// 2004-07-07 Paolo Carlini <[email protected]>
// Copyright (C) 2004-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 27.7.1.3 basic_stringbuf overridden virtual functions.
#include <sstream>
#include <cstdlib>
#include <testsuite_hooks.h>
using namespace std;
string
data(unsigned len)
{
string ret;
for (unsigned i = 0; i < len; ++i)
ret.push_back('a' + rand() % 26);
return ret;
}
void
test01(unsigned iter)
{
bool test __attribute__((unused)) = true;
for (unsigned n = 1; n <= iter; n *= 10)
{
const string str = data(n);
stringbuf sstr;
for (unsigned i = 0; i < n; ++i)
sstr.sputc(str[i]);
VERIFY( str == sstr.str() );
}
}
// This can take long on simulators, timing out the test.
// { dg-options "-DITERATIONS=10000" { target simulator } }
#ifndef ITERATIONS
#define ITERATIONS 10000000
#endif
int main()
{
test01(ITERATIONS);
return 0;
}
| crystax/android-toolchain-gcc-5 | libstdc++-v3/testsuite/27_io/basic_stringbuf/overflow/char/1.cc | C++ | gpl-2.0 | 1,602 |
<?php
/**
* @package Widgetkit
* @author YOOtheme http://www.yootheme.com
* @copyright Copyright (C) YOOtheme GmbH
* @license http://www.gnu.org/licenses/gpl.html GNU/GPL
*/
/*
Class: LightboxWidgetkitHelper
Lightbox helper class
*/
class LightboxWidgetkitHelper extends WidgetkitHelper {
/* type */
public $type;
/* options */
public $options;
/*
Function: Constructor
Class Constructor.
*/
public function __construct($widgetkit) {
parent::__construct($widgetkit);
// init vars
$this->type = strtolower(str_replace('WidgetkitHelper', '', get_class($this)));
$this->options = $this['system']->options;
// register path
$this['path']->register(dirname(__FILE__), $this->type);
}
/*
Function: site
Site init actions
Returns:
Void
*/
public function site() {
$options = array();
// get options
foreach (array('title_position' => 'float', 'transition_in' => 'fade', 'transition_out' => 'fade', 'overlay_show' => 1, 'overlay_color' => '#777', 'overlay_opacity' => 0.7) as $option => $value) {
$var = preg_replace_callback('/[_-]+(.)?/i', create_function('$matches', 'return strtoupper($matches[1]);'), $option);
$val = $this->options->get('lightbox_'.$option, $value);
$options[$var] = is_numeric($val) ? (float) $val : $val;
}
// is enabled ?
if ($this->options->get('lightbox_enable', 1)) {
$lightboxjs = $this['path']->url("lightbox:js/lightbox.js");
$selector = $this->options->get('lightbox_selector', 'a[data-lightbox]');
$params = count($options) ? json_encode($options) : '{}';
// add stylesheets/javascripts
$this['asset']->addFile('css', 'lightbox:css/lightbox.css');
$this['asset']->addString('js', "\$widgetkit.load('{$lightboxjs}').done(function(){
jQuery(function($){
setTimeout(function() {
$('{$selector}').lightbox({$params});
}, 500);
});
});");
// rtl
if ($this['system']->options->get('direction') == 'rtl') {
$this['asset']->addFile('css', 'lightbox:css/rtl.css');
}
}
}
/*
Function: dashboard
Render dashboard layout
Returns:
Void
*/
public function dashboard() {
// get xml
$xml = simplexml_load_file($this['path']->path('lightbox:lightbox.xml'));
// add js
$this['asset']->addFile('js', 'lightbox:js/dashboard.js');
// render dashboard
echo $this['template']->render('lightbox:layouts/dashboard', compact('xml'));
}
/*
Function: config
Save configuration
Returns:
Void
*/
public function config() {
// save configuration
foreach ($this['request']->get('post:', 'array') as $option => $value) {
if (preg_match('/^lightbox_/', $option)) {
$this['system']->options->set($option, $value);
}
}
$this['system']->saveOptions();
}
}
// bind events
$widgetkit = Widgetkit::getInstance();
$widgetkit['event']->bind('site', array($widgetkit['lightbox'], 'site'));
$widgetkit['event']->bind('dashboard', array($widgetkit['lightbox'], 'dashboard'));
$widgetkit['event']->bind('task:config_lightbox', array($widgetkit['lightbox'], 'config'));
| newflit/yoo | wp-content/plugins/widgetkit/widgets/lightbox/lightbox.php | PHP | gpl-2.0 | 3,125 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Marco Miozzo <[email protected]>
*/
#include "lte-radio-bearer-tag.h"
#include "ns3/tag.h"
#include "ns3/uinteger.h"
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (LteRadioBearerTag);
TypeId
LteRadioBearerTag::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::LteRadioBearerTag")
.SetParent<Tag> ()
.AddConstructor<LteRadioBearerTag> ()
.AddAttribute ("rnti", "The rnti that indicates the UE to which packet belongs",
UintegerValue (0),
MakeUintegerAccessor (&LteRadioBearerTag::GetRnti),
MakeUintegerChecker<uint16_t> ())
.AddAttribute ("lcid", "The id whithin the UE identifying the logical channel to which the packet belongs",
UintegerValue (0),
MakeUintegerAccessor (&LteRadioBearerTag::GetLcid),
MakeUintegerChecker<uint8_t> ())
;
return tid;
}
TypeId
LteRadioBearerTag::GetInstanceTypeId (void) const
{
return GetTypeId ();
}
LteRadioBearerTag::LteRadioBearerTag ()
: m_rnti (0),
m_lcid (0),
m_layer (0)
{
}
LteRadioBearerTag::LteRadioBearerTag (uint16_t rnti, uint8_t lcid)
: m_rnti (rnti),
m_lcid (lcid)
{
}
LteRadioBearerTag::LteRadioBearerTag (uint16_t rnti, uint8_t lcid, uint8_t layer)
: m_rnti (rnti),
m_lcid (lcid),
m_layer (layer)
{
}
void
LteRadioBearerTag::SetRnti (uint16_t rnti)
{
m_rnti = rnti;
}
void
LteRadioBearerTag::SetLcid (uint8_t lcid)
{
m_lcid = lcid;
}
void
LteRadioBearerTag::SetLayer (uint8_t layer)
{
m_layer = layer;
}
uint32_t
LteRadioBearerTag::GetSerializedSize (void) const
{
return 4;
}
void
LteRadioBearerTag::Serialize (TagBuffer i) const
{
i.WriteU16 (m_rnti);
i.WriteU8 (m_lcid);
i.WriteU8 (m_layer);
}
void
LteRadioBearerTag::Deserialize (TagBuffer i)
{
m_rnti = (uint16_t) i.ReadU16 ();
m_lcid = (uint8_t) i.ReadU8 ();
m_layer = (uint8_t) i.ReadU8 ();
}
uint16_t
LteRadioBearerTag::GetRnti () const
{
return m_rnti;
}
uint8_t
LteRadioBearerTag::GetLcid () const
{
return m_lcid;
}
uint8_t
LteRadioBearerTag::GetLayer () const
{
return m_layer;
}
void
LteRadioBearerTag::Print (std::ostream &os) const
{
os << "rnti=" << m_rnti << ", lcid=" << (uint16_t) m_lcid << ", layer=" << (uint16_t)m_layer;
}
} // namespace ns3
| thehajime/ns-3-dev | src/lte/model/lte-radio-bearer-tag.cc | C++ | gpl-2.0 | 3,092 |
<?php
/**
*
* product_medias table ( for media)
*
* @package VirtueMart
* @subpackage Calculation tool
* @author Max Milbers
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: product_medias.php 3002 2011-04-08 12:35:45Z alatak $
*/
defined('_JEXEC') or die();
if(!class_exists('VmTableXarray'))require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmtablexarray.php');
/**
* Calculator table class
* The class is is used to manage the media in the shop.
*
* @author Max Milbers
* @package VirtueMart
*/
class TableProduct_manufacturers extends VmTableXarray {
/**
* @author Max Milbers
* @param JDataBase $db
*/
function __construct(&$db){
parent::__construct('#__virtuemart_product_manufacturers', 'id', $db);
$this->setPrimaryKey('virtuemart_product_id');
$this->setSecondaryKey('virtuemart_manufacturer_id');
}
}
| arlesonsilva/fortalpet | tmp/install_5488d6f0c9a33/administrator/components/com_virtuemart/tables/product_manufacturers.php | PHP | gpl-2.0 | 1,258 |
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
//{block name="backend/site/store/shop"}
Ext.define('Shopware.apps.Site.store.Shop', {
extend : 'Shopware.apps.Base.store.ShopLanguage'
});
//{/block}
| Goucher/shopware | themes/Backend/ExtJs/backend/site/store/shop.js | JavaScript | agpl-3.0 | 1,087 |
#-------------------------------------------------------------------------
#
# Makefile for ecpg pgtypes library
#
# Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
# Portions Copyright (c) 1994, Regents of the University of California
#
# $PostgreSQL: pgsql/src/interfaces/ecpg/pgtypeslib/Makefile,v 1.43 2009/01/01 17:24:02 momjian Exp $
#
#-------------------------------------------------------------------------
subdir = src/interfaces/ecpg/pgtypeslib
top_builddir = ../../../..
include $(top_builddir)/src/Makefile.global
NAME= pgtypes
SO_MAJOR_VERSION= 3
SO_MINOR_VERSION= 1
# The frontend doesn't need everything that's in LIBS, some are backend only
LIBS := $(filter-out -lresolv -lbz2, $(LIBS))
# This program isn't interactive, so doesn't need these
LIBS := $(filter-out -lreadline -ledit -ltermcap -lncurses -lcurses -lcurl -lssl -lcrypto -lz, $(LIBS))
override CPPFLAGS := -DFRONTEND \
-I../include -I$(top_srcdir)/src/interfaces/ecpg/include \
-I$(top_srcdir)/src/include/utils -I$(libpq_srcdir) $(CPPFLAGS)
override CFLAGS += $(PTHREAD_CFLAGS)
# Need to recompile any libpgport object files
LIBS := $(filter-out -lpgport, $(LIBS))
SHLIB_LINK += -lm
SHLIB_EXPORTS = exports.txt
OBJS= numeric.o datetime.o common.o dt_common.o timestamp.o interval.o \
pgstrcasecmp.o \
$(filter rint.o snprintf.o, $(LIBOBJS))
all: all-lib
# Shared library stuff
include $(top_srcdir)/src/Makefile.shlib
# We use some port modules verbatim, but since we need to
# compile with appropriate options to build a shared lib, we can't
# necessarily use the same object files as the backend uses. Instead,
# symlink the source files in here and build our own object file.
pgstrcasecmp.c rint.c snprintf.c: % : $(top_srcdir)/src/port/%
rm -f $@ && $(LN_S) $< .
install: all installdirs install-lib
installdirs: installdirs-lib
uninstall: uninstall-lib
clean distclean: clean-lib
rm -f $(OBJS) pgstrcasecmp.c rint.c snprintf.c
maintainer-clean: distclean maintainer-clean-lib
| rubikloud/gpdb | src/interfaces/ecpg/pgtypeslib/Makefile | Makefile | apache-2.0 | 2,007 |
package archive
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
"github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/pools"
"github.com/docker/docker/pkg/system"
)
type ChangeType int
const (
ChangeModify = iota
ChangeAdd
ChangeDelete
)
type Change struct {
Path string
Kind ChangeType
}
func (change *Change) String() string {
var kind string
switch change.Kind {
case ChangeModify:
kind = "C"
case ChangeAdd:
kind = "A"
case ChangeDelete:
kind = "D"
}
return fmt.Sprintf("%s %s", kind, change.Path)
}
// for sort.Sort
type changesByPath []Change
func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path }
func (c changesByPath) Len() int { return len(c) }
func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] }
// Gnu tar and the go tar writer don't have sub-second mtime
// precision, which is problematic when we apply changes via tar
// files, we handle this by comparing for exact times, *or* same
// second count and either a or b having exactly 0 nanoseconds
func sameFsTime(a, b time.Time) bool {
return a == b ||
(a.Unix() == b.Unix() &&
(a.Nanosecond() == 0 || b.Nanosecond() == 0))
}
func sameFsTimeSpec(a, b syscall.Timespec) bool {
return a.Sec == b.Sec &&
(a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0)
}
// Changes walks the path rw and determines changes for the files in the path,
// with respect to the parent layers
func Changes(layers []string, rw string) ([]Change, error) {
var changes []Change
err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
// Rebase path
path, err = filepath.Rel(rw, path)
if err != nil {
return err
}
path = filepath.Join("/", path)
// Skip root
if path == "/" {
return nil
}
// Skip AUFS metadata
if matched, err := filepath.Match("/.wh..wh.*", path); err != nil || matched {
return err
}
change := Change{
Path: path,
}
// Find out what kind of modification happened
file := filepath.Base(path)
// If there is a whiteout, then the file was removed
if strings.HasPrefix(file, ".wh.") {
originalFile := file[len(".wh."):]
change.Path = filepath.Join(filepath.Dir(path), originalFile)
change.Kind = ChangeDelete
} else {
// Otherwise, the file was added
change.Kind = ChangeAdd
// ...Unless it already existed in a top layer, in which case, it's a modification
for _, layer := range layers {
stat, err := os.Stat(filepath.Join(layer, path))
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil {
// The file existed in the top layer, so that's a modification
// However, if it's a directory, maybe it wasn't actually modified.
// If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar
if stat.IsDir() && f.IsDir() {
if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) {
// Both directories are the same, don't record the change
return nil
}
}
change.Kind = ChangeModify
break
}
}
}
// Record change
changes = append(changes, change)
return nil
})
if err != nil && !os.IsNotExist(err) {
return nil, err
}
return changes, nil
}
type FileInfo struct {
parent *FileInfo
name string
stat *system.Stat
children map[string]*FileInfo
capability []byte
added bool
}
func (root *FileInfo) LookUp(path string) *FileInfo {
parent := root
if path == "/" {
return root
}
pathElements := strings.Split(path, "/")
for _, elem := range pathElements {
if elem != "" {
child := parent.children[elem]
if child == nil {
return nil
}
parent = child
}
}
return parent
}
func (info *FileInfo) path() string {
if info.parent == nil {
return "/"
}
return filepath.Join(info.parent.path(), info.name)
}
func (info *FileInfo) isDir() bool {
return info.parent == nil || info.stat.Mode()&syscall.S_IFDIR == syscall.S_IFDIR
}
func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) {
sizeAtEntry := len(*changes)
if oldInfo == nil {
// add
change := Change{
Path: info.path(),
Kind: ChangeAdd,
}
*changes = append(*changes, change)
info.added = true
}
// We make a copy so we can modify it to detect additions
// also, we only recurse on the old dir if the new info is a directory
// otherwise any previous delete/change is considered recursive
oldChildren := make(map[string]*FileInfo)
if oldInfo != nil && info.isDir() {
for k, v := range oldInfo.children {
oldChildren[k] = v
}
}
for name, newChild := range info.children {
oldChild, _ := oldChildren[name]
if oldChild != nil {
// change?
oldStat := oldChild.stat
newStat := newChild.stat
// Note: We can't compare inode or ctime or blocksize here, because these change
// when copying a file into a container. However, that is not generally a problem
// because any content change will change mtime, and any status change should
// be visible when actually comparing the stat fields. The only time this
// breaks down is if some code intentionally hides a change by setting
// back mtime
if oldStat.Mode() != newStat.Mode() ||
oldStat.Uid() != newStat.Uid() ||
oldStat.Gid() != newStat.Gid() ||
oldStat.Rdev() != newStat.Rdev() ||
// Don't look at size for dirs, its not a good measure of change
(oldStat.Size() != newStat.Size() && oldStat.Mode()&syscall.S_IFDIR != syscall.S_IFDIR) ||
!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) ||
bytes.Compare(oldChild.capability, newChild.capability) != 0 {
change := Change{
Path: newChild.path(),
Kind: ChangeModify,
}
*changes = append(*changes, change)
newChild.added = true
}
// Remove from copy so we can detect deletions
delete(oldChildren, name)
}
newChild.addChanges(oldChild, changes)
}
for _, oldChild := range oldChildren {
// delete
change := Change{
Path: oldChild.path(),
Kind: ChangeDelete,
}
*changes = append(*changes, change)
}
// If there were changes inside this directory, we need to add it, even if the directory
// itself wasn't changed. This is needed to properly save and restore filesystem permissions.
if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != "/" {
change := Change{
Path: info.path(),
Kind: ChangeModify,
}
// Let's insert the directory entry before the recently added entries located inside this dir
*changes = append(*changes, change) // just to resize the slice, will be overwritten
copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:])
(*changes)[sizeAtEntry] = change
}
}
func (info *FileInfo) Changes(oldInfo *FileInfo) []Change {
var changes []Change
info.addChanges(oldInfo, &changes)
return changes
}
func newRootFileInfo() *FileInfo {
root := &FileInfo{
name: "/",
children: make(map[string]*FileInfo),
}
return root
}
func collectFileInfo(sourceDir string) (*FileInfo, error) {
root := newRootFileInfo()
err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
// Rebase path
relPath, err := filepath.Rel(sourceDir, path)
if err != nil {
return err
}
relPath = filepath.Join("/", relPath)
if relPath == "/" {
return nil
}
parent := root.LookUp(filepath.Dir(relPath))
if parent == nil {
return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath)
}
info := &FileInfo{
name: filepath.Base(relPath),
children: make(map[string]*FileInfo),
parent: parent,
}
s, err := system.Lstat(path)
if err != nil {
return err
}
info.stat = s
info.capability, _ = system.Lgetxattr(path, "security.capability")
parent.children[info.name] = info
return nil
})
if err != nil {
return nil, err
}
return root, nil
}
// ChangesDirs compares two directories and generates an array of Change objects describing the changes.
// If oldDir is "", then all files in newDir will be Add-Changes.
func ChangesDirs(newDir, oldDir string) ([]Change, error) {
var (
oldRoot, newRoot *FileInfo
err1, err2 error
errs = make(chan error, 2)
)
go func() {
if oldDir != "" {
oldRoot, err1 = collectFileInfo(oldDir)
}
errs <- err1
}()
go func() {
newRoot, err2 = collectFileInfo(newDir)
errs <- err2
}()
// block until both routines have returned
for i := 0; i < 2; i++ {
if err := <-errs; err != nil {
return nil, err
}
}
return newRoot.Changes(oldRoot), nil
}
// ChangesSize calculates the size in bytes of the provided changes, based on newDir.
func ChangesSize(newDir string, changes []Change) int64 {
var size int64
for _, change := range changes {
if change.Kind == ChangeModify || change.Kind == ChangeAdd {
file := filepath.Join(newDir, change.Path)
fileInfo, _ := os.Lstat(file)
if fileInfo != nil && !fileInfo.IsDir() {
size += fileInfo.Size()
}
}
}
return size
}
// ExportChanges produces an Archive from the provided changes, relative to dir.
func ExportChanges(dir string, changes []Change) (Archive, error) {
reader, writer := io.Pipe()
go func() {
ta := &tarAppender{
TarWriter: tar.NewWriter(writer),
Buffer: pools.BufioWriter32KPool.Get(nil),
SeenFiles: make(map[uint64]string),
}
// this buffer is needed for the duration of this piped stream
defer pools.BufioWriter32KPool.Put(ta.Buffer)
sort.Sort(changesByPath(changes))
// In general we log errors here but ignore them because
// during e.g. a diff operation the container can continue
// mutating the filesystem and we can see transient errors
// from this
for _, change := range changes {
if change.Kind == ChangeDelete {
whiteOutDir := filepath.Dir(change.Path)
whiteOutBase := filepath.Base(change.Path)
whiteOut := filepath.Join(whiteOutDir, ".wh."+whiteOutBase)
timestamp := time.Now()
hdr := &tar.Header{
Name: whiteOut[1:],
Size: 0,
ModTime: timestamp,
AccessTime: timestamp,
ChangeTime: timestamp,
}
if err := ta.TarWriter.WriteHeader(hdr); err != nil {
log.Debugf("Can't write whiteout header: %s", err)
}
} else {
path := filepath.Join(dir, change.Path)
if err := ta.addTarFile(path, change.Path[1:]); err != nil {
log.Debugf("Can't add file %s to tar: %s", path, err)
}
}
}
// Make sure to check the error on Close.
if err := ta.TarWriter.Close(); err != nil {
log.Debugf("Can't close layer: %s", err)
}
if err := writer.Close(); err != nil {
log.Debugf("failed close Changes writer: %s", err)
}
}()
return reader, nil
}
| spf13/docker | pkg/archive/changes.go | GO | apache-2.0 | 10,924 |
ALTER TABLE addons ADD COLUMN premium_type tinyint(1) unsigned NOT NULL DEFAULT 0;
CREATE INDEX premium_type_idx ON addons (premium_type);
| harikishen/addons-server | src/olympia/migrations/224-create-premium.sql | SQL | bsd-3-clause | 139 |
TOPDIR = ../../..
include ../../../Makefile.system
include ../generic/Makefile
| boombatower/opentoonz | thirdparty/openblas/xianyi-OpenBLAS-e6e87a2/lapack/laswp/ia64/Makefile | Makefile | bsd-3-clause | 81 |
'use strict';
var hljs = require('highlight.js/lib/highlight');
var Entities = require('html-entities').XmlEntities;
var entities = new Entities();
var alias = require('../highlight_alias.json');
hljs.configure({
classPrefix: ''
});
function highlightUtil(str, options) {
if (typeof str !== 'string') throw new TypeError('str must be a string!');
options = options || {};
var gutter = options.hasOwnProperty('gutter') ? options.gutter : true;
var wrap = options.hasOwnProperty('wrap') ? options.wrap : true;
var firstLine = options.hasOwnProperty('firstLine') ? +options.firstLine : 1;
var caption = options.caption;
var mark = options.hasOwnProperty('mark') ? options.mark : [];
var tab = options.tab;
var data = highlight(str, options);
if (!wrap) return data.value;
var lines = data.value.split('\n');
var numbers = '';
var content = '';
var result = '';
var line;
for (var i = 0, len = lines.length; i < len; i++) {
line = lines[i];
if (tab) line = replaceTabs(line, tab);
numbers += '<div class="line">' + (firstLine + i) + '</div>';
content += '<div class="line';
content += (mark.indexOf(firstLine + i) !== -1) ? ' marked' : '';
content += '">' + line + '</div>';
}
result += '<figure class="highlight' + (data.language ? ' ' + data.language : '') + '">';
if (caption) {
result += '<figcaption>' + caption + '</figcaption>';
}
result += '<table><tr>';
if (gutter) {
result += '<td class="gutter"><pre>' + numbers + '</pre></td>';
}
result += '<td class="code"><pre>' + content + '</pre></td>';
result += '</tr></table></figure>';
return result;
}
function encodePlainString(str) {
return entities.encode(str);
}
function replaceTabs(str, tab) {
return str.replace(/^\t+/, function(match) {
var result = '';
for (var i = 0, len = match.length; i < len; i++) {
result += tab;
}
return result;
});
}
function loadLanguage(lang) {
hljs.registerLanguage(lang, require('highlight.js/lib/languages/' + lang));
}
function tryLanguage(lang) {
if (hljs.getLanguage(lang)) return true;
if (!alias.aliases[lang]) return false;
loadLanguage(alias.aliases[lang]);
return true;
}
function loadAllLanguages() {
alias.languages.filter(function(lang) {
return !hljs.getLanguage(lang);
}).forEach(loadLanguage);
}
function highlight(str, options) {
var lang = options.lang;
var autoDetect = options.hasOwnProperty('autoDetect') ? options.autoDetect : false;
if (!lang) {
if (autoDetect) {
loadAllLanguages();
return hljs.highlightAuto(str);
}
lang = 'plain';
}
var result = {
value: encodePlainString(str),
language: lang.toLowerCase()
};
if (result.language === 'plain') {
return result;
}
if (!tryLanguage(result.language)) {
result.language = 'plain';
return result;
}
return tryHighlight(str, result.language) || result;
}
function tryHighlight(str, lang) {
try {
return hljs.highlight(lang, str);
} catch (err) {
return;
}
}
module.exports = highlightUtil;
| sanskritnotes/sanskritnotes.com | node_modules/hexo/node_modules/hexo-util/lib/highlight.js | JavaScript | mit | 3,092 |
/**
* @private
*/
Ext.define('Ext.slider.Toggle', {
extend: 'Ext.slider.Slider',
config: {
/**
* @cfg
* @inheritdoc
*/
baseCls: 'x-toggle',
/**
* @cfg {String} minValueCls CSS class added to the field when toggled to its minValue
* @accessor
*/
minValueCls: 'x-toggle-off',
/**
* @cfg {String} maxValueCls CSS class added to the field when toggled to its maxValue
* @accessor
*/
maxValueCls: 'x-toggle-on'
},
initialize: function() {
this.callParent();
this.on({
change: 'onChange'
});
},
applyMinValue: function() {
return 0;
},
applyMaxValue: function() {
return 1;
},
applyIncrement: function() {
return 1;
},
updateMinValueCls: function(newCls, oldCls) {
var element = this.element;
if (oldCls && element.hasCls(oldCls)) {
element.replaceCls(oldCls, newCls);
}
},
updateMaxValueCls: function(newCls, oldCls) {
var element = this.element;
if (oldCls && element.hasCls(oldCls)) {
element.replaceCls(oldCls, newCls);
}
},
setValue: function(newValue, oldValue) {
this.callParent(arguments);
this.onChange(this, this.getThumbs()[0], newValue, oldValue);
},
onChange: function(me, thumb, newValue, oldValue) {
var isOn = newValue > 0,
onCls = me.getMaxValueCls(),
offCls = me.getMinValueCls();
this.element.addCls(isOn ? onCls : offCls);
this.element.removeCls(isOn ? offCls : onCls);
},
toggle: function() {
var value = this.getValue();
this.setValue((value == 1) ? 0 : 1);
return this;
},
onTap: function() {
if (this.isDisabled() || this.getReadOnly()) {
return;
}
var oldValue = this.getValue(),
newValue = (oldValue == 1) ? 0 : 1,
thumb = this.getThumb(0);
this.setIndexValue(0, newValue, this.getAnimation());
this.refreshThumbConstraints(thumb);
this.fireEvent('change', this, thumb, newValue, oldValue);
}
});
| hackathon-3d/team-gryffindor-repo | www/touch/src/slider/Toggle.js | JavaScript | gpl-2.0 | 2,265 |
//>>built
define("dojox/gfx/move", ["dojo/_base/lang", "./Mover", "./Moveable"],
function(lang){ return lang.getObject("dojox.gfx.move", true); });
| marcbuils/WorkESB | www/admin/lib/dojo/dojox/gfx/move.js.uncompressed.js | JavaScript | lgpl-3.0 | 151 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.platform.cache.store;
/**
* Marker interface denoting that this instance is platform cache store.
*/
public interface PlatformCacheStore {
// No-op.
} | irudyak/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/store/PlatformCacheStore.java | Java | apache-2.0 | 1,007 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.distributed.dht;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.internal.processors.cache.distributed.GridCachePartitionedReloadAllAbstractSelfTest;
import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
/**
* Tests reloadAll for colocated cache.
*/
public class GridCacheAtomicReloadAllSelfTest extends GridCachePartitionedReloadAllAbstractSelfTest {
/** {@inheritDoc} */
@Override protected CacheAtomicityMode atomicityMode() {
return ATOMIC;
}
/** {@inheritDoc} */
@Override protected boolean nearEnabled() {
return false;
}
} | murador/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridCacheAtomicReloadAllSelfTest.java | Java | apache-2.0 | 1,470 |
<ul class="smartPhoneList">
<li class="title">{$page_navigation->total_count} items, {$page_navigation->cur_page}/{$page_navigation->last_page} pages</li>
<!--@foreach($document_list as $val)-->
<li class="item">
<a href="{getUrl('document_srl',$val->document_srl)}">
<span class="title">{$val->getTitleText()}</span>
<span class="info">
{$val->getRegdate()}
[{$val->getNickName()}]
<!--@if($val->getCommentCount())-->comments({$val->getCommentCount()})<!--@end-->
</span>
</a>
</li>
<!--@end-->
</ul>
| talkwithraon/XE4KAIST | xe4kaist/modules/board/tpl/smartphone/list.html | HTML | apache-2.0 | 618 |
.palette-item {
border: 1px solid transparent;
}
.palette-item-inner {
border: 1px solid #666;
}
.palette-item-hover {
border: 1px solid #000;
} | BryanEngler/alloy-ui | src/aui-palette/assets/skins/sam/aui-palette-skin.css | CSS | bsd-3-clause | 158 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.1.5
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var component_1 = require("../../widgets/component");
var PopupEditorWrapper = (function (_super) {
__extends(PopupEditorWrapper, _super);
function PopupEditorWrapper(cellEditor) {
_super.call(this, '<div class="ag-popup-editor"/>');
this.getGuiCalledOnChild = false;
this.cellEditor = cellEditor;
this.addDestroyFunc(function () { return cellEditor.destroy(); });
this.addDestroyableEventListener(
// this needs to be 'super' and not 'this' as if we call 'this',
// it ends up called 'getGui()' on the child before 'init' was called,
// which is not good
_super.prototype.getGui.call(this), 'keydown', this.onKeyDown.bind(this));
}
PopupEditorWrapper.prototype.onKeyDown = function (event) {
this.params.onKeyDown(event);
};
PopupEditorWrapper.prototype.getGui = function () {
// we call getGui() on child here (rather than in the constructor)
// as we should wait for 'init' to be called on child first.
if (!this.getGuiCalledOnChild) {
this.appendChild(this.cellEditor.getGui());
this.getGuiCalledOnChild = true;
}
return _super.prototype.getGui.call(this);
};
PopupEditorWrapper.prototype.init = function (params) {
this.params = params;
if (this.cellEditor.init) {
this.cellEditor.init(params);
}
};
PopupEditorWrapper.prototype.afterGuiAttached = function () {
if (this.cellEditor.afterGuiAttached) {
this.cellEditor.afterGuiAttached();
}
};
PopupEditorWrapper.prototype.getValue = function () {
return this.cellEditor.getValue();
};
PopupEditorWrapper.prototype.isPopup = function () {
return true;
};
return PopupEditorWrapper;
})(component_1.Component);
exports.PopupEditorWrapper = PopupEditorWrapper;
| Eurofunk/ag-grid | dist/lib/rendering/cellEditors/popupEditorWrapper.js | JavaScript | mit | 2,338 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.1.5
* @link http://www.ag-grid.com/
* @license MIT
*/
var grid_1 = require("./grid");
var gridApi_1 = require("./gridApi");
var events_1 = require("./events");
var componentUtil_1 = require("./components/componentUtil");
var columnController_1 = require("./columnController/columnController");
var agGridNg1_1 = require("./components/agGridNg1");
var agGridWebComponent_1 = require("./components/agGridWebComponent");
var gridCell_1 = require("./entities/gridCell");
var rowNode_1 = require("./entities/rowNode");
var originalColumnGroup_1 = require("./entities/originalColumnGroup");
var columnGroup_1 = require("./entities/columnGroup");
var column_1 = require("./entities/column");
var focusedCellController_1 = require("./focusedCellController");
var functions_1 = require("./functions");
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var balancedColumnTreeBuilder_1 = require("./columnController/balancedColumnTreeBuilder");
var columnKeyCreator_1 = require("./columnController/columnKeyCreator");
var columnUtils_1 = require("./columnController/columnUtils");
var displayedGroupCreator_1 = require("./columnController/displayedGroupCreator");
var groupInstanceIdCreator_1 = require("./columnController/groupInstanceIdCreator");
var context_1 = require("./context/context");
var dragAndDropService_1 = require("./dragAndDrop/dragAndDropService");
var dragService_1 = require("./dragAndDrop/dragService");
var filterManager_1 = require("./filter/filterManager");
var numberFilter_1 = require("./filter/numberFilter");
var textFilter_1 = require("./filter/textFilter");
var gridPanel_1 = require("./gridPanel/gridPanel");
var mouseEventService_1 = require("./gridPanel/mouseEventService");
var cssClassApplier_1 = require("./headerRendering/cssClassApplier");
var headerContainer_1 = require("./headerRendering/headerContainer");
var headerRenderer_1 = require("./headerRendering/headerRenderer");
var headerTemplateLoader_1 = require("./headerRendering/headerTemplateLoader");
var horizontalDragService_1 = require("./headerRendering/horizontalDragService");
var moveColumnController_1 = require("./headerRendering/moveColumnController");
var renderedHeaderCell_1 = require("./headerRendering/renderedHeaderCell");
var renderedHeaderGroupCell_1 = require("./headerRendering/renderedHeaderGroupCell");
var standardMenu_1 = require("./headerRendering/standardMenu");
var borderLayout_1 = require("./layout/borderLayout");
var tabbedLayout_1 = require("./layout/tabbedLayout");
var verticalStack_1 = require("./layout/verticalStack");
var autoWidthCalculator_1 = require("./rendering/autoWidthCalculator");
var renderedRow_1 = require("./rendering/renderedRow");
var rowRenderer_1 = require("./rendering/rowRenderer");
var fillterStage_1 = require("./rowControllers/inMemory/fillterStage");
var flattenStage_1 = require("./rowControllers/inMemory/flattenStage");
var sortStage_1 = require("./rowControllers/inMemory/sortStage");
var floatingRowModel_1 = require("./rowControllers/floatingRowModel");
var paginationController_1 = require("./rowControllers/paginationController");
var component_1 = require("./widgets/component");
var menuList_1 = require("./widgets/menuList");
var cellNavigationService_1 = require("./cellNavigationService");
var columnChangeEvent_1 = require("./columnChangeEvent");
var constants_1 = require("./constants");
var csvCreator_1 = require("./csvCreator");
var eventService_1 = require("./eventService");
var expressionService_1 = require("./expressionService");
var gridCore_1 = require("./gridCore");
var logger_1 = require("./logger");
var masterSlaveService_1 = require("./masterSlaveService");
var selectionController_1 = require("./selectionController");
var selectionRendererFactory_1 = require("./selectionRendererFactory");
var sortController_1 = require("./sortController");
var svgFactory_1 = require("./svgFactory");
var templateService_1 = require("./templateService");
var utils_1 = require("./utils");
var valueService_1 = require("./valueService");
var popupService_1 = require("./widgets/popupService");
var gridRow_1 = require("./entities/gridRow");
var inMemoryRowModel_1 = require("./rowControllers/inMemory/inMemoryRowModel");
var virtualPageRowModel_1 = require("./rowControllers/virtualPageRowModel");
var menuItemComponent_1 = require("./widgets/menuItemComponent");
var animateSlideCellRenderer_1 = require("./rendering/cellRenderers/animateSlideCellRenderer");
var cellEditorFactory_1 = require("./rendering/cellEditorFactory");
var popupEditorWrapper_1 = require("./rendering/cellEditors/popupEditorWrapper");
var popupSelectCellEditor_1 = require("./rendering/cellEditors/popupSelectCellEditor");
var popupTextCellEditor_1 = require("./rendering/cellEditors/popupTextCellEditor");
var selectCellEditor_1 = require("./rendering/cellEditors/selectCellEditor");
var textCellEditor_1 = require("./rendering/cellEditors/textCellEditor");
var cellRendererFactory_1 = require("./rendering/cellRendererFactory");
var groupCellRenderer_1 = require("./rendering/cellRenderers/groupCellRenderer");
var cellRendererService_1 = require("./rendering/cellRendererService");
var valueFormatterService_1 = require("./rendering/valueFormatterService");
var dateCellEditor_1 = require("./rendering/cellEditors/dateCellEditor");
function populateClientExports(exports) {
// columnController
exports.BalancedColumnTreeBuilder = balancedColumnTreeBuilder_1.BalancedColumnTreeBuilder;
exports.ColumnController = columnController_1.ColumnController;
exports.ColumnKeyCreator = columnKeyCreator_1.ColumnKeyCreator;
exports.ColumnUtils = columnUtils_1.ColumnUtils;
exports.DisplayedGroupCreator = displayedGroupCreator_1.DisplayedGroupCreator;
exports.GroupInstanceIdCreator = groupInstanceIdCreator_1.GroupInstanceIdCreator;
// components
exports.ComponentUtil = componentUtil_1.ComponentUtil;
exports.initialiseAgGridWithAngular1 = agGridNg1_1.initialiseAgGridWithAngular1;
exports.initialiseAgGridWithWebComponents = agGridWebComponent_1.initialiseAgGridWithWebComponents;
// context
exports.Context = context_1.Context;
exports.Autowired = context_1.Autowired;
exports.PostConstruct = context_1.PostConstruct;
exports.PreDestroy = context_1.PreDestroy;
exports.Optional = context_1.Optional;
exports.Bean = context_1.Bean;
exports.Qualifier = context_1.Qualifier;
// dragAndDrop
exports.DragAndDropService = dragAndDropService_1.DragAndDropService;
exports.DragService = dragService_1.DragService;
// entities
exports.Column = column_1.Column;
exports.ColumnGroup = columnGroup_1.ColumnGroup;
exports.GridCell = gridCell_1.GridCell;
exports.GridRow = gridRow_1.GridRow;
exports.OriginalColumnGroup = originalColumnGroup_1.OriginalColumnGroup;
exports.RowNode = rowNode_1.RowNode;
// filter
exports.FilterManager = filterManager_1.FilterManager;
exports.NumberFilter = numberFilter_1.NumberFilter;
exports.TextFilter = textFilter_1.TextFilter;
// gridPanel
exports.GridPanel = gridPanel_1.GridPanel;
exports.MouseEventService = mouseEventService_1.MouseEventService;
// headerRendering
exports.CssClassApplier = cssClassApplier_1.CssClassApplier;
exports.HeaderContainer = headerContainer_1.HeaderContainer;
exports.HeaderRenderer = headerRenderer_1.HeaderRenderer;
exports.HeaderTemplateLoader = headerTemplateLoader_1.HeaderTemplateLoader;
exports.HorizontalDragService = horizontalDragService_1.HorizontalDragService;
exports.MoveColumnController = moveColumnController_1.MoveColumnController;
exports.RenderedHeaderCell = renderedHeaderCell_1.RenderedHeaderCell;
exports.RenderedHeaderGroupCell = renderedHeaderGroupCell_1.RenderedHeaderGroupCell;
exports.StandardMenuFactory = standardMenu_1.StandardMenuFactory;
// layout
exports.BorderLayout = borderLayout_1.BorderLayout;
exports.TabbedLayout = tabbedLayout_1.TabbedLayout;
exports.VerticalStack = verticalStack_1.VerticalStack;
// rendering / cellEditors
exports.DateCellEditor = dateCellEditor_1.DateCellEditor;
exports.PopupEditorWrapper = popupEditorWrapper_1.PopupEditorWrapper;
exports.PopupSelectCellEditor = popupSelectCellEditor_1.PopupSelectCellEditor;
exports.PopupTextCellEditor = popupTextCellEditor_1.PopupTextCellEditor;
exports.SelectCellEditor = selectCellEditor_1.SelectCellEditor;
exports.TextCellEditor = textCellEditor_1.TextCellEditor;
// rendering / cellRenderers
exports.AnimateSlideCellRenderer = animateSlideCellRenderer_1.AnimateSlideCellRenderer;
exports.GroupCellRenderer = groupCellRenderer_1.GroupCellRenderer;
// rendering
exports.AutoWidthCalculator = autoWidthCalculator_1.AutoWidthCalculator;
exports.CellEditorFactory = cellEditorFactory_1.CellEditorFactory;
exports.RenderedHeaderCell = renderedHeaderCell_1.RenderedHeaderCell;
exports.CellRendererFactory = cellRendererFactory_1.CellRendererFactory;
exports.CellRendererService = cellRendererService_1.CellRendererService;
exports.RenderedRow = renderedRow_1.RenderedRow;
exports.RowRenderer = rowRenderer_1.RowRenderer;
exports.ValueFormatterService = valueFormatterService_1.ValueFormatterService;
// rowControllers/inMemory
exports.FilterStage = fillterStage_1.FilterStage;
exports.FlattenStage = flattenStage_1.FlattenStage;
exports.InMemoryRowModel = inMemoryRowModel_1.InMemoryRowModel;
exports.SortStage = sortStage_1.SortStage;
// rowControllers
exports.FloatingRowModel = floatingRowModel_1.FloatingRowModel;
exports.PaginationController = paginationController_1.PaginationController;
exports.VirtualPageRowModel = virtualPageRowModel_1.VirtualPageRowModel;
// widgets
exports.PopupService = popupService_1.PopupService;
exports.MenuItemComponent = menuItemComponent_1.MenuItemComponent;
exports.Component = component_1.Component;
exports.MenuList = menuList_1.MenuList;
// root
exports.CellNavigationService = cellNavigationService_1.CellNavigationService;
exports.ColumnChangeEvent = columnChangeEvent_1.ColumnChangeEvent;
exports.Constants = constants_1.Constants;
exports.CsvCreator = csvCreator_1.CsvCreator;
exports.Events = events_1.Events;
exports.EventService = eventService_1.EventService;
exports.ExpressionService = expressionService_1.ExpressionService;
exports.FocusedCellController = focusedCellController_1.FocusedCellController;
exports.defaultGroupComparator = functions_1.defaultGroupComparator;
exports.Grid = grid_1.Grid;
exports.GridApi = gridApi_1.GridApi;
exports.GridCore = gridCore_1.GridCore;
exports.GridOptionsWrapper = gridOptionsWrapper_1.GridOptionsWrapper;
exports.Logger = logger_1.Logger;
exports.MasterSlaveService = masterSlaveService_1.MasterSlaveService;
exports.SelectionController = selectionController_1.SelectionController;
exports.SelectionRendererFactory = selectionRendererFactory_1.SelectionRendererFactory;
exports.SortController = sortController_1.SortController;
exports.SvgFactory = svgFactory_1.SvgFactory;
exports.TemplateService = templateService_1.TemplateService;
exports.Utils = utils_1.Utils;
exports.ValueService = valueService_1.ValueService;
}
exports.populateClientExports = populateClientExports;
| Eurofunk/ag-grid | dist/lib/clientExports.js | JavaScript | mit | 11,515 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt323()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt323();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt323
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt32[] values = new UInt32[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt32();
}
Vector256<UInt32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt32 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt32 insertedValue = TestLibrary.Generator.GetUInt32();
try
{
Vector256<UInt32> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt32[] values = new UInt32[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt32();
}
Vector256<UInt32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt32)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt32 insertedValue = TestLibrary.Generator.GetUInt32();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<UInt32>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt32 result, UInt32[] values, [CallerMemberName] string method = "")
{
if (result != values[3])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement(3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<UInt32> result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "")
{
UInt32[] resultElements = new UInt32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt32[] result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 3) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[3] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement(3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| krk/coreclr | tests/src/JIT/HardwareIntrinsics/General/Vector256_1/GetAndWithElement.UInt32.3.cs | C# | mit | 9,055 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('./core'),
View = _dereq_('../lib/View');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":8,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],6:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
'*': function (data) {
return this.$main.call(this, data, {});
},
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback.call(this, resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],7:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {String=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Remove old data
this._data.remove(chainPacket.data.oldData);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":6,"./Shared":31}],8:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],9:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":5,"./Collection.js":6,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":31}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":27}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
if (sourceType === 'object' && source === null) {
sourceType = 'null';
}
if (testType === 'object' && test === null) {
testType = 'null';
}
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number' || sourceType === 'null' || testType === 'null') {
// Number or null comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
self.triggerStack = {};
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
/**
* Tells the current instance to fire or ignore all triggers whether they
* are enabled or not.
* @param {Boolean} val Set to true to ignore triggers or false to not
* ignore them.
* @returns {*}
*/
ignoreTriggers: function (val) {
if (val !== undefined) {
this._ignoreTriggers = val;
return this;
}
return this._ignoreTriggers;
},
/**
* Generates triggers that fire in the after phase for all CRUD ops
* that automatically transform data back and forth and keep both
* import and export collections in sync with each other.
* @param {String} id The unique id for this link IO.
* @param {Object} ioData The settings for the link IO.
*/
addLinkIO: function (id, ioData) {
var self = this,
matchAll,
exportData,
importData,
exportTriggerMethod,
importTriggerMethod,
exportTo,
importFrom,
allTypes,
i;
// Store the linkIO
self._linkIO = self._linkIO || {};
self._linkIO[id] = ioData;
exportData = ioData['export'];
importData = ioData['import'];
if (exportData) {
exportTo = self.db().collection(exportData.to);
}
if (importData) {
importFrom = self.db().collection(importData.from);
}
allTypes = [
self.TYPE_INSERT,
self.TYPE_UPDATE,
self.TYPE_REMOVE
];
matchAll = function (data, callback) {
// Match all
callback(false, true);
};
if (exportData) {
// Check for export match method
if (!exportData.match) {
// No match method found, use the match all method
exportData.match = matchAll;
}
// Check for export types
if (!exportData.types) {
exportData.types = allTypes;
}
exportTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
exportData.match(newDoc, function (err, doExport) {
if (doExport) {
// Get data to upsert (if any)
exportData.data(newDoc, operation.type, function (err, data, callback) {
if (data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
exportTo.upsert(data, callback);
} else {
// Do remove
exportTo.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (importData) {
// Check for import match method
if (!importData.match) {
// No match method found, use the match all method
importData.match = matchAll;
}
// Check for import types
if (!importData.types) {
importData.types = allTypes;
}
importTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
importData.match(newDoc, function (err, doExport) {
if (doExport) {
// Get data to upsert (if any)
importData.data(newDoc, operation.type, function (err, data, callback) {
if (data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
self.upsert(data, callback);
} else {
// Do remove
self.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod);
}
}
if (importData) {
for (i = 0; i < importData.types.length; i++) {
importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod);
}
}
},
/**
* Removes a previously added link IO via it's ID.
* @param {String} id The id of the link IO to remove.
* @returns {boolean} True if successful, false if the link IO
* was not found.
*/
removeLinkIO: function (id) {
var self = this,
linkIO = self._linkIO[id],
exportData,
importData,
importFrom,
i;
if (linkIO) {
exportData = linkIO['export'];
importData = linkIO['import'];
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER);
}
}
if (importData) {
importFrom = self.db().collection(importData.from);
for (i = 0; i < importData.types.length; i++) {
importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER);
}
}
delete self._linkIO[id];
return true;
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response,
typeName,
phaseName;
if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (self.debug()) {
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Check if the trigger is already in the stack, if it is,
// don't fire it again (this is so we avoid infinite loops
// where a trigger triggers another trigger which calls this
// one and so on)
if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) {
// The trigger is already in the stack, do not fire the trigger again
if (self.debug()) {
console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!');
}
continue;
}
// Add the trigger to the stack so we don't go down an endless
// trigger loop
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = true;
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Remove the trigger from the stack
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = false;
// Check the response for a non-expected result (anything other than
// [undefined, true or false] is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":27}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":31}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":31}],30:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],31:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.743',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],33:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload'),
Path,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.Matching');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Path = Shared.modules.Path;
sharedPathSolver = new Path();
View.prototype.init = function (name, query, options) {
var self = this;
this.sharedPathSolver = sharedPathSolver;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._data = new Collection(this.name() + '_internal');
};
/**
* This reactor IO node is given data changes from source data and
* then acts as a firewall process between the source and view data.
* Data needs to meet the requirements this IO node imposes before
* the data is passed down the reactor chain (to the view). This
* allows us to intercept data changes from the data source and act
* on them such as applying transforms, checking the data matches
* the view's query, applying joins to the data etc before sending it
* down the reactor chain via the this.chainSend() calls.
*
* Update packets are especially complex to handle because an update
* on the underlying source data could translate into an insert,
* update or remove call on the view. Take a scenario where the view's
* query limits the data see from the source. If the source data is
* updated and the data now falls inside the view's query limitations
* the data is technically now an insert on the view, not an update.
* The same is true in reverse where the update becomes a remove. If
* the updated data already exists in the view and will still exist
* after the update operation then the update can remain an update.
* @param {Object} chainPacket The chain reactor packet representing the
* data operation that has just been processed on the source data.
* @param {View} self The reference to the view we are operating for.
* @private
*/
View.prototype._handleChainIO = function (chainPacket, self) {
var type = chainPacket.type,
hasActiveJoin,
hasActiveQuery,
hasTransformIn,
sharedData;
// NOTE: "self" in this context is the view instance.
// NOTE: "this" in this context is the ReactorIO node sitting in
// between the source (sender) and the destination (listener) and
// in this case the source is the view's "from" data source and the
// destination is the view's _data collection. This means
// that "this.chainSend()" is asking the ReactorIO node to send the
// packet on to the destination listener.
// EARLY EXIT: Check that the packet is not a CRUD operation
if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') {
// This packet is NOT a CRUD operation packet so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We only need to check packets under three conditions
// 1) We have a limiting query on the view "active query",
// 2) We have a query options with a $join clause on the view "active join"
// 3) We have a transformIn operation registered on the view.
// If none of these conditions exist we can just allow the chain
// packet to proceed as normal
hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join);
hasActiveQuery = Boolean(self._querySettings.query);
hasTransformIn = self._data._transformIn !== undefined;
// EARLY EXIT: Check for any complex operation flags and if none
// exist, send the packet on and exit early
if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) {
// We don't have any complex operation flags so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We have either an active query, active join or a transformIn
// function registered on the view
// We create a shared data object here so that the disparate method
// calls can share data with each other via this object whilst
// still remaining separate methods to keep code relatively clean.
sharedData = {
dataArr: [],
removeArr: []
};
// Check the packet type to get the data arrays to work on
if (chainPacket.type === 'insert') {
// Check if the insert data is an array
if (chainPacket.data.dataSet instanceof Array) {
// Use the insert data array
sharedData.dataArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single insert object
sharedData.dataArr = [chainPacket.data.dataSet];
}
} else if (chainPacket.type === 'update') {
// Use the dataSet array
sharedData.dataArr = chainPacket.data.dataSet;
} else if (chainPacket.type === 'remove') {
if (chainPacket.data.dataSet instanceof Array) {
// Use the remove data array
sharedData.removeArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single remove object
sharedData.removeArr = [chainPacket.data.dataSet];
}
}
// Safety check
if (!(sharedData.dataArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!');
sharedData.dataArr = [];
}
if (!(sharedData.removeArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!');
sharedData.removeArr = [];
}
// We need to operate in this order:
// 1) Check if there is an active join - active joins are operated
// against the SOURCE data. The joined data can potentially be
// utilised by any active query or transformIn so we do this step first.
// 2) Check if there is an active query - this is a query that is run
// against the SOURCE data after any active joins have been resolved
// on the source data. This allows an active query to operate on data
// that would only exist after an active join has been executed.
// If the source data does not fall inside the limiting factors of the
// active query then we add it to a removal array. If it does fall
// inside the limiting factors when we add it to an upsert array. This
// is because data that falls inside the query could end up being
// either new data or updated data after a transformIn operation.
// 3) Check if there is a transformIn function. If a transformIn function
// exist we run it against the data after doing any active join and
// active query.
if (hasActiveJoin) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
self._handleChainIO_ActiveJoin(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
}
if (hasActiveQuery) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
self._handleChainIO_ActiveQuery(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
}
if (hasTransformIn) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
self._handleChainIO_TransformIn(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
}
// Check if we still have data to operate on and exit
// if there is none left
if (!sharedData.dataArr.length && !sharedData.removeArr.length) {
// There is no more data to operate on, exit without
// sending any data down the chain reactor (return true
// will tell reactor to exit without continuing)!
return true;
}
// Grab the public data collection's primary key
sharedData.pk = self._data.primaryKey();
// We still have data left, let's work out how to handle it
// first let's loop through the removals as these are easy
if (sharedData.removeArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
self._handleChainIO_RemovePackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
}
if (sharedData.dataArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
self._handleChainIO_UpsertPackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
}
// Now return true to tell the chain reactor not to propagate
// the data itself as we have done all that work here
return true;
};
View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) {
var dataArr = sharedData.dataArr,
removeArr;
// Since we have an active join, all we need to do is operate
// the join clause on each item in the packet's data array.
removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {});
// Now that we've run our join keep in mind that joins can exclude data
// if there is no matching joined data and the require: true clause in
// the join options is enabled. This means we have to store a removal
// array that tells us which items from the original data we sent to
// join did not match the join data and were set with a require flag.
// Now that we have our array of items to remove, let's run through the
// original data and remove them from there.
this.spliceArrayByIndexList(dataArr, removeArr);
// Make sure we add any items we removed to the shared removeArr
sharedData.removeArr = sharedData.removeArr.concat(removeArr);
};
View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
i;
// Now we need to run the data against the active query to
// see if the data should be in the final data list or not,
// so we use the _match method.
// Loop backwards so we can safely splice from the array
// while we are looping
for (i = dataArr.length - 1; i >= 0; i--) {
if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
// The data didn't match the active query, add it
// to the shared removeArr
sharedData.removeArr.push(dataArr[i]);
// Now remove it from the shared dataArr
dataArr.splice(i, 1);
}
}
};
View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
removeArr = sharedData.removeArr,
dataIn = self._data._transformIn,
i;
// At this stage we take the remaining items still left in the data
// array and run our transformIn method on each one, modifying it
// from what it was to what it should be on the view. We also have
// to run this on items we want to remove too because transforms can
// affect primary keys and therefore stop us from identifying the
// correct items to run removal operations on.
// It is important that these are transformed BEFORE they are passed
// to the CRUD methods because we use the CU data to check the position
// of the item in the array and that can only happen if it is already
// pre-transformed. The removal stuff also needs pre-transformed
// because ids can be modified by a transform.
for (i = 0; i < dataArr.length; i++) {
// Assign the new value
dataArr[i] = dataIn(dataArr[i]);
}
for (i = 0; i < removeArr.length; i++) {
// Assign the new value
removeArr[i] = dataIn(removeArr[i]);
}
};
View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) {
var $or = [],
pk = sharedData.pk,
removeArr = sharedData.removeArr,
packet = {
dataSet: removeArr,
query: {
$or: $or
}
},
orObj,
i;
for (i = 0; i < removeArr.length; i++) {
orObj = {};
orObj[pk] = removeArr[i][pk];
$or.push(orObj);
}
ioObj.chainSend('remove', packet);
};
View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) {
var data = this._data,
primaryIndex = data._primaryIndex,
primaryCrc = data._primaryCrc,
pk = sharedData.pk,
dataArr = sharedData.dataArr,
arrItem,
insertArr = [],
updateArr = [],
query,
i;
// Let's work out what type of operation this data should
// generate between an insert or an update.
for (i = 0; i < dataArr.length; i++) {
arrItem = dataArr[i];
// Check if the data already exists in the data
if (primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) {
// The document exists in the data collection but data differs, update required
updateArr.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
insertArr.push(arrItem);
}
}
if (insertArr.length) {
ioObj.chainSend('insert', {
dataSet: insertArr
});
}
if (updateArr.length) {
for (i = 0; i < updateArr.length; i++) {
arrItem = updateArr[i];
query = {};
query[pk] = arrItem[pk];
ioObj.chainSend('update', {
query: query,
update: arrItem,
dataSet: [arrItem]
});
}
}
};
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this._data.findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this._data.findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._data;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
// Remove the current reference to the _from since we
// are about to replace it with a new one
delete this._from;
}
// Check if we have an existing reactor io that links the
// previous _from source to the view's internal data
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
// Check if we were passed a source name rather than a
// reference to a source object
if (typeof(source) === 'string') {
// We were passed a name, assume it is a collection and
// get the reference to the collection of that name
source = this._db.collection(source);
}
// Check if we were passed a reference to a view rather than
// a collection. Views need to be handled slightly differently
// since their data is stored in an internal data collection
// rather than actually being a direct data source themselves.
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source._data;
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
// Assign the new data source as the view's _from
this._from = source;
// Hook the new data source's drop event so we can unhook
// it as a data source if it gets dropped. This is important
// so that we don't run into problems using a dropped source
// for active data.
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's _from source and determines how they should be interpreted by
// this view. See the _handleChainIO() method which does all the chain packet
// processing for the view.
this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); });
// Set the view's internal data primary key to the same as the
// current active _from data source
this._data.primaryKey(source.primaryKey());
// Do the initial data lookup and populate the view's internal data
// since at this point we don't actually have any data in the view
// yet.
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData, {}, callback);
// If we have an active query and that query has an $orderBy clause,
// update our active bucket which allows us to keep track of where
// data should be placed in our internal data array. This is about
// ordering of data and making sure that we maintain an ordered array
// so that if we have data-binding we can place an item in the data-
// bound view at the correct location. Active buckets use quick-sort
// algorithms to quickly determine the position of an item inside an
// existing array based on a sort protocol.
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type);
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData);
// Rebuild active bucket as well
this.rebuildActiveBucket(this._querySettings.options);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Make sure we are working with an array
if (!(chainPacket.data.dataSet instanceof Array)) {
chainPacket.data.dataSet = [chainPacket.data.dataSet];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._data._insertHandle(arr[index], insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._data._data.length;
this._data._insertHandle(chainPacket.data.dataSet, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"');
}
primaryKey = this._data.primaryKey();
// Do the update
updates = this._data._handleUpdate(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._data._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"');
}
this._data.remove(chainPacket.data.query, chainPacket.options);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the dataSet and remove the objects from the ActiveBucket
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
this._activeBucket.remove(arr[index]);
}
}
break;
default:
break;
}
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._data.ensureIndex.apply(this._data, arguments);
};
/**
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._data.on.apply(this._data, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._data.off.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._data.emit.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::deferEmit()
*/
View.prototype.deferEmit = function () {
return this._data.deferEmit.apply(this._data, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._data.distinct(key, query, options);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._data.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._data) {
this._data.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._data;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
}
});
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
// TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first!
this.rebuildActiveBucket(options.$orderBy);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
return this;
}
return this._querySettings.options;
};
/**
* Clears the existing active bucket and builds a new one based
* on the passed orderBy object (if one is passed).
* @param {Object=} orderBy The orderBy object describing how to
* order any data.
*/
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._data._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._data.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
var self = this,
refreshResults,
joinArr,
i, k;
if (this._from) {
// Clear the private data collection which will propagate to the public data
// collection automatically via the chain reactor node between them
this._data.remove();
// Grab all the data from the underlying data source
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
// Insert the underlying data into the private data collection
this._data.insert(refreshResults);
// Store the current cursor data
this._data._data.$cursor = refreshResults.$cursor;
this._data._data.$cursor = refreshResults.$cursor;
}
if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) {
// Define the change handler method
self.__joinChange = self.__joinChange || function () {
self._joinChange();
};
// Check for existing join collections
if (this._joinCollections && this._joinCollections.length) {
// Loop the join collections and remove change listeners
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange);
}
}
// Now start hooking any new / existing joins
joinArr = this._querySettings.options.$join;
this._joinCollections = [];
// Loop the joined collections and hook change events
for (i = 0; i < joinArr.length; i++) {
for (k in joinArr[i]) {
if (joinArr[i].hasOwnProperty(k)) {
this._joinCollections.push(k);
}
}
}
if (this._joinCollections.length) {
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange);
}
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Handles when a change has occurred on a collection that is joined
* by query to this view.
* @param objName
* @param objType
* @private
*/
View.prototype._joinChange = function (objName, objType) {
this.emit('joinChange');
// TODO: This is a really dirty solution because it will require a complete
// TODO: rebuild of the view data. We need to implement an IO handler to
// TODO: selectively update the data of the view based on the joined
// TODO: collection data operation.
// FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call
this.refresh();
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._data.count.apply(this._data, arguments);
};
// Call underlying
View.prototype.subset = function () {
return this._data.subset.apply(this._data, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn"
* and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var currentSettings,
newSettings;
currentSettings = this._data.transform();
this._data.transform(obj);
newSettings = this._data.transform();
// Check if transforms are enabled, a dataIn method is set and these
// settings did not match the previous transform settings
if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) {
// The data in the view is now stale, refresh it
this.refresh();
}
return newSettings;
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return this._data.filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.data = function () {
return this._data;
};
/**
* @see Collection.indexOf
* @returns {*}
*/
View.prototype.indexOf = function () {
return this._data.indexOf.apply(this._data, arguments);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this._data.db(db);
// Apply the same debug settings
this.debug(db.debug());
this._data.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} name The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (name) {
var self = this;
// Handle being passed an instance
if (name instanceof View) {
return name;
}
if (this._view[name]) {
return this._view[name];
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + name);
}
this._view[name] = new View(name).db(this);
self.emit('create', self._view[name], 'view', name);
return this._view[name];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} name The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (name) {
return Boolean(this._view[name]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":3,"./Collection":6,"./CollectionGroup":7,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
| ahocevar/cdnjs | ajax/libs/forerunnerdb/1.3.743/fdb-core+views.js | JavaScript | mit | 338,430 |
#
# Makefile for the kernel USB device drivers.
#
# Object files in subdirectories
obj-$(CONFIG_USB) += core/
obj-$(CONFIG_USB_PHY) += phy/
obj-$(CONFIG_USB_DWC3) += dwc3/
obj-$(CONFIG_USB_MON) += mon/
obj-$(CONFIG_PCI) += host/
obj-$(CONFIG_USB_EHCI_HCD) += host/
obj-$(CONFIG_USB_ISP116X_HCD) += host/
obj-$(CONFIG_USB_OHCI_HCD) += host/
obj-$(CONFIG_USB_UHCI_HCD) += host/
obj-$(CONFIG_USB_FHCI_HCD) += host/
obj-$(CONFIG_USB_XHCI_HCD) += host/
obj-$(CONFIG_USB_SL811_HCD) += host/
obj-$(CONFIG_USB_ISP1362_HCD) += host/
obj-$(CONFIG_USB_U132_HCD) += host/
obj-$(CONFIG_USB_R8A66597_HCD) += host/
obj-$(CONFIG_USB_HWA_HCD) += host/
obj-$(CONFIG_USB_ISP1760_HCD) += host/
obj-$(CONFIG_USB_IMX21_HCD) += host/
obj-$(CONFIG_USB_FSL_MPH_DR_OF) += host/
obj-$(CONFIG_USB_ICE40_HCD) += host/
obj-$(CONFIG_USB_C67X00_HCD) += c67x00/
obj-$(CONFIG_USB_WUSB) += wusbcore/
obj-$(CONFIG_USB_ACM) += class/
obj-$(CONFIG_USB_PRINTER) += class/
obj-$(CONFIG_USB_WDM) += class/
obj-$(CONFIG_USB_TMC) += class/
obj-$(CONFIG_USB_CCID_BRIDGE) += class/
obj-$(CONFIG_USB_STORAGE) += storage/
obj-$(CONFIG_USB) += storage/
obj-$(CONFIG_USB_MDC800) += image/
obj-$(CONFIG_USB_MICROTEK) += image/
obj-$(CONFIG_USB_SERIAL) += serial/
obj-$(CONFIG_USB) += misc/
obj-$(CONFIG_EARLY_PRINTK_DBGP) += early/
obj-$(CONFIG_USB_ATM) += atm/
obj-$(CONFIG_USB_SPEEDTOUCH) += atm/
obj-$(CONFIG_USB_MUSB_HDRC) += musb/
obj-$(CONFIG_USB_CHIPIDEA) += chipidea/
obj-$(CONFIG_USB_RENESAS_USBHS) += renesas_usbhs/
obj-$(CONFIG_USB_GADGET) += gadget/
obj-$(CONFIG_TYPEC) += typec/
obj-$(CONFIG_USB_COMMON) += usb-common.o
| Elite-Kernels/Elite_angler | drivers/usb/Makefile | Makefile | gpl-2.0 | 1,611 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.