code_text
stringlengths
604
999k
repo_name
stringlengths
4
100
file_path
stringlengths
4
873
language
stringclasses
23 values
license
stringclasses
15 values
size
int32
1.02k
999k
/* * Image replacement */ /* ========================================================================== Images -- Version: 0.4.1 - Compiled: timestamp() ========================================================================== */ img { display: inherit; height: auto; border: 0; font-style: italics; color: #ef272d; } img:after { content: " (image)"; } img.left { margin-right: 0.5em; } img.right { margin-left: 0.5em; } figure { position: relative; width: 100%; } figure img { margin: 0 auto 1em; } figcaption { margin-bottom: 0.5em; font-size: 14px; font-size: 1.4rem; font-weight: 700; } .image-rounded { border-radius: 3px; background-clip: padding-box; } .image-circular, .avatar-circle { border-radius: 50%; background-clip: padding-box; } .image-bordered { border: 0.5em solid #e6e6e6; } .image-focus, .image-focus-1, .image-focus-2, .image-focus-3, .image-focus-4, .image-focus-5 { min-height: 200px; background-size: cover; background-repeat: no-repeat; background-position: center center; } .image-focus-1 { background-position: 25% center; } .image-focus-2 { background-position: 25% center; } .image-focus-3 { background-position: 50% center; } .image-focus-4 { background-position: 75% center; } .image-focus-5 { background-position: right center; } .ie9 svg:not(:root) { overflow: hidden; } /*# sourceMappingURL=images.css.map */
ryanbuiltthat/style-scaffold
css/partials/images.css
CSS
gpl-2.0
1,423
<?php /** * The loop that displays a single post. * * The loop displays the posts and the post content. See * http://codex.wordpress.org/The_Loop to understand it and * http://codex.wordpress.org/Template_Tags to understand * the tags used in it. * * This can be overridden in child themes with loop-single.php. * */ ?> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <div id="nav-above" class="navigation"> <div class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'smm' ) . '</span> %title' ); ?></div> <div class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', 'smm' ) . '</span>' ); ?></div> </div><!-- #nav-above --> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1 class="entry-title"><?php the_title(); ?></h1> <div class="entry-meta"> <?php smm_posted_on(); ?> </div><!-- .entry-meta --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'smm' ), 'after' => '</div>' ) ); ?> </div><!-- .entry-content --> <?php if ( get_the_author_meta( 'description' ) ) : // If a user has filled out their description, show a bio on their entries ?> <div id="entry-author-info"> <div id="author-avatar"> <?php echo get_avatar( get_the_author_meta( 'user_email' ), apply_filters( 'smm_author_bio_avatar_size', 60 ) ); ?> </div><!-- #author-avatar --> <div id="author-description"> <h2><?php printf( esc_attr__( 'About %s', 'smm' ), get_the_author() ); ?></h2> <?php the_author_meta( 'description' ); ?> <div id="author-link"> <a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>" rel="author"> <?php printf( __( 'View all posts by %s <span class="meta-nav">&rarr;</span>', 'smm' ), get_the_author() ); ?> </a> </div><!-- #author-link --> </div><!-- #author-description --> </div><!-- #entry-author-info --> <?php endif; ?> <div class="entry-utility"> <?php smm_posted_in(); ?> </div><!-- .entry-utility --> </div><!-- #post-## --> <div id="nav-below" class="navigation"> <div class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'smm' ) . '</span> %title' ); ?></div> <div class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', 'smm' ) . '</span>' ); ?></div> </div><!-- #nav-below --> <?php comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?>
sharpmachine/framework
wp-content/themes/smm-fixed-framework/loop-single.php
PHP
gpl-2.0
2,772
/* * Mailbox reservation modules for OMAP2/3 * * Copyright (C) 2006-2009 Nokia Corporation * Written by: Hiroshi DOYU <Hiroshi.DOYU@nokia.com> * and Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/clk.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/io.h> #include <plat/mailbox.h> #include <mach/irqs.h> #define MAILBOX_REVISION 0x000 #define MAILBOX_SYSCONFIG 0x010 #define MAILBOX_SYSSTATUS 0x014 #define MAILBOX_MESSAGE(m) (0x040 + 4 * (m)) #define MAILBOX_FIFOSTATUS(m) (0x080 + 4 * (m)) #define MAILBOX_MSGSTATUS(m) (0x0c0 + 4 * (m)) #define MAILBOX_IRQSTATUS(u) (0x100 + 8 * (u)) #define MAILBOX_IRQENABLE(u) (0x104 + 8 * (u)) #define OMAP4_MAILBOX_IRQSTATUS(u) (0x104 + 10 * (u)) #define OMAP4_MAILBOX_IRQENABLE(u) (0x108 + 10 * (u)) #define OMAP4_MAILBOX_IRQENABLE_CLR(u) (0x10c + 10 * (u)) #define MAILBOX_IRQ_NEWMSG(m) (1 << (2 * (m))) #define MAILBOX_IRQ_NOTFULL(m) (1 << (2 * (m) + 1)) /* SYSCONFIG: register bit definition */ #define AUTOIDLE (1 << 0) #define SOFTRESET (1 << 1) #define SMARTIDLE (2 << 3) #define OMAP4_SOFTRESET (1 << 0) #define OMAP4_NOIDLE (1 << 2) #define OMAP4_SMARTIDLE (2 << 2) /* SYSSTATUS: register bit definition */ #define RESETDONE (1 << 0) #define MBOX_REG_SIZE 0x120 #define OMAP4_MBOX_REG_SIZE 0x130 #define MBOX_NR_REGS (MBOX_REG_SIZE / sizeof(u32)) #define OMAP4_MBOX_NR_REGS (OMAP4_MBOX_REG_SIZE / sizeof(u32)) static void __iomem *mbox_base; struct omap_mbox2_fifo { unsigned long msg; unsigned long fifo_stat; unsigned long msg_stat; }; struct omap_mbox2_priv { struct omap_mbox2_fifo tx_fifo; struct omap_mbox2_fifo rx_fifo; unsigned long irqenable; unsigned long irqstatus; u32 newmsg_bit; u32 notfull_bit; u32 ctx[OMAP4_MBOX_NR_REGS]; unsigned long irqdisable; }; static struct clk *mbox_ick_handle; static void omap2_mbox_enable_irq(struct omap_mbox *mbox, omap_mbox_type_t irq); static inline unsigned int mbox_read_reg(size_t ofs) { return __raw_readl(mbox_base + ofs); } static inline void mbox_write_reg(u32 val, size_t ofs) { __raw_writel(val, mbox_base + ofs); } /* Mailbox H/W preparations */ static int omap2_mbox_startup(struct omap_mbox *mbox) { u32 l; unsigned long timeout; mbox_ick_handle = clk_get(NULL, "mailboxes_ick"); if (IS_ERR(mbox_ick_handle)) { printk(KERN_ERR "Could not get mailboxes_ick: %ld\n", PTR_ERR(mbox_ick_handle)); return PTR_ERR(mbox_ick_handle); } clk_enable(mbox_ick_handle); if (cpu_is_omap44xx()) { mbox_write_reg(OMAP4_SOFTRESET, MAILBOX_SYSCONFIG); timeout = jiffies + msecs_to_jiffies(20); do { l = mbox_read_reg(MAILBOX_SYSCONFIG); if (!(l & OMAP4_SOFTRESET)) break; } while (!time_after(jiffies, timeout)); if (l & OMAP4_SOFTRESET) { pr_err("Can't take mailbox out of reset\n"); return -ENODEV; } } else { mbox_write_reg(SOFTRESET, MAILBOX_SYSCONFIG); timeout = jiffies + msecs_to_jiffies(20); do { l = mbox_read_reg(MAILBOX_SYSSTATUS); if (l & RESETDONE) break; } while (!time_after(jiffies, timeout)); if (!(l & RESETDONE)) { pr_err("Can't take mailbox out of reset\n"); return -ENODEV; } } l = mbox_read_reg(MAILBOX_REVISION); pr_debug("omap mailbox rev %d.%d\n", (l & 0xf0) >> 4, (l & 0x0f)); if (cpu_is_omap44xx()) l = OMAP4_SMARTIDLE; else l = SMARTIDLE | AUTOIDLE; mbox_write_reg(l, MAILBOX_SYSCONFIG); omap2_mbox_enable_irq(mbox, IRQ_RX); return 0; } static void omap2_mbox_shutdown(struct omap_mbox *mbox) { clk_disable(mbox_ick_handle); clk_put(mbox_ick_handle); mbox_ick_handle = NULL; } /* Mailbox FIFO handle functions */ static mbox_msg_t omap2_mbox_fifo_read(struct omap_mbox *mbox) { struct omap_mbox2_fifo *fifo = &((struct omap_mbox2_priv *)mbox->priv)->rx_fifo; return (mbox_msg_t) mbox_read_reg(fifo->msg); } static void omap2_mbox_fifo_write(struct omap_mbox *mbox, mbox_msg_t msg) { struct omap_mbox2_fifo *fifo = &((struct omap_mbox2_priv *)mbox->priv)->tx_fifo; mbox_write_reg(msg, fifo->msg); } static int omap2_mbox_fifo_empty(struct omap_mbox *mbox) { struct omap_mbox2_fifo *fifo = &((struct omap_mbox2_priv *)mbox->priv)->rx_fifo; return (mbox_read_reg(fifo->msg_stat) == 0); } static int omap2_mbox_fifo_full(struct omap_mbox *mbox) { struct omap_mbox2_fifo *fifo = &((struct omap_mbox2_priv *)mbox->priv)->tx_fifo; return mbox_read_reg(fifo->fifo_stat); } /* Mailbox IRQ handle functions */ static void omap2_mbox_enable_irq(struct omap_mbox *mbox, omap_mbox_type_t irq) { struct omap_mbox2_priv *p = mbox->priv; u32 l, bit = (irq == IRQ_TX) ? p->notfull_bit : p->newmsg_bit; l = mbox_read_reg(p->irqenable); l |= bit; mbox_write_reg(l, p->irqenable); } static void omap2_mbox_disable_irq(struct omap_mbox *mbox, omap_mbox_type_t irq) { struct omap_mbox2_priv *p = mbox->priv; u32 l, bit = (irq == IRQ_TX) ? p->notfull_bit : p->newmsg_bit; l = mbox_read_reg(p->irqdisable); l &= ~bit; mbox_write_reg(l, p->irqdisable); } static void omap2_mbox_ack_irq(struct omap_mbox *mbox, omap_mbox_type_t irq) { struct omap_mbox2_priv *p = mbox->priv; u32 bit = (irq == IRQ_TX) ? p->notfull_bit : p->newmsg_bit; mbox_write_reg(bit, p->irqstatus); /* Flush posted write for irq status to avoid spurious interrupts */ mbox_read_reg(p->irqstatus); } static int omap2_mbox_is_irq(struct omap_mbox *mbox, omap_mbox_type_t irq) { struct omap_mbox2_priv *p = mbox->priv; u32 bit = (irq == IRQ_TX) ? p->notfull_bit : p->newmsg_bit; u32 enable = mbox_read_reg(p->irqenable); u32 status = mbox_read_reg(p->irqstatus); return (int)(enable & status & bit); } static void omap2_mbox_save_ctx(struct omap_mbox *mbox) { int i; struct omap_mbox2_priv *p = mbox->priv; int nr_regs; if (cpu_is_omap44xx()) nr_regs = OMAP4_MBOX_NR_REGS; else nr_regs = MBOX_NR_REGS; for (i = 0; i < nr_regs; i++) { p->ctx[i] = mbox_read_reg(i * sizeof(u32)); dev_dbg(mbox->dev, "%s: [%02x] %08x\n", __func__, i, p->ctx[i]); } } static void omap2_mbox_restore_ctx(struct omap_mbox *mbox) { int i; struct omap_mbox2_priv *p = mbox->priv; int nr_regs; if (cpu_is_omap44xx()) nr_regs = OMAP4_MBOX_NR_REGS; else nr_regs = MBOX_NR_REGS; for (i = 0; i < nr_regs; i++) { mbox_write_reg(p->ctx[i], i * sizeof(u32)); dev_dbg(mbox->dev, "%s: [%02x] %08x\n", __func__, i, p->ctx[i]); } } static struct omap_mbox_ops omap2_mbox_ops = { .type = OMAP_MBOX_TYPE2, .startup = omap2_mbox_startup, .shutdown = omap2_mbox_shutdown, .fifo_read = omap2_mbox_fifo_read, .fifo_write = omap2_mbox_fifo_write, .fifo_empty = omap2_mbox_fifo_empty, .fifo_full = omap2_mbox_fifo_full, .enable_irq = omap2_mbox_enable_irq, .disable_irq = omap2_mbox_disable_irq, .ack_irq = omap2_mbox_ack_irq, .is_irq = omap2_mbox_is_irq, .save_ctx = omap2_mbox_save_ctx, .restore_ctx = omap2_mbox_restore_ctx, }; /* * MAILBOX 0: ARM -> DSP, * MAILBOX 1: ARM <- DSP. * MAILBOX 2: ARM -> IVA, * MAILBOX 3: ARM <- IVA. */ /* FIXME: the following structs should be filled automatically by the user id */ #if defined(CONFIG_ARCH_OMAP3) || defined(CONFIG_ARCH_OMAP2) /* DSP */ static struct omap_mbox2_priv omap2_mbox_dsp_priv = { .tx_fifo = { .msg = MAILBOX_MESSAGE(0), .fifo_stat = MAILBOX_FIFOSTATUS(0), }, .rx_fifo = { .msg = MAILBOX_MESSAGE(1), .msg_stat = MAILBOX_MSGSTATUS(1), }, .irqenable = MAILBOX_IRQENABLE(0), .irqstatus = MAILBOX_IRQSTATUS(0), .notfull_bit = MAILBOX_IRQ_NOTFULL(0), .newmsg_bit = MAILBOX_IRQ_NEWMSG(1), .irqdisable = MAILBOX_IRQENABLE(0), }; struct omap_mbox mbox_dsp_info = { .name = "dsp", .ops = &omap2_mbox_ops, .priv = &omap2_mbox_dsp_priv, }; #endif #if defined(CONFIG_ARCH_OMAP3) struct omap_mbox *omap3_mboxes[] = { &mbox_dsp_info, NULL }; #endif #if defined(CONFIG_ARCH_OMAP2420) /* IVA */ static struct omap_mbox2_priv omap2_mbox_iva_priv = { .tx_fifo = { .msg = MAILBOX_MESSAGE(2), .fifo_stat = MAILBOX_FIFOSTATUS(2), }, .rx_fifo = { .msg = MAILBOX_MESSAGE(3), .msg_stat = MAILBOX_MSGSTATUS(3), }, .irqenable = MAILBOX_IRQENABLE(3), .irqstatus = MAILBOX_IRQSTATUS(3), .notfull_bit = MAILBOX_IRQ_NOTFULL(2), .newmsg_bit = MAILBOX_IRQ_NEWMSG(3), .irqdisable = MAILBOX_IRQENABLE(3), }; static struct omap_mbox mbox_iva_info = { .name = "iva", .ops = &omap2_mbox_ops, .priv = &omap2_mbox_iva_priv, }; struct omap_mbox *omap2_mboxes[] = { &mbox_dsp_info, &mbox_iva_info, NULL }; #endif #if defined(CONFIG_ARCH_OMAP4) /* OMAP4 */ static struct omap_mbox2_priv omap2_mbox_1_priv = { .tx_fifo = { .msg = MAILBOX_MESSAGE(0), .fifo_stat = MAILBOX_FIFOSTATUS(0), }, .rx_fifo = { .msg = MAILBOX_MESSAGE(1), .msg_stat = MAILBOX_MSGSTATUS(1), }, .irqenable = OMAP4_MAILBOX_IRQENABLE(0), .irqstatus = OMAP4_MAILBOX_IRQSTATUS(0), .notfull_bit = MAILBOX_IRQ_NOTFULL(0), .newmsg_bit = MAILBOX_IRQ_NEWMSG(1), .irqdisable = OMAP4_MAILBOX_IRQENABLE_CLR(0), }; struct omap_mbox mbox_1_info = { .name = "mailbox-1", .ops = &omap2_mbox_ops, .priv = &omap2_mbox_1_priv, }; static struct omap_mbox2_priv omap2_mbox_2_priv = { .tx_fifo = { .msg = MAILBOX_MESSAGE(3), .fifo_stat = MAILBOX_FIFOSTATUS(3), }, .rx_fifo = { .msg = MAILBOX_MESSAGE(2), .msg_stat = MAILBOX_MSGSTATUS(2), }, .irqenable = OMAP4_MAILBOX_IRQENABLE(0), .irqstatus = OMAP4_MAILBOX_IRQSTATUS(0), .notfull_bit = MAILBOX_IRQ_NOTFULL(3), .newmsg_bit = MAILBOX_IRQ_NEWMSG(2), .irqdisable = OMAP4_MAILBOX_IRQENABLE_CLR(0), }; struct omap_mbox mbox_2_info = { .name = "mailbox-2", .ops = &omap2_mbox_ops, .priv = &omap2_mbox_2_priv, }; struct omap_mbox *omap4_mboxes[] = { &mbox_1_info, &mbox_2_info, NULL }; #endif static int __devinit omap2_mbox_probe(struct platform_device *pdev) { struct resource *mem; int ret; struct omap_mbox **list; if (false) ; #if defined(CONFIG_ARCH_OMAP3) else if (cpu_is_omap34xx()) { list = omap3_mboxes; list[0]->irq = platform_get_irq_byname(pdev, "dsp"); } #endif #if defined(CONFIG_ARCH_OMAP2) else if (cpu_is_omap2430()) { list = omap2_mboxes; list[0]->irq = platform_get_irq_byname(pdev, "dsp"); } else if (cpu_is_omap2420()) { list = omap2_mboxes; list[0]->irq = platform_get_irq_byname(pdev, "dsp"); list[1]->irq = platform_get_irq_byname(pdev, "iva"); } #endif #if defined(CONFIG_ARCH_OMAP4) else if (cpu_is_omap44xx()) { list = omap4_mboxes; list[0]->irq = list[1]->irq = platform_get_irq_byname(pdev, "mbox"); } #endif else { pr_err("%s: platform not supported\n", __func__); return -ENODEV; } mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); mbox_base = ioremap(mem->start, resource_size(mem)); if (!mbox_base) return -ENOMEM; ret = omap_mbox_register(&pdev->dev, list); if (ret) { iounmap(mbox_base); return ret; } return 0; } static int __devexit omap2_mbox_remove(struct platform_device *pdev) { omap_mbox_unregister(); iounmap(mbox_base); return 0; } static struct platform_driver omap2_mbox_driver = { .probe = omap2_mbox_probe, .remove = __devexit_p(omap2_mbox_remove), .driver = { .name = "omap-mailbox", }, }; static int __init omap2_mbox_init(void) { return platform_driver_register(&omap2_mbox_driver); } static void __exit omap2_mbox_exit(void) { platform_driver_unregister(&omap2_mbox_driver); } module_init(omap2_mbox_init); module_exit(omap2_mbox_exit); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("omap mailbox: omap2/3/4 architecture specific functions"); MODULE_AUTHOR("Hiroshi DOYU <Hiroshi.DOYU@nokia.com>"); MODULE_AUTHOR("Paul Mundt"); MODULE_ALIAS("platform:omap2-mailbox");
gamerlulea/linux.2.6-custom
arch/arm/mach-omap2/mailbox.c
C
gpl-2.0
11,701
/* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved. * Copyright (c) 2013 Sony Mobile Communications AB. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only 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. */ #include <linux/err.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/irqdomain.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_platform.h> #include <linux/memory.h> #include <linux/regulator/machine.h> #include <linux/regulator/krait-regulator.h> #include <linux/memory.h> #include <linux/memblock.h> #include <asm/setup.h> #include <linux/msm_tsens.h> #include <linux/msm_thermal.h> #include <linux/persistent_ram.h> #include <asm/mach/map.h> #include <asm/hardware/gic.h> #include <asm/mach/map.h> #include <asm/mach/arch.h> #include <mach/board.h> #include <mach/gpiomux.h> #include <mach/msm_iomap.h> #include <mach/msm_memtypes.h> #include <mach/msm_smd.h> #include <mach/restart.h> #include <mach/rpm-smd.h> #include <mach/rpm-regulator-smd.h> #include <mach/socinfo.h> #include <mach/msm_smem.h> #include <mach/msm_memory_dump.h> #include "board-dt.h" #include "clock.h" #include "devices.h" #include "spm.h" #include "pm.h" #include "modem_notifier.h" #include "platsmp.h" #ifdef CONFIG_RAMDUMP_TAGS #include "board-rdtags.h" #endif #include "board-8974-console.h" #ifdef CONFIG_RAMDUMP_TAGS static struct resource rdtags_resources[] = { [0] = { .name = "rdtags_mem", .flags = IORESOURCE_MEM, }, }; static struct platform_device rdtags_device = { .name = "rdtags", .id = -1, .dev = { .platform_data = &rdtags_platdata, }, }; #endif #ifdef CONFIG_CRASH_LAST_LOGS static struct resource lastlogs_resources[] = { [0] = { .name = "last_kmsg", .flags = IORESOURCE_MEM, }, [1] = { .name = "last_amsslog", .flags = IORESOURCE_MEM, }, }; static struct platform_device lastlogs_device = { .name = "last_logs", .id = -1, }; #endif #define DEBUG_MEM_SIZE SZ_1M #define RDTAGS_MEM_SIZE (256 * SZ_1K) #define RDTAGS_MEM_DESC_SIZE (256 * SZ_1K) #define LAST_LOGS_OFFSET (RDTAGS_MEM_SIZE + RDTAGS_MEM_DESC_SIZE) #ifdef CONFIG_CRASH_LAST_LOGS #define LAST_LOG_HEADER_SIZE 4096 #define KMSG_LOG_SIZE ((1 << CONFIG_LOG_BUF_SHIFT) + LAST_LOG_HEADER_SIZE) #define AMSS_LOG_SIZE ((16 * SZ_1K) + LAST_LOG_HEADER_SIZE) #endif #if defined(CONFIG_RAMDUMP_TAGS) || defined(CONFIG_CRASH_LAST_LOGS) static void reserve_debug_memory(void) { struct membank *mb = &meminfo.bank[meminfo.nr_banks - 1]; unsigned long bank_end = mb->start + mb->size; /*Base address for rdtags*/ unsigned long debug_mem_base = bank_end - DEBUG_MEM_SIZE; /*Base address for crash logs memory*/ #ifdef CONFIG_CRASH_LAST_LOGS unsigned long lastlogs_base = debug_mem_base + LAST_LOGS_OFFSET; #endif memblock_free(debug_mem_base, SZ_1M); memblock_remove(debug_mem_base, SZ_1M); #ifdef CONFIG_RAMDUMP_TAGS rdtags_resources[0].start = debug_mem_base; rdtags_resources[0].end = debug_mem_base + RDTAGS_MEM_SIZE - 1; debug_mem_base += RDTAGS_MEM_SIZE; pr_info("Rdtags start %x end %x\n", \ (unsigned int)rdtags_resources[0].start, \ (unsigned int)rdtags_resources[0].end); rdtags_device.num_resources = ARRAY_SIZE(rdtags_resources); rdtags_device.resource = rdtags_resources; #endif #ifdef CONFIG_CRASH_LAST_LOGS lastlogs_resources[0].start = lastlogs_base; lastlogs_resources[0].end = lastlogs_base + KMSG_LOG_SIZE - 1; lastlogs_base += KMSG_LOG_SIZE; pr_info("last_kmsg start %x end %x\n", \ (unsigned int)lastlogs_resources[0].start, \ (unsigned int)lastlogs_resources[0].end); lastlogs_resources[1].start = lastlogs_base; lastlogs_resources[1].end = lastlogs_base + AMSS_LOG_SIZE - 1; lastlogs_device.num_resources = ARRAY_SIZE(lastlogs_resources); lastlogs_device.resource = lastlogs_resources; pr_info("last_amsslog start %x end %x\n", \ (unsigned int)lastlogs_resources[1].start, \ (unsigned int)lastlogs_resources[1].end); #endif } #endif #ifdef CONFIG_ANDROID_PERSISTENT_RAM #define MSM_PERSISTENT_RAM_SIZE (SZ_1M) #define MSM_RAM_CONSOLE_SIZE (128 * SZ_1K) static struct persistent_ram_descriptor pr_desc = { #ifdef CONFIG_ANDROID_RAM_CONSOLE .name = "ram_console", .size = MSM_RAM_CONSOLE_SIZE #endif }; static struct persistent_ram msm_pram = { .size = MSM_PERSISTENT_RAM_SIZE, .num_descs = 1, .descs = &pr_desc }; static void reserve_persistent_ram(void) { struct membank *mb = &meminfo.bank[meminfo.nr_banks - 1]; unsigned long bank_end = mb->start + mb->size; msm_pram.start = bank_end - DEBUG_MEM_SIZE - MSM_PERSISTENT_RAM_SIZE; persistent_ram_early_init(&msm_pram); } #endif #ifdef CONFIG_ANDROID_RAM_CONSOLE static struct platform_device ram_console_device = { .name = "ram_console", .id = -1, .dev = { .platform_data = &ram_console_pdata, } }; #endif void __init msm_8974_reserve(void) { #if defined(CONFIG_RAMDUMP_TAGS) || defined(CONFIG_CRASH_LAST_LOGS) reserve_debug_memory(); #endif #ifdef CONFIG_ANDROID_PERSISTENT_RAM reserve_persistent_ram(); #endif of_scan_flat_dt(dt_scan_for_memory_reserve, NULL); } static void __init msm8974_early_memory(void) { of_scan_flat_dt(dt_scan_for_memory_hole, NULL); } void __init msm8974_add_devices(void) { #ifdef CONFIG_RAMDUMP_TAGS platform_device_register(&rdtags_device); #endif #ifdef CONFIG_CRASH_LAST_LOGS platform_device_register(&lastlogs_device); #endif #ifdef CONFIG_ANDROID_RAM_CONSOLE platform_device_register(&ram_console_device); #endif } /* * Used to satisfy dependencies for devices that need to be * run early or in a particular order. Most likely your device doesn't fall * into this category, and thus the driver should not be added here. The * EPROBE_DEFER can satisfy most dependency problems. */ void __init msm8974_add_drivers(void) { msm_smem_init(); msm_init_modem_notifier_list(); msm_smd_init(); msm_rpm_driver_init(); msm_pm_sleep_status_init(); rpm_regulator_smd_driver_init(); msm_spm_device_init(); krait_power_init(); if (of_board_is_rumi()) msm_clock_init(&msm8974_rumi_clock_init_data); else msm_clock_init(&msm8974_clock_init_data); tsens_tm_init_driver(); msm_thermal_device_init(); } static struct of_dev_auxdata msm_hsic_host_adata[] = { OF_DEV_AUXDATA("qcom,hsic-host", 0xF9A00000, "msm_hsic_host", NULL), {} }; static struct of_dev_auxdata msm8974_auxdata_lookup[] __initdata = { OF_DEV_AUXDATA("qcom,hsusb-otg", 0xF9A55000, \ "msm_otg", NULL), OF_DEV_AUXDATA("qcom,ehci-host", 0xF9A55000, \ "msm_ehci_host", NULL), OF_DEV_AUXDATA("qcom,dwc-usb3-msm", 0xF9200000, \ "msm_dwc3", NULL), OF_DEV_AUXDATA("qcom,usb-bam-msm", 0xF9304000, \ "usb_bam", NULL), OF_DEV_AUXDATA("qcom,spi-qup-v2", 0xF9924000, \ "spi_qsd.1", NULL), OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF9824000, \ "msm_sdcc.1", NULL), OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF98A4000, \ "msm_sdcc.2", NULL), OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF9864000, \ "msm_sdcc.3", NULL), OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF98E4000, \ "msm_sdcc.4", NULL), OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF9824900, \ "msm_sdcc.1", NULL), OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF98A4900, \ "msm_sdcc.2", NULL), OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF9864900, \ "msm_sdcc.3", NULL), OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF98E4900, \ "msm_sdcc.4", NULL), OF_DEV_AUXDATA("qcom,msm-rng", 0xF9BFF000, \ "msm_rng", NULL), OF_DEV_AUXDATA("qcom,qseecom", 0xFE806000, \ "qseecom", NULL), OF_DEV_AUXDATA("qcom,mdss_mdp", 0xFD900000, "mdp.0", NULL), OF_DEV_AUXDATA("qcom,msm-tsens", 0xFC4A8000, \ "msm-tsens", NULL), OF_DEV_AUXDATA("qcom,qcedev", 0xFD440000, \ "qcedev.0", NULL), OF_DEV_AUXDATA("qcom,qcrypto", 0xFD440000, \ "qcrypto.0", NULL), OF_DEV_AUXDATA("qcom,hsic-host", 0xF9A00000, \ "msm_hsic_host", NULL), OF_DEV_AUXDATA("qcom,hsic-smsc-hub", 0, "msm_smsc_hub", msm_hsic_host_adata), {} }; static void __init msm8974_map_io(void) { msm_map_8974_io(); } void __init msm8974_init(void) { struct of_dev_auxdata *adata = msm8974_auxdata_lookup; if (socinfo_init() < 0) pr_err("%s: socinfo_init() failed\n", __func__); msm_8974_init_gpiomux(); regulator_has_full_constraints(); board_dt_populate(adata); msm8974_add_devices(); msm8974_add_drivers(); } void __init msm8974_init_very_early(void) { msm8974_early_memory(); } void __init msm8974_init_early(void) { msm_reserve_last_regs(); } static const char *msm8974_dt_match[] __initconst = { "qcom,msm8974", "qcom,apq8074", NULL }; DT_MACHINE_START(MSM8974_DT, "Qualcomm MSM 8974 (Flattened Device Tree)") .map_io = msm8974_map_io, .init_irq = msm_dt_init_irq, .init_machine = msm8974_init, .handle_irq = gic_handle_irq, .timer = &msm_dt_timer, .dt_compat = msm8974_dt_match, .reserve = msm_8974_reserve, .init_very_early = msm8974_init_very_early, .init_early = msm8974_init_early, .restart = msm_restart, .smp = &msm8974_smp_ops, MACHINE_END
zhuoyang/android_kernel_sony_msm8974
arch/arm/mach-msm/board-8974.c
C
gpl-2.0
9,346
/* * (C) Copyright 2001 * Raymond Lo, lo@routefree.com * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* * Support for harddisk partitions. * * To be compatible with LinuxPPC and Apple we use the standard Apple * SCSI disk partitioning scheme. For more information see: * http://developer.apple.com/techpubs/mac/Devices/Devices-126.html#MARKER-14-92 */ #include <common.h> #include <command.h> #include <ide.h> #include "part_dos.h" #if ((CONFIG_COMMANDS & CFG_CMD_IDE) || \ (CONFIG_COMMANDS & CFG_CMD_SCSI) || \ (CONFIG_COMMANDS & CFG_CMD_USB) || \ defined(CONFIG_MMC) || \ defined(CONFIG_SYSTEMACE) ) && defined(CONFIG_DOS_PARTITION) /* Convert char[4] in little endian format to the host format integer */ static inline int le32_to_int(unsigned char *le32) { return ((le32[3] << 24) + (le32[2] << 16) + (le32[1] << 8) + le32[0] ); } static inline int is_extended(int part_type) { return (part_type == 0x5 || part_type == 0xf || part_type == 0x85); } static void print_one_part (dos_partition_t *p, int ext_part_sector, int part_num) { int lba_start = ext_part_sector + le32_to_int (p->start4); int lba_size = le32_to_int (p->size4); printf ("%5d\t\t%10d\t%10d\t%2x%s\n", part_num, lba_start, lba_size, p->sys_ind, (is_extended (p->sys_ind) ? " Extd" : "")); } static int test_block_type(unsigned char *buffer) { if((buffer[DOS_PART_MAGIC_OFFSET + 0] != 0x55) || (buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) ) { return (-1); } /* no DOS Signature at all */ if(strncmp((char *)&buffer[DOS_PBR_FSTYPE_OFFSET],"FAT",3)==0) return DOS_PBR; /* is PBR */ return DOS_MBR; /* Is MBR */ } int test_part_dos (block_dev_desc_t *dev_desc) { unsigned char buffer[DEFAULT_SECTOR_SIZE]; if ((dev_desc->block_read(dev_desc->dev, 0, 1, (ulong *) buffer) != 1) || (buffer[DOS_PART_MAGIC_OFFSET + 0] != 0x55) || (buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) ) { return (-1); } return (0); } /* Print a partition that is relative to its Extended partition table */ static unsigned char buffer_111[DEFAULT_SECTOR_SIZE]; static void print_partition_extended (block_dev_desc_t *dev_desc, int ext_part_sector, int relative, int part_num) { dos_partition_t *pt; int i; if (dev_desc->block_read(dev_desc->dev, ext_part_sector, 1, (ulong *) buffer_111) != 1) { printf ("** Can't read partition table on %d:%d **\n", dev_desc->dev, ext_part_sector); return; } i=test_block_type(buffer_111); if(i==-1) { printf ("bad MBR sector signature 0x%02x%02x\n", buffer_111[DOS_PART_MAGIC_OFFSET], buffer_111[DOS_PART_MAGIC_OFFSET + 1]); return; } if(i==DOS_PBR) { printf (" 1\t\t 0\t%10ld\t%2x\n", dev_desc->lba, buffer_111[DOS_PBR_MEDIA_TYPE_OFFSET]); return; } /* Print all primary/logical partitions */ pt = (dos_partition_t *) (buffer_111 + DOS_PART_TBL_OFFSET); for (i = 0; i < 4; i++, pt++) { /* * fdisk does not show the extended partitions that * are not in the MBR */ if ((pt->sys_ind != 0) && (ext_part_sector == 0 || !is_extended (pt->sys_ind)) ) { print_one_part (pt, ext_part_sector, part_num); } /* Reverse engr the fdisk part# assignment rule! */ if ((ext_part_sector == 0) || (pt->sys_ind != 0 && !is_extended (pt->sys_ind)) ) { part_num++; } } /* Follows the extended partitions */ pt = (dos_partition_t *) (buffer_111 + DOS_PART_TBL_OFFSET); for (i = 0; i < 4; i++, pt++) { if (is_extended (pt->sys_ind)) { int lba_start = le32_to_int (pt->start4) + relative; print_partition_extended (dev_desc, lba_start, ext_part_sector == 0 ? lba_start : relative, part_num); } } return; } /* Print a partition that is relative to its Extended partition table */ unsigned char buffer_222[DEFAULT_SECTOR_SIZE]; static int get_partition_info_extended (block_dev_desc_t *dev_desc, int ext_part_sector, int relative, int part_num, int which_part, disk_partition_t *info) { dos_partition_t *pt; int i; if (dev_desc->block_read (dev_desc->dev, ext_part_sector, 1, (ulong *) buffer_222) != 1) { printf ("** Can't read partition table on %d:%d **\n", dev_desc->dev, ext_part_sector); return -1; } if (buffer_222[DOS_PART_MAGIC_OFFSET] != 0x55 || buffer_222[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) { printf ("bad MBR sector signature 0x%02x%02x\n", buffer_222[DOS_PART_MAGIC_OFFSET], buffer_222[DOS_PART_MAGIC_OFFSET + 1]); return -1; } /* Print all primary/logical partitions */ pt = (dos_partition_t *) (buffer_222 + DOS_PART_TBL_OFFSET); for (i = 0; i < 4; i++, pt++) { /* * fdisk does not show the extended partitions that * are not in the MBR */ if ((pt->sys_ind != 0) && (part_num == which_part) && (is_extended(pt->sys_ind) == 0)) { info->blksz = 512; info->start = ext_part_sector + le32_to_int (pt->start4); info->size = le32_to_int (pt->size4); switch(dev_desc->if_type) { case IF_TYPE_IDE: case IF_TYPE_ATAPI: sprintf ((char *)info->name, "hd%c%d\n", 'a' + dev_desc->dev, part_num); break; case IF_TYPE_SCSI: sprintf ((char *)info->name, "sd%c%d\n", 'a' + dev_desc->dev, part_num); break; case IF_TYPE_USB: sprintf ((char *)info->name, "usbd%c%d\n", 'a' + dev_desc->dev, part_num); break; case IF_TYPE_DOC: sprintf ((char *)info->name, "docd%c%d\n", 'a' + dev_desc->dev, part_num); break; default: sprintf ((char *)info->name, "xx%c%d\n", 'a' + dev_desc->dev, part_num); break; } /* sprintf(info->type, "%d, pt->sys_ind); */ sprintf ((char *)info->type, "U-Boot"); return 0; } /* Reverse engr the fdisk part# assignment rule! */ if ((ext_part_sector == 0) || (pt->sys_ind != 0 && !is_extended (pt->sys_ind)) ) { part_num++; } } /* Follows the extended partitions */ pt = (dos_partition_t *) (buffer_222 + DOS_PART_TBL_OFFSET); for (i = 0; i < 4; i++, pt++) { if (is_extended (pt->sys_ind)) { int lba_start = le32_to_int (pt->start4) + relative; return get_partition_info_extended (dev_desc, lba_start, ext_part_sector == 0 ? lba_start : relative, part_num, which_part, info); } } return -1; } void print_part_dos (block_dev_desc_t *dev_desc) { printf ("Partition Start Sector Num Sectors Type\n"); print_partition_extended (dev_desc, 0, 0, 1); } int get_partition_info_dos (block_dev_desc_t *dev_desc, int part, disk_partition_t * info) { return get_partition_info_extended (dev_desc, 0, 0, 1, part, info); } #endif /* (CONFIG_COMMANDS & CFG_CMD_IDE) && CONFIG_DOS_PARTITION */
mdxy2010/forlinux-ok6410
u-boot/disk/part_dos.c
C
gpl-2.0
7,451
<?php /* Copyright (C) 2014, Siemens AG 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ namespace Fossology\Lib\Report; use Fossology\Lib\Dao\UploadDao; use Fossology\Lib\Dao\TreeDao; use Mockery as M; use Mockery\MockInterface; include_once(dirname(dirname(__DIR__))."/common-string.php"); class TestClearedGetter extends ClearedGetterCommon { public function __construct($groupBy = "content") { parent::__construct($groupBy); } protected function getStatements($uploadId, $uploadTreeTableName, $userId = null, $groupId=null) { return array( array("content" => "1", "text" => "t1", "comments" => "c1", "uploadtree_pk" => 1), array("content" => "1", "text" => "t2", "comments" => "c1", "uploadtree_pk" => 2), array("content" => "2", "text" => "t3", "comments" => "c3", "uploadtree_pk" => 3), ); } } class WeirdCharClearedGetter extends ClearedGetterCommon { public function __construct($groupBy = "content") { parent::__construct($groupBy); } protected function getStatements($uploadId, $uploadTreeTableName, $userId = null, $groupId=null){} public function getCleared($uploadId, $groupId=null) { return array( array("good" => "漢", "esc" => "escape", "uml" => ' ü ') ); } } class ClearedComonReportTest extends \PHPUnit_Framework_TestCase { /** @var UploadDao|MockInterface */ private $uploadDao; /** @var TreeDao|MockInterface */ private $treeDao; protected function setUp() { $this->uploadDao = M::mock(UploadDao::classname()); $this->treeDao = M::mock(TreeDao::classname()); $container = M::mock('ContainerBuilder'); $GLOBALS['container'] = $container; $container->shouldReceive('get')->with('dao.upload')->andReturn($this->uploadDao); $container->shouldReceive('get')->with('dao.tree')->andReturn($this->treeDao); $this->assertCountBefore = \Hamcrest\MatcherAssert::getCount(); } protected function tearDown() { $this->addToAssertionCount(\Hamcrest\MatcherAssert::getCount()-$this->assertCountBefore); } public function testGetFileNames() { $this->clearedGetterTest = new TestClearedGetter(); $uploadId = 1; $parentId = 112; $uploadTreeTableName = "ut"; $this->uploadDao ->shouldReceive('getUploadtreeTableName') ->with($uploadId) ->andReturn($uploadTreeTableName); $this->treeDao ->shouldReceive('getMinimalCoveringItem') ->with($uploadId,$uploadTreeTableName) ->andReturn($parentId); $this->treeDao ->shouldReceive('getFullPath') ->with(1, $uploadTreeTableName, $parentId) ->andReturn("a/1"); $this->treeDao ->shouldReceive('getFullPath') ->with(2, $uploadTreeTableName, $parentId) ->andReturn("a/2"); $this->treeDao ->shouldReceive('getFullPath') ->with(3, $uploadTreeTableName, $parentId) ->andReturn("a/b/1"); $statements = $this->clearedGetterTest->getCleared($uploadId); $expected = array( "statements" => array( array( "content" => "1", "text" => "t1", "comments" => "c1", "files" => array("a/1", "a/2") ), array( "content" => "2", "text" => "t3", "comments" => "c3", "files" => array("a/b/1") ) ) ); $expected = arsort($expected); assertThat($expected, equalTo($statements)); } public function testGetFileNamesGroupByText() { $this->clearedGetterTest = new TestClearedGetter(); $uploadId = 1; $parentId = 112; $uploadTreeTableName = "ut"; $this->uploadDao ->shouldReceive('getUploadtreeTableName') ->with($uploadId) ->andReturn($uploadTreeTableName); $this->treeDao ->shouldReceive('getMinimalCoveringItem') ->with($uploadId,$uploadTreeTableName) ->andReturn($parentId); $this->treeDao ->shouldReceive('getFullPath') ->with(1, $uploadTreeTableName, $parentId) ->andReturn("a/1"); $this->treeDao ->shouldReceive('getFullPath') ->with(2, $uploadTreeTableName, $parentId) ->andReturn("a/2"); $this->treeDao ->shouldReceive('getFullPath') ->with(3, $uploadTreeTableName, $parentId) ->andReturn("a/b/1"); $tester = new TestClearedGetter("text"); $statements = $tester->getCleared($uploadId); $expected = array( "statements" => array( array( "content" => "1", "text" => "t1", "comments" => "c1", "files" => array("a/1") ), array( "content" => "1", "text" => "t2", "comments" => "c1", "files" => array("a/2") ), array( "content" => "2", "text" => "t3", "comments" => "c3", "files" => array("a/b/1") ) ) ); $expected = arsort($expected); assertThat($expected, equalTo($statements)); } function testWeirdChars() { $weirdCharclearedGetter = new WeirdCharclearedGetter(); $json = $weirdCharclearedGetter->cJson(0); assertThat($json, containsString('"good":"\\u6f22"')); assertThat($json, containsString('"esc":"escape"')); assertThat($json, containsString('"uml":" \\u00fc "')); } }
timurphy/fossology
src/lib/php/Report/tests/ClearedGetterCommonTest.php
PHP
gpl-2.0
5,960
package com.variamos.gui.maineditor; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.JToolBar; import javax.swing.TransferHandler; import com.variamos.gui.maineditor.EditorActions.ColorAction; import com.variamos.gui.maineditor.EditorActions.FontStyleAction; import com.variamos.gui.maineditor.EditorActions.HistoryAction; import com.variamos.gui.maineditor.EditorActions.KeyValueAction; import com.variamos.gui.maineditor.EditorActions.NewAction; import com.variamos.gui.maineditor.EditorActions.OpenAction; import com.variamos.gui.maineditor.EditorActions.PrintAction; import com.variamos.gui.maineditor.EditorActions.SaveAction; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.swing.util.mxGraphActions; import com.mxgraph.util.mxConstants; import com.mxgraph.util.mxEvent; import com.mxgraph.util.mxEventObject; import com.mxgraph.util.mxResources; import com.mxgraph.util.mxEventSource.mxIEventListener; import com.mxgraph.view.mxGraph; import com.mxgraph.view.mxGraphView; public class EditorToolBar extends JToolBar { /** * */ private static final long serialVersionUID = -8015443128436394471L; /** * * @param frame * @param orientation */ private boolean ignoreZoomChange = false; /** * */ public EditorToolBar(final BasicGraphEditor editor, int orientation) { super(orientation); setBorder(BorderFactory.createCompoundBorder(BorderFactory .createEmptyBorder(3, 3, 3, 3), getBorder())); setFloatable(false); add(editor.bind("New", new NewAction(), "/com/mxgraph/examples/swing/images/new.gif")); add(editor.bind("Open", new OpenAction(), "/com/mxgraph/examples/swing/images/open.gif")); add(editor.bind("Save", new SaveAction(false), "/com/mxgraph/examples/swing/images/save.gif")); addSeparator(); add(editor.bind("Print", new PrintAction(), "/com/mxgraph/examples/swing/images/print.gif")); addSeparator(); add(editor.bind("Cut", TransferHandler.getCutAction(), "/com/mxgraph/examples/swing/images/cut.gif")); add(editor.bind("Copy", TransferHandler.getCopyAction(), "/com/mxgraph/examples/swing/images/copy.gif")); add(editor.bind("Paste", TransferHandler.getPasteAction(), "/com/mxgraph/examples/swing/images/paste.gif")); addSeparator(); add(editor.bind("Delete", mxGraphActions.getDeleteAction(), "/com/mxgraph/examples/swing/images/delete.gif")); addSeparator(); add(editor.bind("Undo", new HistoryAction(true), "/com/mxgraph/examples/swing/images/undo.gif")); add(editor.bind("Redo", new HistoryAction(false), "/com/mxgraph/examples/swing/images/redo.gif")); addSeparator(); // Gets the list of available fonts from the local graphics environment // and adds some frequently used fonts at the beginning of the list GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); List<String> fonts = new ArrayList<String>(); fonts.addAll(Arrays.asList(new String[] { "Helvetica", "Verdana", "Times New Roman", "Garamond", "Courier New", "-" })); fonts.addAll(Arrays.asList(env.getAvailableFontFamilyNames())); final JComboBox fontCombo = new JComboBox(fonts.toArray()); fontCombo.setEditable(true); fontCombo.setMinimumSize(new Dimension(120, 0)); fontCombo.setPreferredSize(new Dimension(120, 0)); fontCombo.setMaximumSize(new Dimension(120, 100)); add(fontCombo); fontCombo.addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { String font = fontCombo.getSelectedItem().toString(); if (font != null && !font.equals("-")) { mxGraph graph = editor.getGraphComponent().getGraph(); graph.setCellStyles(mxConstants.STYLE_FONTFAMILY, font); } } }); final JComboBox sizeCombo = new JComboBox(new Object[] { "6pt", "8pt", "9pt", "10pt", "12pt", "14pt", "18pt", "24pt", "30pt", "36pt", "48pt", "60pt" }); sizeCombo.setEditable(true); sizeCombo.setMinimumSize(new Dimension(65, 0)); sizeCombo.setPreferredSize(new Dimension(65, 0)); sizeCombo.setMaximumSize(new Dimension(65, 100)); add(sizeCombo); sizeCombo.addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { mxGraph graph = editor.getGraphComponent().getGraph(); graph.setCellStyles(mxConstants.STYLE_FONTSIZE, sizeCombo .getSelectedItem().toString().replace("pt", "")); } }); addSeparator(); add(editor.bind("Bold", new FontStyleAction(true), "/com/mxgraph/examples/swing/images/bold.gif")); add(editor.bind("Italic", new FontStyleAction(false), "/com/mxgraph/examples/swing/images/italic.gif")); addSeparator(); add(editor.bind("Left", new KeyValueAction(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_LEFT), "/com/mxgraph/examples/swing/images/left.gif")); add(editor.bind("Center", new KeyValueAction(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_CENTER), "/com/mxgraph/examples/swing/images/center.gif")); add(editor.bind("Right", new KeyValueAction(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_RIGHT), "/com/mxgraph/examples/swing/images/right.gif")); addSeparator(); add(editor.bind("Font", new ColorAction("Font", mxConstants.STYLE_FONTCOLOR), "/com/mxgraph/examples/swing/images/fontcolor.gif")); add(editor.bind("Stroke", new ColorAction("Stroke", mxConstants.STYLE_STROKECOLOR), "/com/mxgraph/examples/swing/images/linecolor.gif")); add(editor.bind("Fill", new ColorAction("Fill", mxConstants.STYLE_FILLCOLOR), "/com/mxgraph/examples/swing/images/fillcolor.gif")); addSeparator(); final mxGraphView view = editor.getGraphComponent().getGraph() .getView(); final JComboBox zoomCombo = new JComboBox(new Object[] { "400%", "200%", "150%", "100%", "90%", "75%", "50%", mxResources.get("page"), mxResources.get("width"), mxResources.get("actualSize") }); zoomCombo.setEditable(true); zoomCombo.setMinimumSize(new Dimension(75, 0)); zoomCombo.setPreferredSize(new Dimension(75, 0)); zoomCombo.setMaximumSize(new Dimension(75, 100)); zoomCombo.setMaximumRowCount(9); add(zoomCombo); // Sets the zoom in the zoom combo the current value mxIEventListener scaleTracker = new mxIEventListener() { /** * */ public void invoke(Object sender, mxEventObject evt) { ignoreZoomChange = true; try { zoomCombo.setSelectedItem((int) Math.round(100 * view .getScale()) + "%"); } finally { ignoreZoomChange = false; } } }; // Installs the scale tracker to update the value in the combo box // if the zoom is changed from outside the combo box view.getGraph().getView().addListener(mxEvent.SCALE, scaleTracker); view.getGraph().getView().addListener(mxEvent.SCALE_AND_TRANSLATE, scaleTracker); // Invokes once to sync with the actual zoom value scaleTracker.invoke(null, null); zoomCombo.addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { mxGraphComponent graphComponent = editor.getGraphComponent(); // Zoomcombo is changed when the scale is changed in the diagram // but the change is ignored here if (!ignoreZoomChange) { String zoom = zoomCombo.getSelectedItem().toString(); if (zoom.equals(mxResources.get("page"))) { graphComponent.setPageVisible(true); graphComponent .setZoomPolicy(mxGraphComponent.ZOOM_POLICY_PAGE); } else if (zoom.equals(mxResources.get("width"))) { graphComponent.setPageVisible(true); graphComponent .setZoomPolicy(mxGraphComponent.ZOOM_POLICY_WIDTH); } else if (zoom.equals(mxResources.get("actualSize"))) { graphComponent.zoomActual(); } else { try { zoom = zoom.replace("%", ""); double scale = Math.min(16, Math.max(0.01, Double.parseDouble(zoom) / 100)); graphComponent.zoomTo(scale, graphComponent .isCenterZoom()); } catch (Exception ex) { JOptionPane.showMessageDialog(editor, ex .getMessage()); } } } } }); } }
leonjaramillo/VARIAMOS
com.variamos.gui/src/com/variamos/gui/maineditor/EditorToolBar.java
Java
gpl-2.0
8,476
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package quest.sarpan; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.aionemu.commons.utils.Rnd; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; import com.aionemu.gameserver.world.World; /** * @author vlog */ public class _10053Revelations extends QuestHandler { private static final int questId = 10053; private static List<Integer> mobs = new ArrayList<Integer>(); static { mobs.add(218760); mobs.add(218762); mobs.add(218761); mobs.add(218763); } public _10053Revelations() { super(questId); } @Override public void register() { int[] npcIds = {205987, 730493, 205795, 205535}; for (int npcId : npcIds) { qe.registerQuestNpc(npcId).addOnTalkEvent(questId); } for (int mob : mobs) { qe.registerQuestNpc(mob).addOnKillEvent(questId); } qe.registerOnLevelUp(questId); qe.registerOnEnterZoneMissionEnd(questId); qe.registerOnEnterWorld(questId); qe.registerOnQuestTimerEnd(questId); qe.registerOnInvisibleTimerEnd(questId); qe.registerOnDie(questId); } @Override public boolean onZoneMissionEndEvent(QuestEnv env) { return defaultOnZoneMissionEndEvent(env); } @Override public boolean onLvlUpEvent(QuestEnv env) { return defaultOnLvlUpEvent(env, 10052, true); } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null) { return false; } DialogAction dialog = env.getDialog(); int targetId = env.getTargetId(); if (qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); switch (targetId) { case 205987: { // Garnon switch (dialog) { case QUEST_SELECT: { if (var == 0) { return sendQuestDialog(env, 1011); } } case SETPRO1: { return defaultCloseDialog(env, 0, 1); // 1 } } break; } case 730493: { // Protector's Seal switch (dialog) { case USE_OBJECT: { if (var == 2) { changeQuestStep(env, 2, 3, false); // 3 QuestService.questTimerStart(env, 180); // 3 minutes QuestService.invisibleTimerStart(env, 170); // 2:50 minutes invisible timer for dragon spawn // doesent work. maybe should be 2:40? spawn(player); return true; } } } break; } case 205795: { // Oriata should be spawned after timer ends? switch (dialog) { case QUEST_SELECT: { if (var == 4) { return sendQuestDialog(env, 2375); } else if (var == 5) { playQuestMovie(env, 709); return sendQuestDialog(env, 2716); } } case CHECK_USER_HAS_QUEST_ITEM: { return checkQuestItems(env, 5, 5, true, 10000, 10001); // reward } case SETPRO5: { return defaultCloseDialog(env, 4, 5); // 5 } case FINISH_DIALOG: { return closeDialogWindow(env); } } break; } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 205535) { // Killios if (dialog == DialogAction.USE_OBJECT) { return sendQuestDialog(env, 10002); } else { return sendQuestEndDialog(env); } } } return false; } @Override public boolean onEnterWorldEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (player.getWorldId() == 300330000) { if (var == 1) { QuestService.addNewSpawn(300330000, player.getInstanceId(), 730493, (float) 250.348, (float) 245.210, (float) 126.270, (byte) 60); changeQuestStep(env, 1, 2, false); // 2 return true; } else if (var >= 2 && var < 4) { changeQuestStep(env, var, 1, false); // 1 return true; } else if (var == 4 || var == 5) { QuestService.addNewSpawn(300330000, player.getInstanceId(), 205795, (float) 241.348, (float) 245.879, (float) 125.475, (byte) 56); return true; } } } return false; } @Override public boolean onDieEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (player.getWorldId() == 300330000) { if (var == 1) { changeQuestStep(env, 1, 2, false); // 2 return true; } } else { if (var >= 2 && var < 4) { changeQuestStep(env, var, 1, false); // 1 return true; } } } return false; } @Override public boolean onKillEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var == 3) { int targetId = env.getTargetId(); if (mobs.contains(targetId)) { spawn(player); return true; } } } return false; } @Override public boolean onQuestTimerEndEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var == 3) { QuestService.addNewSpawn(300330000, player.getInstanceId(), 205795, (float) 241.348, (float) 245.879, (float) 125.475, (byte) 56); changeQuestStep(env, 3, 4, false); // 4 return playQuestMovie(env, 707); } } return false; } @Override public boolean onInvisibleTimerEndEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var == 3) { spawnHesibanata(player); return true; } } return false; } private void spawn(Player player) { int mobToSpawn = mobs.get(Rnd.get(0, 3)); float x = 0; float y = 0; final float z = 124.942f; switch (mobToSpawn) { case 218760: { x = 250.081f; y = 268.308f; break; } case 218762: { x = 273.354f; y = 244.489f; break; } case 218761: { x = 272.994f; y = 244.674f; break; } case 218763: { x = 250.800f; y = 222.782f; break; } } Npc spawn = (Npc) QuestService.spawnQuestNpc(300330000, player.getInstanceId(), mobToSpawn, x, y, z, (byte) 0); Collection<Npc> allNpcs = World.getInstance().getNpcs(); Npc target = null; for (Npc npc : allNpcs) { if (npc.getNpcId() == 730493) { target = npc; } } if (target != null) { spawn.getAggroList().addHate(target, 1); } } private void spawnHesibanata(Player player) { Npc spawn = (Npc) QuestService.spawnQuestNpc(300330000, player.getInstanceId(), 218890, 250.970f, 221.711f, 124.942f, (byte) 0); spawn.getAggroList().addHate(player, 1); } }
GiGa-Emulator/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/quest/sarpan/_10053Revelations.java
Java
gpl-2.0
11,270
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Sun Oct 21 14:27:45 PDT 2001 --> <TITLE> : Class REMatchEnumeration </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_top"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../gnu/regexp/REMatch.html"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../gnu/regexp/RESyntax.html"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="REMatchEnumeration.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY: &nbsp;INNER&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL: &nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> gnu.regexp</FONT> <BR> Class REMatchEnumeration</H2> <PRE> java.lang.Object | +--<B>gnu.regexp.REMatchEnumeration</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>java.util.Enumeration, java.io.Serializable</DD> </DL> <HR> <DL> <DT>public class <B>REMatchEnumeration</B><DT>extends java.lang.Object<DT>implements java.util.Enumeration, java.io.Serializable</DL> <P> An REMatchEnumeration enumerates regular expression matches over a given input text. You obtain a reference to an enumeration using the <code>getMatchEnumeration()</code> methods on an instance of RE. <P> REMatchEnumeration does lazy computation; that is, it will not search for a match until it needs to. If you'd rather just get all the matches at once in a big array, use the <code>getAllMatches()</code> methods on RE. However, using an enumeration can help speed performance when the entire text does not need to be searched immediately. <P> The enumerated type is especially useful when searching on a Reader or InputStream, because the InputStream read position cannot be guaranteed after calling <code>getMatch()</code> (see the description of that method for an explanation of why). Enumeration also saves a lot of overhead required when calling <code>getMatch()</code> multiple times. <P> <DL> <DT><B>Author: </B><DD><A HREF="mailto:wes@cacas.org">Wes Biggs</A></DD> <DT><B>See Also: </B><DD><A HREF="../../serialized-form.html#gnu.regexp.REMatchEnumeration">Serialized Form</A></DL> <HR> <P> <!-- ======== INNER CLASS SUMMARY ======== --> <!-- =========== FIELD SUMMARY =========== --> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Method Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/regexp/REMatchEnumeration.html#hasMoreElements()">hasMoreElements</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns true if there are more matches in the input text.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/regexp/REMatchEnumeration.html#hasMoreMatches()">hasMoreMatches</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns true if there are more matches in the input text.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/regexp/REMatchEnumeration.html#hasMoreMatches(java.lang.StringBuffer)">hasMoreMatches</A></B>(java.lang.StringBuffer&nbsp;buffer)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns true if there are more matches in the input text.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.Object</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/regexp/REMatchEnumeration.html#nextElement()">nextElement</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the next match in the input text.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../gnu/regexp/REMatch.html">REMatch</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/regexp/REMatchEnumeration.html#nextMatch()">nextMatch</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the next match in the input text.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class java.lang.Object</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Method Detail</B></FONT></TD> </TR> </TABLE> <A NAME="hasMoreElements()"><!-- --></A><H3> hasMoreElements</H3> <PRE> public boolean <B>hasMoreElements</B>()</PRE> <DL> <DD>Returns true if there are more matches in the input text.<DD><DL> <DT><B>Specified by: </B><DD><CODE>hasMoreElements</CODE> in interface <CODE>java.util.Enumeration</CODE></DL> </DD> </DL> <HR> <A NAME="hasMoreMatches()"><!-- --></A><H3> hasMoreMatches</H3> <PRE> public boolean <B>hasMoreMatches</B>()</PRE> <DL> <DD>Returns true if there are more matches in the input text.<DD><DL> </DL> </DD> </DL> <HR> <A NAME="hasMoreMatches(java.lang.StringBuffer)"><!-- --></A><H3> hasMoreMatches</H3> <PRE> public boolean <B>hasMoreMatches</B>(java.lang.StringBuffer&nbsp;buffer)</PRE> <DL> <DD>Returns true if there are more matches in the input text. Saves the text leading up to the match (or to the end of the input) in the specified buffer.<DD><DL> </DL> </DD> </DL> <HR> <A NAME="nextElement()"><!-- --></A><H3> nextElement</H3> <PRE> public java.lang.Object <B>nextElement</B>() throws java.util.NoSuchElementException</PRE> <DL> <DD>Returns the next match in the input text.<DD><DL> <DT><B>Specified by: </B><DD><CODE>nextElement</CODE> in interface <CODE>java.util.Enumeration</CODE></DL> </DD> </DL> <HR> <A NAME="nextMatch()"><!-- --></A><H3> nextMatch</H3> <PRE> public <A HREF="../../gnu/regexp/REMatch.html">REMatch</A> <B>nextMatch</B>() throws java.util.NoSuchElementException</PRE> <DL> <DD>Returns the next match in the input text. This method is provided for convenience to avoid having to explicitly cast the return value to class REMatch.<DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_bottom"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../gnu/regexp/REMatch.html"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../gnu/regexp/RESyntax.html"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="REMatchEnumeration.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY: &nbsp;INNER&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL: &nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> </BODY> </HTML>
simonward86/Spectra
load/doc/gnu.regexp/api/gnu/regexp/REMatchEnumeration.html
HTML
gpl-2.0
11,365
/* * ALSA sequencer Ports * Copyright (c) 1998 by Frank van de Pol <fvdpol@coil.demon.nl> * Jaroslav Kysela <perex@perex.cz> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <sound/core.h> #include <linux/slab.h> #include <linux/module.h> #include "seq_system.h" #include "seq_ports.h" #include "seq_clientmgr.h" /* registration of client ports */ /* NOTE: the current implementation of the port structure as a linked list is not optimal for clients that have many ports. For sending messages to all subscribers of a port we first need to find the address of the port structure, which means we have to traverse the list. A direct access table (array) would be better, but big preallocated arrays waste memory. Possible actions: 1) leave it this way, a client does normaly does not have more than a few ports 2) replace the linked list of ports by a array of pointers which is dynamicly kmalloced. When a port is added or deleted we can simply allocate a new array, copy the corresponding pointers, and delete the old one. We then only need a pointer to this array, and an integer that tells us how much elements are in array. */ /* return pointer to port structure - port is locked if found */ struct snd_seq_client_port *snd_seq_port_use_ptr(struct snd_seq_client *client, int num) { struct snd_seq_client_port *port; if (client == NULL) return NULL; read_lock(&client->ports_lock); list_for_each_entry(port, &client->ports_list_head, list) { if (port->addr.port == num) { if (port->closing) break; /* deleting now */ snd_use_lock_use(&port->use_lock); read_unlock(&client->ports_lock); return port; } } read_unlock(&client->ports_lock); return NULL; /* not found */ } /* search for the next port - port is locked if found */ struct snd_seq_client_port *snd_seq_port_query_nearest(struct snd_seq_client *client, struct snd_seq_port_info *pinfo) { int num; struct snd_seq_client_port *port, *found; num = pinfo->addr.port; found = NULL; read_lock(&client->ports_lock); list_for_each_entry(port, &client->ports_list_head, list) { if (port->addr.port < num) continue; if (port->addr.port == num) { found = port; break; } if (found == NULL || port->addr.port < found->addr.port) found = port; } if (found) { if (found->closing) found = NULL; else snd_use_lock_use(&found->use_lock); } read_unlock(&client->ports_lock); return found; } /* initialize snd_seq_port_subs_info */ static void port_subs_info_init(struct snd_seq_port_subs_info *grp) { INIT_LIST_HEAD(&grp->list_head); grp->count = 0; grp->exclusive = 0; rwlock_init(&grp->list_lock); init_rwsem(&grp->list_mutex); grp->open = NULL; grp->close = NULL; } /* create a port, port number is returned (-1 on failure) */ struct snd_seq_client_port *snd_seq_create_port(struct snd_seq_client *client, int port) { unsigned long flags; struct snd_seq_client_port *new_port, *p; int num = -1; /* sanity check */ if (snd_BUG_ON(!client)) return NULL; if (client->num_ports >= SNDRV_SEQ_MAX_PORTS - 1) { snd_printk(KERN_WARNING "too many ports for client %d\n", client->number); return NULL; } /* create a new port */ new_port = kzalloc(sizeof(*new_port), GFP_KERNEL); if (! new_port) { snd_printd("malloc failed for registering client port\n"); return NULL; /* failure, out of memory */ } /* init port data */ new_port->addr.client = client->number; new_port->addr.port = -1; new_port->owner = THIS_MODULE; sprintf(new_port->name, "port-%d", num); snd_use_lock_init(&new_port->use_lock); port_subs_info_init(&new_port->c_src); port_subs_info_init(&new_port->c_dest); num = port >= 0 ? port : 0; mutex_lock(&client->ports_mutex); write_lock_irqsave(&client->ports_lock, flags); list_for_each_entry(p, &client->ports_list_head, list) { if (p->addr.port > num) break; if (port < 0) /* auto-probe mode */ num = p->addr.port + 1; } /* insert the new port */ list_add_tail(&new_port->list, &p->list); client->num_ports++; new_port->addr.port = num; /* store the port number in the port */ write_unlock_irqrestore(&client->ports_lock, flags); mutex_unlock(&client->ports_mutex); sprintf(new_port->name, "port-%d", num); return new_port; } /* */ static int subscribe_port(struct snd_seq_client *client, struct snd_seq_client_port *port, struct snd_seq_port_subs_info *grp, struct snd_seq_port_subscribe *info, int send_ack); static int unsubscribe_port(struct snd_seq_client *client, struct snd_seq_client_port *port, struct snd_seq_port_subs_info *grp, struct snd_seq_port_subscribe *info, int send_ack); static struct snd_seq_client_port *get_client_port(struct snd_seq_addr *addr, struct snd_seq_client **cp) { struct snd_seq_client_port *p; *cp = snd_seq_client_use_ptr(addr->client); if (*cp) { p = snd_seq_port_use_ptr(*cp, addr->port); if (! p) { snd_seq_client_unlock(*cp); *cp = NULL; } return p; } return NULL; } static void delete_and_unsubscribe_port(struct snd_seq_client *client, struct snd_seq_client_port *port, struct snd_seq_subscribers *subs, bool is_src, bool ack); static inline struct snd_seq_subscribers * get_subscriber(struct list_head *p, bool is_src) { if (is_src) return list_entry(p, struct snd_seq_subscribers, src_list); else return list_entry(p, struct snd_seq_subscribers, dest_list); } /* * remove all subscribers on the list * this is called from port_delete, for each src and dest list. */ static void clear_subscriber_list(struct snd_seq_client *client, struct snd_seq_client_port *port, struct snd_seq_port_subs_info *grp, int is_src) { struct list_head *p, *n; list_for_each_safe(p, n, &grp->list_head) { struct snd_seq_subscribers *subs; struct snd_seq_client *c; struct snd_seq_client_port *aport; subs = get_subscriber(p, is_src); if (is_src) aport = get_client_port(&subs->info.dest, &c); else aport = get_client_port(&subs->info.sender, &c); delete_and_unsubscribe_port(client, port, subs, is_src, false); if (!aport) { /* looks like the connected port is being deleted. * we decrease the counter, and when both ports are deleted * remove the subscriber info */ if (atomic_dec_and_test(&subs->ref_count)) kfree(subs); continue; } /* ok we got the connected port */ delete_and_unsubscribe_port(c, aport, subs, !is_src, true); kfree(subs); snd_seq_port_unlock(aport); snd_seq_client_unlock(c); } } /* delete port data */ static int port_delete(struct snd_seq_client *client, struct snd_seq_client_port *port) { /* set closing flag and wait for all port access are gone */ port->closing = 1; snd_use_lock_sync(&port->use_lock); /* clear subscribers info */ clear_subscriber_list(client, port, &port->c_src, true); clear_subscriber_list(client, port, &port->c_dest, false); if (port->private_free) port->private_free(port->private_data); snd_BUG_ON(port->c_src.count != 0); snd_BUG_ON(port->c_dest.count != 0); kfree(port); return 0; } /* delete a port with the given port id */ int snd_seq_delete_port(struct snd_seq_client *client, int port) { unsigned long flags; struct snd_seq_client_port *found = NULL, *p; mutex_lock(&client->ports_mutex); write_lock_irqsave(&client->ports_lock, flags); list_for_each_entry(p, &client->ports_list_head, list) { if (p->addr.port == port) { /* ok found. delete from the list at first */ list_del(&p->list); client->num_ports--; found = p; break; } } write_unlock_irqrestore(&client->ports_lock, flags); mutex_unlock(&client->ports_mutex); if (found) return port_delete(client, found); else return -ENOENT; } /* delete the all ports belonging to the given client */ int snd_seq_delete_all_ports(struct snd_seq_client *client) { unsigned long flags; struct list_head deleted_list; struct snd_seq_client_port *port, *tmp; /* move the port list to deleted_list, and * clear the port list in the client data. */ mutex_lock(&client->ports_mutex); write_lock_irqsave(&client->ports_lock, flags); if (! list_empty(&client->ports_list_head)) { list_add(&deleted_list, &client->ports_list_head); list_del_init(&client->ports_list_head); } else { INIT_LIST_HEAD(&deleted_list); } client->num_ports = 0; write_unlock_irqrestore(&client->ports_lock, flags); /* remove each port in deleted_list */ list_for_each_entry_safe(port, tmp, &deleted_list, list) { list_del(&port->list); snd_seq_system_client_ev_port_exit(port->addr.client, port->addr.port); port_delete(client, port); } mutex_unlock(&client->ports_mutex); return 0; } /* set port info fields */ int snd_seq_set_port_info(struct snd_seq_client_port * port, struct snd_seq_port_info * info) { if (snd_BUG_ON(!port || !info)) return -EINVAL; /* set port name */ if (info->name[0]) strlcpy(port->name, info->name, sizeof(port->name)); /* set capabilities */ port->capability = info->capability; /* get port type */ port->type = info->type; /* information about supported channels/voices */ port->midi_channels = info->midi_channels; port->midi_voices = info->midi_voices; port->synth_voices = info->synth_voices; /* timestamping */ port->timestamping = (info->flags & SNDRV_SEQ_PORT_FLG_TIMESTAMP) ? 1 : 0; port->time_real = (info->flags & SNDRV_SEQ_PORT_FLG_TIME_REAL) ? 1 : 0; port->time_queue = info->time_queue; return 0; } /* get port info fields */ int snd_seq_get_port_info(struct snd_seq_client_port * port, struct snd_seq_port_info * info) { if (snd_BUG_ON(!port || !info)) return -EINVAL; /* get port name */ strlcpy(info->name, port->name, sizeof(info->name)); /* get capabilities */ info->capability = port->capability; /* get port type */ info->type = port->type; /* information about supported channels/voices */ info->midi_channels = port->midi_channels; info->midi_voices = port->midi_voices; info->synth_voices = port->synth_voices; /* get subscriber counts */ info->read_use = port->c_src.count; info->write_use = port->c_dest.count; /* timestamping */ info->flags = 0; if (port->timestamping) { info->flags |= SNDRV_SEQ_PORT_FLG_TIMESTAMP; if (port->time_real) info->flags |= SNDRV_SEQ_PORT_FLG_TIME_REAL; info->time_queue = port->time_queue; } return 0; } /* * call callback functions (if any): * the callbacks are invoked only when the first (for connection) or * the last subscription (for disconnection) is done. Second or later * subscription results in increment of counter, but no callback is * invoked. * This feature is useful if these callbacks are associated with * initialization or termination of devices (see seq_midi.c). * * If callback_all option is set, the callback function is invoked * at each connection/disconnection. */ static int subscribe_port(struct snd_seq_client *client, struct snd_seq_client_port *port, struct snd_seq_port_subs_info *grp, struct snd_seq_port_subscribe *info, int send_ack) { int err = 0; if (!try_module_get(port->owner)) return -EFAULT; grp->count++; if (grp->open && (port->callback_all || grp->count == 1)) { err = grp->open(port->private_data, info); if (err < 0) { module_put(port->owner); grp->count--; } } if (err >= 0 && send_ack && client->type == USER_CLIENT) snd_seq_client_notify_subscription(port->addr.client, port->addr.port, info, SNDRV_SEQ_EVENT_PORT_SUBSCRIBED); return err; } static int unsubscribe_port(struct snd_seq_client *client, struct snd_seq_client_port *port, struct snd_seq_port_subs_info *grp, struct snd_seq_port_subscribe *info, int send_ack) { int err = 0; if (! grp->count) return -EINVAL; grp->count--; if (grp->close && (port->callback_all || grp->count == 0)) err = grp->close(port->private_data, info); if (send_ack && client->type == USER_CLIENT) snd_seq_client_notify_subscription(port->addr.client, port->addr.port, info, SNDRV_SEQ_EVENT_PORT_UNSUBSCRIBED); module_put(port->owner); return err; } /* check if both addresses are identical */ static inline int addr_match(struct snd_seq_addr *r, struct snd_seq_addr *s) { return (r->client == s->client) && (r->port == s->port); } /* check the two subscribe info match */ /* if flags is zero, checks only sender and destination addresses */ static int match_subs_info(struct snd_seq_port_subscribe *r, struct snd_seq_port_subscribe *s) { if (addr_match(&r->sender, &s->sender) && addr_match(&r->dest, &s->dest)) { if (r->flags && r->flags == s->flags) return r->queue == s->queue; else if (! r->flags) return 1; } return 0; } static int check_and_subscribe_port(struct snd_seq_client *client, struct snd_seq_client_port *port, struct snd_seq_subscribers *subs, bool is_src, bool exclusive, bool ack) { struct snd_seq_port_subs_info *grp; struct list_head *p; struct snd_seq_subscribers *s; int err; grp = is_src ? &port->c_src : &port->c_dest; err = -EBUSY; down_write(&grp->list_mutex); if (exclusive) { if (!list_empty(&grp->list_head)) goto __error; } else { if (grp->exclusive) goto __error; /* check whether already exists */ list_for_each(p, &grp->list_head) { s = get_subscriber(p, is_src); if (match_subs_info(&subs->info, &s->info)) goto __error; } } err = subscribe_port(client, port, grp, &subs->info, ack); if (err < 0) { grp->exclusive = 0; goto __error; } /* add to list */ write_lock_irq(&grp->list_lock); if (is_src) list_add_tail(&subs->src_list, &grp->list_head); else list_add_tail(&subs->dest_list, &grp->list_head); grp->exclusive = exclusive; atomic_inc(&subs->ref_count); write_unlock_irq(&grp->list_lock); err = 0; __error: up_write(&grp->list_mutex); return err; } static void delete_and_unsubscribe_port(struct snd_seq_client *client, struct snd_seq_client_port *port, struct snd_seq_subscribers *subs, bool is_src, bool ack) { struct snd_seq_port_subs_info *grp; grp = is_src ? &port->c_src : &port->c_dest; down_write(&grp->list_mutex); write_lock_irq(&grp->list_lock); if (is_src) list_del(&subs->src_list); else list_del(&subs->dest_list); grp->exclusive = 0; write_unlock_irq(&grp->list_lock); up_write(&grp->list_mutex); unsubscribe_port(client, port, grp, &subs->info, ack); } /* connect two ports */ int snd_seq_port_connect(struct snd_seq_client *connector, struct snd_seq_client *src_client, struct snd_seq_client_port *src_port, struct snd_seq_client *dest_client, struct snd_seq_client_port *dest_port, struct snd_seq_port_subscribe *info) { struct snd_seq_subscribers *subs; bool exclusive; int err; subs = kzalloc(sizeof(*subs), GFP_KERNEL); if (!subs) return -ENOMEM; subs->info = *info; atomic_set(&subs->ref_count, 0); INIT_LIST_HEAD(&subs->src_list); INIT_LIST_HEAD(&subs->dest_list); exclusive = !!(info->flags & SNDRV_SEQ_PORT_SUBS_EXCLUSIVE); err = check_and_subscribe_port(src_client, src_port, subs, true, exclusive, connector->number != src_client->number); if (err < 0) goto error; err = check_and_subscribe_port(dest_client, dest_port, subs, false, exclusive, connector->number != dest_client->number); if (err < 0) goto error_dest; return 0; error_dest: delete_and_unsubscribe_port(src_client, src_port, subs, true, connector->number != src_client->number); error: kfree(subs); return err; } /* remove the connection */ int snd_seq_port_disconnect(struct snd_seq_client *connector, struct snd_seq_client *src_client, struct snd_seq_client_port *src_port, struct snd_seq_client *dest_client, struct snd_seq_client_port *dest_port, struct snd_seq_port_subscribe *info) { struct snd_seq_port_subs_info *src = &src_port->c_src; struct snd_seq_subscribers *subs; int err = -ENOENT; down_write(&src->list_mutex); /* look for the connection */ list_for_each_entry(subs, &src->list_head, src_list) { if (match_subs_info(info, &subs->info)) { atomic_dec(&subs->ref_count); /* mark as not ready */ err = 0; break; } } up_write(&src->list_mutex); if (err < 0) return err; delete_and_unsubscribe_port(src_client, src_port, subs, true, connector->number != src_client->number); delete_and_unsubscribe_port(dest_client, dest_port, subs, false, connector->number != dest_client->number); kfree(subs); return 0; } /* get matched subscriber */ struct snd_seq_subscribers *snd_seq_port_get_subscription(struct snd_seq_port_subs_info *src_grp, struct snd_seq_addr *dest_addr) { struct snd_seq_subscribers *s, *found = NULL; down_read(&src_grp->list_mutex); list_for_each_entry(s, &src_grp->list_head, src_list) { if (addr_match(dest_addr, &s->info.dest)) { found = s; break; } } up_read(&src_grp->list_mutex); return found; } /* * Attach a device driver that wants to receive events from the * sequencer. Returns the new port number on success. * A driver that wants to receive the events converted to midi, will * use snd_seq_midisynth_register_port(). */ /* exported */ int snd_seq_event_port_attach(int client, struct snd_seq_port_callback *pcbp, int cap, int type, int midi_channels, int midi_voices, char *portname) { struct snd_seq_port_info portinfo; int ret; /* Set up the port */ memset(&portinfo, 0, sizeof(portinfo)); portinfo.addr.client = client; strlcpy(portinfo.name, portname ? portname : "Unamed port", sizeof(portinfo.name)); portinfo.capability = cap; portinfo.type = type; portinfo.kernel = pcbp; portinfo.midi_channels = midi_channels; portinfo.midi_voices = midi_voices; /* Create it */ ret = snd_seq_kernel_client_ctl(client, SNDRV_SEQ_IOCTL_CREATE_PORT, &portinfo); if (ret >= 0) ret = portinfo.addr.port; return ret; } EXPORT_SYMBOL(snd_seq_event_port_attach); /* * Detach the driver from a port. */ /* exported */ int snd_seq_event_port_detach(int client, int port) { struct snd_seq_port_info portinfo; int err; memset(&portinfo, 0, sizeof(portinfo)); portinfo.addr.client = client; portinfo.addr.port = port; err = snd_seq_kernel_client_ctl(client, SNDRV_SEQ_IOCTL_DELETE_PORT, &portinfo); return err; } EXPORT_SYMBOL(snd_seq_event_port_detach);
FEDEVEL/openrex-linux-3.14
sound/core/seq/seq_ports.c
C
gpl-2.0
19,187
package ABSnake; /** * Configuration parameters for the snake plug-in * * @author thomas * @created 11 mai 2004 */ public class SnakeConfig { private double gradThreshold; private double maxDisplacement; private double maxSearch; private double regMin; private double regMax; private double alphaDeriche; /** * Constructor for the snakeConfig object * * @param gt Description of the Parameter * @param md Description of the Parameter * @param rmin Description of the Parameter * @param rmax Description of the Parameter * @param ms Description of the Parameter * @param alpha Description of the Parameter */ public SnakeConfig(double gt, double md, double ms, double rmin, double rmax, double alpha) { gradThreshold = gt; maxDisplacement = md; maxSearch = ms; regMin = rmin; regMax = rmax; alphaDeriche = alpha; } /** * Constructor for the SnakeConfig object * * @param conf Description of the Parameter */ public SnakeConfig(SnakeConfig conf) { gradThreshold = conf.getGradThreshold(); maxDisplacement = conf.getMaxDisplacement(); maxSearch = conf.getMaxSearch(); regMin = conf.getRegMin(); regMax = conf.getRegMax(); alphaDeriche = conf.getAlpha(); } /** * Gets the gradThreshold attribute of the SnakeConfig object * * @return The gradThreshold value */ public double getGradThreshold() { return gradThreshold; } /** * Gets the maxDisplacement attribute of the SnakeConfig object * * @return The maxDisplacement value */ public double getMaxDisplacement() { return maxDisplacement; } /** * Gets the maxSearch attribute of the SnakeConfig object * * @return The maxSearch value */ public double getMaxSearch() { return maxSearch; } /** * Gets the regMin attribute of the SnakeConfig object * * @return The regMin value */ public double getRegMin() { return regMin; } /** * Gets the regMax attribute of the SnakeConfig object * * @return The regMax value */ public double getRegMax() { return regMax; } /** * Gets the alpha attribute of the SnakeConfig object * * @return The alpha value */ public double getAlpha() { return alphaDeriche; } /** * Description of the Method * * @param mul Description of the Parameter */ public void update(double mul) { alphaDeriche /= mul; //maxDisplacement *= mul; //maxSearch *= mul; regMax *= mul; regMin *= mul; } }
salsaj-boudier/ABSnake
src/main/java/ABSnake/SnakeConfig.java
Java
gpl-2.0
2,505
/* * This file is part of nzbget * * Copyright (C) 2015 Andrey Prygunkov <hugbug@users.sourceforge.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * $Revision$ * $Date$ * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef WIN32 #include "win32.h" #endif #include <fstream> #include <stdlib.h> #include <string.h> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #endif #include "catch.h" #include "nzbget.h" #include "Options.h" #include "ParChecker.h" #include "TestUtil.h" class ParCheckerMock: public ParChecker { private: unsigned long CalcFileCrc(const char* szFilename); protected: virtual bool RequestMorePars(int iBlockNeeded, int* pBlockFound) { return false; } virtual EFileStatus FindFileCrc(const char* szFilename, unsigned long* lCrc, SegmentList* pSegments); public: ParCheckerMock(); void Execute(); void CorruptFile(const char* szFilename, int iOffset); }; ParCheckerMock::ParCheckerMock() { TestUtil::PrepareWorkingDir("parchecker"); SetDestDir(TestUtil::WorkingDir().c_str()); } void ParCheckerMock::Execute() { TestUtil::DisableCout(); Start(); while (IsRunning()) { usleep(10*1000); } TestUtil::EnableCout(); } void ParCheckerMock::CorruptFile(const char* szFilename, int iOffset) { std::string fullfilename(TestUtil::WorkingDir() + "/" + szFilename); FILE* pFile = fopen(fullfilename.c_str(), FOPEN_RBP); REQUIRE(pFile != NULL); fseek(pFile, iOffset, SEEK_SET); char b = 0; int written = fwrite(&b, 1, 1, pFile); REQUIRE(written == 1); fclose(pFile); } ParCheckerMock::EFileStatus ParCheckerMock::FindFileCrc(const char* szFilename, unsigned long* lCrc, SegmentList* pSegments) { std::ifstream sm((TestUtil::WorkingDir() + "/crc.txt").c_str()); std::string filename, crc; while (!sm.eof()) { sm >> filename >> crc; if (filename == szFilename) { *lCrc = strtoul(crc.c_str(), NULL, 16); unsigned long lRealCrc = CalcFileCrc((TestUtil::WorkingDir() + "/" + filename).c_str()); return *lCrc == lRealCrc ? ParChecker::fsSuccess : ParChecker::fsUnknown; } } return ParChecker::fsUnknown; } unsigned long ParCheckerMock::CalcFileCrc(const char* szFilename) { FILE* infile = fopen(szFilename, FOPEN_RB); REQUIRE(infile); static const int BUFFER_SIZE = 1024 * 64; unsigned char* buffer = (unsigned char*)malloc(BUFFER_SIZE); unsigned long lDownloadCrc = 0xFFFFFFFF; int cnt = BUFFER_SIZE; while (cnt == BUFFER_SIZE) { cnt = (int)fread(buffer, 1, BUFFER_SIZE, infile); lDownloadCrc = Util::Crc32m(lDownloadCrc, buffer, cnt); } free(buffer); fclose(infile); lDownloadCrc ^= 0xFFFFFFFF; return lDownloadCrc; } TEST_CASE("Par-checker: repair not needed", "[Par][ParChecker][Slow][TestData]") { Options::CmdOptList cmdOpts; cmdOpts.push_back("ParRepair=no"); Options options(&cmdOpts, NULL); ParCheckerMock parChecker; parChecker.Execute(); REQUIRE(parChecker.GetStatus() == ParChecker::psRepairNotNeeded); REQUIRE(parChecker.GetParFull() == true); } TEST_CASE("Par-checker: repair possible", "[Par][ParChecker][Slow][TestData]") { Options::CmdOptList cmdOpts; cmdOpts.push_back("ParRepair=no"); cmdOpts.push_back("BrokenLog=no"); Options options(&cmdOpts, NULL); ParCheckerMock parChecker; parChecker.CorruptFile("testfile.dat", 20000); parChecker.Execute(); REQUIRE(parChecker.GetStatus() == ParChecker::psRepairPossible); REQUIRE(parChecker.GetParFull() == true); } TEST_CASE("Par-checker: repair successful", "[Par][ParChecker][Slow][TestData]") { Options::CmdOptList cmdOpts; cmdOpts.push_back("ParRepair=yes"); cmdOpts.push_back("BrokenLog=no"); Options options(&cmdOpts, NULL); ParCheckerMock parChecker; parChecker.CorruptFile("testfile.dat", 20000); parChecker.Execute(); REQUIRE(parChecker.GetStatus() == ParChecker::psRepaired); REQUIRE(parChecker.GetParFull() == true); } TEST_CASE("Par-checker: repair failed", "[Par][ParChecker][Slow][TestData]") { Options::CmdOptList cmdOpts; cmdOpts.push_back("ParRepair=no"); cmdOpts.push_back("BrokenLog=no"); Options options(&cmdOpts, NULL); ParCheckerMock parChecker; parChecker.CorruptFile("testfile.dat", 20000); parChecker.CorruptFile("testfile.dat", 30000); parChecker.CorruptFile("testfile.dat", 40000); parChecker.CorruptFile("testfile.dat", 50000); parChecker.CorruptFile("testfile.dat", 60000); parChecker.CorruptFile("testfile.dat", 70000); parChecker.CorruptFile("testfile.dat", 80000); parChecker.Execute(); REQUIRE(parChecker.GetStatus() == ParChecker::psFailed); REQUIRE(parChecker.GetParFull() == true); } TEST_CASE("Par-checker: quick verification repair not needed", "[Par][ParChecker][Slow][TestData]") { Options::CmdOptList cmdOpts; cmdOpts.push_back("ParRepair=no"); Options options(&cmdOpts, NULL); ParCheckerMock parChecker; parChecker.SetParQuick(true); parChecker.Execute(); REQUIRE(parChecker.GetStatus() == ParChecker::psRepairNotNeeded); REQUIRE(parChecker.GetParFull() == false); } TEST_CASE("Par-checker: quick verification repair successful", "[Par][ParChecker][Slow][TestData]") { Options::CmdOptList cmdOpts; cmdOpts.push_back("ParRepair=yes"); cmdOpts.push_back("BrokenLog=no"); Options options(&cmdOpts, NULL); ParCheckerMock parChecker; parChecker.SetParQuick(true); parChecker.CorruptFile("testfile.dat", 20000); parChecker.Execute(); REQUIRE(parChecker.GetStatus() == ParChecker::psRepaired); REQUIRE(parChecker.GetParFull() == false); } TEST_CASE("Par-checker: quick full verification repair successful", "[Par][ParChecker][Slow][TestData]") { Options::CmdOptList cmdOpts; cmdOpts.push_back("ParRepair=yes"); cmdOpts.push_back("BrokenLog=no"); Options options(&cmdOpts, NULL); ParCheckerMock parChecker; parChecker.SetParQuick(true); parChecker.CorruptFile("testfile.dat", 20000); parChecker.CorruptFile("testfile.nfo", 100); parChecker.Execute(); // All files were damaged, the full verification was performed REQUIRE(parChecker.GetStatus() == ParChecker::psRepaired); REQUIRE(parChecker.GetParFull() == true); } TEST_CASE("Par-checker: ignoring extensions", "[Par][ParChecker][Slow][TestData]") { Options::CmdOptList cmdOpts; cmdOpts.push_back("ParRepair=yes"); cmdOpts.push_back("BrokenLog=no"); SECTION("ParIgnoreExt") { cmdOpts.push_back("ParIgnoreExt=.dat"); } SECTION("ExtCleanupDisk") { cmdOpts.push_back("ExtCleanupDisk=.dat"); } Options options(&cmdOpts, NULL); ParCheckerMock parChecker; parChecker.CorruptFile("testfile.dat", 20000); parChecker.CorruptFile("testfile.dat", 30000); parChecker.CorruptFile("testfile.dat", 40000); parChecker.CorruptFile("testfile.dat", 50000); parChecker.CorruptFile("testfile.dat", 60000); parChecker.CorruptFile("testfile.dat", 70000); parChecker.CorruptFile("testfile.dat", 80000); parChecker.Execute(); REQUIRE(parChecker.GetStatus() == ParChecker::psRepairNotNeeded); }
ta264/nzbget_svn
tests/postprocess/ParCheckerTest.cpp
C++
gpl-2.0
7,543
/* * drivers/char/Tcc83xx_scaler.c * * Copyright (C) 2004 Texas Instruments, Inc. * * Video-for-Linux (Version 2) graphic capture driver for * the OMAP H2 and H3 camera controller. * * Adapted from omap24xx driver written by Andy Lowe (source@mvista.com) * Copyright (C) 2003-2004 MontaVista Software, Inc. * * This package 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 PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * History: * 27/03/05 Vladimir Barinov - Added support for power management */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/dma-mapping.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/wait.h> #include <linux/sched.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <asm/io.h> #include <asm/uaccess.h> #include <asm/div64.h> #include <asm/mach/map.h> #include <mach/bsp.h> #include <mach/irqs.h> #include <mach/vioc_ireq.h> #include <mach/vioc_rdma.h> #include <mach/vioc_wdma.h> #include <mach/vioc_wmix.h> #include <mach/vioc_config.h> #include <mach/vioc_plugin_tcc892x.h> #include <mach/vioc_scaler.h> #include <mach/vioc_api.h> #include <linux/poll.h> #include "tcc_scaler.h" #include <mach/tcc_scaler_ctrl.h> #include <mach/tccfb_address.h> #if 0 static int debug = 1; #else static int debug = 0; #endif volatile PVIOC_SC pM2MSCALER0; volatile PVIOC_RDMA SC2_pRDMABase; volatile PVIOC_WMIX SC2_pWIXBase; volatile PVIOC_WDMA SC2_pWDMABase; #define dprintk(msg...) if(debug) { printk("tcc_scaler2: " msg); } typedef struct _intr_data_t { //wait for Poll!! wait_queue_head_t poll_wq; spinlock_t poll_lock; unsigned int poll_count; //wait for Ioctl command!! wait_queue_head_t cmd_wq; spinlock_t cmd_lock; unsigned int cmd_count; struct mutex io_mutex; unsigned char block_operating; unsigned char block_waiting; unsigned char irq_reged; unsigned int dev_opened; } intr_data_t; static intr_data_t SC2_data; #define DEVICE_NAME "scaler2" #define MAJOR_ID 202 #define MINOR_ID 1 static struct clk *scaler2_clk; extern unsigned int scaler_ended; extern void tccxxx_GetAddress(unsigned char format, unsigned int base_Yaddr, unsigned int src_imgx, unsigned int src_imgy, unsigned int start_x, unsigned int start_y, unsigned int* Y, unsigned int* U,unsigned int* V); char M2M_Scaler2_Ctrl_Detail(SCALER_TYPE *scale_img) { int ret = 0; unsigned int pSrcBase0 = 0, pSrcBase1 = 0, pSrcBase2 = 0; unsigned int pDstBase0 = 0, pDstBase1 = 0, pDstBase2 = 0; unsigned int crop_width; VIOC_SCALER_INFO_Type pScalerInfo; pSrcBase0 = (unsigned int)scale_img->src_Yaddr; pSrcBase1 = (unsigned int)scale_img->src_Uaddr; pSrcBase2 = (unsigned int)scale_img->src_Vaddr; // address limitation!! crop_width = scale_img->src_winRight - scale_img->src_winLeft; scale_img->src_winLeft = (scale_img->src_winLeft>>3)<<3; scale_img->src_winRight = scale_img->src_winLeft + crop_width; tccxxx_GetAddress(scale_img->src_fmt, (unsigned int)scale_img->src_Yaddr, scale_img->src_ImgWidth, scale_img->src_ImgHeight, scale_img->src_winLeft, scale_img->src_winTop, &pSrcBase0, &pSrcBase1, &pSrcBase2); pDstBase0 = (unsigned int)scale_img->dest_Yaddr; pDstBase1 = (unsigned int)scale_img->dest_Uaddr; pDstBase2 = (unsigned int)scale_img->dest_Vaddr; // address limitation!! crop_width = scale_img->dest_winRight - scale_img->dest_winLeft; scale_img->dest_winLeft = (scale_img->dest_winLeft>>3)<<3; scale_img->dest_winRight = scale_img->dest_winLeft + crop_width; tccxxx_GetAddress(scale_img->dest_fmt, (unsigned int)scale_img->dest_Yaddr, scale_img->dest_ImgWidth, scale_img->dest_ImgHeight, scale_img->dest_winLeft, scale_img->dest_winTop, &pDstBase0, &pDstBase1, &pDstBase2); spin_lock_irq(&(SC2_data.cmd_lock)); // set to VRDMA if((scale_img->src_fmt == SC_IMG_FMT_ARGB6666) || (scale_img->src_fmt == SC_IMG_FMT_ARGB8888)) { VIOC_RDMA_SetImageAlphaSelect(SC2_pRDMABase, 1); VIOC_RDMA_SetImageAlphaEnable(SC2_pRDMABase, 1); } else { VIOC_RDMA_SetImageAlphaSelect(SC2_pRDMABase, 0); VIOC_RDMA_SetImageAlphaEnable(SC2_pRDMABase, 0); } VIOC_RDMA_SetImageFormat(SC2_pRDMABase, scale_img->src_fmt); VIOC_RDMA_SetImageSize(SC2_pRDMABase,scale_img->src_winRight- scale_img->src_winLeft, scale_img->src_winBottom - scale_img->src_winTop); VIOC_RDMA_SetImageOffset(SC2_pRDMABase, scale_img->src_fmt, scale_img->src_ImgWidth); VIOC_RDMA_SetImageBase(SC2_pRDMABase, pSrcBase0, pSrcBase1, pSrcBase2); //VIOC_RDMA_SetImageEnable(SC2_pRDMABase); // set to VIOC Scaler2 pScalerInfo.BYPASS = FALSE /* 0 */; pScalerInfo.DST_WIDTH = (scale_img->dest_winRight - scale_img->dest_winLeft); pScalerInfo.DST_HEIGHT = (scale_img->dest_winBottom - scale_img->dest_winTop); pScalerInfo.OUTPUT_POS_X = 0; pScalerInfo.OUTPUT_POS_Y = 0; pScalerInfo.OUTPUT_WIDTH = pScalerInfo.DST_WIDTH; pScalerInfo.OUTPUT_HEIGHT = pScalerInfo.DST_HEIGHT; VIOC_API_SCALER_SetConfig(VIOC_SC0, &pScalerInfo); VIOC_API_SCALER_SetPlugIn(VIOC_SC0, VIOC_SC_RDMA_17); VIOC_API_SCALER_SetUpdate(VIOC_SC0); VIOC_RDMA_SetImageEnable(SC2_pRDMABase); // SoC guide info. // set to WMIX30 VIOC_CONFIG_WMIXPath(WMIX60, 1 /* mixer */); VIOC_WMIX_SetSize(SC2_pWIXBase, pScalerInfo.DST_WIDTH, pScalerInfo.DST_HEIGHT); VIOC_WMIX_SetUpdate(SC2_pWIXBase); // set to VWRMA VIOC_WDMA_SetImageFormat(SC2_pWDMABase, scale_img->dest_fmt); VIOC_WDMA_SetImageSize(SC2_pWDMABase, pScalerInfo.DST_WIDTH, pScalerInfo.DST_HEIGHT); VIOC_WDMA_SetImageOffset(SC2_pWDMABase, scale_img->dest_fmt, scale_img->dest_ImgWidth); VIOC_WDMA_SetImageBase(SC2_pWDMABase, pDstBase0, pDstBase1, pDstBase2); VIOC_WDMA_SetImageEnable(SC2_pWDMABase, 0 /* OFF */); SC2_pWDMABase->uIRQSTS.nREG = 0xFFFFFFFF; // wdma status register all clear. spin_unlock_irq(&(SC2_data.cmd_lock)); if(scale_img->responsetype == SCALER_POLLING) { ret = wait_event_interruptible_timeout(SC2_data.poll_wq, SC2_data.block_operating == 0, msecs_to_jiffies(500)); if(ret <= 0) { SC2_data.block_operating = 0; printk("Scaler time out :%d Line :%d \n", __LINE__, ret); } } else if(scale_img->responsetype == SCALER_NOWAIT) { if(scale_img->viqe_onthefly & 0x2) SC2_data.block_operating = 0; } return ret; } char M2M_Scaler2_Ctrl_Divide(SCALER_TYPE *scale_img) { int ret = 0; unsigned int pSrcBaseY = 0, pSrcBaseU = 0, pSrcBaseV = 0; unsigned int pDstBase0 = 0, pDstBase1 = 0, pDstBaseU = 0, pDstBaseV = 0; unsigned int img_wd, img_ht; VIOC_SCALER_INFO_Type pScalerInfo; PVIOC_WDMA pWDMABase1 = (PVIOC_WDMA)tcc_p2v(HwVIOC_WDMA08); PVIOC_WDMA pWDMABase0 = (PVIOC_WDMA)SC2_pWDMABase; pSrcBaseY = (unsigned int)scale_img->src_Yaddr; pSrcBaseU = (unsigned int)scale_img->src_Uaddr; pSrcBaseV = (unsigned int)scale_img->src_Vaddr; pDstBase0 = (unsigned int)scale_img->dest_Yaddr; pDstBase1 = (unsigned int)scale_img->dest_Yaddr; pDstBaseU = (unsigned int)scale_img->dest_Uaddr; pDstBaseV = (unsigned int)scale_img->dest_Vaddr; spin_lock_irq(&(SC2_data.cmd_lock)); // set to VRDMA switch path //VIOC_CONFIG_RDMA12PathCtrl(0 /* RDMA12 */); // set to VRDMA VIOC_RDMA_SetImageAlphaSelect(SC2_pRDMABase, 1); VIOC_RDMA_SetImageAlphaEnable(SC2_pRDMABase, 1); VIOC_RDMA_SetImageFormat(SC2_pRDMABase, scale_img->src_fmt); VIOC_RDMA_SetImageSize(SC2_pRDMABase, scale_img->src_ImgWidth, scale_img->src_ImgHeight); VIOC_RDMA_SetImageOffset(SC2_pRDMABase, scale_img->src_fmt, scale_img->src_ImgWidth); VIOC_RDMA_SetImageBase(SC2_pRDMABase, pSrcBaseY, pSrcBaseU, pSrcBaseV); //VIOC_RDMA_SetImageEnable(SC2_pRDMABase); img_wd = (scale_img->dest_winRight - scale_img->dest_winLeft); img_ht = (scale_img->dest_winBottom - scale_img->dest_winTop); // set to VIOC Scaler2 pScalerInfo.BYPASS = FALSE /* 0 */; pScalerInfo.SRC_WIDTH = scale_img->src_ImgWidth; pScalerInfo.SRC_HEIGHT = scale_img->src_ImgHeight; pScalerInfo.DST_WIDTH = img_wd; pScalerInfo.DST_HEIGHT = img_ht; pScalerInfo.OUTPUT_POS_X = 0; pScalerInfo.OUTPUT_POS_Y = 0; pScalerInfo.OUTPUT_WIDTH = img_wd; pScalerInfo.OUTPUT_HEIGHT = img_ht; VIOC_API_SCALER_SetConfig(VIOC_SC0, &pScalerInfo); VIOC_API_SCALER_SetPlugIn(VIOC_SC0, VIOC_SC_RDMA_17); VIOC_API_SCALER_SetUpdate(VIOC_SC0); VIOC_RDMA_SetImageEnable(SC2_pRDMABase); // SoC guide info. /* Side-By-Side */ if(scale_img->divide_path == 0x01) { img_wd = scale_img->dest_ImgWidth/2; img_ht = scale_img->dest_ImgHeight; pDstBase0 = scale_img->dest_Yaddr; pDstBase1 = pDstBase0 + img_wd*4; } /* Top-N-Bottom */ else if(scale_img->divide_path == 0x02) { img_wd = scale_img->dest_ImgWidth; img_ht = scale_img->dest_ImgHeight/2; pDstBase0 = scale_img->dest_Yaddr; pDstBase1 = pDstBase0 + img_wd*img_ht*4; } VIOC_CONFIG_WMIXPath(WMIX60, 1 /* mixing */); VIOC_WMIX_SetSize(SC2_pWIXBase, img_wd, img_ht); VIOC_WMIX_SetPosition(SC2_pWIXBase, 0, scale_img->dest_winLeft, scale_img->dest_winTop); VIOC_WMIX_SetPosition(SC2_pWIXBase, 1, scale_img->dest_winLeft, scale_img->dest_winTop); VIOC_WMIX_SetUpdate(SC2_pWIXBase); // set to VWRMA VIOC_WDMA_SetImageFormat(pWDMABase0, scale_img->dest_fmt); VIOC_WDMA_SetImageSize(pWDMABase0, img_wd, img_ht); VIOC_WDMA_SetImageOffset(pWDMABase0, scale_img->dest_fmt, scale_img->dest_ImgWidth); VIOC_WDMA_SetImageBase(pWDMABase0, pDstBase0, pDstBaseU, pDstBaseV); VIOC_WDMA_SetImageEnable(pWDMABase0, 0 /* OFF */); pWDMABase0->uIRQSTS.nREG = 0xFFFFFFFF; // wdma status register all clear. VIOC_WDMA_SetImageFormat(pWDMABase1, scale_img->dest_fmt); VIOC_WDMA_SetImageSize(pWDMABase1, img_wd, img_ht); VIOC_WDMA_SetImageOffset(pWDMABase1, scale_img->dest_fmt, scale_img->dest_ImgWidth); VIOC_WDMA_SetImageBase(pWDMABase1, pDstBase1, pDstBaseU, pDstBaseV); VIOC_WDMA_SetImageEnable(pWDMABase1, 0 /* OFF */); pWDMABase1->uIRQSTS.nREG = 0xFFFFFFFF; // wdma status register all clear. spin_unlock_irq(&(SC2_data.cmd_lock)); if(scale_img->responsetype == SCALER_POLLING) { ret = wait_event_interruptible_timeout(SC2_data.poll_wq, SC2_data.block_operating == 0, msecs_to_jiffies(500)); if(ret <= 0) { SC2_data.block_operating = 0; printk("Scaler time out :%d Line :%d \n", __LINE__, ret); } } else if(scale_img->responsetype == SCALER_NOWAIT) { if(scale_img->viqe_onthefly & 0x2) SC2_data.block_operating = 0; } return ret; } static unsigned int tccxxx_scaler2_poll(struct file *filp, poll_table *wait) { int ret = 0; intr_data_t *msc_data = (intr_data_t *)filp->private_data; if (msc_data == NULL) return -EFAULT; poll_wait(filp, &(msc_data->poll_wq), wait); spin_lock_irq(&(msc_data->poll_lock)); if (msc_data->block_operating == 0) { ret = (POLLIN | POLLRDNORM); } spin_unlock_irq(&(msc_data->poll_lock)); return ret; } // interrupt handler static irqreturn_t tccxxx_scaler2_handler(int irq, void *client_data/*, struct pt_regs *reg*/) { unsigned long IFlag; intr_data_t *msc_data = (intr_data_t *)client_data; if(SC2_pWDMABase->uIRQSTS.nREG & VIOC_WDMA_IREQ_EOFR_MASK) { dprintk("WDMA Interrupt is VIOC_WDMA_IREQ_EOFR_MASK. \n"); SC2_pWDMABase->uIRQSTS.nREG = 0xFFFFFFFF; // wdma status register all clear. } if(msc_data->block_operating >= 1) { msc_data->block_operating = 0; } wake_up_interruptible(&(msc_data->poll_wq)); if(msc_data->block_waiting) wake_up_interruptible(&msc_data->cmd_wq); return IRQ_HANDLED; } extern void tccxxx_convert_image_format(SCALER_TYPE *pScalerInfo); long tccxxx_scaler2_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret = 0; SCALER_TYPE scaler_v; intr_data_t *msc_data = (intr_data_t *)file->private_data; dprintk("scaler2 ::cmd:0x%x block_operating(%d) - block_waiting(%d) - cmd_count(%d) - poll_count(%d)!!!\n", \ cmd, msc_data->block_operating, msc_data->block_waiting, msc_data->cmd_count, msc_data->poll_count); switch(cmd) { case TCC_SCALER_IOCTRL: case TCC_SCALER_IOCTRL_KERENL: mutex_lock(&msc_data->io_mutex); if(msc_data->block_operating) { msc_data->block_waiting = 1; ret = wait_event_interruptible_timeout(msc_data->cmd_wq, msc_data->block_operating == 0, msecs_to_jiffies(200)); if(ret <= 0) { msc_data->block_operating = 0; printk("[%d]: scaler 2 timed_out block_operation:%d!! cmd_count:%d \n", ret, msc_data->block_waiting, msc_data->cmd_count); } ret = 0; } if(cmd == TCC_SCALER_IOCTRL_KERENL) { memcpy(&scaler_v, (SCALER_TYPE *)arg, sizeof(scaler_v)); } else { if(copy_from_user(&scaler_v, (SCALER_TYPE *)arg, sizeof(scaler_v))) { printk(KERN_ALERT "Not Supported copy_from_user(%d). \n", cmd); ret = -EFAULT; } } if(ret >= 0) { if(msc_data->block_operating >= 1) { printk("scaler + :: block_operating(%d) - block_waiting(%d) - cmd_count(%d) - poll_count(%d)!!!\n", \ msc_data->block_operating, msc_data->block_waiting, msc_data->cmd_count, msc_data->poll_count); } tccxxx_convert_image_format(&scaler_v); msc_data->block_waiting = 0; msc_data->block_operating = 1; if(scaler_v.divide_path) ret = M2M_Scaler2_Ctrl_Divide(&scaler_v); else ret = M2M_Scaler2_Ctrl_Detail(&scaler_v); if(ret < 0) msc_data->block_operating = 0; } mutex_unlock(&msc_data->io_mutex); return ret; default: printk(KERN_ALERT "Not Supported SCALER_IOCTL(%d)\n", cmd); break; } return 0; } EXPORT_SYMBOL(tccxxx_scaler2_ioctl); int tccxxx_scaler2_release(struct inode *inode, struct file *filp) { int ret = 0; dprintk("scaler2_release In!! %d'th, block(%d/%d), cmd(%d), irq(%d) \n", SC2_data.dev_opened, SC2_data.block_operating, \ SC2_data.block_waiting, SC2_data.cmd_count, SC2_data.irq_reged); if(SC2_data.dev_opened > 0) SC2_data.dev_opened--; if(SC2_data.dev_opened == 0) { if(SC2_data.block_operating) { ret = wait_event_interruptible_timeout(SC2_data.cmd_wq, SC2_data.block_operating == 0, msecs_to_jiffies(200)); if(ret <= 0) { printk("[%d]: scaler2 timed_out block_operation:%d!! cmd_count:%d \n", ret, SC2_data.block_waiting, SC2_data.cmd_count); } } if(SC2_data.irq_reged) { free_irq(INT_VIOC_WD7, &SC2_data); SC2_data.irq_reged = 0; } VIOC_CONFIG_PlugOut(VIOC_SC0); VIOC_SC_SetSWReset(VIOC_SC0, 17/*VIOC_SC_RDMA_17*/, 7/*VIOC_SC_WDMA_07*/); SC2_data.block_operating = SC2_data.block_waiting = 0; SC2_data.poll_count = SC2_data.cmd_count = 0; } clk_disable(scaler2_clk); dprintk("scaler2_release Out!! %d'th \n", SC2_data.dev_opened); return 0; } EXPORT_SYMBOL(tccxxx_scaler2_release); int tccxxx_scaler2_open(struct inode *inode, struct file *filp) { int ret = 0; dprintk("scaler2_open In!! %d'th, block(%d/%d), cmd(%d), irq(%d) \n", SC2_data.dev_opened, SC2_data.block_operating, \ SC2_data.block_waiting, SC2_data.cmd_count, SC2_data.irq_reged); clk_enable(scaler2_clk); if(!SC2_data.irq_reged) { // set to VRDMA 17 SC2_pRDMABase = (volatile PVIOC_RDMA)tcc_p2v((unsigned int)HwVIOC_RDMA17); // set to WMIX6 SC2_pWIXBase = (volatile PVIOC_WMIX)tcc_p2v((unsigned int)HwVIOC_WMIX6); // set to VWDMA SC2_pWDMABase = (volatile PVIOC_WDMA)tcc_p2v((unsigned int)HwVIOC_WDMA07); VIOC_SC_SetSWReset(VIOC_SC0, 17/*VIOC_SC_RDMA_17*/, 7/*VIOC_SC_WDMA_07*/); VIOC_WDMA_SetIreqMask(SC2_pWDMABase, VIOC_WDMA_IREQ_EOFR_MASK, 0x0); ret = request_irq(INT_VIOC_WD7, tccxxx_scaler2_handler, IRQF_SHARED, "scaler2", &SC2_data); if(ret) { clk_disable(scaler2_clk); printk("FAILED to aquire scaler2-irq. \n"); return -EFAULT; } SC2_data.irq_reged = 1; } SC2_data.dev_opened++; filp->private_data = &SC2_data; dprintk("scaler2_open Out!! %d'th \n", SC2_data.dev_opened); return ret; } EXPORT_SYMBOL(tccxxx_scaler2_open); static struct file_operations tcc_scaler2_fops = { .owner = THIS_MODULE, .unlocked_ioctl = tccxxx_scaler2_ioctl, .open = tccxxx_scaler2_open, .release = tccxxx_scaler2_release, .poll = tccxxx_scaler2_poll, }; void __exit tccxxx_scaler2_cleanup(void) { unregister_chrdev(MAJOR_ID, DEVICE_NAME); clk_put(scaler2_clk); return; } static char banner[] __initdata = KERN_INFO "TCC Scaler-2 Driver Initializing. \n"; static struct class *scaler2_class; int __init tccxxx_scaler2_init(void) { printk(banner); register_chrdev(MAJOR_ID, DEVICE_NAME, &tcc_scaler2_fops); scaler2_class = class_create(THIS_MODULE, DEVICE_NAME); device_create(scaler2_class, NULL, MKDEV(MAJOR_ID, MINOR_ID), NULL, DEVICE_NAME); memset(&SC2_data, 0, sizeof(intr_data_t)); spin_lock_init(&(SC2_data.poll_lock)); spin_lock_init(&(SC2_data.cmd_lock)); mutex_init(&(SC2_data.io_mutex)); init_waitqueue_head(&(SC2_data.poll_wq)); init_waitqueue_head(&(SC2_data.cmd_wq)); scaler2_clk = clk_get(NULL, "ddi"); BUG_ON(scaler2_clk == NULL); pM2MSCALER0 = (volatile PVIOC_SC)tcc_p2v((unsigned int)HwVIOC_SC0); return 0; } MODULE_AUTHOR("Telechips."); MODULE_DESCRIPTION("TCC Scaler-2 Driver"); MODULE_LICENSE("GPL"); arch_initcall(tccxxx_scaler2_init); module_exit(tccxxx_scaler2_cleanup);
UpgradeAndroid/telechips
drivers/char/tcc_scaler2.c
C
gpl-2.0
17,562
/* * GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net * See file COPYING. */ package de.ueller.gps; import java.util.Date; /** Container for the data of a GPS satellite. */ public class Satellite { private static final int STATUS_ACQUISITION_SUCCESSFUL = 0x1; private static final int STATUS_CARRIER_PHASE_VALID = 0x2; private static final int STATUS_BIT_SYNC = 0x4; private static final int STATUS_SUBFRAME_SYNC = 0x8; private static final int STATUS_CARRIER_PULL_IN = 0x10; private static final int STATUS_CODE_LOCKED = 0x20; private static final int STATUS_ACQUISITION_FAILED = 0x40; private static final int STATUS_EPHEMERIS = 0x80; public int id; public float azimut; public float elev; /** State of this satellite, see the STATUS_* constants for possible values */ public int state; /** Signal to noise ratio in arbitrary units */ public int snr; public Date lastUpdate; public Satellite() { } private boolean isState(int mask) { return ((state & mask) > 0); } public boolean isAcquisitionSuccessful() { return isState(STATUS_ACQUISITION_SUCCESSFUL); } public boolean isCharrierPhaseValid() { return isState(STATUS_CARRIER_PHASE_VALID); } public boolean isBitSync() { return isState(STATUS_BIT_SYNC); } public boolean isSubframeSync() { return isState(STATUS_SUBFRAME_SYNC); } public boolean isCarrierPullIn() { return isState(STATUS_CARRIER_PULL_IN); } public boolean isLocked() { return isState(STATUS_CODE_LOCKED); } public void isLocked(boolean locked) { if (locked == true) { state |= STATUS_CODE_LOCKED; } else { state &= ~STATUS_CODE_LOCKED; } } public boolean isAcquisitionFailed() { return isState(STATUS_ACQUISITION_FAILED); } public boolean isEphemeris() { return isState(STATUS_EPHEMERIS); } public Date getLastUpdate() { return lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } }
martints/gpsmid
src/de/ueller/gps/Satellite.java
Java
gpl-2.0
1,979
/* mpz_xor -- Logical xor. Copyright 1991, 1993, 1994, 1996, 1997, 2000, 2001, 2005, 2012 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * 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. or both in parallel, as here. The GNU MP 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 copies of the GNU General Public License and the GNU Lesser General Public License along with the GNU MP Library. If not, see https://www.gnu.org/licenses/. */ #include "gmp.h" #include "gmp-impl.h" void mpz_xor (mpz_ptr res, mpz_srcptr op1, mpz_srcptr op2) { mp_srcptr op1_ptr, op2_ptr; mp_size_t op1_size, op2_size; mp_ptr res_ptr; mp_size_t res_size, res_alloc; TMP_DECL; TMP_MARK; op1_size = SIZ(op1); op2_size = SIZ(op2); op1_ptr = PTR(op1); op2_ptr = PTR(op2); res_ptr = PTR(res); if (op1_size >= 0) { if (op2_size >= 0) { if (op1_size >= op2_size) { if (ALLOC(res) < op1_size) { _mpz_realloc (res, op1_size); /* No overlapping possible: op1_ptr = PTR(op1); */ op2_ptr = PTR(op2); res_ptr = PTR(res); } if (res_ptr != op1_ptr) MPN_COPY (res_ptr + op2_size, op1_ptr + op2_size, op1_size - op2_size); if (LIKELY (op2_size != 0)) mpn_xor_n (res_ptr, op1_ptr, op2_ptr, op2_size); res_size = op1_size; } else { if (ALLOC(res) < op2_size) { _mpz_realloc (res, op2_size); op1_ptr = PTR(op1); /* No overlapping possible: op2_ptr = PTR(op2); */ res_ptr = PTR(res); } if (res_ptr != op2_ptr) MPN_COPY (res_ptr + op1_size, op2_ptr + op1_size, op2_size - op1_size); if (LIKELY (op1_size != 0)) mpn_xor_n (res_ptr, op1_ptr, op2_ptr, op1_size); res_size = op2_size; } MPN_NORMALIZE (res_ptr, res_size); SIZ(res) = (int) res_size; // (int) added by PM return; } else /* op2_size < 0 */ { /* Fall through to the code at the end of the function. */ } } else { if (op2_size < 0) { mp_ptr opx, opy; /* Both operands are negative, the result will be positive. (-OP1) ^ (-OP2) = = ~(OP1 - 1) ^ ~(OP2 - 1) = = (OP1 - 1) ^ (OP2 - 1) */ op1_size = -op1_size; op2_size = -op2_size; /* Possible optimization: Decrease mpn_sub precision, as we won't use the entire res of both. */ TMP_ALLOC_LIMBS_2 (opx, op1_size, opy, op2_size); mpn_sub_1 (opx, op1_ptr, op1_size, (mp_limb_t) 1); op1_ptr = opx; mpn_sub_1 (opy, op2_ptr, op2_size, (mp_limb_t) 1); op2_ptr = opy; if (op1_size > op2_size) MPN_SRCPTR_SWAP (op1_ptr,op1_size, op2_ptr,op2_size); res_alloc = op2_size; res_ptr = MPZ_REALLOC (res, res_alloc); MPN_COPY (res_ptr + op1_size, op2_ptr + op1_size, op2_size - op1_size); mpn_xor_n (res_ptr, op1_ptr, op2_ptr, op1_size); res_size = op2_size; MPN_NORMALIZE (res_ptr, res_size); SIZ(res) = (int) res_size; // (int) added by PM TMP_FREE; return; } else { /* We should compute -OP1 ^ OP2. Swap OP1 and OP2 and fall through to the code that handles OP1 ^ -OP2. */ MPZ_SRCPTR_SWAP (op1, op2); MPN_SRCPTR_SWAP (op1_ptr,op1_size, op2_ptr,op2_size); } } { mp_ptr opx; mp_limb_t cy; /* Operand 2 negative, so will be the result. -(OP1 ^ (-OP2)) = -(OP1 ^ ~(OP2 - 1)) = = ~(OP1 ^ ~(OP2 - 1)) + 1 = = (OP1 ^ (OP2 - 1)) + 1 */ op2_size = -op2_size; opx = TMP_ALLOC_LIMBS (op2_size); mpn_sub_1 (opx, op2_ptr, op2_size, (mp_limb_t) 1); op2_ptr = opx; res_alloc = MAX (op1_size, op2_size) + 1; if (ALLOC(res) < res_alloc) { _mpz_realloc (res, res_alloc); op1_ptr = PTR(op1); /* op2_ptr points to temporary space. */ res_ptr = PTR(res); } if (op1_size > op2_size) { MPN_COPY (res_ptr + op2_size, op1_ptr + op2_size, op1_size - op2_size); mpn_xor_n (res_ptr, op1_ptr, op2_ptr, op2_size); res_size = op1_size; } else { MPN_COPY (res_ptr + op1_size, op2_ptr + op1_size, op2_size - op1_size); if (LIKELY (op1_size != 0)) mpn_xor_n (res_ptr, op1_ptr, op2_ptr, op1_size); res_size = op2_size; } cy = mpn_add_1 (res_ptr, res_ptr, res_size, (mp_limb_t) 1); res_ptr[res_size] = cy; res_size += (cy != 0); MPN_NORMALIZE (res_ptr, res_size); SIZ(res) = (int) -res_size; // (int) added by PM TMP_FREE; } }
TrampolineRTOS/GTL
build/libpm/gmp/mpz-xor.c
C
gpl-2.0
4,979
/** @file pa_test_mono_asio_channel_select.c @ingroup test_src @brief Play a monophonic sine wave on a specific ASIO channel. @author Ross Bencina <rossb@audiomulch.com> @author Phil Burk <philburk@softsynth.com> */ /* * $Id: patest_mono_asio_channel_select.c,v 1.8 2008-12-31 15:38:36 richardash1981 Exp $ * * Authors: * Ross Bencina <rossb@audiomulch.com> * Phil Burk <philburk@softsynth.com> * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com * Copyright (c) 1999-2000 Ross Bencina and Phil Burk * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * The text above constitutes the entire PortAudio license; however, * the PortAudio community also makes the following non-binding requests: * * Any person wishing to distribute modifications to the Software is * requested to send the modifications to the original developer so that * they can be incorporated into the canonical version. It is also * requested that these non-binding requests be included along with the * license above. */ #include <stdio.h> #include <math.h> #include "portaudio.h" #include "pa_asio.h" #define NUM_SECONDS (10) #define SAMPLE_RATE (44100) #define AMPLITUDE (0.8) #define FRAMES_PER_BUFFER (64) #define OUTPUT_DEVICE Pa_GetDefaultOutputDevice() #ifndef M_PI #define M_PI (3.14159265) #endif #define TABLE_SIZE (200) typedef struct { float sine[TABLE_SIZE]; int phase; } paTestData; /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ static int patestCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; unsigned long i; int finished = 0; /* avoid unused variable warnings */ (void) inputBuffer; (void) timeInfo; (void) statusFlags; for( i=0; i<framesPerBuffer; i++ ) { *out++ = data->sine[data->phase]; /* left */ data->phase += 1; if( data->phase >= TABLE_SIZE ) data->phase -= TABLE_SIZE; } return finished; } /*******************************************************************/ int main(void); int main(void) { PaStreamParameters outputParameters; PaAsioStreamInfo asioOutputInfo; PaStream *stream; PaError err; paTestData data; int outputChannelSelectors[1]; int i; printf("PortAudio Test: output MONO sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); /* initialise sinusoidal wavetable */ for( i=0; i<TABLE_SIZE; i++ ) { data.sine[i] = (float) (AMPLITUDE * sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. )); } data.phase = 0; err = Pa_Initialize(); if( err != paNoError ) goto error; outputParameters.device = OUTPUT_DEVICE; outputParameters.channelCount = 1; /* MONO output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; asioOutputInfo.size = sizeof(PaAsioStreamInfo); asioOutputInfo.hostApiType = paASIO; asioOutputInfo.version = 1; asioOutputInfo.flags = paAsioUseChannelSelectors; outputChannelSelectors[0] = 1; /* select the second (right) ASIO device channel */ asioOutputInfo.channelSelectors = outputChannelSelectors; outputParameters.hostApiSpecificStreamInfo = &asioOutputInfo; err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play for %d seconds.\n", NUM_SECONDS ); fflush(stdout); Pa_Sleep( NUM_SECONDS * 1000 ); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
nlphacker/Audacity
lib-src/portaudio-v19/test/patest_mono_asio_channel_select.c
C
gpl-2.0
5,906
<?php #************************************************************************** # openSIS is a free student information system for public and non-public # schools from Open Solutions for Education, Inc. web: www.os4ed.com # # openSIS is web-based, open source, and comes packed with features that # include student demographic info, scheduling, grade book, attendance, # report cards, eligibility, transcripts, parent portal, # student portal and more. # # Visit the openSIS web site at http://www.opensis.com to learn more. # If you have question regarding this system or the license, please send # an email to info@os4ed.com. # # This program is released under the terms of the GNU General Public License as # published by the Free Software Foundation, version 2 of the License. # See license.txt. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # #*************************************************************************************** include('../../RedirectModulesInc.php'); unset($_SESSION['_REQUEST_vars']['subject_id']);unset($_SESSION['_REQUEST_vars']['course_id']);unset($_SESSION['_REQUEST_vars']['course_period_id']); if($_REQUEST['ses']) { DBQuery("DROP TABLE IF EXISTS temp_schedule"); DBQuery("CREATE TABLE temp_schedule AS SELECT * FROM schedule WHERE 0"); unset($_SESSION['course_periods']); } // if only one subject, select it automatically -- works for Course Setup and Choose a Course if($_REQUEST['modfunc']!='delete' && !$_REQUEST['subject_id']) { $subjects_RET = DBGet(DBQuery('SELECT SUBJECT_ID,TITLE FROM course_subjects WHERE SCHOOL_ID=\''.UserSchool().'\' AND SYEAR=\''.UserSyear().'\'')); if(count($subjects_RET)==1) $_REQUEST['subject_id'] = $subjects_RET[1]['SUBJECT_ID']; } if($_REQUEST['course_modfunc']=='search') { PopTable('header','Search'); echo "<FORM name=F1 id=F1 action=ForWindow.php?modname=".strip_tags(trim($_REQUEST[modname]))."&modfunc=".strip_tags(trim($_REQUEST[modfunc]))."&course_modfunc=search method=POST>"; echo '<TABLE><TR><TD><INPUT type=text class=cell_floating name=search_term value="'.strip_tags(trim($_REQUEST['search_term'])).'"></TD><TD><INPUT type=submit class=btn_medium value=Search onclick=\'formload_ajax("F1")\';></TD></TR></TABLE>'; echo '</FORM>'; PopTable('footer'); if($_REQUEST['search_term']) { $subjects_RET = DBGet(DBQuery('SELECT SUBJECT_ID,TITLE FROM course_subjects WHERE (UPPER(TITLE) LIKE \''.'%'.strtoupper($_REQUEST['search_term']).'%' .'\' OR UPPER(SHORT_NAME) = \''.strtoupper($_REQUEST['search_term']).'\') AND SYEAR=\''.UserSyear().'\' AND SCHOOL_ID=\''.UserSchool().'\'')); $courses_RET = DBGet(DBQuery('SELECT SUBJECT_ID,COURSE_ID,TITLE FROM courses WHERE (UPPER(TITLE) LIKE \''.'%'.strtoupper($_REQUEST['search_term']).'%'.'\' OR UPPER(SHORT_NAME) = \''.strtoupper($_REQUEST['search_term']).'\') AND SYEAR=\''.UserSyear().'\' AND SCHOOL_ID=\''.UserSchool().'\'')); $periods_RET = DBGet(DBQuery('SELECT c.SUBJECT_ID,cp.COURSE_ID,cp.COURSE_PERIOD_ID,cp.TITLE FROM course_periods cp,courses c WHERE cp.COURSE_ID=c.COURSE_ID AND (UPPER(cp.TITLE) LIKE \''.'%'.strtoupper($_REQUEST['search_term']).'%'.'\' OR UPPER(cp.SHORT_NAME) = \''.strtoupper($_REQUEST['search_term']).'\') AND cp.SYEAR=\''.UserSyear().'\' AND cp.SCHOOL_ID=\''.UserSchool().'\'')); echo '<TABLE><TR><TD valign=top>'; $link['TITLE']['link'] = "ForWindow.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]"; $link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID'); ListOutput($subjects_RET,array('TITLE'=>'Subject'),'Subject','Subjects',$link,array(),array('search'=>false,'save'=>false)); echo '</TD><TD valign=top>'; $link['TITLE']['link'] = "ForWindow.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]"; $link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID'); ListOutput($courses_RET,array('TITLE'=>'Course'),'Course','Courses',$link,array(),array('search'=>false,'save'=>false)); echo '</TD><TD valign=top>'; $link['TITLE']['link'] = "ForWindow.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]"; $link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID','course_period_id'=>'COURSE_PERIOD_ID'); ListOutput($periods_RET,array('TITLE'=>'Course Period'),'Course Period','Course Periods',$link,array(),array('search'=>false,'save'=>false)); echo '</TD></TR></TABLE>'; } } if((!$_REQUEST['modfunc'] || $_REQUEST['modfunc']=='choose_course') && !$_REQUEST['course_modfunc']) { if($_REQUEST['modfunc']!='choose_course') DrawBC("Scheduling > ".ProgramTitle()); echo '<center><div id="conf_div"></div></center>'; echo '<center><div id="calculating" style=display:none><img src="assets/ajax-loader.gif" width="15px" ><br />Checking schedule Please Wait...</div></center>'; if($clash) echo "<center><b>There is a conflict. You cannot add this course period </b></center>".ErrorMessage($clash,'note').""; echo '<FORM name="courses" method="post">'; echo '<center><div id="resp_div">'; echo '<TABLE id="resp_table">'; foreach($_SESSION['course_periods'] as $cp_id=>$title) { echo '<tr id="selected_course_tr_'.$cp_id.'"><td align=left><INPUT type="checkbox" id="selected_course_'.$cp_id.'" name="selected_course_periods[]" checked="checked" value="'.$cp_id.'"></td><td><b> '.$title.'</b></td></tr>'; } echo '</TABLE>'; echo '</div></center>'; if($_POST['exit']) { DBQuery("DROP TABLE IF EXISTS temp_schedule"); unset($_SESSION['course_periods']); unset($_REQUEST['selected_course_periods']); echo '<script type=text/javascript>window.close();</script>'; } else if($_POST['done']) { $cp_list = '\''.implode('\',\'',$_REQUEST['selected_course_periods']).'\''; DBQuery("INSERT INTO schedule(syear, school_id, student_id, start_date, end_date,modified_by, course_id, course_weight, course_period_id, mp, marking_period_id, scheduler_lock, dropped) SELECT syear, school_id, student_id, start_date, end_date, modified_by, course_id, course_weight, course_period_id, mp, marking_period_id, scheduler_lock, dropped FROM temp_schedule WHERE course_period_id IN ($cp_list)"); DBQuery("DROP TABLE IF EXISTS temp_schedule"); unset($_SESSION['course_periods']); unset($_SESSION['marking_period_id']); unset($_REQUEST['selected_course_periods']); echo '<script type=text/javascript>opener.document.location="Modules.php?modname='.strip_tags(trim($_REQUEST[modname])).'";window.close();</script>'; } $LO_options = array('save'=>false,'search'=>false); if(!$_REQUEST['subject_id'] || $_REQUEST['modfunc']=='choose_course') DrawHeaderHome('Courses',"<A HREF=ForWindow.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]&course_modfunc=search>Search</A>"); echo '<TABLE><TR>'; $sql = "SELECT SUBJECT_ID,TITLE FROM course_subjects WHERE SCHOOL_ID='".UserSchool()."' AND SYEAR='".UserSyear()."' ORDER BY TITLE"; $QI = DBQuery($sql); $subjects_RET = DBGet($QI); if(count($subjects_RET)) { if($_REQUEST['subject_id']) { foreach($subjects_RET as $key=>$value) { if($value['SUBJECT_ID']==$_REQUEST['subject_id']) $subjects_RET[$key]['row_color'] = Preferences('HIGHLIGHT'); } } } echo '<TD valign=top>'; $columns = array('TITLE'=>'Subject'); $link = array(); $link['TITLE']['link'] = "ForWindow.php?modname=$_REQUEST[modname]"; $link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID'); if($_REQUEST['modfunc']!='choose_course') $link['add']['link'] = "ForWindow.php?modname=$_REQUEST[modname]&subject_id=new"; else $link['TITLE']['link'] .= "&modfunc=$_REQUEST[modfunc]"; ListOutput($subjects_RET,$columns,'Subject','Subjects',$link,array(),$LO_options,'ForWindow'); echo '</TD>'; if($_REQUEST['subject_id'] && $_REQUEST['subject_id']!='new') { $sql="SELECT COURSE_ID,c.TITLE, CONCAT_WS(' - ',c.title,sg.title) AS GRADE_COURSE FROM courses c LEFT JOIN school_gradelevels sg ON c.grade_level=sg.id WHERE SUBJECT_ID='$_REQUEST[subject_id]' ORDER BY c.TITLE"; $QI = DBQuery($sql); $courses_RET = DBGet($QI); if(count($courses_RET)) { if($_REQUEST['course_id']) { foreach($courses_RET as $key=>$value) { if($value['COURSE_ID']==$_REQUEST['course_id']) $courses_RET[$key]['row_color'] = Preferences('HIGHLIGHT'); } } } echo '<TD valign=top>'; $columns = array('GRADE_COURSE'=>'Course'); $link = array(); $link['GRADE_COURSE']['link'] = "ForWindow.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]"; $link['GRADE_COURSE']['variables'] = array('course_id'=>'COURSE_ID'); if($_REQUEST['modfunc']!='choose_course') $link['add']['link'] = "ForWindow.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=new"; else $link['GRADE_COURSE']['link'] .= "&modfunc=$_REQUEST[modfunc]"; ListOutput($courses_RET,$columns,'Course','Courses',$link,array(),$LO_options,'ForWindow'); echo '</TD>'; if($_REQUEST['course_id'] && $_REQUEST['course_id']!='new') { $sql = "SELECT COURSE_PERIOD_ID AS CHECKBOX,COURSE_PERIOD_ID,TITLE,COALESCE(TOTAL_SEATS-FILLED_SEATS,0) AS AVAILABLE_SEATS FROM course_periods WHERE COURSE_ID='$_REQUEST[course_id]'AND (marking_period_id IS NOT NULL AND marking_period_id IN(". GetAllMP(GetMPTable(GetMP(UserMP(),'TABLE')), UserMP()).") OR marking_period_id IS NULL AND '".date('Y-m-d')."' <= end_date) ORDER BY TITLE"; $QI = DBQuery($sql); $functions= array('CHECKBOX'=>'_makeChooseCheckbox'); $periods_RET = DBGet($QI,$functions); if(count($periods_RET)) { if($_REQUEST['course_period_id']) { foreach($periods_RET as $key=>$value) { if($value['COURSE_PERIOD_ID']==$_REQUEST['course_period_id']) $periods_RET[$key]['row_color'] = Preferences('HIGHLIGHT'); } } } echo '<TD valign=top>'; $columns = array('CHECKBOX'=>'</A><A>','TITLE'=>'Course Period'); if($_REQUEST['modname']=='scheduling/Schedule.php') $columns += array('AVAILABLE_SEATS'=>'Available Seats'); $link = array(); ListOutput($periods_RET,$columns,'Period','Periods',$link,array(),$LO_options,'ForWindow'); if(count($periods_RET)) { echo '<BR>'.SubmitButton('Done','done','class=btn_medium ').'&nbsp;&nbsp;'.SubmitButton('Clear&Exit','exit','class=btn_medium '); } echo '</TD>'; echo '</FORM>'; } } echo '</TR></TABLE>'; } function _makeChooseCheckbox($value,$title) { return '<INPUT type=checkbox id=course_'.$value.' name=course_periods['.$value.'] value='.$value. (array_key_exists($value,$_SESSION['course_periods'])?' checked':'').' onchange="verify_schedule(this);" >'; } // # ------------------------ functions Start ----------------------------- # // # ------------------------ functions End ----------------------------- # // ?>
jicheng17/fh
modules/scheduling/MultiCoursesforWindow.php
PHP
gpl-2.0
12,145
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2012 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "NoCancelOperationEnvironment.hpp" #include "OS/Sleep.h" bool NoCancelOperationEnvironment::IsCancelled() const { return false; } void NoCancelOperationEnvironment::Sleep(unsigned ms) { /* some OperationEnvironment implementations may ignore Sleep() calls when the operation is cancelled; override that */ ::Sleep(ms); }
damianob/xcsoar
src/Operation/NoCancelOperationEnvironment.cpp
C++
gpl-2.0
1,244
/* Copyright (C) 1994-1995 Apogee Software, Ltd. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //****************************************************************************** // // RT_STR.C // Contains the menu stuff! // //****************************************************************************** #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <string.h> #include <ctype.h> #include "rt_def.h" #include "rt_menu.h" #include "rt_util.h" #include "rt_vid.h" #include "rt_build.h" #include "lumpy.h" #include "rt_str.h" #include "_rt_str.h" #include "isr.h" #include "rt_in.h" #include "rt_menu.h" #include "rt_view.h" #include "w_wad.h" #include "z_zone.h" #include "modexlib.h" #include "rt_main.h" #include "rt_msg.h" #include "rt_playr.h" #include "rt_sound.h" #include "myprint.h" //MED #include "memcheck.h" //****************************************************************************** // // GLOBALS // //****************************************************************************** int fontcolor; //****************************************************************************** // // LOCALS // //****************************************************************************** static int BKw; static int BKh; static char strbuf[MaxString]; //****************************************************************************** // // VW_DrawClippedString () // // Draws a string at x, y to bufferofs // //****************************************************************************** void VW_DrawClippedString (int x, int y, const char *string) { int width,height,ht; byte *source; int ch; int oy; ht = CurrentFont->height; oy=y; while ((ch = (unsigned char)*string++)!=0) { ch -= 31; width = CurrentFont->width[ch]; source = ((byte *)CurrentFont)+CurrentFont->charofs[ch]; while (width--) { if ((x>=0) && (x<iGLOBAL_SCREENWIDTH)) { y=oy; VGAWRITEMAP(x&3); height = ht; while (height--) { if ((y>=0) && (y<iGLOBAL_SCREENHEIGHT)) { if (*source>0) #ifdef DOS *((byte *)(bufferofs+ylookup[y]+(x>>2))) = *source; #else *((byte *)(bufferofs+ylookup[y]+x)) = *source; #endif } source++; y++; } } x++; } } } //****************************************************************************** // // US_ClippedPrint() - Prints a string in bufferofs. Newlines are supported. // //****************************************************************************** void US_ClippedPrint (int x, int y, const char *string) { char c, *se; char *s; int startx; strcpy(strbuf, string); s = strbuf; startx=x; while (*s) { se = s; while ((c = *se) && (c != '\n')) se++; *se = '\0'; VW_DrawClippedString ( x, y, s); s = se; if (c) { *se = c; s++; y += CurrentFont->height; } } } //****************************************************************************** // // VW_DrawPropString () // // Draws a string at px, py to bufferofs // //****************************************************************************** void VW_DrawPropString (const char *string) { #ifdef DOS byte pix; int width,step,height,ht; byte *source, *dest, *origdest; int ch,mask; ht = CurrentFont->height; dest = origdest = (byte *)(bufferofs+ylookup[py]+(px>>2)); mask = 1<<(px&3); while ((ch = *string++)!=0) { ch -= 31; width = step = CurrentFont->width[ch]; source = ((byte *)CurrentFont)+CurrentFont->charofs[ch]; while (width--) { VGAMAPMASK(mask); height = ht; while (height--) { pix = *source; if (pix) *dest = pix; source++; dest += linewidth; } px++; mask <<= 1; if (mask == 16) { mask = 1; origdest++; } dest = origdest; } } bufferheight = ht; bufferwidth = ((dest+1)-origdest)*4; #else byte pix; int width,step,height,ht; byte *source, *dest, *origdest; int ch,mask; ht = CurrentFont->height; dest = origdest = (byte *)(bufferofs+ylookup[py]+px); while ((ch = (unsigned char)*string++)!=0) { ch -= 31; width = step = CurrentFont->width[ch]; source = ((byte *)CurrentFont)+CurrentFont->charofs[ch]; while (width--) { height = ht; while (height--) { pix = *source; if (pix) *dest = pix; source++; dest += linewidth; } px++; origdest++; dest = origdest; } } bufferheight = ht; bufferwidth = ((dest+1)-origdest); #endif } //****************************************************************************** // // VWB_DrawPropString () // // Calls VW_DrawPropString then updates the mark block. // //****************************************************************************** void VWB_DrawPropString (const char *string) { int x; x = px; VW_DrawPropString (string); VW_MarkUpdateBlock (x, py, px-1, py+bufferheight-1); } //****************************************************************************** // // VW_DrawIPropString () // // Draws a string at px, py to bufferofs // //****************************************************************************** void VW_DrawIPropString (const char *string) { byte pix; int width,step,height,ht; byte *source, *dest, *origdest; int ch,mask; ht = CurrentFont->height; #ifdef DOS dest = origdest = (byte *)(bufferofs+ylookup[py]+(px>>2)); #else dest = origdest = (byte *)(bufferofs+ylookup[py]+px); #endif mask = 1<<(px&3); while ((ch = (unsigned char)*string++)!=0) { ch -= 31; width = step = CurrentFont->width[ch]; source = ((byte *)CurrentFont)+CurrentFont->charofs[ch]; while (width--) { VGAMAPMASK(mask); height = ht; while (height--) { pix = *source; if (pix) *dest = pix; source++; dest += linewidth; } px++; #ifdef DOS mask <<= 1; if (mask == 16) { mask = 1; origdest++; } #else origdest++; #endif dest = origdest; } } bufferheight = ht; #ifdef DOS bufferwidth = ((dest+1)-origdest)*4; #else bufferwidth = ((dest+1)-origdest); #endif } //****************************************************************************** // // VWB_DrawIPropString () // // Calls VW_DrawIPropString then updates the mark block. // //****************************************************************************** void VWB_DrawIPropString (const char *string) { int x; x = px; VW_DrawIPropString (string); VW_MarkUpdateBlock (x, py, px-1, py+bufferheight-1); } //****************************************************************************** // // VWL_MeasureString () // //****************************************************************************** void VWL_MeasureString (const char *s, int *width, int *height, const font_t *font) { *height = font->height; for (*width = 0; *s; s++) *width += font->width[(*((byte *)s))-31]; // proportional width } //****************************************************************************** // // VWL_MeasureIntensityString () // //****************************************************************************** void VWL_MeasureIntensityString (const char *s, int *width, int *height, const cfont_t *font) { *height = font->height; for (*width = 0; *s; s++) *width += font->width[(*((byte *)s))-31]; // proportional width } //****************************************************************************** // // VW_MeasureIntensityPropString () // //****************************************************************************** void VW_MeasureIntensityPropString (const char *string, int *width, int *height) { VWL_MeasureIntensityString (string, width, height, IFont); } //****************************************************************************** // // VW_MeasurePropString () // //****************************************************************************** void VW_MeasurePropString (const char *string, int *width, int *height) { VWL_MeasureString (string, width, height, CurrentFont); } //****************************************************************************** // // US_MeasureStr () // //****************************************************************************** void US_MeasureStr (int *width, int *height, const char * s, ...) { char c, *se, *ss; int w,h; va_list strptr; char buf[300]; *width = 0; *height = 0; memset (&buf[0], 0, sizeof (buf)); va_start (strptr, s); vsprintf (&buf[0], s, strptr); va_end (strptr); ss = &buf[0]; while (*ss) { se = ss; while ((c = *se) && (c != '\n')) se++; *se = '\0'; VWL_MeasureString (ss, &w, &h, CurrentFont); *height += h; if (w > *width) *width = w; ss = se; if (c) { *se = c; ss++; } } } //****************************************************************************** // // US_SetPrintRoutines() - Sets the routines used to measure and print // from within the User Mgr. Primarily provided to allow switching // between masked and non-masked fonts // //****************************************************************************** void US_SetPrintRoutines (void (*measure)(const char *, int *, int *, font_t *), void (*print)(const char *)) { USL_MeasureString = measure; USL_DrawString = print; } //****************************************************************************** // // US_Print() - Prints a string in the current window. Newlines are // supported. // //****************************************************************************** void US_Print (const char *string) { char c, *se, *s; int w,h; strcpy(strbuf, string); s = strbuf; while (*s) { se = s; while ((c = *se) && (c != '\n')) se++; *se = '\0'; USL_MeasureString (s, &w, &h, CurrentFont); px = PrintX; py = PrintY; USL_DrawString (s); s = se; if (c) { *se = c; s++; PrintX = WindowX; PrintY += h; } else PrintX += w; } } //****************************************************************************** // // US_BufPrint() - Prints a string in bufferofs. Newlines are supported. // //****************************************************************************** void US_BufPrint (const char *string) { char c, *se, *s; int startx; strcpy(strbuf, string); s = strbuf; startx=PrintX; while (*s) { se = s; while ((c = *se) && (c != '\n')) se++; *se = '\0'; px = PrintX; py = PrintY; USL_DrawString (s); PrintY = py; PrintX = px; s = se; if (c) { *se = c; s++; PrintY += CurrentFont->height; PrintX = startx; } } } //****************************************************************************** // // US_PrintUnsigned () - Prints an unsigned long int // //****************************************************************************** void US_PrintUnsigned (unsigned long int n) { char buffer[32]; US_Print (ultoa (n, buffer, 10)); } //****************************************************************************** // // US_PrintSigned() - Prints a signed long // //****************************************************************************** void US_PrintSigned (long int n) { char buffer[32]; US_Print (ltoa (n, buffer, 10)); } //****************************************************************************** // // USL_PrintInCenter() - Prints a string in the center of the given rect // //****************************************************************************** void USL_PrintInCenter (const char *s, Rect r) { int w,h, rw,rh; USL_MeasureString (s,&w,&h, CurrentFont); rw = r.lr.x - r.ul.x; rh = r.lr.y - r.ul.y; px = r.ul.x + ((rw - w) / 2); py = r.ul.y + ((rh - h) / 2); USL_DrawString (s); } //****************************************************************************** // // US_PrintCentered() - Prints a string centered in the current window. // //****************************************************************************** void US_PrintCentered (const char *s) { Rect r; r.ul.x = WindowX; r.ul.y = WindowY; r.lr.x = r.ul.x + WindowW; r.lr.y = r.ul.y + WindowH; USL_PrintInCenter (s, r); } //****************************************************************************** // // US_CPrintLine() - Prints a string centered on the current line and // advances to the next line. Newlines are not supported. // //****************************************************************************** void US_CPrintLine (const char *s) { int w, h; USL_MeasureString (s, &w, &h, CurrentFont); if (w > WindowW) Error("US_CPrintLine() - String exceeds width"); px = WindowX + ((WindowW - w) / 2); py = PrintY; USL_DrawString (s); PrintY += h; } //****************************************************************************** // // US_CPrint() - Prints a string in the current window. Newlines are // supported. // //****************************************************************************** void US_CPrint (const char *string) { char c, *se, *s; strcpy(strbuf, string); s = strbuf; while (*s) { se = s; while ((c = *se) && (c != '\n')) se++; *se = '\0'; US_CPrintLine (s); s = se; if (c) { *se = c; s++; } } } // // // Text Input routines // // // //****************************************************************************** // // USL_XORICursor() - XORs the I-bar text cursor. Used by US_LineInput() // //****************************************************************************** static void USL_XORICursor (int x, int y, const char *s, int cursor, int color) { static boolean status; // VGA doesn't XOR... char buf[MaxString]; int w,h; int oldx = px; int oldy = py; strcpy (buf,s); buf[cursor] = '\0'; USL_MeasureString (buf, &w, &h, CurrentFont); if (status^=1) { px = x + w; py = y; if (color) USL_DrawString ("\x80"); else DrawMenuBufPropString (px, py, "\x80"); } else { if (color) { VWB_Bar (px, py, BKw, BKh, color); USL_DrawString (s); } else { EraseMenuBufRegion (px, py, BKw, BKh); // EraseMenuBufRegion (px, py+1, BKw, BKh-2); DrawMenuBufPropString (px, py, s); } } px = oldx; py = oldy; } //****************************************************************************** // // US_LineInput() - Gets a line of user input at (x,y), the string defaults // to whatever is pointed at by def. Input is restricted to maxchars // chars or maxwidth pixels wide. If the user hits escape (and escok is // true), nothing is copied into buf, and false is returned. If the // user hits return, the current string is copied into buf, and true is // returned // ///****************************************************************************** extern byte * IN_GetScanName (ScanCode scan); boolean US_LineInput (int x, int y, char *buf, const char *def, boolean escok, int maxchars, int maxwidth, int color) { boolean redraw, cursorvis, cursormoved, done, result; char s[MaxString], olds[MaxString]; int i, cursor, w,h, len; int lasttime; int lastkey; int cursorwidth; cursorwidth = CurrentFont->width[80-31]; memset (s, 0, MaxString); memset (olds, 0, MaxString); IN_ClearKeyboardQueue (); BKw = maxwidth; BKh = CurrentFont->height; if (def) strcpy (s, def); else *s = '\0'; *olds = '\0'; cursor = strlen (s); cursormoved = redraw = true; cursorvis = done = false; lasttime = GetTicCount(); lastkey = getASCII (); while (!done) { // if (GameEscaped==true) // PauseLoop (); IN_PumpEvents(); if (cursorvis) USL_XORICursor (x, y, s, cursor, color); LastScan = IN_InputUpdateKeyboard (); if (Keyboard[sc_LShift] || Keyboard[sc_RShift]) lastkey = ShiftNames[LastScan]; else lastkey = ASCIINames[LastScan]; switch (LastScan) { case sc_LeftArrow: if (cursor) { cursor--; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_LeftArrow] = 0; break; case sc_RightArrow: if (s[cursor]) { cursor++; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_RightArrow] = 0; break; case sc_Home: if ( cursor ) { cursor = 0; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } Keyboard[sc_Home] = 0; lastkey = key_None; break; case sc_End: if ( cursor != (int)strlen (s) ) { cursor = strlen (s); cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_End] = 0; break; case sc_Return: strcpy (buf,s); done = true; result = true; lastkey = key_None; MN_PlayMenuSnd (SD_SELECTSND); break; case sc_Escape: if (escok) { done = true; result = false; MN_PlayMenuSnd (SD_ESCPRESSEDSND); } lastkey = key_None; break; case sc_BackSpace: if (cursor) { strcpy (s + cursor - 1,s + cursor); cursor--; redraw = true; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_BackSpace] = 0; IN_ClearKeyboardQueue (); break; case sc_Delete: if (s[cursor]) { strcpy (s + cursor,s + cursor + 1); redraw = true; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_Delete] = 0; IN_ClearKeyboardQueue (); break; case 0x4c: // Keypad 5 case sc_UpArrow: case sc_DownArrow: case sc_PgUp: case sc_PgDn: case sc_Insert: lastkey = key_None; break; } // if (GameEscaped==true) // PauseLoop (); if (lastkey) { len = strlen (s); USL_MeasureString (s, &w, &h, CurrentFont); if ( isprint(lastkey) && (len < MaxString - 1) && ((!maxchars) || (len < maxchars)) && ((!maxwidth) || ((w+2) < (maxwidth-cursorwidth-2))) ) { int ls; int rs; for (i = len + 1;i > cursor;i--) s[i] = s[i - 1]; s[cursor++] = lastkey; redraw = true; ls = Keyboard[sc_LShift]; rs = Keyboard[sc_RShift]; memset ((void*)Keyboard, 0, 127*sizeof(int)); // Clear printable keys Keyboard[sc_LShift] = ls; Keyboard[sc_RShift] = rs; MN_PlayMenuSnd (SD_MOVECURSORSND); } } // if (GameEscaped==true) // PauseLoop (); if (redraw) { if (color) VWB_Bar (x, y, BKw, BKh, color); else EraseMenuBufRegion (x, y, BKw, BKh); strcpy (olds, s); px = x; py = y; if (color) USL_DrawString (s); else DrawMenuBufPropString (px, py, s); px = x; py = y; redraw = false; } if (cursormoved) { cursorvis = false; lasttime = GetTicCount() - VBLCOUNTER; cursormoved = false; } if (GetTicCount() - lasttime > VBLCOUNTER / 2) { lasttime = GetTicCount(); cursorvis ^= true; } if (cursorvis) USL_XORICursor (x, y, s, cursor, color); // if (GameEscaped==true) // PauseLoop (); if (color) VW_UpdateScreen (); else RefreshMenuBuf (0); } if (cursorvis) USL_XORICursor (x, y, s, cursor, color); if (!result) { px = x; py = y; if (color) USL_DrawString (olds); else DrawMenuBufPropString (px, py, olds); } // if (GameEscaped==true) // PauseLoop (); if (color) VW_UpdateScreen (); else RefreshMenuBuf (0); IN_ClearKeyboardQueue (); return (result); } //****************************************************************************** // // US_lineinput() - Gets a line of user input at (x,y), the string defaults // to whatever is pointed at by def. Input is restricted to maxchars // chars or maxwidth pixels wide. If the user hits escape (and escok is // true), nothing is copied into buf, and false is returned. If the // user hits return, the current string is copied into buf, and true is // returned - PASSWORD INPUT // ///****************************************************************************** boolean US_lineinput (int x, int y, char *buf, const char *def, boolean escok, int maxchars, int maxwidth, int color) { boolean redraw, cursorvis, cursormoved, done, result; char s[MaxString], xx[MaxString], olds[MaxString]; int i, cursor, w,h, len; int lasttime; int lastkey; int cursorwidth; cursorwidth = CurrentFont->width[80-31]; memset (s, 0, MaxString); memset (xx, 0, MaxString); memset (olds, 0, MaxString); IN_ClearKeyboardQueue (); BKw = maxwidth; BKh = CurrentFont->height; if (def) strcpy (s, def); else *s = '\0'; *olds = '\0'; cursor = strlen (s); cursormoved = redraw = true; cursorvis = done = false; lasttime = GetTicCount(); lastkey = getASCII (); while (!done) { // if (GameEscaped == true) // PauseLoop (); IN_PumpEvents(); if (cursorvis) USL_XORICursor (x, y, xx, cursor, color); LastScan = IN_InputUpdateKeyboard (); if (Keyboard[sc_LShift] || Keyboard[sc_RShift]) lastkey = ShiftNames[LastScan]; else lastkey = ASCIINames[LastScan]; switch (LastScan) { case sc_LeftArrow: if (cursor) { cursor--; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_LeftArrow] = 0; break; case sc_RightArrow: if (s[cursor]) { cursor++; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_RightArrow] = 0; break; case sc_Home: if ( cursor != 0 ) { cursor = 0; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } Keyboard[sc_Home] = 0; lastkey = key_None; break; case sc_End: if ( cursor != (int)strlen( s ) ) { cursor = strlen (s); cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_End] = 0; break; case sc_Return: strcpy (buf,s); done = true; result = true; lastkey = key_None; MN_PlayMenuSnd (SD_SELECTSND); break; case sc_Escape: if (escok) { done = true; result = false; MN_PlayMenuSnd (SD_ESCPRESSEDSND); } lastkey = key_None; break; case sc_BackSpace: if (cursor) { strcpy (s + cursor - 1,s + cursor); strcpy (xx + cursor - 1,xx + cursor); cursor--; redraw = true; MN_PlayMenuSnd (SD_MOVECURSORSND); cursormoved = true; } lastkey = key_None; Keyboard[sc_BackSpace] = 0; IN_ClearKeyboardQueue (); break; case sc_Delete: if (s[cursor]) { strcpy (s + cursor,s + cursor + 1); strcpy (xx + cursor,xx + cursor + 1); redraw = true; cursormoved = true; MN_PlayMenuSnd (SD_MOVECURSORSND); } lastkey = key_None; Keyboard[sc_Delete] = 0; IN_ClearKeyboardQueue (); break; case 0x4c: // Keypad 5 case sc_UpArrow: case sc_DownArrow: case sc_PgUp: case sc_PgDn: case sc_Insert: lastkey = key_None; break; } // if (GameEscaped==true) // PauseLoop (); if (lastkey) { len = strlen (s); USL_MeasureString (xx, &w, &h, CurrentFont); if ( isprint(lastkey) && (len < MaxString - 1) && ((!maxchars) || (len < maxchars)) && ((!maxwidth) || ((w+2) < (maxwidth-cursorwidth-2))) ) { int ls; int rs; for (i = len + 1;i > cursor;i--) s[i] = s[i - 1]; s[cursor] = lastkey; xx[cursor++] = '*'; redraw = true; ls = Keyboard[sc_LShift]; rs = Keyboard[sc_RShift]; memset ((void*)Keyboard, 0, 127*sizeof(int)); // Clear printable keys Keyboard[sc_LShift] = ls; Keyboard[sc_RShift] = rs; MN_PlayMenuSnd (SD_MOVECURSORSND); } } // if (GameEscaped==true) // PauseLoop (); if (redraw) { if (color) VWB_Bar (x, y, BKw, BKh, color); else EraseMenuBufRegion (x, y, BKw, BKh); strcpy (olds, s); px = x; py = y; if (color) USL_DrawString (xx); else DrawMenuBufPropString (px, py, xx); px = x; py = y; redraw = false; } if (cursormoved) { cursorvis = false; lasttime = GetTicCount() - VBLCOUNTER; cursormoved = false; } if (GetTicCount() - lasttime > VBLCOUNTER / 2) { lasttime = GetTicCount(); cursorvis ^= true; } if (cursorvis) USL_XORICursor (x, y, xx, cursor, color); if (color) VW_UpdateScreen (); else RefreshMenuBuf (0); } if (cursorvis) USL_XORICursor (x, y, xx, cursor, color); if (!result) { px = x; py = y; if (color) USL_DrawString (xx); else DrawMenuBufPropString (px, py, xx); } // if (GameEscaped==true) // PauseLoop (); if (color) VW_UpdateScreen (); else RefreshMenuBuf (0); IN_ClearKeyboardQueue (); return (result); } //****************************************************************************** //****************************************************************************** // // WINDOWING ROUTINES // //****************************************************************************** //****************************************************************************** //****************************************************************************** // // US_ClearWindow() - Clears the current window to white and homes the // cursor // //****************************************************************************** void US_ClearWindow (void) { VWB_Bar (WindowX, WindowY, WindowW, WindowH, 13); PrintX = WindowX; PrintY = WindowY; } //****************************************************************************** // // US_DrawWindow() - Draws a frame and sets the current window parms // //****************************************************************************** void US_DrawWindow (int x, int y, int w, int h) { int i, sx, sy, sw, sh; byte * shape; pic_t *Win1; pic_t *Win2; pic_t *Win3; pic_t *Win4; pic_t *Win5; pic_t *Win6; pic_t *Win7; pic_t *Win8; pic_t *Win9; // Cache in windowing shapes shape = W_CacheLumpNum (W_GetNumForName ("window1"), PU_CACHE, Cvt_pic_t, 1); Win1 = (pic_t *) shape; shape = W_CacheLumpNum (W_GetNumForName ("window2"), PU_CACHE, Cvt_pic_t, 1); Win2 = (pic_t *) shape; shape = W_CacheLumpNum (W_GetNumForName ("window3"), PU_CACHE, Cvt_pic_t, 1); Win3 = (pic_t *) shape; shape = W_CacheLumpNum (W_GetNumForName ("window4"), PU_CACHE, Cvt_pic_t, 1); Win4 = (pic_t *) shape; shape = W_CacheLumpNum (W_GetNumForName ("window5"), PU_CACHE, Cvt_pic_t, 1); Win5 = (pic_t *) shape; shape = W_CacheLumpNum (W_GetNumForName ("window6"), PU_CACHE, Cvt_pic_t, 1); Win6 = (pic_t *) shape; shape = W_CacheLumpNum (W_GetNumForName ("window7"), PU_CACHE, Cvt_pic_t, 1); Win7 = (pic_t *) shape; shape = W_CacheLumpNum (W_GetNumForName ("window8"), PU_CACHE, Cvt_pic_t, 1); Win8 = (pic_t *) shape; shape = W_CacheLumpNum (W_GetNumForName ("window9"), PU_CACHE, Cvt_pic_t, 1); Win9 = (pic_t *) shape; WindowX = x * 8; WindowY = y * 8; WindowW = w * 8; WindowH = h * 8; PrintX = WindowX; PrintY = WindowY; sx = (x - 1) * 8; sy = (y - 1) * 8; sw = (w + 1) * 8; sh = (h + 1) * 8; US_ClearWindow (); VWB_DrawPic (sx, sy, Win1); VWB_DrawPic (sx, sy + sh, Win7); for (i = sx + 8;i <= sx + sw - 8; i += 8) { VWB_DrawPic (i, sy, Win2); VWB_DrawPic (i, sy + sh, Win8); } VWB_DrawPic (i, sy, Win3); VWB_DrawPic (i, sy + sh, Win9); for (i = sy + 8;i <= sy + sh - 8; i += 8) { VWB_DrawPic (sx, i, Win4); VWB_DrawPic (sx + sw, i, Win6); } } //****************************************************************************** // // US_CenterWindow() - Generates a window of a given width & height in the // middle of the screen // //****************************************************************************** void US_CenterWindow (int w, int h) { //HDG US_DrawWindow (((MaxX / 8) - w) / 2, ((MaxY / 8) - h) / 2, w, h); US_DrawWindow (((iGLOBAL_SCREENWIDTH / 8) - w) / 2,((iGLOBAL_SCREENHEIGHT / 8) - h) / 2, w, h); } //============================================================================== // // Intensity Font stuff // // TEXT FORMATTING COMMANDS - (Use EGA colors ONLY!) // ------------------------------------------------- // /<hex digit> - Change the following word to <hex digit> color // ` - Highlights the following word with lighter color of fontcolor // /N<hex digit> - Change the fontcolor to a certain color // //============================================================================== //****************************************************************************** // // GetIntensityColor () // //****************************************************************************** byte GetIntensityColor (byte pix) { if ((fontcolor<0) || (fontcolor>255)) Error("Intensity Color out of range\n"); return ((byte) intensitytable[(pix<<8)+fontcolor]); } //****************************************************************************** // // DrawIntensityChar () // // Draws an intensity character at px, py // //****************************************************************************** void DrawIntensityChar ( char ch ) { byte pix; int px1,py1; int width,w1; int height,h1; int ht; byte *source,*src1; byte *dest; byte *origdest,*orgdst1; int mask; px1 = px;py1 = py; ht = IFont->height; origdest = ( byte * )( bufferofs + ylookup[ py ] + px ); dest = origdest; ch -= 31; width = IFont->width[ (unsigned char)ch ]; source = ( ( byte * )IFont ) + IFont->charofs[ (unsigned char)ch ]; mask = 1 << ( px & 3 ); if ((iGLOBAL_SCREENWIDTH <= 320)||(StretchScreen == true)){ while( width-- ) { VGAMAPMASK( mask ); height = ht; while( height-- ) { pix = *source; if ( pix != 0xFE ) { *dest = GetIntensityColor( pix ); } source++; dest += linewidth; } px++; origdest++; dest = origdest; } }else{//strech letter in x any direction w1 = width; h1 = ht; orgdst1 = origdest; src1 = source; while( width-- ) { VGAMAPMASK( mask ); height = ht; while( height-- ) { pix = *source; if ( pix != 0xFE ) { *dest = GetIntensityColor( pix ); *(dest+iGLOBAL_SCREENWIDTH) = GetIntensityColor( pix ); *(dest+1) = GetIntensityColor( pix ); *(dest+1+iGLOBAL_SCREENWIDTH) = GetIntensityColor( pix ); } source++; dest += linewidth*2; } px++;px++; origdest++;origdest++; dest = origdest; } } } //****************************************************************************** // // GetColor () // //****************************************************************************** int GetColor (int num) { int returnval; if ((num >= '0') && (num <= '9')) returnval = egacolor[num - '0']; else if ((num >= 'A') && (num <= 'F')) returnval = egacolor[((num - 'A') + 10)]; return (returnval); } //****************************************************************************** // // DrawIString () // //****************************************************************************** static int oldfontcolor = 0; static boolean highlight = false; void DrawIString (unsigned short int x, unsigned short int y, const char *string, int flags) { char ch; char temp; px = x; py = y; while ((ch = *string++) != 0) { if ( !PERMANENT_MSG( flags ) ) { // Highlighting is done only for 1 word - if we get a "space" // and highlight is on ...., reset variables. // if ((ch == ' ') && (highlight == true)) { highlight = false; fontcolor = oldfontcolor; DrawIntensityChar (ch); } else // '\\' is color change to a specific EGA color (ie. egacolor) // if (ch == '\\') { temp = *string++; temp = toupper (temp); // Force fontcolor to a specific color egacolor[ RED ]; if (temp == 'N') { temp = *string++; fontcolor = GetColor (temp); oldfontcolor = fontcolor; } //bna added else if (temp == 'X') { temp = *string; fontcolor = egacolor[ RED ]; oldfontcolor = fontcolor; } else if (temp == 'Y') { temp = *string; fontcolor = egacolor[ YELLOW ]; oldfontcolor = fontcolor; } else if (temp == 'Z') { temp = *string; fontcolor = egacolor[ GREEN ]; oldfontcolor = fontcolor; } //bna added end // Restore fontcolor to a previous color else if (temp == 'O') { fontcolor = oldfontcolor; } else { oldfontcolor = fontcolor; // save off old font color highlight = true; // set highlight fontcolor = GetColor (temp); } } else // '`' is highlight the current fontcolor // if (ch == '`') { oldfontcolor = fontcolor; // save off old font color highlight = true; // set highlight if (fontcolor < 8) // only highlight the fontcolor = fontcolor-10; // lower colors } else DrawIntensityChar (ch); } else DrawIntensityChar (ch); } if (highlight == true) { highlight = false; fontcolor = oldfontcolor; } } //****************************************************************************** // // DrawIntensityString () // //****************************************************************************** void DrawIntensityString (unsigned short int x, unsigned short int y, const char *string, int color) { char ch; px = x; py = y; fontcolor=color; while ((ch = *string++) != 0) { DrawIntensityChar (ch); } } static unsigned short disp_offset = 160 * 24; void DrawRottText ( int x, int y, int ch, int foreground, int background ) { char *vid; vid = ( char * )( 0xb0000 ); vid += y * 160; vid += x * 2; if ( ch != NONE ) { *vid = ch; } vid++; *vid = ( ( background & 0x0f ) << 4 ) | ( foreground & 0x0f ); } void TextBox ( int x1, int y1, int x2, int y2, int ch, int foreground, int background ) { int x; int y; for( x = x1; x <= x2; x++ ) { for( y = y1; y <= y2; y++ ) { DrawRottText( x, y, ch, foreground, background ); } } } void TextFrame ( int x1, int y1, int x2, int y2, int type, int foreground, int background ) { int x; int y; if ( type == 0 ) { for( x = x1 + 1; x < x2; x++ ) { DrawRottText( x, y1, type, foreground, background ); DrawRottText( x, y2, type, foreground, background ); } for( y = y1 + 1; y < y2; y++ ) { DrawRottText( x1, y, type, foreground, background ); DrawRottText( x2, y, type, foreground, background ); } } if ( type == SINGLE_FRAME ) { DrawRottText( x1, y1, 'Ú', foreground, background ); DrawRottText( x2, y1, '¿', foreground, background ); DrawRottText( x1, y2, 'À', foreground, background ); DrawRottText( x2, y2, 'Ù', foreground, background ); for( x = x1 + 1; x < x2; x++ ) { DrawRottText( x, y1, 'Ä', foreground, background ); DrawRottText( x, y2, 'Ä', foreground, background ); } for( y = y1 + 1; y < y2; y++ ) { DrawRottText( x1, y, '³', foreground, background ); DrawRottText( x2, y, '³', foreground, background ); } } if ( type == DOUBLE_FRAME ) { DrawRottText( x1, y1, 'É', foreground, background ); DrawRottText( x2, y1, '»', foreground, background ); DrawRottText( x1, y2, 'È', foreground, background ); DrawRottText( x2, y2, '¼', foreground, background ); for( x = x1 + 1; x < x2; x++ ) { DrawRottText( x, y1, 'Í', foreground, background ); DrawRottText( x, y2, 'Í', foreground, background ); } for( y = y1 + 1; y < y2; y++ ) { DrawRottText( x1, y, 'º', foreground, background ); DrawRottText( x2, y, 'º', foreground, background ); } } } void mysetxy ( int x, int y ) { disp_offset = ( x * 2 ) + ( y * 160 ); } void myputch ( char ch ) { int j; char *disp_start = (char *)( 0xb0000 ); if ( disp_offset >= 160 * 24 ) { for ( j = 160; j < 160 * 24; j += 2 ) { *( disp_start + j - 160 ) = *( disp_start + j ); } disp_offset = 160 * 23; for ( j = disp_offset; j < ( 160 * 24 ); j += 2 ) { *( disp_start + j ) = ' '; } } if ( ch >= 32 ) { *( disp_start + disp_offset ) = ch; disp_offset = disp_offset + 2; } if ( ch == '\r' ) { disp_offset = disp_offset / 160; disp_offset = disp_offset * 160; } if ( ch == '\n' ) { disp_offset = disp_offset + 160; if ( disp_offset < 160 * 24 ) { for ( j = disp_offset; j < ( ( ( disp_offset / 160 ) + 1 ) * 160 ); j += 2 ) { *( disp_start + j ) = ' '; } } } } int printstring ( char *string ) { int count; char *ptr; ptr = string; count = 0; while ( *ptr ) { myputch( *ptr ); count++; ptr++; } return( count ); } int printnum ( int number ) { char string[ 100 ]; int count; itoa( number, string, 10 ); count = printstring( string ); return( count ); } int printunsigned ( unsigned long number, int radix ) { char string[ 100 ]; int count; ultoa( number, string, radix ); count = printstring( string ); return( count ); } int myprintf ( char *fmt, ... ) { va_list argptr; int count; char *ptr; if (MONOPRESENT==false) { Debug("%s", fmt); return 0; } va_start( argptr, fmt ); ptr = fmt; count = 0; while( *ptr != 0 ) { if ( *ptr == '%' ) { ptr++; switch( *ptr ) { case 0 : return( EOF ); break; case 'l' : count += printnum( va_arg( argptr, int ) ); ptr++; break; case 'd' : count += printnum( va_arg( argptr, int ) ); break; case 's' : count += printstring( va_arg( argptr, char * ) ); break; case 'u' : count += printunsigned( va_arg( argptr, int ), 10 ); break; case 'x' : case 'X' : count += printunsigned( va_arg( argptr, int ), 16 ); break; } ptr++; } else { myputch( *ptr ); count++; ptr++; } } va_end( argptr ); return( count ); }
JohnnyonFlame/RoTT
rott/rt_str.c
C
gpl-2.0
44,463
<?php /** * This software is intended for use with Oxwall Free Community Software http://www.oxwall.org/ and is * licensed under The BSD license. * --- * Copyright (c) 2011, Oxwall Foundation * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of conditions and * the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * - Neither the name of the Oxwall Foundation nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** * Data Access Object for `forum_subscription` table. * * @author Egor Bulgakov <egor.bulgakov@gmail.com> * @package ow.ow_plugins.forum.bol * @since 1.0 */ class FORUM_BOL_SubscriptionDao extends OW_BaseDao { /** * Class constructor * */ protected function __construct() { parent::__construct(); } /** * Class instance * * @var FORUM_BOL_SubscriptionDao */ private static $classInstance; /** * Returns class instance * * @return FORUM_BOL_SubscriptionDao */ public static function getInstance() { if ( self::$classInstance === null ) { self::$classInstance = new self(); } return self::$classInstance; } /** * @see OW_BaseDao::getDtoClassName() * */ public function getDtoClassName() { return 'FORUM_BOL_Subscription'; } /** * @see OW_BaseDao::getTableName() * */ public function getTableName() { return OW_DB_PREFIX . 'forum_subscription'; } /** * Returns list of topic subscribers * * @param int $topicId * @return array */ public function findTopicSubscribers( $topicId ) { $sql = "SELECT `userId` FROM `".$this->getTableName()."` WHERE `topicId`=:topicId"; return $this->dbo->queryForColumnList($sql, array('topicId' => $topicId)); } public function addSubscription( FORUM_BOL_Subscription $subscription ) { $this->save($subscription); return $subscription->id; } public function deleteSubscription( $userId, $topicId ) { $example = new OW_Example(); $example->andFieldEqual('userId', $userId); $example->andFieldEqual('topicId', $topicId); $this->deleteByExample($example); } public function isUserSubscribed( $userId, $topicId ) { $example = new OW_Example(); $example->andFieldEqual('userId', $userId); $example->andFieldEqual('topicId', $topicId); return $this->findObjectByExample($example) ? true : false; } }
seret/oxtebafu1org
ow_plugins/forum/bol/subscription_dao.php
PHP
gpl-2.0
3,908
/********************************************************************** * * PostGIS - Spatial Types for PostgreSQL * http://postgis.refractions.net * * Copyright (C) 2001-2006 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU General Public Licence. See the COPYING file. * **********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "liblwgeom_internal.h" #include "lwgeom_log.h" #define CHECK_LWGEOM_ZM 1 void lwcollection_release(LWCOLLECTION *lwcollection) { lwgeom_release(lwcollection_as_lwgeom(lwcollection)); } LWCOLLECTION * lwcollection_construct(uint8_t type, int srid, GBOX *bbox, uint32_t ngeoms, LWGEOM **geoms) { LWCOLLECTION *ret; int hasz, hasm; #ifdef CHECK_LWGEOM_ZM char zm; uint32_t i; #endif LWDEBUGF(2, "lwcollection_construct called with %d, %d, %p, %d, %p.", type, srid, bbox, ngeoms, geoms); if( ! lwtype_is_collection(type) ) lwerror("Non-collection type specified in collection constructor!"); hasz = 0; hasm = 0; if ( ngeoms > 0 ) { hasz = FLAGS_GET_Z(geoms[0]->flags); hasm = FLAGS_GET_M(geoms[0]->flags); #ifdef CHECK_LWGEOM_ZM zm = FLAGS_GET_ZM(geoms[0]->flags); LWDEBUGF(3, "lwcollection_construct type[0]=%d", geoms[0]->type); for (i=1; i<ngeoms; i++) { LWDEBUGF(3, "lwcollection_construct type=[%d]=%d", i, geoms[i]->type); if ( zm != FLAGS_GET_ZM(geoms[i]->flags) ) lwerror("lwcollection_construct: mixed dimension geometries: %d/%d", zm, FLAGS_GET_ZM(geoms[i]->flags)); } #endif } ret = lwalloc(sizeof(LWCOLLECTION)); ret->type = type; ret->flags = gflags(hasz,hasm,0); FLAGS_SET_BBOX(ret->flags, bbox?1:0); ret->srid = srid; ret->ngeoms = ngeoms; ret->maxgeoms = ngeoms; ret->geoms = geoms; ret->bbox = bbox; return ret; } LWCOLLECTION * lwcollection_construct_empty(uint8_t type, int srid, char hasz, char hasm) { LWCOLLECTION *ret; if( ! lwtype_is_collection(type) ) lwerror("Non-collection type specified in collection constructor!"); ret = lwalloc(sizeof(LWCOLLECTION)); ret->type = type; ret->flags = gflags(hasz,hasm,0); ret->srid = srid; ret->ngeoms = 0; ret->maxgeoms = 1; /* Allocate room for sub-members, just in case. */ ret->geoms = lwalloc(ret->maxgeoms * sizeof(LWGEOM*)); ret->bbox = NULL; return ret; } LWGEOM * lwcollection_getsubgeom(LWCOLLECTION *col, int gnum) { return (LWGEOM *)col->geoms[gnum]; } /** * @brief Clone #LWCOLLECTION object. #POINTARRAY are not copied. * Bbox is cloned if present in input. */ LWCOLLECTION * lwcollection_clone(const LWCOLLECTION *g) { uint32_t i; LWCOLLECTION *ret = lwalloc(sizeof(LWCOLLECTION)); memcpy(ret, g, sizeof(LWCOLLECTION)); if ( g->ngeoms > 0 ) { ret->geoms = lwalloc(sizeof(LWGEOM *)*g->ngeoms); for (i=0; i<g->ngeoms; i++) { ret->geoms[i] = lwgeom_clone(g->geoms[i]); } if ( g->bbox ) ret->bbox = gbox_copy(g->bbox); } else { ret->bbox = NULL; /* empty collection */ ret->geoms = NULL; } return ret; } /** * @brief Deep clone #LWCOLLECTION object. #POINTARRAY are copied. */ LWCOLLECTION * lwcollection_clone_deep(const LWCOLLECTION *g) { uint32_t i; LWCOLLECTION *ret = lwalloc(sizeof(LWCOLLECTION)); memcpy(ret, g, sizeof(LWCOLLECTION)); if ( g->ngeoms > 0 ) { ret->geoms = lwalloc(sizeof(LWGEOM *)*g->ngeoms); for (i=0; i<g->ngeoms; i++) { ret->geoms[i] = lwgeom_clone_deep(g->geoms[i]); } if ( g->bbox ) ret->bbox = gbox_copy(g->bbox); } else { ret->bbox = NULL; /* empty collection */ ret->geoms = NULL; } return ret; } /** * Ensure the collection can hold up at least ngeoms */ void lwcollection_reserve(LWCOLLECTION *col, int ngeoms) { if ( ngeoms <= col->maxgeoms ) return; /* Allocate more space if we need it */ do { col->maxgeoms *= 2; } while ( col->maxgeoms < ngeoms ); col->geoms = lwrealloc(col->geoms, sizeof(LWGEOM*) * col->maxgeoms); } /** * Appends geom to the collection managed by col. Does not copy or * clone, simply takes a reference on the passed geom. */ LWCOLLECTION* lwcollection_add_lwgeom(LWCOLLECTION *col, const LWGEOM *geom) { int i = 0; if ( col == NULL || geom == NULL ) return NULL; if ( col->geoms == NULL && (col->ngeoms || col->maxgeoms) ) { lwerror("Collection is in inconsistent state. Null memory but non-zero collection counts."); return NULL; } /* Check type compatibility */ if ( ! lwcollection_allows_subtype(col->type, geom->type) ) { lwerror("%s cannot contain %s element", lwtype_name(col->type), lwtype_name(geom->type)); return NULL; } /* In case this is a truly empty, make some initial space */ if ( col->geoms == NULL ) { col->maxgeoms = 2; col->ngeoms = 0; col->geoms = lwalloc(col->maxgeoms * sizeof(LWGEOM*)); } /* Allocate more space if we need it */ lwcollection_reserve(col, col->ngeoms + 1); /* Make sure we don't already have a reference to this geom */ /* TODO: drop this check ... */ for ( i = 0; i < col->ngeoms; i++ ) { if ( col->geoms[i] == geom ) { LWDEBUGF(4, "Found duplicate geometry in collection %p == %p", col->geoms[i], geom); return col; } } col->geoms[col->ngeoms] = (LWGEOM*)geom; col->ngeoms++; return col; } LWCOLLECTION * lwcollection_segmentize2d(LWCOLLECTION *col, double dist) { uint32_t i; LWGEOM **newgeoms; if ( ! col->ngeoms ) return lwcollection_clone(col); newgeoms = lwalloc(sizeof(LWGEOM *)*col->ngeoms); for (i=0; i<col->ngeoms; i++) newgeoms[i] = lwgeom_segmentize2d(col->geoms[i], dist); return lwcollection_construct(col->type, col->srid, NULL, col->ngeoms, newgeoms); } /** @brief check for same geometry composition * */ char lwcollection_same(const LWCOLLECTION *c1, const LWCOLLECTION *c2) { uint32_t i; LWDEBUG(2, "lwcollection_same called"); if ( c1->type != c2->type ) return LW_FALSE; if ( c1->ngeoms != c2->ngeoms ) return LW_FALSE; for ( i = 0; i < c1->ngeoms; i++ ) { if ( ! lwgeom_same(c1->geoms[i], c2->geoms[i]) ) return LW_FALSE; } /* Former method allowed out-of-order equality between collections hit = lwalloc(sizeof(uint32_t)*c1->ngeoms); memset(hit, 0, sizeof(uint32_t)*c1->ngeoms); for (i=0; i<c1->ngeoms; i++) { char found=0; for (j=0; j<c2->ngeoms; j++) { if ( hit[j] ) continue; if ( lwgeom_same(c1->geoms[i], c2->geoms[j]) ) { hit[j] = 1; found=1; break; } } if ( ! found ) return LW_FALSE; } */ return LW_TRUE; } int lwcollection_ngeoms(const LWCOLLECTION *col) { int i; int ngeoms = 0; if ( ! col ) { lwerror("Null input geometry."); return 0; } for ( i = 0; i < col->ngeoms; i++ ) { if ( col->geoms[i]) { switch (col->geoms[i]->type) { case POINTTYPE: case LINETYPE: case CIRCSTRINGTYPE: case POLYGONTYPE: ngeoms += 1; break; case MULTIPOINTTYPE: case MULTILINETYPE: case MULTICURVETYPE: case MULTIPOLYGONTYPE: ngeoms += col->ngeoms; break; case COLLECTIONTYPE: ngeoms += lwcollection_ngeoms((LWCOLLECTION*)col->geoms[i]); break; } } } return ngeoms; } void lwcollection_free(LWCOLLECTION *col) { int i; if ( ! col ) return; if ( col->bbox ) { lwfree(col->bbox); } for ( i = 0; i < col->ngeoms; i++ ) { LWDEBUGF(4,"freeing geom[%d]", i); if ( col->geoms && col->geoms[i] ) lwgeom_free(col->geoms[i]); } if ( col->geoms ) { lwfree(col->geoms); } lwfree(col); } /** * Takes a potentially heterogeneous collection and returns a homogeneous * collection consisting only of the specified type. */ LWCOLLECTION* lwcollection_extract(LWCOLLECTION *col, int type) { int i = 0; LWGEOM **geomlist; LWCOLLECTION *outcol; int geomlistsize = 16; int geomlistlen = 0; uint8_t outtype; if ( ! col ) return NULL; switch (type) { case POINTTYPE: outtype = MULTIPOINTTYPE; break; case LINETYPE: outtype = MULTILINETYPE; break; case POLYGONTYPE: outtype = MULTIPOLYGONTYPE; break; default: lwerror("Only POLYGON, LINESTRING and POINT are supported by lwcollection_extract. %s requested.", lwtype_name(type)); return NULL; } geomlist = lwalloc(sizeof(LWGEOM*) * geomlistsize); /* Process each sub-geometry */ for ( i = 0; i < col->ngeoms; i++ ) { int subtype = col->geoms[i]->type; /* Don't bother adding empty sub-geometries */ if ( lwgeom_is_empty(col->geoms[i]) ) { continue; } /* Copy our sub-types into the output list */ if ( subtype == type ) { /* We've over-run our buffer, double the memory segment */ if ( geomlistlen == geomlistsize ) { geomlistsize *= 2; geomlist = lwrealloc(geomlist, sizeof(LWGEOM*) * geomlistsize); } geomlist[geomlistlen] = lwgeom_clone(col->geoms[i]); geomlistlen++; } /* Recurse into sub-collections */ if ( lwtype_is_collection( subtype ) ) { int j = 0; LWCOLLECTION *tmpcol = lwcollection_extract((LWCOLLECTION*)col->geoms[i], type); for ( j = 0; j < tmpcol->ngeoms; j++ ) { /* We've over-run our buffer, double the memory segment */ if ( geomlistlen == geomlistsize ) { geomlistsize *= 2; geomlist = lwrealloc(geomlist, sizeof(LWGEOM*) * geomlistsize); } geomlist[geomlistlen] = tmpcol->geoms[j]; geomlistlen++; } lwfree(tmpcol); } } if ( geomlistlen > 0 ) { GBOX gbox; outcol = lwcollection_construct(outtype, col->srid, NULL, geomlistlen, geomlist); lwgeom_calculate_gbox((LWGEOM *) outcol, &gbox); outcol->bbox = gbox_copy(&gbox); } else { lwfree(geomlist); outcol = lwcollection_construct_empty(outtype, col->srid, FLAGS_GET_Z(col->flags), FLAGS_GET_M(col->flags)); } return outcol; } LWGEOM* lwcollection_remove_repeated_points(LWCOLLECTION *coll) { uint32_t i; LWGEOM **newgeoms; newgeoms = lwalloc(sizeof(LWGEOM *)*coll->ngeoms); for (i=0; i<coll->ngeoms; i++) { newgeoms[i] = lwgeom_remove_repeated_points(coll->geoms[i]); } return (LWGEOM*)lwcollection_construct(coll->type, coll->srid, coll->bbox ? gbox_copy(coll->bbox) : NULL, coll->ngeoms, newgeoms); } LWCOLLECTION* lwcollection_force_dims(const LWCOLLECTION *col, int hasz, int hasm) { LWCOLLECTION *colout; /* Return 2D empty */ if( lwcollection_is_empty(col) ) { colout = lwcollection_construct_empty(col->type, col->srid, hasz, hasm); } else { int i; LWGEOM **geoms = NULL; geoms = lwalloc(sizeof(LWGEOM*) * col->ngeoms); for( i = 0; i < col->ngeoms; i++ ) { geoms[i] = lwgeom_force_dims(col->geoms[i], hasz, hasm); } colout = lwcollection_construct(col->type, col->srid, NULL, col->ngeoms, geoms); } return colout; } int lwcollection_is_empty(const LWCOLLECTION *col) { int i; if ( (col->ngeoms == 0) || (!col->geoms) ) return LW_TRUE; for( i = 0; i < col->ngeoms; i++ ) { if ( ! lwgeom_is_empty(col->geoms[i]) ) return LW_FALSE; } return LW_TRUE; } int lwcollection_count_vertices(LWCOLLECTION *col) { int i = 0; int v = 0; /* vertices */ assert(col); for ( i = 0; i < col->ngeoms; i++ ) { v += lwgeom_count_vertices(col->geoms[i]); } return v; } LWCOLLECTION* lwcollection_simplify(const LWCOLLECTION *igeom, double dist) { int i; LWCOLLECTION *out = lwcollection_construct_empty(igeom->type, igeom->srid, FLAGS_GET_Z(igeom->flags), FLAGS_GET_M(igeom->flags)); if( lwcollection_is_empty(igeom) ) return out; /* should we return NULL instead ? */ for( i = 0; i < igeom->ngeoms; i++ ) { LWGEOM *ngeom = lwgeom_simplify(igeom->geoms[i], dist); if ( ngeom ) out = lwcollection_add_lwgeom(out, ngeom); } return out; } int lwcollection_allows_subtype(int collectiontype, int subtype) { if ( collectiontype == COLLECTIONTYPE ) return LW_TRUE; if ( collectiontype == MULTIPOINTTYPE && subtype == POINTTYPE ) return LW_TRUE; if ( collectiontype == MULTILINETYPE && subtype == LINETYPE ) return LW_TRUE; if ( collectiontype == MULTIPOLYGONTYPE && subtype == POLYGONTYPE ) return LW_TRUE; if ( collectiontype == COMPOUNDTYPE && (subtype == LINETYPE || subtype == CIRCSTRINGTYPE) ) return LW_TRUE; if ( collectiontype == CURVEPOLYTYPE && (subtype == CIRCSTRINGTYPE || subtype == LINETYPE || subtype == COMPOUNDTYPE) ) return LW_TRUE; if ( collectiontype == MULTICURVETYPE && (subtype == CIRCSTRINGTYPE || subtype == LINETYPE || subtype == COMPOUNDTYPE) ) return LW_TRUE; if ( collectiontype == MULTISURFACETYPE && (subtype == POLYGONTYPE || subtype == CURVEPOLYTYPE) ) return LW_TRUE; if ( collectiontype == POLYHEDRALSURFACETYPE && subtype == POLYGONTYPE ) return LW_TRUE; if ( collectiontype == TINTYPE && subtype == TRIANGLETYPE ) return LW_TRUE; /* Must be a bad combination! */ return LW_FALSE; } int lwcollection_startpoint(const LWCOLLECTION* col, POINT4D* pt) { if ( col->ngeoms < 1 ) return LW_FAILURE; return lwgeom_startpoint(col->geoms[0], pt); }
ahinz/postgis
liblwgeom/lwcollection.c
C
gpl-2.0
13,014
/* * Copyright 2014 by SCSK Corporation. * * This file is part of PrimeCloud Controller(TM). * * PrimeCloud Controller(TM) 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. * * PrimeCloud Controller(TM) 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 PrimeCloud Controller(TM). If not, see <http://www.gnu.org/licenses/>. */ package jp.primecloud.auto.dao.crud; import java.util.Collection; import java.util.List; import jp.primecloud.auto.entity.crud.User; /** * <p> * USERに対応したDAOのベースインタフェースです。 * </p> * */ public interface BaseUserDao { /** * 主キーに該当するレコードを検索します。 * * @param userNo userNo * @return 主キーに該当するレコードのエンティティ。レコードがない場合はnull。 */ public User read( Long userNo ); /** * 全てのレコードを検索します。 * * @return 全てのレコードのエンティティのリスト。レコードがない場合は空リスト。 */ public List<User> readAll(); /** * 一意キーに該当するレコードを検索します。 * * @param username username * @return 一意キーに該当するレコードのエンティティ。レコードがない場合はnull。 */ public User readByUsername( String username ); /** * 主キーのコレクションに該当するレコードを検索します。 * * @param userNos userNoのコレクション * @return 主キーのコレクションに該当するレコードのエンティティのリスト。レコードがない場合は空リスト。 */ public List<User> readInUserNos( Collection<Long> userNos ); /** * 与えられたエンティティの内容でレコードを挿入します。 * * @param entity エンティティ */ public void create(User entity); /** * 与えられたエンティティの内容でレコードを更新します。 * * @param entity エンティティ */ public void update(User entity); /** * 与えられたエンティティのレコードを削除します。 * * @param entity エンティティ */ public void delete(User entity); /** * 全てのレコードを削除します。 */ public void deleteAll(); /** * 主キーに該当するレコードを削除します。 * * @param userNo userNo */ public void deleteByUserNo( Long userNo ); /** * 一意キーに該当するレコードを削除します。 * * @param username username */ public void deleteByUsername( String username ); /** * 全てのレコードの件数を取得します。 * * @return 全てのレコードの件数。 */ public long countAll(); /** * 主キーに該当するレコードの件数を取得します。 * * @param userNo userNo * @return 主キーに該当するレコードの件数。 */ public long countByUserNo( Long userNo ); /** * 一意キーに該当するレコードの件数を取得します。 * * @param username username * @return 一意キーに該当するレコードの件数。 */ public long countByUsername( String username ); /** * マスターユーザーに該当するレコードの件数を取得します。 * * @param userNo userNo * @return マスターユーザーに該当するレコードの件数。 */ public List<User> readByMasterUser( Long masterUserNo ); }
aigamo/primecloud-controller
auto-project/auto-data/src/main/java/jp/primecloud/auto/dao/crud/BaseUserDao.java
Java
gpl-2.0
4,302
<?php if ( ! defined( 'ABSPATH' ) ) exit; return apply_filters( 'ninja_forms_plugin_settings_advanced', array( /* |-------------------------------------------------------------------------- | Delete on Uninstall |-------------------------------------------------------------------------- */ 'delete_on_uninstall' => array( 'id' => 'delete_on_uninstall', 'type' => 'checkbox', 'label' => __( 'Remove ALL Ninja Forms data upon uninstall?', 'ninja-forms' ), 'desc' => sprintf( __( 'If this box is checked, ALL Ninja Forms data will be removed from the database upon deletion. %sAll form and submission data will be unrecoverable.%s', 'ninja-forms' ), '<span class="nf-nuke-warning">', '</span>' ), ), /* |-------------------------------------------------------------------------- | Delete Prompt for Delete on Uninstall |-------------------------------------------------------------------------- */ 'delete_prompt' => array( 'id' => 'delete_prompt', 'type' => 'prompt', 'desc' => __( 'This setting will COMPLETELY remove anything Ninja Forms related upon plugin deletion. This includes SUBMISSIONS and FORMS. It cannot be undone.', 'ninja-forms' ), 'deps' => array( 'delete_on_uninstall' => 'checked' ) ), /* |-------------------------------------------------------------------------- | Disable Admin Notices |-------------------------------------------------------------------------- */ 'disable_admin_notices' => array( 'id' => 'disable_admin_notices', 'type' => 'checkbox', 'label' => __( 'Disable Admin Notices', 'ninja-forms' ), 'desc' => __( 'Never see an admin notice on the dashboard from Ninja Forms. Uncheck to see them again.', 'ninja-forms' ), ), /* |-------------------------------------------------------------------------- | Tracking Opt-in |-------------------------------------------------------------------------- */ 'allow_tracking' => array( 'id' => 'allow_tracking', 'type' => 'checkbox', 'label' => __( 'Allow Tracking', 'ninja-forms' ), 'desc' => __( 'If you opt-in, some data about your installation of Ninja Forms will be sent to NinjaForms.com (this does NOT include your submissions).', 'ninja-forms' ) ), /* |-------------------------------------------------------------------------- | Opinionated Styles |-------------------------------------------------------------------------- */ 'opinionated_styles' => array( 'id' => 'opinionated_styles', 'type' => 'select', 'label' => __( 'Opinionated Styles', 'ninja-forms' ), 'options' => array( array( 'label' => __( 'None', 'ninja-forms' ), 'value' => '', ), array( 'label' => __( 'Light', 'ninja-forms' ), 'value' => 'light', ), array( 'label' => __( 'Dark', 'ninja-forms' ), 'value' => 'dark', ), ), 'desc' => __( 'Use default Ninja Forms styling conventions.', 'ninja-forms' ), 'value' => '' ), /* |-------------------------------------------------------------------------- | Rollback to v2.9.x |-------------------------------------------------------------------------- */ 'rollback' => array( 'id' => 'rollback', 'type' => 'html', 'html' => '<a id="nfRollback" href="' . admin_url( 'admin.php?page=ninja-forms&nf-switcher=rollback' ) . '" class="button">' . __( 'Rollback', 'ninja-forms' ) . '</a>', 'label' => __( 'Rollback to v2.9.x', 'ninja-forms' ), 'desc' => __( 'Rollback to the most recent 2.9.x release.', 'ninja-forms' ) . '<br /><div style="color: red">' . __( 'IMPORTANT: All 3.0 data will be removed.', 'ninja-forms' ) . '<br />' . __( 'Please export any forms or submissions you do not want to be lost during this process.', 'ninja-forms' ) . '</div>', ), ));
JordanPak/RenaRomano
wp-content/plugins/ninja-forms/includes/Config/PluginSettingsAdvanced.php
PHP
gpl-2.0
4,177
/* * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * This code 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. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * 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 work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Codename One through http://www.codenameone.com/ if you * need additional information or have any questions. */ package com.codename1.testing; import com.codename1.ui.Display; import java.io.IOException; import java.io.OutputStream; /** * Produces test reporting in the format of JUnit XML for compatibility with * tools that consume JUnit test case results see http://code.google.com/p/codenameone/issues/detail?id=446 * for more details.<br/> * * @author Shai Almog */ public class JUnitXMLReporting extends TestReporting { private String testCases = ""; private String output; private int passed; private int failed; /** * @inheritDoc */ public void startingTestCase(UnitTest test) { testCases += "<testcase classname=\"" + test.getClass().getName() + "\" >"; output = ""; } /** * @inheritDoc */ public void logMessage(String message) { output += message + "\n"; } /** * @inheritDoc */ public void logException(Throwable err) { testCases += "<error type=\"" + err.getClass().getName() + "\">" + err.toString() + "</error>\n"; } /** * @inheritDoc */ public void finishedTestCase(UnitTest test, boolean passed) { if(passed) { this.passed++; testCases += "<system-out>\n" + output + "</system-out>\n" + "</testcase>"; } else { failed++; testCases += "<system-out>\n" + output + "</system-out><error/>\n" + "</testcase>"; } } /** * @inheritDoc */ public void writeReport(OutputStream os) throws IOException { os.write(("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<testsuite failures=\"" + failed + "\" " + "skipped=\"0\" tests=\"" + (passed + failed) + "\" name=\"" + Display.getInstance().getProperty("AppName", "Unnamed") + "\">\n" + testCases + "\n</testsuite>").getBytes()); } /** * @inheritDoc */ public void testExecutionFinished() { } }
skyHALud/codenameone
CodenameOne/src/com/codename1/testing/JUnitXMLReporting.java
Java
gpl-2.0
3,224
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>BS Wysiwyg Example 1</title> <script type="text/javascript" src="/_bsJavascript/core/lang/Bs_Misc.lib.js"></script> <script type="text/javascript" src="/_bsJavascript/core/html/Bs_HtmlUtil.lib.js"></script> <script type="text/javascript" src="/_bsJavascript/components/tabset/Bs_TabSet.class.js"></script> <link rel='stylesheet' href='/_bsJavascript/components/tabset/default.css'> <script type="text/javascript" src="/_bsJavascript/components/wysiwyg/Bs_WysiwygNew.class.js"></script> <script type="text/javascript" src="/_bsJavascript/components/wysiwyg/lang/en.js"></script> <link rel='stylesheet' href='/_bsJavascript/components/wysiwyg/styles.css'> <script type="text/javascript" src="/_bsJavascript/core/form/Bs_FormFieldSelect.class.js"></script> <script type="text/javascript" src="/_bsJavascript/components/toolbar/Bs_ButtonBar.class.js"></script> <script type="text/javascript" src="/_bsJavascript/components/toolbar/Bs_Button.class.js"></script> <script type="text/javascript" src="/_bsJavascript/components/resizegrip/Bs_ResizeGrip.class.js"></script> <script> if (moz) { document.writeln("<link rel='stylesheet' href='/_bsJavascript/components/toolbar/win2k_mz.css'>"); } else { document.writeln("<link rel='stylesheet' href='/_bsJavascript/components/toolbar/win2k_ie.css'>"); } onload = function() { w = new Bs_Wysiwyg('w'); //w.dataType = 'html'; //w.setValue('foo <a>asdf</a>'); w.setValue('blah <a href="http://www.bar.com/">foo</a> <font color="#008200"><b>bold</b></font> <img id="xxx" src="http://homepage.swissonline.ch/blueshoes/img/javaScript/wysiwyg/screenshot1.gif" alt="alt foo" width="200"> <i>italic</i><br><br><table><tr><td>td</td></tr></table><form name="f"></form>'); //w.mayResize = false; w.imageSelector[3] = new Array('/_bsApplications/filebrowser/examples/example1.php', 500, 300); var status = w.drawInto('test'); } </script> </head> <body bgcolor="white" id="body"> <h1>Wysiwyg Editor Example 1</h1> <a href="javascript:void(0);" onclick="alert(w.getValue()); return false;">alert the current value of instance 1</a><br> <br><br> <table bgcolor="green" width="500" height="450"> <tr> <td valign="top"> <!-- make it at least 446 pixel in width! --> <div id="test" style="width:446; height:400;"></div> </td></tr></table><br><br> foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar </body> </html>
avinash/nuzimazz
FilteredSearch/javascript/components/wysiwyg/examples/example1new.html
HTML
gpl-2.0
2,705
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/svn/docs/wafbook/single.html#_obtaining_the_waf_file import os.path,shutil,re from waflib import Context,Task,Utils,Logs,Options,Errors from waflib.TaskGen import extension from waflib.Configure import conf class valac(Task.Task): vars=["VALAC","VALAC_VERSION","VALAFLAGS"] ext_out=['.h'] def run(self): env=self.env cmd=[env['VALAC'],'-C','--quiet'] cmd.extend(Utils.to_list(env['VALAFLAGS'])) if self.threading: cmd.append('--thread') if self.profile: cmd.append('--profile=%s'%self.profile) if self.target_glib: cmd.append('--target-glib=%s'%self.target_glib) if self.is_lib: cmd.append('--library='+self.target) for x in self.outputs: if x.name.endswith('.h'): cmd.append('--header='+x.name) if self.gir: cmd.append('--gir=%s.gir'%self.gir) for vapi_dir in self.vapi_dirs: cmd.append('--vapidir=%s'%vapi_dir) for package in self.packages: cmd.append('--pkg=%s'%package) for package in self.packages_private: cmd.append('--pkg=%s'%package) for define in self.vala_defines: cmd.append('--define=%s'%define) cmd.extend([a.abspath()for a in self.inputs]) ret=self.exec_command(cmd,cwd=self.outputs[0].parent.abspath()) if ret: return ret for x in self.outputs: if id(x.parent)!=id(self.outputs[0].parent): shutil.move(self.outputs[0].parent.abspath()+os.sep+x.name,x.abspath()) if self.packages and getattr(self,'deps_node',None): self.deps_node.write('\n'.join(self.packages)) return ret def vala_file(self,node): valatask=getattr(self,"valatask",None) if not valatask: def _get_api_version(): api_version='1.0' if hasattr(Context.g_module,'API_VERSION'): version=Context.g_module.API_VERSION.split(".") if version[0]=="0": api_version="0."+version[1] else: api_version=version[0]+".0" return api_version valatask=self.create_task('valac') self.valatask=valatask self.includes=Utils.to_list(getattr(self,'includes',[])) self.uselib=self.to_list(getattr(self,'uselib',[])) valatask.packages=[] valatask.packages_private=Utils.to_list(getattr(self,'packages_private',[])) valatask.vapi_dirs=[] valatask.target=self.target valatask.threading=False valatask.install_path=getattr(self,'install_path','') valatask.profile=getattr(self,'profile','gobject') valatask.vala_defines=getattr(self,'vala_defines',[]) valatask.target_glib=None valatask.gir=getattr(self,'gir',None) valatask.gir_path=getattr(self,'gir_path','${DATAROOTDIR}/gir-1.0') valatask.vapi_path=getattr(self,'vapi_path','${DATAROOTDIR}/vala/vapi') valatask.pkg_name=getattr(self,'pkg_name',self.env['PACKAGE']) valatask.header_path=getattr(self,'header_path','${INCLUDEDIR}/%s-%s'%(valatask.pkg_name,_get_api_version())) valatask.is_lib=False if not'cprogram'in self.features: valatask.is_lib=True packages=Utils.to_list(getattr(self,'packages',[])) vapi_dirs=Utils.to_list(getattr(self,'vapi_dirs',[])) includes=[] if hasattr(self,'use'): local_packages=Utils.to_list(self.use)[:] seen=[] while len(local_packages)>0: package=local_packages.pop() if package in seen: continue seen.append(package) try: package_obj=self.bld.get_tgen_by_name(package) except Errors.WafError: continue package_name=package_obj.target package_node=package_obj.path package_dir=package_node.path_from(self.path) for task in package_obj.tasks: for output in task.outputs: if output.name==package_name+".vapi": valatask.set_run_after(task) if package_name not in packages: packages.append(package_name) if package_dir not in vapi_dirs: vapi_dirs.append(package_dir) if package_dir not in includes: includes.append(package_dir) if hasattr(package_obj,'use'): lst=self.to_list(package_obj.use) lst.reverse() local_packages=[pkg for pkg in lst if pkg not in seen]+local_packages valatask.packages=packages for vapi_dir in vapi_dirs: try: valatask.vapi_dirs.append(self.path.find_dir(vapi_dir).abspath()) valatask.vapi_dirs.append(self.path.find_dir(vapi_dir).get_bld().abspath()) except AttributeError: Logs.warn("Unable to locate Vala API directory: '%s'"%vapi_dir) self.includes.append(self.bld.srcnode.abspath()) self.includes.append(self.bld.bldnode.abspath()) for include in includes: try: self.includes.append(self.path.find_dir(include).abspath()) self.includes.append(self.path.find_dir(include).get_bld().abspath()) except AttributeError: Logs.warn("Unable to locate include directory: '%s'"%include) if valatask.profile=='gobject': if hasattr(self,'target_glib'): Logs.warn('target_glib on vala tasks is not supported --vala-target-glib=MAJOR.MINOR from the vala tool options') if getattr(Options.options,'vala_target_glib',None): valatask.target_glib=Options.options.vala_target_glib if not'GOBJECT'in self.uselib: self.uselib.append('GOBJECT') if hasattr(self,'threading'): if valatask.profile=='gobject': valatask.threading=self.threading if not'GTHREAD'in self.uselib: self.uselib.append('GTHREAD') else: Logs.warn("Profile %s does not have threading support"%valatask.profile) if valatask.is_lib: valatask.outputs.append(self.path.find_or_declare('%s.h'%self.target)) valatask.outputs.append(self.path.find_or_declare('%s.vapi'%self.target)) if valatask.gir: valatask.outputs.append(self.path.find_or_declare('%s.gir'%self.gir)) if valatask.packages: d=self.path.find_or_declare('%s.deps'%self.target) valatask.outputs.append(d) valatask.deps_node=d valatask.inputs.append(node) c_node=node.change_ext('.c') valatask.outputs.append(c_node) self.source.append(c_node) if valatask.is_lib: headers_list=[o for o in valatask.outputs if o.suffix()==".h"] try: self.install_vheader.source=headers_list except AttributeError: self.install_vheader=self.bld.install_files(valatask.header_path,headers_list,self.env) vapi_list=[o for o in valatask.outputs if(o.suffix()in(".vapi",".deps"))] try: self.install_vapi.source=vapi_list except AttributeError: self.install_vapi=self.bld.install_files(valatask.vapi_path,vapi_list,self.env) gir_list=[o for o in valatask.outputs if o.suffix()==".gir"] try: self.install_gir.source=gir_list except AttributeError: self.install_gir=self.bld.install_files(valatask.gir_path,gir_list,self.env) valac=Task.update_outputs(valac) def find_valac(self,valac_name,min_version): valac=self.find_program(valac_name,var='VALAC') try: output=self.cmd_and_log(valac+' --version') except Exception: valac_version=None else: ver=re.search(r'\d+.\d+.\d+',output).group(0).split('.') valac_version=tuple([int(x)for x in ver]) self.msg('Checking for %s version >= %r'%(valac_name,min_version),valac_version,valac_version and valac_version>=min_version) if valac and valac_version<min_version: self.fatal("%s version %r is too old, need >= %r"%(valac_name,valac_version,min_version)) self.env['VALAC_VERSION']=valac_version return valac def check_vala(self,min_version=(0,8,0),branch=None): if not branch: branch=min_version[:2] try: find_valac(self,'valac-%d.%d'%(branch[0],branch[1]),min_version) except self.errors.ConfigurationError: find_valac(self,'valac',min_version) def check_vala_deps(self): if not self.env['HAVE_GOBJECT']: pkg_args={'package':'gobject-2.0','uselib_store':'GOBJECT','args':'--cflags --libs'} if getattr(Options.options,'vala_target_glib',None): pkg_args['atleast_version']=Options.options.vala_target_glib self.check_cfg(**pkg_args) if not self.env['HAVE_GTHREAD']: pkg_args={'package':'gthread-2.0','uselib_store':'GTHREAD','args':'--cflags --libs'} if getattr(Options.options,'vala_target_glib',None): pkg_args['atleast_version']=Options.options.vala_target_glib self.check_cfg(**pkg_args) def configure(self): self.load('gnu_dirs') self.check_vala_deps() self.check_vala() def options(opt): opt.load('gnu_dirs') valaopts=opt.add_option_group('Vala Compiler Options') valaopts.add_option('--vala-target-glib',default=None,dest='vala_target_glib',metavar='MAJOR.MINOR',help='Target version of glib for Vala GObject code generation') extension('.vala','.gs')(vala_file) conf(find_valac) conf(check_vala) conf(check_vala_deps)
lanfker/tdma_imac
.waf-1.6.7-0a94702c61504c487a251b8d0a04ca9a/waflib/Tools/vala.py
Python
gpl-2.0
8,447
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* * (C) Copyright 2000-2004 * DENX Software Engineering * Wolfgang Denk, wd@denx.de * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef __WIN32__ #include <netinet/in.h> /* for host / network byte order conversions */ #endif #include <sys/mman.h> #include <sys/stat.h> #include <time.h> #include <unistd.h> #if defined(__BEOS__) || defined(__NetBSD__) || defined(__APPLE__) #include <inttypes.h> #endif #ifdef __WIN32__ typedef unsigned int __u32; #define SWAP_LONG(x) \ ((__u32)( \ (((__u32)(x) & (__u32)0x000000ffUL) << 24) | \ (((__u32)(x) & (__u32)0x0000ff00UL) << 8) | \ (((__u32)(x) & (__u32)0x00ff0000UL) >> 8) | \ (((__u32)(x) & (__u32)0xff000000UL) >> 24) )) typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #define ntohl(a) SWAP_LONG(a) #define htonl(a) SWAP_LONG(a) #endif /* __WIN32__ */ #ifndef O_BINARY /* should be define'd on __WIN32__ */ #define O_BINARY 0 #endif #include <image.h> extern int errno; #ifndef MAP_FAILED #define MAP_FAILED (-1) #endif char *cmdname; extern unsigned long crc32 (unsigned long crc, const char *buf, unsigned int len); typedef struct table_entry { int val; /* as defined in image.h */ char *sname; /* short (input) name */ char *lname; /* long (output) name */ } table_entry_t; table_entry_t arch_name[] = { { IH_CPU_INVALID, NULL, "Invalid CPU", }, { IH_CPU_ALPHA, "alpha", "Alpha", }, { IH_CPU_ARM, "arm", "ARM", }, { IH_CPU_I386, "x86", "Intel x86", }, { IH_CPU_IA64, "ia64", "IA64", }, { IH_CPU_M68K, "m68k", "MC68000", }, { IH_CPU_MICROBLAZE, "microblaze", "MicroBlaze", }, { IH_CPU_MIPS, "mips", "MIPS", }, { IH_CPU_MIPS64, "mips64", "MIPS 64 Bit", }, { IH_CPU_PPC, "ppc", "PowerPC", }, { IH_CPU_S390, "s390", "IBM S390", }, { IH_CPU_SH, "sh", "SuperH", }, { IH_CPU_SPARC, "sparc", "SPARC", }, { IH_CPU_SPARC64, "sparc64", "SPARC 64 Bit", }, { -1, "", "", }, }; table_entry_t os_name[] = { { IH_OS_INVALID, NULL, "Invalid OS", }, { IH_OS_4_4BSD, "4_4bsd", "4_4BSD", }, { IH_OS_ARTOS, "artos", "ARTOS", }, { IH_OS_DELL, "dell", "Dell", }, { IH_OS_ESIX, "esix", "Esix", }, { IH_OS_FREEBSD, "freebsd", "FreeBSD", }, { IH_OS_IRIX, "irix", "Irix", }, { IH_OS_LINUX, "linux", "Linux", }, { IH_OS_LYNXOS, "lynxos", "LynxOS", }, { IH_OS_NCR, "ncr", "NCR", }, { IH_OS_NETBSD, "netbsd", "NetBSD", }, { IH_OS_OPENBSD, "openbsd", "OpenBSD", }, { IH_OS_PSOS, "psos", "pSOS", }, { IH_OS_QNX, "qnx", "QNX", }, { IH_OS_RTEMS, "rtems", "RTEMS", }, { IH_OS_SCO, "sco", "SCO", }, { IH_OS_SOLARIS, "solaris", "Solaris", }, { IH_OS_SVR4, "svr4", "SVR4", }, { IH_OS_U_BOOT, "u-boot", "U-Boot", }, { IH_OS_VXWORKS, "vxworks", "VxWorks", }, { -1, "", "", }, }; table_entry_t type_name[] = { { IH_TYPE_INVALID, NULL, "Invalid Image", }, { IH_TYPE_FILESYSTEM, "filesystem", "Filesystem Image", }, { IH_TYPE_FIRMWARE, "firmware", "Firmware", }, { IH_TYPE_KERNEL, "kernel", "Kernel Image", }, { IH_TYPE_MULTI, "multi", "Multi-File Image", }, { IH_TYPE_RAMDISK, "ramdisk", "RAMDisk Image", }, { IH_TYPE_SCRIPT, "script", "Script", }, { IH_TYPE_STANDALONE, "standalone", "Standalone Program", }, { -1, "", "", }, }; table_entry_t comp_name[] = { { IH_COMP_NONE, "none", "uncompressed", }, { IH_COMP_BZIP2, "bzip2", "bzip2 compressed", }, { IH_COMP_GZIP, "gzip", "gzip compressed", }, { IH_COMP_LZMA, "lzma", "lzma compressed", }, { -1, "", "", }, }; static void copy_file (int, const char *, int); static void usage (void); static void print_header (image_header_t *); static void print_type (image_header_t *); static char *put_table_entry (table_entry_t *, char *, int); static char *put_arch (int); static char *put_type (int); static char *put_os (int); static char *put_comp (int); static int get_table_entry (table_entry_t *, char *, char *); static int get_arch(char *); static int get_comp(char *); static int get_os (char *); static int get_type(char *); char *datafile; char *imagefile; int dflag = 0; int eflag = 0; int lflag = 0; int vflag = 0; int xflag = 0; int opt_os = IH_OS_LINUX; int opt_arch = IH_CPU_PPC; int opt_type = IH_TYPE_KERNEL; int opt_comp = IH_COMP_GZIP; int vargv = 0; //added by Chen-I image_header_t header; image_header_t *hdr = &header; TAIL tail_pre; int main (int argc, char **argv) { int ifd; int i; uint32_t checksum; uint32_t addr; uint32_t ep; uint32_t rfs_offset=0; struct stat sbuf; unsigned char *ptr; char *name = ""; memset(&tail_pre, 0, sizeof(tail_pre)); cmdname = *argv; addr = ep = 0; while (--argc > 0 && **++argv == '-') { while (*++*argv) { switch (**argv) { case 'l': lflag = 1; break; case 'A': if ((--argc <= 0) || (opt_arch = get_arch(*++argv)) < 0) usage (); goto NXTARG; case 'C': if ((--argc <= 0) || (opt_comp = get_comp(*++argv)) < 0) usage (); goto NXTARG; case 'O': if ((--argc <= 0) || (opt_os = get_os(*++argv)) < 0) usage (); goto NXTARG; case 'T': if ((--argc <= 0) || (opt_type = get_type(*++argv)) < 0) usage (); goto NXTARG; case 'a': if (--argc <= 0) usage (); addr = strtoul (*++argv, (char **)&ptr, 16); if (*ptr) { fprintf (stderr, "%s: invalid load address %s\n", cmdname, *argv); exit (EXIT_FAILURE); } goto NXTARG; case 'd': if (--argc <= 0) usage (); datafile = *++argv; dflag = 1; goto NXTARG; case 'e': if (--argc <= 0) usage (); ep = strtoul (*++argv, (char **)&ptr, 16); if (*ptr) { fprintf (stderr, "%s: invalid entry point %s\n", cmdname, *argv); exit (EXIT_FAILURE); } eflag = 1; goto NXTARG; case 'r': if (--argc <= 0) usage (); rfs_offset = (uint32_t)strtoul(*++argv, NULL, 0); goto NXTARG; case 'n': if (--argc <= 0) usage (); name = *++argv; goto NXTARG; case 'V': if ((argc-=10) < 0) usage (); sscanf(argv[1], "%d.%d", &tail_pre.kernel.major, &tail_pre.kernel.minor); sscanf(argv[2], "%d.%d", &tail_pre.fs.major, &tail_pre.fs.minor); for(i=0; i<(MAX_VER*2); i++) sscanf(argv[i+3], "%d.%d", &tail_pre.hw[i].major, &tail_pre.hw[i].minor); argv+=10; vargv=1; goto NXTARG; case 'v': vflag++; break; case 'x': xflag++; break; default: usage (); } } NXTARG: ; } if ((argc != 1) || ((lflag ^ dflag) == 0)) usage(); if (!eflag) { ep = addr; /* If XIP, entry point must be after the U-Boot header */ if (xflag) ep += sizeof(image_header_t); } /* * If XIP, ensure the entry point is equal to the load address plus * the size of the U-Boot header. */ if (xflag) { if (ep != addr + sizeof(image_header_t)) { fprintf (stderr, "%s: For XIP, the entry point must be the load addr + %lu\n", cmdname, (unsigned long)sizeof(image_header_t)); exit (EXIT_FAILURE); } } imagefile = *argv; fprintf(stderr, "img file: %s\n", imagefile); if (lflag) { ifd = open(imagefile, O_RDONLY|O_BINARY); } else { ifd = open(imagefile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, 0666); } if (ifd < 0) { fprintf (stderr, "%s: Can't open %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (lflag) { int len; char *data; /* * list header information of existing image */ if (fstat(ifd, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } if ((unsigned)sbuf.st_size < sizeof(image_header_t)) { fprintf (stderr, "%s: Bad size: \"%s\" is no valid image\n", cmdname, imagefile); exit (EXIT_FAILURE); } ptr = (unsigned char *)mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, ifd, 0); if ((caddr_t)ptr == (caddr_t)-1) { fprintf (stderr, "%s: Can't read %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } /* * create copy of header so that we can blank out the * checksum field for checking - this can't be done * on the PROT_READ mapped data. */ memcpy (hdr, ptr, sizeof(image_header_t)); if (ntohl(hdr->ih_magic) != IH_MAGIC) { fprintf (stderr, "%s: Bad Magic Number: \"%s\" is no valid image\n", cmdname, imagefile); exit (EXIT_FAILURE); } data = (char *)hdr; len = sizeof(image_header_t); checksum = ntohl(hdr->ih_hcrc); hdr->ih_hcrc = htonl(0); /* clear for re-calculation */ if (crc32 (0, data, len) != checksum) { fprintf (stderr, "*** Warning: \"%s\" has bad header checksum!\n", imagefile); } data = (char *)(ptr + sizeof(image_header_t)); len = sbuf.st_size - sizeof(image_header_t) ; if (crc32 (0, data, len) != ntohl(hdr->ih_dcrc)) { fprintf (stderr, "*** Warning: \"%s\" has corrupted data!\n", imagefile); } /* for multi-file images we need the data part, too */ print_header ((image_header_t *)ptr); (void) munmap((void *)ptr, sbuf.st_size); (void) close (ifd); exit (EXIT_SUCCESS); } /* * Must be -w then: * * write dummy header, to be fixed later */ memset (hdr, 0, sizeof(image_header_t)); if (write(ifd, hdr, sizeof(image_header_t)) != sizeof(image_header_t)) { fprintf (stderr, "%s: Write error on %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (opt_type == IH_TYPE_MULTI || opt_type == IH_TYPE_SCRIPT) { char *file = datafile; unsigned long size; for (;;) { char *sep = NULL; if (file) { if ((sep = strchr(file, ':')) != NULL) { *sep = '\0'; } if (stat (file, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", cmdname, file, strerror(errno)); exit (EXIT_FAILURE); } size = htonl(sbuf.st_size); } else { size = 0; } if (write(ifd, (char *)&size, sizeof(size)) != sizeof(size)) { fprintf (stderr, "%s: Write error on %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (!file) { break; } if (sep) { *sep = ':'; file = sep + 1; } else { file = NULL; } } file = datafile; for (;;) { char *sep = strchr(file, ':'); if (sep) { *sep = '\0'; copy_file (ifd, file, 1); *sep++ = ':'; file = sep; } else { copy_file (ifd, file, 0); break; } } } else { copy_file (ifd, datafile, 0); } /* We're a bit of paranoid */ #if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__) (void) fdatasync (ifd); #else (void) fsync (ifd); #endif if (fstat(ifd, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } ptr = (unsigned char *)mmap(0, sbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, ifd, 0); if (ptr == (unsigned char *)MAP_FAILED) { fprintf (stderr, "%s: Can't map %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } hdr = (image_header_t *)ptr; checksum = crc32 (0, (const char *)(ptr + sizeof(image_header_t)), sbuf.st_size - sizeof(image_header_t) ); /* Build new header */ hdr->ih_magic = htonl(IH_MAGIC); hdr->ih_time = htonl(sbuf.st_mtime); hdr->ih_size = htonl(sbuf.st_size - sizeof(image_header_t)); hdr->ih_load = htonl(addr); hdr->ih_ep = htonl(ep); hdr->ih_dcrc = htonl(checksum); hdr->ih_os = opt_os; hdr->ih_arch = opt_arch; hdr->ih_type = opt_type; hdr->ih_comp = opt_comp; if(vargv==0) { strncpy((char *)hdr->u.ih_name, name, IH_NMLEN); } else { strncpy((char *)tail_pre.productid, name, MAX_STRING); memcpy(&hdr->u.tail, &tail_pre, sizeof(TAIL)); if (rfs_offset) { version_t *v1 = &hdr->u.tail.hw[MAX_VER*2 - 2], *v2 = v1+1; union { uint32_t rfs_offset_net_endian; uint8_t p[4]; } u; u.rfs_offset_net_endian = htonl(rfs_offset); if (v1->major || v1->minor || v2->major || v2->minor) printf("Hardware Compatible List: %d.%d and %d.%d " "are override by rootfilesystem offset.\n", v1->major, v1->minor, v2->major, v2->minor); v1->major = ROOTFS_OFFSET_MAGIC; v1->minor = u.p[1]; v2->major = u.p[2]; v2->minor = u.p[3]; } } checksum = crc32(0,(const char *)hdr,sizeof(image_header_t)); hdr->ih_hcrc = htonl(checksum); print_header (hdr); (void) munmap((void *)ptr, sbuf.st_size); /* We're a bit of paranoid */ #if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__) (void) fdatasync (ifd); #else (void) fsync (ifd); #endif if (close(ifd)) { fprintf (stderr, "%s: Write error on %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } exit (EXIT_SUCCESS); } static void copy_file (int ifd, const char *datafile, int pad) { int dfd; struct stat sbuf; unsigned char *ptr; int tail; int zero = 0; int offset = 0; int size; if (vflag) { fprintf (stderr, "Adding Image %s\n", datafile); } if ((dfd = open(datafile, O_RDONLY|O_BINARY)) < 0) { fprintf (stderr, "%s: Can't open %s: %s\n", cmdname, datafile, strerror(errno)); exit (EXIT_FAILURE); } if (fstat(dfd, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", cmdname, datafile, strerror(errno)); exit (EXIT_FAILURE); } ptr = (unsigned char *)mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0); if (ptr == (unsigned char *)MAP_FAILED) { fprintf (stderr, "%s: Can't read %s: %s\n", cmdname, datafile, strerror(errno)); exit (EXIT_FAILURE); } if (xflag) { unsigned char *p = NULL; /* * XIP: do not append the image_header_t at the * beginning of the file, but consume the space * reserved for it. */ if ((unsigned)sbuf.st_size < sizeof(image_header_t)) { fprintf (stderr, "%s: Bad size: \"%s\" is too small for XIP\n", cmdname, datafile); exit (EXIT_FAILURE); } for (p=ptr; p < ptr+sizeof(image_header_t); p++) { if ( *p != 0xff ) { fprintf (stderr, "%s: Bad file: \"%s\" has invalid buffer for XIP\n", cmdname, datafile); exit (EXIT_FAILURE); } } offset = sizeof(image_header_t); } size = sbuf.st_size - offset; if (write(ifd, ptr + offset, size) != size) { fprintf (stderr, "%s: Write error on %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (pad && ((tail = size % 4) != 0)) { if (write(ifd, (char *)&zero, 4-tail) != 4-tail) { fprintf (stderr, "%s: Write error on %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } } (void) munmap((void *)ptr, sbuf.st_size); (void) close (dfd); } void usage () { fprintf (stderr, "Usage: %s -l image\n" " -l ==> list image header information\n" " %s [-x] -A arch -O os -T type -C comp " "-a addr -e ep -n name -d data_file[:data_file...] image\n", cmdname, cmdname); fprintf (stderr, " -A ==> set architecture to 'arch'\n" " -O ==> set operating system to 'os'\n" " -T ==> set image type to 'type'\n" " -C ==> set compression type 'comp'\n" " -a ==> set load address to 'addr' (hex)\n" " -e ==> set entry point to 'ep' (hex)\n" " -n ==> set image name to 'name'\n" " -d ==> use image data from 'datafile'\n" " -x ==> set XIP (execute in place)\n" ); exit (EXIT_FAILURE); } static void print_header (image_header_t *hdr) { time_t timestamp; uint32_t size; int i; uint32_t rfs_offset; timestamp = (time_t)ntohl(hdr->ih_time); size = ntohl(hdr->ih_size); if(vargv==0) { printf ("Image Name: %.*s\n", IH_NMLEN, hdr->u.ih_name); } else { printf ("Product ID: %.*s\n", MAX_STRING, hdr->u.tail.productid); } printf ("Created: %s", ctime(&timestamp)); printf ("Image Type: "); print_type(hdr); printf ("Data Size: %d Bytes = %.2f kB = %.2f MB\n", size, (double)size / 1.024e3, (double)size / 1.048576e6 ); printf ("Load Address: 0x%08X\n", ntohl(hdr->ih_load)); printf ("Entry Point: 0x%08X\n", ntohl(hdr->ih_ep)); if(vargv==1) { version_t *hw = &(hdr->u.tail.hw[0]); union { uint32_t rfs_offset_net_endian; uint8_t p[4]; } u; rfs_offset = u.rfs_offset_net_endian = 0; printf ("Kernel Ver.: %d.%d\n", hdr->u.tail.kernel.major, hdr->u.tail.kernel.minor); printf ("FS Ver: %d.%d\n", hdr->u.tail.fs.major, hdr->u.tail.fs.minor); printf ("Hardware Compatible List:\n"); for(i=0; i<(MAX_VER*2); i++, hw++) { if (hw->major == ROOTFS_OFFSET_MAGIC) { u.p[1] = hw->minor; hw++; i++; u.p[2] = hw->major; u.p[3] = hw->minor; rfs_offset = ntohl(u.rfs_offset_net_endian); } else { printf(" %d: %d.%d\n", i+1, hw->major, hw->minor); } } printf ("Rootfilesystem offset: 0x%08X\n", rfs_offset); } if (hdr->ih_type == IH_TYPE_MULTI || hdr->ih_type == IH_TYPE_SCRIPT) { int i, ptrs; uint32_t pos; unsigned long *len_ptr = (unsigned long *) ( (unsigned long)hdr + sizeof(image_header_t) ); /* determine number of images first (to calculate image offsets) */ for (i=0; len_ptr[i]; ++i) /* null pointer terminates list */ ; ptrs = i; /* null pointer terminates list */ pos = sizeof(image_header_t) + ptrs * sizeof(long); printf ("Contents:\n"); for (i=0; len_ptr[i]; ++i) { size = ntohl(len_ptr[i]); printf (" Image %d: %8d Bytes = %4d kB = %d MB\n", i, size, size>>10, size>>20); if (hdr->ih_type == IH_TYPE_SCRIPT && i > 0) { /* * the user may need to know offsets * if planning to do something with * multiple files */ printf (" Offset = %08X\n", pos); } /* copy_file() will pad the first files to even word align */ size += 3; size &= ~3; pos += size; } } } static void print_type (image_header_t *hdr) { printf ("%s %s %s (%s)\n", put_arch (hdr->ih_arch), put_os (hdr->ih_os ), put_type (hdr->ih_type), put_comp (hdr->ih_comp) ); } static char *put_arch (int arch) { return (put_table_entry(arch_name, "Unknown Architecture", arch)); } static char *put_os (int os) { return (put_table_entry(os_name, "Unknown OS", os)); } static char *put_type (int type) { return (put_table_entry(type_name, "Unknown Image", type)); } static char *put_comp (int comp) { return (put_table_entry(comp_name, "Unknown Compression", comp)); } static char *put_table_entry (table_entry_t *table, char *msg, int type) { for (; table->val>=0; ++table) { if (table->val == type) return (table->lname); } return (msg); } static int get_arch(char *name) { return (get_table_entry(arch_name, "CPU", name)); } static int get_comp(char *name) { return (get_table_entry(comp_name, "Compression", name)); } static int get_os (char *name) { return (get_table_entry(os_name, "OS", name)); } static int get_type(char *name) { return (get_table_entry(type_name, "Image", name)); } static int get_table_entry (table_entry_t *table, char *msg, char *name) { table_entry_t *t; int first = 1; for (t=table; t->val>=0; ++t) { if (t->sname && strcasecmp(t->sname, name)==0) return (t->val); } fprintf (stderr, "\nInvalid %s Type - valid names are", msg); for (t=table; t->val>=0; ++t) { if (t->sname == NULL) continue; fprintf (stderr, "%c %s", (first) ? ':' : ',', t->sname); first = 0; } fprintf (stderr, "\n"); return (-1); }
pigworlds/asuswrttest
release/src-ra/asustools/mkimage.src/mkimage.c
C
gpl-2.0
21,126
<?php use \ParagonIE\ConstantTime\Base64; class Base64Test extends PHPUnit_Framework_TestCase { /** * @covers Base64::encode() * @covers Base64::decode() */ public function testRandom() { for ($i = 1; $i < 32; ++$i) { for ($j = 0; $j < 50; ++$j) { $random = \random_bytes($i); $enc = Base64::encode($random); $this->assertSame( $random, Base64::decode($enc) ); $this->assertSame( \base64_encode($random), $enc ); $unpadded = \rtrim($enc, '='); $this->assertSame( $random, Base64::decode($unpadded, false) ); $extra_pad = $enc . '======='; $this->assertSame( $random, Base64::decode($extra_pad, false) ); } } $str = 'MIIFzzCCBLegAwIBAgIDAfdlMA0GCSqGSIb3DQEBBQUAMHMxCzAJBgNVBAYTAlBM' . 'MSgwJgYDVQQKDB9LcmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMSQwIgYDVQQ' . 'DDBtDT1BFIFNaQUZJUiAtIEt3YWxpZmlrb3dhbnkxFDASBgNVBAUTC05yIHdwaXN1Oi' . 'A2MB4XDTExMTEwOTA2MDAwMFoXDTEzMTEwOTA2MDAwMFowgdkxCzAJBgNVBAYTAlBMM' . 'RwwGgYDVQQKDBNVcnrEhWQgTWlhc3RhIEdkeW5pMRswGQYDVQQFExJQRVNFTDogNjEw' . 'NjA2MDMxMTgxGTAXBgNVBAMMEEplcnp5IFByemV3b3Jza2kxTzBNBgNVBBAwRgwiQWw' . 'uIE1hcnN6YcWCa2EgUGnFgnN1ZHNraWVnbyA1Mi81NAwNODEtMzgyIEdkeW5pYQwGUG' . '9sc2thDAlwb21vcnNraWUxDjAMBgNVBCoMBUplcnp5MRMwEQYDVQQEDApQcnpld29yc' . '2tpMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMm5vjGqHPthJCMqKpqssSISRo' . 's0PYDTcEQzyyurfX67EJWKtZj6HNwuDMEGJ02iBNZfjUl7r8dIi28bSKhNlsfycXZKY' . 'RcIjp0+r5RqtR2auo9GQ6veKb61DEAGIqaR+uLLcJVTHCu0w9oXLGbRlGth5eNoj03C' . 'xXVAH2IfhbNwIDAQABo4IChzCCAoMwDAYDVR0TAQH/BAIwADCCAUgGA1UdIAEB/wSCA' . 'TwwggE4MIIBNAYJKoRoAYb3IwEBMIIBJTCB3QYIKwYBBQUHAgIwgdAMgc1EZWtsYXJh' . 'Y2phIHRhIGplc3Qgb8Wbd2lhZGN6ZW5pZW0gd3lkYXdjeSwgxbxlIHRlbiBjZXJ0eWZ' . 'pa2F0IHpvc3RhxYIgd3lkYW55IGpha28gY2VydHlmaWthdCBrd2FsaWZpa293YW55IH' . 'pnb2RuaWUgeiB3eW1hZ2FuaWFtaSB1c3Rhd3kgbyBwb2RwaXNpZSBlbGVrdHJvbmlje' . 'm55bSBvcmF6IHRvd2FyenlzesSFY3ltaSBqZWogcm96cG9yesSFZHplbmlhbWkuMEMG' . 'CCsGAQUFBwIBFjdodHRwOi8vd3d3Lmtpci5jb20ucGwvY2VydHlmaWthY2phX2tsdWN' . '6eS9wb2xpdHlrYS5odG1sMAkGA1UdCQQCMAAwIQYDVR0RBBowGIEWai5wcnpld29yc2' . 'tpQGdkeW5pYS5wbDAOBgNVHQ8BAf8EBAMCBkAwgZ4GA1UdIwSBljCBk4AU3TGldJXip' . 'N4oGS3ZYmnBDMFs8gKhd6R1MHMxCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9LcmFqb3dh' . 'IEl6YmEgUm96bGljemVuaW93YSBTLkEuMSQwIgYDVQQDDBtDT1BFIFNaQUZJUiAtIEt' . '3YWxpZmlrb3dhbnkxFDASBgNVBAUTC05yIHdwaXN1OiA2ggJb9jBIBgNVHR8EQTA/MD' . '2gO6A5hjdodHRwOi8vd3d3Lmtpci5jb20ucGwvY2VydHlmaWthY2phX2tsdWN6eS9DU' . 'kxfT1pLMzIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQBYPIqnAreyeql7/opJjcar/qWZ' . 'y9ruhB2q0lZFsJOhwgMnbQXzp/4vv93YJqcHGAXdHP6EO8FQX47mjo2ZKQmi+cIHJHL' . 'ONdX/3Im+M17V0iNAh7Z1lOSfTRT+iiwe/F8phcEaD5q2RmvYusR7zXZq/cLL0If0hX' . 'oPZ/EHQxjN8pxzxiUx6bJAgturnIMEfRNesxwghdr1dkUjOhGLf3kHVzgM6j3VAM7oF' . 'mMUb5y5s96Bzl10DodWitjOEH0vvnIcsppSxH1C1dCAi0o9f/1y2XuLNhBNHMAyTqpY' . 'PX8Yvav1c+Z50OMaSXHAnTa20zv8UtiHbaAhwlifCelUMj93S'; $str = preg_replace('#[\r\n]#', '', $str); $this->assertSame( Base64::decode($str), \base64_decode($str) ); $str = 'zbhle48rXrbJUdodb6FAQvkj0W/vDhBzt/mZiCTpaJ/zumnG1wCDuEQBoh9P'; $this->assertSame( Base64::decode($str), \base64_decode($str) ); } }
zabbix/zabbix-patches
zabbix-3.0/ZBXNEXT-4640/vendor/paragonie/constant_time_encoding/tests/Base64Test.php
PHP
gpl-2.0
3,883
<?php /** * Abstract class that stablish an structure for all subclasses * Every subclass should copy only one area of WordPress Core * */ if ( ! class_exists( 'Site_Copier' ) ) { abstract class Site_Copier { public function __construct( $source_blog_id, $template = array(), $args, $user_id = 0 ) { // The source blog ID from we are going to copy stuff $this->source_blog_id = $source_blog_id; // The template selected. This is only for New Blog Templates // It does not make sense with Cloner Plugin $this->template = $template; // The user ID that created the new blog $this->user_id = $user_id; // Parse the arguments $this->args = wp_parse_args( $args, $this->get_default_args() ); } /** * Set default arguments for every subclass * * @return Array */ public abstract function get_default_args(); /** * The main method. This will copy all the stuff that the subclass manages of * * @return Mixed Can be a boolean or additional information about what have been done */ public abstract function copy(); } }
BrentPatientsGuide/wrinkles-060115
wp-content/plugins/cloner/copier/class.copier.php
PHP
gpl-2.0
1,269
/* ** Zabbix ** Copyright (C) 2001-2014 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ #include "common.h" #include "log.h" #include "setproctitle.h" #ifdef _WINDOWS char ZABBIX_SERVICE_NAME[ZBX_SERVICE_NAME_LEN] = APPLICATION_NAME; char ZABBIX_EVENT_SOURCE[ZBX_SERVICE_NAME_LEN] = APPLICATION_NAME; int __zbx_stat(const char *path, zbx_stat_t *buf) { int ret, fd; wchar_t *wpath; wpath = zbx_utf8_to_unicode(path); if (-1 == (ret = _wstat64(wpath, buf))) goto out; if (0 != S_ISDIR(buf->st_mode) || 0 != buf->st_size) goto out; /* In the case of symlinks _wstat64 returns zero file size. */ /* Try to work around it by opening the file and using fstat. */ ret = -1; if (-1 != (fd = _wopen(wpath, O_RDONLY))) { ret = _fstat64(fd, buf); _close(fd); } out: zbx_free(wpath); return ret; } #endif /****************************************************************************** * * * Function: get_program_name * * * * Purpose: return program name without path * * * * Parameters: path * * * * Return value: program name without path * * * * Author: Eugene Grigorjev * * * ******************************************************************************/ const char *get_program_name(const char *path) { const char *filename = NULL; for (filename = path; path && *path; path++) { if ('\\' == *path || '/' == *path) filename = path + 1; } return filename; } /****************************************************************************** * * * Function: zbx_timespec * * * * Purpose: Gets the current time. * * * * Author: Alexander Vladishev * * * * Comments: Time in seconds since midnight (00:00:00), * * January 1, 1970, coordinated universal time (UTC). * * * ******************************************************************************/ void zbx_timespec(zbx_timespec_t *ts) { static zbx_timespec_t *last_ts = NULL; static int corr = 0; #ifdef _WINDOWS LARGE_INTEGER tickPerSecond, tick; static int boottime = 0; BOOL rc = FALSE; #else struct timeval tv; int rc = -1; # ifdef HAVE_TIME_CLOCK_GETTIME struct timespec tp; # endif #endif if (NULL == last_ts) last_ts = zbx_calloc(last_ts, 1, sizeof(zbx_timespec_t)); #ifdef _WINDOWS if (TRUE == (rc = QueryPerformanceFrequency(&tickPerSecond))) { if (TRUE == (rc = QueryPerformanceCounter(&tick))) { ts->ns = (int)(1000000000 * (tick.QuadPart % tickPerSecond.QuadPart) / tickPerSecond.QuadPart); tick.QuadPart = tick.QuadPart / tickPerSecond.QuadPart; if (0 == boottime) boottime = (int)(time(NULL) - tick.QuadPart); ts->sec = (int)(tick.QuadPart + boottime); } } if (TRUE != rc) { struct _timeb tb; _ftime(&tb); ts->sec = (int)tb.time; ts->ns = tb.millitm * 1000000; } #else /* not _WINDOWS */ #ifdef HAVE_TIME_CLOCK_GETTIME if (0 == (rc = clock_gettime(CLOCK_REALTIME, &tp))) { ts->sec = (int)tp.tv_sec; ts->ns = (int)tp.tv_nsec; } #endif /* HAVE_TIME_CLOCK_GETTIME */ if (0 != rc && 0 == (rc = gettimeofday(&tv, NULL))) { ts->sec = (int)tv.tv_sec; ts->ns = (int)tv.tv_usec * 1000; } if (0 != rc) { ts->sec = (int)time(NULL); ts->ns = 0; } #endif /* not _WINDOWS */ if (last_ts->ns == ts->ns && last_ts->sec == ts->sec) { ts->ns += ++corr; while (ts->ns >= 1000000000) { ts->sec++; ts->ns -= 1000000000; } } else { last_ts->sec = ts->sec; last_ts->ns = ts->ns; corr = 0; } } /****************************************************************************** * * * Function: zbx_time * * * * Purpose: Gets the current time. * * * * Return value: Time in seconds * * * * Author: Eugene Grigorjev * * * * Comments: Time in seconds since midnight (00:00:00), * * January 1, 1970, coordinated universal time (UTC). * * * ******************************************************************************/ double zbx_time(void) { zbx_timespec_t ts; zbx_timespec(&ts); return (double)ts.sec + 1.0e-9 * (double)ts.ns; } /****************************************************************************** * * * Function: zbx_current_time * * * * Purpose: Gets the current time including UTC offset * * * * Return value: Time in seconds * * * * Author: Eugene Grigorjev * * * ******************************************************************************/ double zbx_current_time(void) { return zbx_time() + ZBX_JAN_1970_IN_SEC; } /****************************************************************************** * * * Function: zbx_calloc2 * * * * Purpose: allocates nmemb * size bytes of memory and fills it with zeros * * * * Return value: returns a pointer to the newly allocated memory * * * * Author: Eugene Grigorjev, Rudolfs Kreicbergs * * * ******************************************************************************/ void *zbx_calloc2(const char *filename, int line, void *old, size_t nmemb, size_t size) { int max_attempts; void *ptr = NULL; /* old pointer must be NULL */ if (NULL != old) { zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] zbx_calloc: allocating already allocated memory. " "Please report this to Zabbix developers.", filename, line); } for ( max_attempts = 10, nmemb = MAX(nmemb, 1), size = MAX(size, 1); 0 < max_attempts && NULL == ptr; ptr = calloc(nmemb, size), max_attempts-- ); if (NULL != ptr) return ptr; zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] zbx_calloc: out of memory. Requested " ZBX_FS_SIZE_T " bytes.", filename, line, (zbx_fs_size_t)size); exit(EXIT_FAILURE); } /****************************************************************************** * * * Function: zbx_malloc2 * * * * Purpose: allocates size bytes of memory * * * * Return value: returns a pointer to the newly allocated memory * * * * Author: Eugene Grigorjev * * * ******************************************************************************/ void *zbx_malloc2(const char *filename, int line, void *old, size_t size) { int max_attempts; void *ptr = NULL; /* old pointer must be NULL */ if (NULL != old) { zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] zbx_malloc: allocating already allocated memory. " "Please report this to Zabbix developers.", filename, line); } for ( max_attempts = 10, size = MAX(size, 1); 0 < max_attempts && NULL == ptr; ptr = malloc(size), max_attempts-- ); if (NULL != ptr) return ptr; zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] zbx_malloc: out of memory. Requested " ZBX_FS_SIZE_T " bytes.", filename, line, (zbx_fs_size_t)size); exit(EXIT_FAILURE); } /****************************************************************************** * * * Function: zbx_realloc2 * * * * Purpose: changes the size of the memory block pointed to by old * * to size bytes * * * * Return value: returns a pointer to the newly allocated memory * * * * Author: Eugene Grigorjev * * * ******************************************************************************/ void *zbx_realloc2(const char *filename, int line, void *old, size_t size) { int max_attempts; void *ptr = NULL; for ( max_attempts = 10, size = MAX(size, 1); 0 < max_attempts && NULL == ptr; ptr = realloc(old, size), max_attempts-- ); if (NULL != ptr) return ptr; zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] zbx_realloc: out of memory. Requested " ZBX_FS_SIZE_T " bytes.", filename, line, (zbx_fs_size_t)size); exit(EXIT_FAILURE); } char *zbx_strdup2(const char *filename, int line, char *old, const char *str) { int retry; char *ptr = NULL; zbx_free(old); for (retry = 10; 0 < retry && NULL == ptr; ptr = strdup(str), retry--) ; if (NULL != ptr) return ptr; zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] zbx_strdup: out of memory. Requested " ZBX_FS_SIZE_T " bytes.", filename, line, (zbx_fs_size_t)(strlen(str) + 1)); exit(EXIT_FAILURE); } /****************************************************************************** * * * Function: zbx_setproctitle * * * * Purpose: set process title * * * * Author: Eugene Grigorjev * * * ******************************************************************************/ void __zbx_zbx_setproctitle(const char *fmt, ...) { #if defined(HAVE_FUNCTION_SETPROCTITLE) || defined(PS_OVERWRITE_ARGV) || defined(PS_PSTAT_ARGV) char title[MAX_STRING_LEN]; va_list args; va_start(args, fmt); zbx_vsnprintf(title, sizeof(title), fmt, args); va_end(args); zabbix_log(LOG_LEVEL_DEBUG, "%s", title); #endif #if defined(HAVE_FUNCTION_SETPROCTITLE) setproctitle(title); #elif defined(PS_OVERWRITE_ARGV) || defined(PS_PSTAT_ARGV) setproctitle_set_status(title); #endif } /****************************************************************************** * * * Function: check_time_period * * * * Purpose: check if current time is within given period * * * * Parameters: period - time period in format [d1-d2,hh:mm-hh:mm]* * * now - timestamp for comparison * * if NULL - use current timestamp. * * * * Return value: FAIL - out of period, SUCCEED - within the period * * * * Author: Alexei Vladishev * * * * Comments: !!! Don't forget to sync code with PHP !!! * * * ******************************************************************************/ int check_time_period(const char *period, time_t now) { const char *__function_name = "check_time_period"; const char *s, *delim; int d1, d2, h1, h2, m1, m2, flag, day, sec, sec1, sec2, ret = FAIL; struct tm *tm; zabbix_log(LOG_LEVEL_DEBUG, "In %s() period:'%s'", __function_name, period); if (now == (time_t)NULL) now = time(NULL); tm = localtime(&now); day = 0 == tm->tm_wday ? 7 : tm->tm_wday; sec = SEC_PER_HOUR * tm->tm_hour + SEC_PER_MIN * tm->tm_min + tm->tm_sec; zabbix_log(LOG_LEVEL_DEBUG, "%d,%d:%d", day, (int)tm->tm_hour, (int)tm->tm_min); for (s = period; '\0' != *s;) { delim = strchr(s, ';'); zabbix_log(LOG_LEVEL_DEBUG, "period [%s]", s); flag = (6 == sscanf(s, "%d-%d,%d:%d-%d:%d", &d1, &d2, &h1, &m1, &h2, &m2)); if (0 == flag) { flag = (5 == sscanf(s, "%d,%d:%d-%d:%d", &d1, &h1, &m1, &h2, &m2)); d2 = d1; } if (0 != flag) { zabbix_log(LOG_LEVEL_DEBUG, "%d-%d,%d:%d-%d:%d", d1, d2, h1, m1, h2, m2); sec1 = SEC_PER_HOUR * h1 + SEC_PER_MIN * m1; sec2 = SEC_PER_HOUR * h2 + SEC_PER_MIN * m2; /* do not include upper bound */ if (d1 <= day && day <= d2 && sec1 <= sec && sec < sec2) { ret = SUCCEED; break; } } else zabbix_log(LOG_LEVEL_ERR, "wrong time period format [%s]", period); if (NULL != delim) s = delim + 1; else break; } zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret)); return ret; } /****************************************************************************** * * * Function: get_current_delay * * * * Purpose: return delay value that is currently applicable * * * * Parameters: delay - [IN] default delay value, can be overridden * * flex_intervals - [IN] descriptions of flexible intervals * * in the form [dd/d1-d2,hh:mm-hh:mm;] * * now - [IN] current time * * * * Return value: delay value - either default or minimum delay value * * out of all applicable intervals * * * * Author: Alexei Vladishev, Alexander Vladishev, Aleksandrs Saveljevs * * * ******************************************************************************/ static int get_current_delay(int delay, const char *flex_intervals, time_t now) { const char *s, *delim; char flex_period[30]; int flex_delay, current_delay = -1; if (NULL == flex_intervals || '\0' == *flex_intervals) return delay; for (s = flex_intervals; '\0' != *s; s = delim + 1) { delim = strchr(s, ';'); zabbix_log(LOG_LEVEL_DEBUG, "delay period [%s]", s); if (2 == sscanf(s, "%d/%29[^;]s", &flex_delay, flex_period)) { zabbix_log(LOG_LEVEL_DEBUG, "%d sec at %s", flex_delay, flex_period); if ((-1 == current_delay || flex_delay < current_delay) && SUCCEED == check_time_period(flex_period, now)) { current_delay = flex_delay; } } else zabbix_log(LOG_LEVEL_ERR, "wrong delay period format [%s]", s); if (NULL == delim) break; } if (-1 == current_delay) return delay; return current_delay; } /****************************************************************************** * * * Function: get_next_delay_interval * * * * Purpose: return time when next delay settings take effect * * * * Parameters: flex_intervals - [IN] descriptions of flexible intervals * * in the form [dd/d1-d2,hh:mm-hh:mm;] * * now = [IN] current time * * next_interval = [OUT] start of next delay interval * * * * Return value: SUCCEED - there is a next interval * * FAIL - otherwise (in this case, next_interval is unaffected) * * * * Author: Alexei Vladishev, Alexander Vladishev, Aleksandrs Saveljevs * * * ******************************************************************************/ static int get_next_delay_interval(const char *flex_intervals, time_t now, time_t *next_interval) { const char *s, *delim; struct tm *tm; int day, sec, sec1, sec2, delay, d1, d2, h1, h2, m1, m2, flag; time_t next = 0; if (NULL == flex_intervals || '\0' == *flex_intervals) return FAIL; tm = localtime(&now); day = 0 == tm->tm_wday ? 7 : tm->tm_wday; sec = SEC_PER_HOUR * tm->tm_hour + SEC_PER_MIN * tm->tm_min + tm->tm_sec; for (s = flex_intervals; '\0' != *s;) { delim = strchr(s, ';'); zabbix_log(LOG_LEVEL_DEBUG, "delay period [%s]", s); flag = (7 == sscanf(s, "%d/%d-%d,%d:%d-%d:%d", &delay, &d1, &d2, &h1, &m1, &h2, &m2)); if (0 == flag) { flag = (6 == sscanf(s, "%d/%d,%d:%d-%d:%d", &delay, &d1, &h1, &m1, &h2, &m2)); d2 = d1; } if (0 != flag) { zabbix_log(LOG_LEVEL_DEBUG, "%d/%d-%d,%d:%d-%d:%d", delay, d1, d2, h1, m1, h2, m2); sec1 = SEC_PER_HOUR * h1 + SEC_PER_MIN * m1; sec2 = SEC_PER_HOUR * h2 + SEC_PER_MIN * m2; /* do not include upper bound */ if (d1 <= day && day <= d2 && sec1 <= sec && sec < sec2) /* current period */ { if (0 == next || next > now - sec + sec2) next = now - sec + sec2; /* the next second after the */ /* current interval's upper bound */ } else if (d1 <= day && day <= d2 && sec < sec1) /* will be active today */ { if (0 == next || next > now - sec + sec1) next = now - sec + sec1; } else { int next_day; next_day = (7 >= day + 1 ? day + 1 : 1); if (d1 <= next_day && next_day <= d2) /* will be active tomorrow */ { if (0 == next || next > now - sec + SEC_PER_DAY + sec1) next = now - sec + SEC_PER_DAY + sec1; } else /* later in the future */ { int day_diff = -1; if (day < d1) day_diff = d1 - day; if (day >= d2) day_diff = (d1 + 7) - day; if (d1 <= day && day < d2) { /* should never happen */ zabbix_log(LOG_LEVEL_ERR, "could not deduce day difference" " [%s, day=%d, time=%02d:%02d:%02d]", s, day, tm->tm_hour, tm->tm_min, tm->tm_sec); day_diff = -1; } if (-1 != day_diff && (0 == next || next > now - sec + SEC_PER_DAY * day_diff + sec1)) next = now - sec + SEC_PER_DAY * day_diff + sec1; } } } else zabbix_log(LOG_LEVEL_ERR, "wrong delay period format [%s]", s); if (NULL != delim) s = delim + 1; else break; } if (0 != next && NULL != next_interval) *next_interval = next; return 0 != next ? SUCCEED : FAIL; } /****************************************************************************** * * * Function: calculate_item_nextcheck * * * * Purpose: calculate nextcheck timestamp for item * * * * Parameters: seed - [IN] the seed value applied to delay to spread * * item checks over the delay period * * item_type - [IN] the item type * * delay - [IN] default delay value, can be overridden * * flex_intervals - [IN] descriptions of flexible intervals * * in the form [dd/d1-d2,hh:mm-hh:mm;] * * now - [IN] current timestamp * * * * Return value: nextcheck value * * * * Author: Alexei Vladishev, Aleksandrs Saveljevs * * * * Comments: if item check is forbidden with delay=0 (default and flexible), * * a timestamp very far in the future is returned * * * * Old algorithm: now+delay * * New one: preserve period, if delay==5, nextcheck = 0,5,10,15,... * * !!! Don't forget to sync code with PHP !!! * * * ******************************************************************************/ int calculate_item_nextcheck(zbx_uint64_t seed, int item_type, int delay, const char *flex_intervals, time_t now) { int nextcheck = 0; /* special processing of active items to see better view in queue */ if (ITEM_TYPE_ZABBIX_ACTIVE == item_type) { if (0 != delay) nextcheck = (int)now + delay; else nextcheck = ZBX_JAN_2038; } else { int current_delay = 0, try = 0; time_t next_interval, t, tmax; /* Try to find the nearest 'nextcheck' value with condition */ /* 'now' < 'nextcheck' < 'now' + SEC_PER_YEAR. If it is not */ /* possible to check the item within a year, fail. */ t = now; tmax = now + SEC_PER_YEAR; while (t < tmax) { /* calculate 'nextcheck' value for the current interval */ current_delay = get_current_delay(delay, flex_intervals, t); if (0 != current_delay) { nextcheck = current_delay * (int)(t / (time_t)current_delay) + (int)(seed % (zbx_uint64_t)current_delay); if (0 == try) { while (nextcheck <= t) nextcheck += current_delay; } else { while (nextcheck < t) nextcheck += current_delay; } } else nextcheck = ZBX_JAN_2038; /* 'nextcheck' < end of the current interval ? */ /* the end of the current interval is the beginning of the next interval - 1 */ if (FAIL != get_next_delay_interval(flex_intervals, t, &next_interval) && nextcheck >= next_interval) { /* 'nextcheck' is beyond the current interval */ t = next_interval; try++; } else break; /* nextcheck is within the current interval */ } } return nextcheck; } /****************************************************************************** * * * Function: calculate_proxy_nextcheck * * * * Purpose: calculate nextcheck timestamp for passive proxy * * * * Parameters: hostid - [IN] host identificator from database * * delay - [IN] default delay value, can be overridden * * now - [IN] current timestamp * * * * Return value: nextcheck value * * * * Author: Alexander Vladishev * * * ******************************************************************************/ time_t calculate_proxy_nextcheck(zbx_uint64_t hostid, unsigned int delay, time_t now) { time_t nextcheck; nextcheck = delay * (now / delay) + (unsigned int)(hostid % delay); while (nextcheck <= now) nextcheck += delay; return nextcheck; } /****************************************************************************** * * * Function: is_ip4 * * * * Purpose: is string IPv4 address * * * * Parameters: ip - string * * * * Return value: SUCCEED - is IPv4 address * * FAIL - otherwise * * * * Author: Alexei Vladishev, Alexander Vladishev * * * ******************************************************************************/ int is_ip4(const char *ip) { const char *__function_name = "is_ip4"; const char *p = ip; int nums = 0, dots = 0, res = FAIL; zabbix_log(LOG_LEVEL_DEBUG, "In %s() ip:'%s'", __function_name, ip); while ('\0' != *p) { if (0 != isdigit(*p)) { nums++; } else if ('.' == *p) { if (0 == nums || 3 < nums) break; nums = 0; dots++; } else { nums = 0; break; } p++; } if (dots == 3 && 1 <= nums && nums <= 3) res = SUCCEED; zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(res)); return res; } #if defined(HAVE_IPV6) /****************************************************************************** * * * Function: is_ip6 * * * * Purpose: is string IPv6 address * * * * Parameters: ip - string * * * * Return value: SUCCEED - is IPv6 address * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * * Comments: could be improved (not supported x:x:x:x:x:x:d.d.d.d addresses) * * * ******************************************************************************/ int is_ip6(const char *ip) { const char *__function_name = "is_ip6"; const char *p = ip; int nums = 0, is_nums = 0, colons = 0, dcolons = 0, res = FAIL; zabbix_log(LOG_LEVEL_DEBUG, "In %s() ip:'%s'", __function_name, ip); while ('\0' != *p) { if (0 != isxdigit(*p)) { nums++; is_nums = 1; } else if (':' == *p) { if (0 == nums && 0 < colons) dcolons++; if (4 < nums || 1 < dcolons) break; nums = 0; colons++; } else { is_nums = 0; break; } p++; } if (2 <= colons && colons <= 7 && 4 >= nums && 1 == is_nums) res = SUCCEED; zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(res)); return res; } #endif /*HAVE_IPV6*/ /****************************************************************************** * * * Function: is_ip * * * * Purpose: is string IP address * * * * Parameters: ip - string * * * * Return value: SUCCEED - is IP address * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * ******************************************************************************/ int is_ip(const char *ip) { zabbix_log(LOG_LEVEL_DEBUG, "In is_ip() ip:'%s'", ip); if (SUCCEED == is_ip4(ip)) return SUCCEED; #if defined(HAVE_IPV6) if (SUCCEED == is_ip6(ip)) return SUCCEED; #endif return FAIL; } /****************************************************************************** * * * Function: ip6_str2dig * * * * Purpose: convert short ipv6 addresses to the digital type * * * * Parameters: ip - [IN] IPv6 IP address [12fc::2] * * groups - [OUT] 8 groups of 16 bit each * * 2001:0db8:0000:0000:0000:ff00:0042:8329 * * * * Return value: FAIL - invalid IP address, SUCCEED - conversion OK * * * ******************************************************************************/ int ip6_str2dig(const char *ip, unsigned short *groups) { const char *ptr; char buf[5]; int c = 0, dc, pos = 0; size_t ip_len, j, len; for (ptr = strchr(ip, ':'); NULL != ptr; ptr = strchr(ptr + 1, ':')) c++; if (2 > c || c > 7) return FAIL; ip_len = strlen(ip); if ((':' == ip[0] && ':' != ip[1]) || (':' == ip[ip_len - 1] && ':' != ip[ip_len - 2])) return FAIL; memset(groups, 0, sizeof(unsigned short) * 8); dc = 0; /* double colon flag */ len = 0; for (j = 0; j < ip_len; j++) { if (0 != isxdigit(ip[j])) { if (len > 3) return FAIL; buf[len++] = ip[j]; } else if (':' != ip[j]) return FAIL; if (':' == ip[j] || '\0' == ip[j + 1]) { if (0 != len) { buf[len] = '\0'; sscanf(buf, "%hx", &groups[pos]); pos++; len = 0; } if (':' == ip[j + 1]) { if (0 == dc) { dc = 1; pos += (8 - c) + (0 == j); } else return FAIL; } } } return SUCCEED; } #if defined(HAVE_IPV6) /****************************************************************************** * * * Function: ip6_dig2str * * * * Purpose: convert ipv6 addresses to a string * * * * Parameters: groups - [IN] 8 groups of 16 bit each * * ip - [OUT] short IPv6 address [12fc::0] * * ip_len - [IN] ip buffer len * * * * Return value: pointer to result buffer * * * ******************************************************************************/ void ip6_dig2str(unsigned short *groups, char *ip, size_t ip_len) { size_t offset = 0; int i, c = 0, m = 0, idx = -1, idx2 = -1; for (i = 0; i <= 8; i++) { if (i < 8 && groups[i] == 0) { if (idx2 == -1) idx2 = i; c++; } else { if (c != 0 && c > m) { m = c; idx = idx2; } c = 0; idx2 = -1; } } for (i = 0; i < 8; i++) { if (groups[i] != 0 || idx == -1 || i < idx) { offset += zbx_snprintf(ip + offset, ip_len - offset, "%hx", groups[i]); if (i > idx) idx = -1; if (i < 7) offset += zbx_snprintf(ip + offset, ip_len - offset, ":"); } else if (idx == i) { offset += zbx_snprintf(ip + offset, ip_len - offset, ":"); if (idx == 0) offset += zbx_snprintf(ip + offset, ip_len - offset, ":"); } } } /****************************************************************************** * * * Function: ip6_in_list * * * * Purpose: check if ip matches range of ip addresses * * * * Parameters: list - [IN] comma-separated list of ip ranges * * 12fc::2-55,::45,12fc::ff00/120 * * ip - [IN] IPv6 ip address [12fc::2] * * * * Return value: FAIL - out of range, SUCCEED - within the range * * * ******************************************************************************/ static int ip6_in_list(char *list, const char *ip) { unsigned short i[8], j[9], mask; char *start, *comma = NULL, *slash = NULL, *dash = NULL; int ret = FAIL; if (FAIL == ip6_str2dig(ip, i)) return FAIL; for (start = list; '\0' != *start;) { if (NULL != (comma = strchr(start, ','))) *comma = '\0'; if (NULL != (dash = strchr(start, '-'))) *dash = '\0'; else if (NULL != (slash = strchr(start, '/'))) *slash = '\0'; if (FAIL == ip6_str2dig(start, j)) goto next; if (i[0] != j[0] || i[1] != j[1] || i[2] != j[2] || i[3] != j[3] || i[4] != j[4] || i[5] != j[5] || i[6] != j[6]) { goto next; } if (NULL != dash) { if (1 != sscanf(dash + 1, "%hx", &j[8])) goto next; } else if (NULL != slash) { if (1 != sscanf(slash + 1, "%hu", &j[8]) || 112 > j[8] || j[8] > 128) goto next; mask = 0xffff << (128 - j[8]); j[8] = j[7] | ~mask; j[7] = j[7] & mask; } else j[8] = j[7]; if (i[7] >= j[7] && i[7] <= j[8]) { ret = SUCCEED; break; } next: if (NULL != dash) { *dash = '-'; dash = NULL; } else if (NULL != slash) { *slash = '/'; slash = NULL; } if (comma != NULL) { *comma = ','; start = comma + 1; comma = NULL; } else break; } if (dash != NULL) *dash = '-'; else if (slash != NULL) *slash = '/'; if (comma != NULL) *comma = ','; return ret; } #endif /* HAVE_IPV6 */ /****************************************************************************** * * * Function: ip4_str2dig * * * * Purpose: convert short ipv4 addresses to the digital type * * * * Parameters: ip - [IN] IPv4 IP address [192.168.0.1] * * ip_dig - [OUT] 4-byte unsigned integer * * * * Return value: FAIL - invalid IP address, SUCCEED - conversion OK * * * ******************************************************************************/ int ip4_str2dig(const char *ip, unsigned int *ip_dig) { unsigned short i[4]; if (4 != sscanf(ip, "%hu.%hu.%hu.%hu", &i[0], &i[1], &i[2], &i[3])) return FAIL; if (255 < i[0] || 255 < i[1] || 255 < i[2] || 255 < i[3]) return FAIL; *ip_dig = (i[0] << 24) + (i[1] << 16) + (i[2] << 8) + i[3]; return SUCCEED; } /****************************************************************************** * * * Function: ip4_in_list * * * * Purpose: check if ip matches range of ip addresses * * * * Parameters: list - [IN] comma-separated list of ip ranges * * 192.168.0.1-64,192.168.0.128,10.10.0.0/24 * * ip - [IN] IPv4 ip address [192.168.0.1] * * * * Return value: FAIL - out of range, SUCCEED - within the range * * * ******************************************************************************/ static int ip4_in_list(char *list, const char *ip) { unsigned short i; unsigned int mask, ip_dig[2], first, last; char *start = NULL, *comma = NULL, *slash = NULL, *dash = NULL; int ret = FAIL; if (SUCCEED != ip4_str2dig(ip, &ip_dig[0])) return FAIL; for (start = list; '\0' != *start;) { if (NULL != (comma = strchr(start, ','))) *comma = '\0'; if (NULL != (dash = strchr(start, '-'))) *dash = '\0'; else if (NULL != (slash = strchr(start, '/'))) *slash = '\0'; if (SUCCEED != ip4_str2dig(start, &ip_dig[1])) goto next; if (NULL != dash) { if (1 != sscanf(dash + 1, "%hu", &i) || 255 < i) goto next; first = ip_dig[1]; last = (ip_dig[1] & 0xffffff00) + i; } else if (NULL != slash) { if (1 != sscanf(slash + 1, "%hu", &i) || 16 > i || i > 30) goto next; mask = 0xffffffff << (32 - i); first = (ip_dig[1] & mask) + 1; last = (ip_dig[1] | ~mask) - 1; } else { first = ip_dig[1]; last = ip_dig[1]; } if (first <= ip_dig[0] && ip_dig[0] <= last) { ret = SUCCEED; break; } next: if (NULL != dash) { *dash = '-'; dash = NULL; } else if (NULL != slash) { *slash = '/'; slash = NULL; } if (NULL != comma) { *comma = ','; start = comma + 1; comma = NULL; } else break; } if (NULL != dash) *dash = '-'; else if (NULL != slash) *slash = '/'; if (NULL != comma) *comma = ','; return ret; } /****************************************************************************** * * * Function: ip_in_list * * * * Purpose: check if ip matches range of ip addresses * * * * Parameters: ip - [IN] ip address * * list - [IN] comma-separated list of ip ranges * * 192.168.0.1-64,192.168.0.128,10.10.0.0/24,12fc:21 * * * * Return value: FAIL - out of range, SUCCEED - within the range * * * ******************************************************************************/ int ip_in_list(char *list, const char *ip) { const char *__function_name = "ip_in_list"; int ret = FAIL; zabbix_log(LOG_LEVEL_DEBUG, "In %s() list:'%s' ip:'%s'", __function_name, list, ip); ret = ip4_in_list(list, ip); #if defined(HAVE_IPV6) if (SUCCEED != ret) ret = ip6_in_list(list, ip); #endif zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret)); return ret; } /****************************************************************************** * * * Function: int_in_list * * * * Purpose: check if integer matches a list of integers * * * * Parameters: list - integers [i1-i2,i3,i4,i5-i6] (10-25,45,67-699 * * value- value * * * * Return value: FAIL - out of period, SUCCEED - within the period * * * * Author: Alexei Vladishev * * * ******************************************************************************/ int int_in_list(char *list, int value) { const char *__function_name = "int_in_list"; char *start = NULL, *end = NULL, c = '\0'; int i1, i2, ret = FAIL; zabbix_log(LOG_LEVEL_DEBUG, "In %s() list:'%s' value:%d", __function_name, list, value); for (start = list; '\0' != *start;) { if (NULL != (end = strchr(start, ','))) { c = *end; *end = '\0'; } if (2 == sscanf(start, "%d-%d", &i1, &i2)) { if (i1 <= value && value <= i2) { ret = SUCCEED; break; } } else { if (value == atoi(start)) { ret = SUCCEED; break; } } if (NULL != end) { *end = c; start = end + 1; } else break; } if (NULL != end) *end = c; zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret)); return ret; } int zbx_double_compare(double a, double b) { return fabs(a - b) < ZBX_DOUBLE_EPSILON ? SUCCEED : FAIL; } /****************************************************************************** * * * Function: is_double_suffix * * * * Purpose: check if the string is double * * * * Parameters: str - string to check * * * * Return value: SUCCEED - the string is double * * FAIL - otherwise * * * * Author: Alexei Vladishev * * * * Comments: the function automatically processes suffixes K, M, G, T and * * s, m, h, d, w * * * ******************************************************************************/ int is_double_suffix(const char *str) { size_t i; char dot = 0; for (i = 0; '\0' != str[i]; i++) { /* negative number? */ if ('-' == str[i] && 0 == i) continue; if (0 != isdigit(str[i])) continue; if ('.' == str[i] && 0 == dot) { dot = 1; continue; } /* last character is suffix */ if (NULL != strchr("KMGTsmhdw", str[i]) && '\0' == str[i + 1]) continue; return FAIL; } return SUCCEED; } /****************************************************************************** * * * Function: is_double * * * * Purpose: check if the string is double * * * * Parameters: str - string to check * * * * Return value: SUCCEED - the string is double * * FAIL - otherwise * * * * Author: Alexei Vladishev, Aleksandrs Saveljevs * * * ******************************************************************************/ int is_double(const char *str) { int i = 0, digits = 0; while (' ' == str[i]) /* trim left spaces */ i++; if ('-' == str[i] || '+' == str[i]) /* check leading sign */ i++; while (0 != isdigit(str[i])) /* check digits before dot */ { i++; digits = 1; } if ('.' == str[i]) /* check decimal dot */ i++; while (0 != isdigit(str[i])) /* check digits after dot */ { i++; digits = 1; } if (0 == digits) /* 1., .1, and 1.1 are good, just . is not */ return FAIL; if ('e' == str[i] || 'E' == str[i]) /* check exponential part */ { i++; if ('-' == str[i] || '+' == str[i]) /* check exponent sign */ i++; if (0 == isdigit(str[i])) /* check exponent */ return FAIL; while (0 != isdigit(str[i])) i++; } while (' ' == str[i]) /* trim right spaces */ i++; return '\0' == str[i] ? SUCCEED : FAIL; } /****************************************************************************** * * * Function: is_uint_suffix * * * * Purpose: check if the string is unsigned integer * * * * Parameters: str - string to check * * value - a pointer to converted value (optional) * * * * Return value: SUCCEED - the string is unsigned integer * * FAIL - otherwise * * * * Author: Aleksandrs Saveljevs, Vladimir Levijev * * * * Comments: the function automatically processes suffixes s, m, h, d, w * * * ******************************************************************************/ int is_uint_suffix(const char *str, unsigned int *value) { const unsigned int max_uint = ~0U; unsigned int value_uint = 0, c, factor = 1; if ('\0' == *str || '0' > *str || *str > '9') return FAIL; while ('\0' != *str && 0 != isdigit(*str)) { c = (unsigned int)(unsigned char)(*str - '0'); if ((max_uint - c) / 10 < value_uint) return FAIL; /* overflow */ value_uint = value_uint * 10 + c; str++; } if ('\0' != *str) { switch (*str) { case 's': break; case 'm': factor = SEC_PER_MIN; break; case 'h': factor = SEC_PER_HOUR; break; case 'd': factor = SEC_PER_DAY; break; case 'w': factor = SEC_PER_WEEK; break; default: return FAIL; } str++; } if ('\0' != *str) return FAIL; if (max_uint / factor < value_uint) return FAIL; /* overflow */ if (NULL != value) *value = value_uint * factor; return SUCCEED; } #if defined(_WINDOWS) int _wis_uint(const wchar_t *wide_string) { const wchar_t *wide_char = wide_string; if (L'\0' == *wide_char) return FAIL; while (L'\0' != *wide_char) { if (0 != iswdigit(*wide_char)) { wide_char++; continue; } return FAIL; } return SUCCEED; } #endif /****************************************************************************** * * * Function: is_int_prefix * * * * Purpose: check if the beginning of string is a signed integer * * * * Parameters: str - string to check * * * * Return value: SUCCEED - the beginning of string is a signed integer * * FAIL - otherwise * * * * Author: Aleksandrs Saveljevs * * * ******************************************************************************/ int is_int_prefix(const char *str) { size_t i = 0; while (' ' == str[i]) /* trim left spaces */ i++; if ('-' == str[i] || '+' == str[i]) i++; if (0 == isdigit(str[i])) return FAIL; return SUCCEED; } /****************************************************************************** * * * Function: is_uint_n_range * * * * Purpose: check if the string is unsigned integer within the specified * * range and optionally store it into value parameter * * * * Parameters: str - [IN] string to check * * n - [IN] string length or ZBX_MAX_UINT64_LEN * * value - [OUT] a pointer to output buffer where the converted * * value is to be written (optional, can be NULL) * * size - [IN] size of the output buffer (optional) * * min - [IN] the minimum acceptable value * * max - [IN] the maximum acceptable value * * * * Return value: SUCCEED - the string is unsigned integer * * FAIL - the string is not a number or its value is outside * * the specified range * * * * Author: Alexander Vladishev, Andris Zeila * * * ******************************************************************************/ int is_uint_n_range(const char *str, size_t n, void *value, size_t size, zbx_uint64_t min, zbx_uint64_t max) { zbx_uint64_t value_uint64 = 0, c; const zbx_uint64_t max_uint64 = ~(zbx_uint64_t)__UINT64_C(0); int len = 0; if ('\0' == *str || 0 == n || sizeof(zbx_uint64_t) < size || (0 == size && NULL != value)) return FAIL; while ('\0' != *str && 0 < n--) { if (0 == isdigit(*str)) return FAIL; /* not a digit */ c = (zbx_uint64_t)(unsigned char)(*str - '0'); if (20 <= ++len && (max_uint64 - c) / 10 < value_uint64) return FAIL; /* maximum value exceeded */ value_uint64 = value_uint64 * 10 + c; str++; } if (min > value_uint64 || value_uint64 > max) return FAIL; if (NULL != value) { /* On little endian architecture the output value will be stored starting from the first bytes */ /* of 'value' buffer while on big endian architecture it will be stored starting from the last */ /* bytes. We handle it by storing the offset in the most significant byte of short value and */ /* then use the first byte as source offset. */ unsigned short value_offset = (unsigned short)((sizeof(zbx_uint64_t) - size) << 8); memcpy(value, (unsigned char *)&value_uint64 + *((unsigned char *)&value_offset), size); } return SUCCEED; } /****************************************************************************** * * * Function: is_boolean * * * * Purpose: check if the string is boolean * * * * Parameters: str - string to check * * * * Return value: SUCCEED - the string is boolean * * FAIL - otherwise * * * * Author: Aleksandrs Saveljevs * * * * Comments: * * * ******************************************************************************/ int is_boolean(const char *str, zbx_uint64_t *value) { int res; if (SUCCEED == (res = is_double(str))) *value = (0 != atof(str)); else { char tmp[16]; strscpy(tmp, str); zbx_strlower(tmp); if (SUCCEED == (res = str_in_list("true,t,yes,y,on,up,running,enabled,available", tmp, ','))) *value = 1; else if (SUCCEED == (res = str_in_list("false,f,no,n,off,down,unused,disabled,unavailable", tmp, ','))) *value = 0; } return res; } /****************************************************************************** * * * Function: is_uoct * * * * Purpose: check if the string is unsigned octal * * * * Parameters: str - string to check * * * * Return value: SUCCEED - the string is unsigned octal * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * ******************************************************************************/ int is_uoct(const char *str) { int res = FAIL; while (' ' == *str) /* trim left spaces */ str++; for (; '\0' != *str; str++) { if (*str < '0' || *str > '7') break; res = SUCCEED; } while (' ' == *str) /* check right spaces */ str++; if ('\0' != *str) return FAIL; return res; } /****************************************************************************** * * * Function: is_uhex * * * * Purpose: check if the string is unsigned hexadecimal * * * * Parameters: str - string to check * * * * Return value: SUCCEED - the string is unsigned hexadecimal * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * ******************************************************************************/ int is_uhex(const char *str) { int res = FAIL; while (' ' == *str) /* trim left spaces */ str++; for (; '\0' != *str; str++) { if (0 == isxdigit(*str)) break; res = SUCCEED; } while (' ' == *str) /* check right spaces */ str++; if ('\0' != *str) return FAIL; return res; } /****************************************************************************** * * * Function: is_hex_string * * * * Purpose: check if the string is a hexadecimal representation of data in * * the form "F4 CE 46 01 0C 44 8B F4\nA0 2C 29 74 5D 3F 13 49\n" * * * * Parameters: str - string to check * * * * Return value: SUCCEED - the string is formatted like the example above * * FAIL - otherwise * * * * Author: Aleksandrs Saveljevs * * * ******************************************************************************/ int is_hex_string(const char *str) { if ('\0' == *str) return FAIL; while ('\0' != *str) { if (0 == isxdigit(*str)) return FAIL; if (0 == isxdigit(*(str + 1))) return FAIL; if ('\0' == *(str + 2)) break; if (' ' != *(str + 2) && '\n' != *(str + 2)) return FAIL; str += 3; } return SUCCEED; } /****************************************************************************** * * * Function: uint64_in_list * * * * Purpose: check if uin64 integer matches a list of integers * * * * Parameters: list - integers [i1-i2,i3,i4,i5-i6] (10-25,45,67-699) * * value - value * * * * Return value: FAIL - out of period, SUCCEED - within the list * * * * Author: Alexei Vladishev * * * ******************************************************************************/ int uint64_in_list(char *list, zbx_uint64_t value) { const char *__function_name = "uint64_in_list"; char *start = NULL, *end = NULL; zbx_uint64_t i1, i2, tmp_uint64; int ret = FAIL; char c = '\0'; zabbix_log(LOG_LEVEL_DEBUG, "In %s() list:'%s' value:" ZBX_FS_UI64, __function_name, list, value); for (start = list; start[0] != '\0';) { if (NULL != (end = strchr(start, ','))) { c=end[0]; end[0]='\0'; } if (sscanf(start,ZBX_FS_UI64 "-" ZBX_FS_UI64,&i1,&i2) == 2) { if (i1 <= value && value <= i2) { ret = SUCCEED; break; } } else { sscanf(start, ZBX_FS_UI64, &tmp_uint64); if (tmp_uint64 == value) { ret = SUCCEED; break; } } if (end != NULL) { *end = c; start = end + 1; } else break; } if (NULL != end) *end = c; zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret)); return ret; } /****************************************************************************** * * * Function: get_nearestindex * * * * Purpose: get nearest index position of sorted elements in array * * * * Parameters: p - pointer to array of elements * * sz - element size * * num - number of elements * * id - index to look for * * * * Return value: index at which it would be possible to insert the element so * * that the array is still sorted * * * ******************************************************************************/ int get_nearestindex(const void *p, size_t sz, int num, zbx_uint64_t id) { int first_index, last_index, index; zbx_uint64_t element_id; if (0 == num) return 0; first_index = 0; last_index = num - 1; while (1) { index = first_index + (last_index - first_index) / 2; if (id == (element_id = *(const zbx_uint64_t *)((const char *)p + index * sz))) return index; if (last_index == first_index) { if (element_id < id) index++; return index; } if (element_id < id) first_index = index + 1; else last_index = index; } } /****************************************************************************** * * * Function: uint64_array_add * * * * Purpose: add uint64 value to dynamic array * * * * Author: Alexander Vladishev * * * ******************************************************************************/ int uint64_array_add(zbx_uint64_t **values, int *alloc, int *num, zbx_uint64_t value, int alloc_step) { int index; index = get_nearestindex(*values, sizeof(zbx_uint64_t), *num, value); if (index < (*num) && (*values)[index] == value) return index; if (*alloc == *num) { if (0 == alloc_step) { zbx_error("Unable to reallocate buffer"); assert(0); } *alloc += alloc_step; *values = zbx_realloc(*values, *alloc * sizeof(zbx_uint64_t)); } memmove(&(*values)[index + 1], &(*values)[index], sizeof(zbx_uint64_t) * (*num - index)); (*values)[index] = value; (*num)++; return index; } /****************************************************************************** * * * Function: uint64_array_merge * * * * Purpose: merge two uint64 arrays * * * * Author: Alexander Vladishev * * * ******************************************************************************/ void uint64_array_merge(zbx_uint64_t **values, int *alloc, int *num, zbx_uint64_t *value, int value_num, int alloc_step) { int i; for (i = 0; i < value_num; i++) uint64_array_add(values, alloc, num, value[i], alloc_step); } /****************************************************************************** * * * Function: uint64_array_exists * * * * Author: Alexander Vladishev * * * ******************************************************************************/ int uint64_array_exists(const zbx_uint64_t *values, int num, zbx_uint64_t value) { int index; index = get_nearestindex(values, sizeof(zbx_uint64_t), num, value); if (index < num && values[index] == value) return SUCCEED; return FAIL; } /****************************************************************************** * * * Function: uint64_array_remove * * * * Purpose: remove uint64 values from array * * * * Author: Alexander Vladishev * * * ******************************************************************************/ void uint64_array_remove(zbx_uint64_t *values, int *num, const zbx_uint64_t *rm_values, int rm_num) { int rindex, index; for (rindex = 0; rindex < rm_num; rindex++) { index = get_nearestindex(values, sizeof(zbx_uint64_t), *num, rm_values[rindex]); if (index == *num || values[index] != rm_values[rindex]) continue; memmove(&values[index], &values[index + 1], sizeof(zbx_uint64_t) * ((*num) - index - 1)); (*num)--; } } /****************************************************************************** * * * Function: uint64_array_remove_both * * * * Purpose: remove equal values from both arrays * * * * Parameters: * * * * Return value: * * * * Author: Alexander Vladishev * * * * Comments: * * * ******************************************************************************/ void uint64_array_remove_both(zbx_uint64_t *values, int *num, zbx_uint64_t *rm_values, int *rm_num) { int rindex, index; for (rindex = 0; rindex < *rm_num; rindex++) { index = get_nearestindex(values, sizeof(zbx_uint64_t), *num, rm_values[rindex]); if (index == *num || values[index] != rm_values[rindex]) continue; memmove(&values[index], &values[index + 1], sizeof(zbx_uint64_t) * ((*num) - index - 1)); (*num)--; memmove(&rm_values[rindex], &rm_values[rindex + 1], sizeof(zbx_uint64_t) * ((*rm_num) - rindex - 1)); (*rm_num)--; rindex--; } } zbx_uint64_t suffix2factor(char c) { switch (c) { case 'K': return ZBX_KIBIBYTE; case 'M': return ZBX_MEBIBYTE; case 'G': return ZBX_GIBIBYTE; case 'T': return ZBX_TEBIBYTE; case 's': return 1; case 'm': return SEC_PER_MIN; case 'h': return SEC_PER_HOUR; case 'd': return SEC_PER_DAY; case 'w': return SEC_PER_WEEK; default: return 1; } } /****************************************************************************** * * * Function: str2uint64 * * * * Purpose: convert string to 64bit unsigned integer * * * * Parameters: str - string to convert * * value - a pointer to converted value * * * * Return value: SUCCEED - the string is unsigned integer * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * * Comments: the function automatically processes suffixes K, M, G, T * * * ******************************************************************************/ int str2uint64(const char *str, const char *suffixes, zbx_uint64_t *value) { size_t sz; const char *p; int ret; zbx_uint64_t factor = 1; sz = strlen(str); p = str + sz - 1; if (NULL != strchr(suffixes, *p)) { factor = suffix2factor(*p); sz--; } if (SUCCEED == (ret = is_uint64_n(str, sz, value))) *value *= factor; return ret; } /****************************************************************************** * * * Function: str2double * * * * Purpose: convert string to double * * * * Parameters: str - string to convert * * * * Return value: converted double value * * * * Author: Alexei Vladishev * * * * Comments: the function automatically processes suffixes K, M, G, T and * * s, m, h, d, w * * * ******************************************************************************/ double str2double(const char *str) { size_t sz; sz = strlen(str) - 1; return atof(str) * suffix2factor(str[sz]); } /****************************************************************************** * * * Function: is_hostname_char * * * * Return value: SUCCEED - the char is allowed in the host name * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * * Comments: in host name allowed characters: '0-9a-zA-Z. _-' * * !!! Don't forget to sync the code with PHP !!! * * * ******************************************************************************/ int is_hostname_char(char c) { if (0 != isalnum(c)) return SUCCEED; if (c == '.' || c == ' ' || c == '_' || c == '-') return SUCCEED; return FAIL; } /****************************************************************************** * * * Function: is_key_char * * * * Return value: SUCCEED - the char is allowed in the item key * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * * Comments: in key allowed characters: '0-9a-zA-Z._-' * * !!! Don't forget to sync the code with PHP !!! * * * ******************************************************************************/ int is_key_char(char c) { if (0 != isalnum(c)) return SUCCEED; if (c == '.' || c == '_' || c == '-') return SUCCEED; return FAIL; } /****************************************************************************** * * * Function: is_function_char * * * * Return value: SUCCEED - the char is allowed in the trigger function * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * * Comments: in trigger function allowed characters: 'a-z' * * !!! Don't forget to sync the code with PHP !!! * * * ******************************************************************************/ int is_function_char(char c) { if (0 != islower(c)) return SUCCEED; return FAIL; } /****************************************************************************** * * * Function: is_macro_char * * * * Return value: SUCCEED - the char is allowed in the macro name * * FAIL - otherwise * * * * Author: Alexander Vladishev * * * * Comments: allowed characters in macro names: '0-9A-Z._' * * !!! Don't forget to sync the code with PHP !!! * * * ******************************************************************************/ int is_macro_char(char c) { if (0 != isupper(c)) return SUCCEED; if ('.' == c || '_' == c) return SUCCEED; if (0 != isdigit(c)) return SUCCEED; return FAIL; } /****************************************************************************** * * * Function: is_time_function * * * * Return value: SUCCEED - given function is time-based * * FAIL - otherwise * * * * Author: Aleksandrs Saveljevs * * * ******************************************************************************/ int is_time_function(const char *func) { return str_in_list("nodata,date,dayofmonth,dayofweek,time,now", func, ','); } /****************************************************************************** * * * Function: is_snmp_type * * * * Return value: SUCCEED - the given type is one of regular SNMP types * * FAIL - otherwise * * * * Author: Aleksandrs Saveljevs * * * ******************************************************************************/ int is_snmp_type(unsigned char type) { return ITEM_TYPE_SNMPv1 == type || ITEM_TYPE_SNMPv2c == type || ITEM_TYPE_SNMPv3 == type ? SUCCEED : FAIL; } /****************************************************************************** * * * Function: make_hostname * * * * Purpose: replace all not-allowed hostname characters in the string * * * * Parameters: host - the target C-style string * * * * Author: Dmitry Borovikov * * * * Comments: the string must be null-terminated, otherwise not secure! * * * ******************************************************************************/ void make_hostname(char *host) { char *c; assert(host); for (c = host; '\0' != *c; ++c) { if (FAIL == is_hostname_char(*c)) *c = '_'; } } /****************************************************************************** * * * Function: get_interface_type_by_item_type * * * * Purpose: * * * * Parameters: * * * * Return value: Interface type * * * * Author: Alexander Vladishev * * * * Comments: !!! Don't forget to sync the code with PHP !!! * * * ******************************************************************************/ unsigned char get_interface_type_by_item_type(unsigned char type) { switch (type) { case ITEM_TYPE_ZABBIX: return INTERFACE_TYPE_AGENT; case ITEM_TYPE_SNMPv1: case ITEM_TYPE_SNMPv2c: case ITEM_TYPE_SNMPv3: case ITEM_TYPE_SNMPTRAP: return INTERFACE_TYPE_SNMP; case ITEM_TYPE_IPMI: return INTERFACE_TYPE_IPMI; case ITEM_TYPE_JMX: return INTERFACE_TYPE_JMX; case ITEM_TYPE_SIMPLE: case ITEM_TYPE_EXTERNAL: case ITEM_TYPE_SSH: case ITEM_TYPE_TELNET: return INTERFACE_TYPE_ANY; default: return INTERFACE_TYPE_UNKNOWN; } } /****************************************************************************** * * * Function: calculate_sleeptime * * * * Purpose: calculate sleep time for Zabbix processes * * * * Parameters: nextcheck - [IN] next check or -1 (FAIL) if nothing to do * * max_sleeptime - [IN] maximum sleep time, in seconds * * * * Return value: sleep time, in seconds * * * * Author: Alexander Vladishev * * * ******************************************************************************/ int calculate_sleeptime(int nextcheck, int max_sleeptime) { int sleeptime; if (FAIL == nextcheck) return max_sleeptime; sleeptime = nextcheck - (int)time(NULL); if (sleeptime < 0) return 0; if (sleeptime > max_sleeptime) return max_sleeptime; return sleeptime; } /****************************************************************************** * * * Function: parse_serveractive_element * * * * Purpose: parse a ServerActive element like "IP<:port>" or "[IPv6]<:port>" * * * ******************************************************************************/ int parse_serveractive_element(char *str, char **host, unsigned short *port, unsigned short port_default) { #ifdef HAVE_IPV6 char *r1 = NULL; #endif char *r2 = NULL; int res = FAIL; *port = port_default; #ifdef HAVE_IPV6 if ('[' == *str) { str++; if (NULL == (r1 = strchr(str, ']'))) goto fail; if (':' != r1[1] && '\0' != r1[1]) goto fail; if (':' == r1[1] && SUCCEED != is_ushort(r1 + 2, port)) goto fail; *r1 = '\0'; if (SUCCEED != is_ip6(str)) goto fail; *host = zbx_strdup(*host, str); } else if (SUCCEED == is_ip6(str)) { *host = zbx_strdup(*host, str); } else { #endif if (NULL != (r2 = strchr(str, ':'))) { if (SUCCEED != is_ushort(r2 + 1, port)) goto fail; *r2 = '\0'; } *host = zbx_strdup(NULL, str); #ifdef HAVE_IPV6 } #endif res = SUCCEED; fail: #ifdef HAVE_IPV6 if (NULL != r1) *r1 = ']'; #endif if (NULL != r2) *r2 = ':'; return res; }
lazy404/zabbix
src/libs/zbxcommon/misc.c
C
gpl-2.0
89,146
/***********************************************************************/ /* */ /* Objective Caml */ /* */ /* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ /* */ /* Copyright 1996 Institut National de Recherche en Informatique et */ /* en Automatique. All rights reserved. This file is distributed */ /* under the terms of the GNU Library General Public License, with */ /* the special exception on linking described in file ../../LICENSE. */ /* */ /***********************************************************************/ /* $Id: getgr.c 4144 2001-12-07 13:41:02Z xleroy $ */ #include <mlvalues.h> #include <fail.h> #include <alloc.h> #include <memory.h> #include "unixsupport.h" #include <stdio.h> #include <grp.h> static value alloc_group_entry(struct group *entry) { value res; value name = Val_unit, pass = Val_unit, mem = Val_unit; Begin_roots3 (name, pass, mem); name = copy_string(entry->gr_name); pass = copy_string(entry->gr_passwd); mem = copy_string_array((const char**)entry->gr_mem); res = alloc_small(4, 0); Field(res,0) = name; Field(res,1) = pass; Field(res,2) = Val_int(entry->gr_gid); Field(res,3) = mem; End_roots(); return res; } CAMLprim value unix_getgrnam(value name) { struct group * entry; entry = getgrnam(String_val(name)); if (entry == NULL) raise_not_found(); return alloc_group_entry(entry); } CAMLprim value unix_getgrgid(value gid) { struct group * entry; entry = getgrgid(Int_val(gid)); if (entry == NULL) raise_not_found(); return alloc_group_entry(entry); }
MicroTrustRepos/microkernel
src/l4/pkg/ocaml/contrib/otherlibs/unix/getgr.c
C
gpl-2.0
1,923
<?php /** * @package RSForm! Pro * @copyright (C) 2007-2014 www.rsjoomla.com * @license GPL, http://www.gnu.org/copyleft/gpl.html */ defined('_JEXEC') or die('Restricted access'); class RSFormModelFiles extends JModelLegacy { protected $_folder = null; public function __construct() { parent::__construct(); jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.path'); $this->_folder = JPATH_SITE; $folder = JRequest::getVar('folder'); if (is_dir($folder)) { $folder = rtrim($folder, '\\/'); $this->_folder = $folder; } } public function getFolders() { $return = array(); $folders = JFolder::folders($this->_folder); foreach ($folders as $folder) { $return[] = (object) array( 'name' => $folder, 'fullpath' => $this->_folder . DIRECTORY_SEPARATOR . $folder ); } return $return; } public function getFiles() { $return = array(); $files = JFolder::files($this->_folder); foreach ($files as $file) { $return[] = (object) array( 'name' => $file, 'fullpath' => $this->_folder . DIRECTORY_SEPARATOR . $file ); } return $return; } public function getElements() { $elements = explode(DIRECTORY_SEPARATOR, $this->_folder); $navigation_path = ''; if(!empty($elements)) foreach($elements as $i=>$element) { $navigation_path .= $element; $newelement = new stdClass(); $newelement->name = $element; $newelement->fullpath = $navigation_path; $elements[$i] = $newelement; $navigation_path .= DIRECTORY_SEPARATOR; } return $elements; } public function getCurrent() { return $this->_folder; } public function getPrevious() { $elements = explode(DIRECTORY_SEPARATOR, $this->_folder); if (count($elements) > 1) array_pop($elements); return implode(DIRECTORY_SEPARATOR, $elements); } public function upload() { $files = JRequest::get('files'); $upload = $files['upload']; if (!$files['error']) return JFile::upload($upload['tmp_name'], $this->getCurrent().'/'.JFile::getName($upload['name'])); else return false; } public function getCanUpload() { return is_writable($this->_folder); } public function getUploadFile() { $files = JRequest::get('files'); $upload = $files['upload']; return JFile::getName($upload['name']); } }
jbake11/Briarstone
administrator/components/com_rsform/models/files.php
PHP
gpl-2.0
2,477
/**************************************************************************************** * Copyright (c) 2012 Andrzej J. R. Hunt <andrzej at ahunt.org> * * Copyright (c) Mark Kretschmann <kretschmann@kde.org> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ #include "DiagnosticDialog.h" #include "context/ContextView.h" #include "PluginManager.h" #include "scripting/scriptmanager/ScriptManager.h" #include <KAboutData> #include <KApplication> #include <KGlobal> #include <KPluginInfo> #include <KService> #include <KServiceTypeTrader> #include <Plasma/Applet> #include <phonon/pulsesupport.h> #include <QClipboard> #include <QPlainTextEdit> DiagnosticDialog::DiagnosticDialog( const KAboutData *aboutData, QWidget *parent ) : KDialog( parent ) { if( aboutData == 0 ) aboutData = KGlobal::mainComponent().aboutData(); m_textBox = new QPlainTextEdit( generateReport( aboutData ), this ); setPlainCaption( i18nc( "%1 is the program name", "%1 Diagnostics", aboutData->programName() ) ); setButtons( Close | User1 ); setButtonText( User1, i18n( "Copy to Clipboard" ) ); m_textBox->setReadOnly( true ); setMainWidget( m_textBox ); setInitialSize( QSize( 480, 460 ) ); connect( this, SIGNAL(user1Clicked()), SLOT(slotCopyToClipboard()) ); connect( this, SIGNAL(finished()), SLOT(deleteLater()) ); } const QString DiagnosticDialog::generateReport( const KAboutData *aboutData ) { // Get scripts -- we have to assemble 3 lists into one KPluginInfo::List aScripts; const ScriptManager *aScriptManager = ScriptManager::instance(); aScripts.append( aScriptManager->scripts( QLatin1String( "Generic" ) ) ); aScripts.append( aScriptManager->scripts( QLatin1String( "Lyrics" ) ) ); aScripts.append( aScriptManager->scripts( QLatin1String( "Scriptable Service" ) ) ); // Format the data to be readable QString aScriptString; foreach( KPluginInfo aInfo, aScripts ) { if( aInfo.isPluginEnabled() ) aScriptString += " " + aInfo.name() + " (" + aInfo.version() + ")\n"; } // Get plugins -- we have to assemble a list again. KPluginInfo::List aPlugins; const Plugins::PluginManager *aPluginManager = Plugins::PluginManager::instance(); aPlugins.append( aPluginManager->plugins( QLatin1String( "Collection" ) ) ); aPlugins.append( aPluginManager->plugins( QLatin1String( "Service" ) ) ); QString aPluginString; foreach( KPluginInfo aInfo, aPlugins ) { if( aInfo.isPluginEnabled() ) aPluginString += " " + aInfo.name() + " (" + aInfo.version() + ")\n"; } // Get applets const QStringList appletList = Context::ContextView::self()->currentAppletNames(); QString appletString; foreach( const QString &applet, appletList ) { // Currently we cannot extract the applet version number this way appletString += " " + applet + '\n'; } const KService::Ptr aPhononBackend = KServiceTypeTrader::self()->preferredService( "PhononBackend" ); const bool hasPulse = Phonon::PulseSupport::getInstance()->isActive(); const QString pulse = hasPulse ? i18nc( "Usage", "Yes" ) : i18nc( "Usage", "No" ); return i18n( "%1 Diagnostics\n\nGeneral Information:\n" " %1 Version: %2\n" " KDE Version: %3\n" " Qt Version: %4\n" " Phonon Version: %5\n" " Phonon Backend: %6 (%7)\n" " PulseAudio: %8\n\n", aboutData->programName(), aboutData->version(), // Amarok KDE::versionString(), // KDE qVersion(), // QT Phonon::phononVersion(), // Phonon aPhononBackend.data()->name(), aPhononBackend.data()->property( "X-KDE-PhononBackendInfo-Version", QVariant::String ).toString(), // & Backend pulse // PulseAudio ) + i18n( "Enabled Scripts:\n%1\n" "Enabled Plugins:\n%2\n" "Enabled Applets:\n%3\n", aScriptString, aPluginString, appletString ); } void DiagnosticDialog::slotCopyToClipboard() const { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText( m_textBox->toPlainText() ); }
jailuthra/amarok
src/dialogs/DiagnosticDialog.cpp
C++
gpl-2.0
5,666
<?php /** * @package Ajaxy */ /* Plugin Name: Ajaxy Live Search Plugin URI: http://ajaxy.org Description: Transfer wordpress form into an advanced ajax search form the same as facebook live search, This version supports themes and can work with almost all themes without any modifications Version: 3.0.7 Author: Ajaxy Team Author URI: http://www.ajaxy.org License: GPLv2 or later */ define('AJAXY_SF_VERSION', '3.0.7'); define('AJAXY_SF_PLUGIN_URL', plugin_dir_url( __FILE__ ) ); define('AJAXY_THEMES_DIR', dirname(__FILE__)."/themes/"); define('AJAXY_SF_NO_IMAGE', plugin_dir_url( __FILE__ ) ."themes/default/images/no-image.gif"); require_once('admin/widgets/search.php'); class AjaxyLiveSearch { public static $woocommerce_taxonomies = array('product_cat', 'product_tag', 'product_shipping_class'); public static $woocommerce_post_types = array('product', 'shop_order', 'shop_coupon'); private $noimage = ''; function __construct(){ $this->actions(); $this->filters(); $this->shortcodes(); } function actions(){ //ACTIONS if(class_exists('AJAXY_SF_WIDGET')){ add_action( 'widgets_init', create_function( '', 'return register_widget( "AJAXY_SF_WIDGET" );' ) ); } add_action( 'wp_enqueue_scripts', array(&$this, "enqueue_scripts")); add_action( 'admin_enqueue_scripts', array(&$this, "enqueue_scripts")); add_action( "admin_menu",array(&$this, "menu_pages")); add_action( 'wp_head', array(&$this, 'head')); add_action( 'admin_head', array(&$this, 'head')); add_action( 'wp_footer', array(&$this, 'footer')); add_action( 'admin_footer', array(&$this, 'footer')); add_action( 'wp_ajax_ajaxy_sf', array(&$this, 'get_search_results')); add_action( 'wp_ajax_nopriv_ajaxy_sf', array(&$this, 'get_search_results')); add_action( 'wp_ajax_ajaxy_sf_shortcode', array(&$this, 'get_shortcode')); add_action( 'admin_notices', array(&$this, 'admin_notice') ); add_action( 'plugins_loaded', array(&$this, 'load_textdomain') ); } function filters(){ //FILTERS if($this->get_style_setting( 'hook_search_form', 1 ) > 0) { add_filter( 'get_search_form', array(&$this, 'form_shortcode'), 1); } add_filter( 'ajaxy-overview', array(&$this, 'admin_page'), 10 ); } function shortcodes() { add_shortcode( 'ajaxy-live-search', array(&$this, 'form_shortcode') ); add_shortcode( 'ajaxy-selective-search', array(&$this, 'selective_input_shortcode') ); } function overview(){ echo apply_filters('ajaxy-overview', 'main'); } function load_textdomain() { load_plugin_textdomain( 'ajaxy-sf', false, dirname( plugin_basename( __FILE__ ) ) . '/langs/' ); } function menu_page_exists( $menu_slug ) { global $menu; foreach ( $menu as $i => $item ) { if ( $menu_slug == $item[2] ) { return true; } } return false; } function menu_pages(){ if(!$this->menu_page_exists('ajaxy-page')){ add_menu_page( _n( 'Ajaxy', 'Ajaxy', 1, 'ajaxy' ), _n( 'Ajaxy', 'Ajaxy', 1 ), 'Ajaxy', 'ajaxy-page', array(&$this, 'overview'), AJAXY_SF_PLUGIN_URL.'/images/ico.png'); } add_submenu_page( 'ajaxy-page', __('Live Search'), __('Live Search'), 'manage_options', 'ajaxy_sf_admin', array(&$this, 'admin_page')); } function admin_page(){ $message = false; require_once('admin/classes/class-wp-ajaxy-sf-list-table.php'); require_once('admin/classes/class-wp-ajaxy-sf-themes-list-table.php'); if(isset($_GET['edit'])){ if($_GET['type'] == 'taxonomy'){ include_once('admin/admin-edit-taxonomy-form.php'); return true; }elseif($_GET['type'] == 'role'){ include_once('admin/admin-edit-role-form.php'); return true; }else{ include_once('admin/admin-edit-post-form.php'); return true; } } $tab = (!empty($_GET['tab']) ? trim($_GET['tab']) : false); $type = (!empty($_GET['type']) ? trim($_GET['type']) : false); //form data switch($tab) { case 'woocommerce': case 'taxonomy': case 'author': case 'post_type': case 'templates': $public = ($tab == 'author' ? false : true); if(isset($_POST['action'])){ $action = trim($_POST['action']); $ids = (isset($_POST['template_id']) ? (array)$_POST['template_id'] : false); if($action == 'hide' && $ids){ global $AjaxyLiveSearch; $k = 0; foreach($ids as $id){ $setting = (array)$AjaxyLiveSearch->get_setting($id, $public); $setting['show'] = 0; $AjaxyLiveSearch->set_setting($id, $setting); $k ++; } $message = sprintf(_('%s templates hidden'), $k); } elseif($action == 'show' && $ids){ global $AjaxyLiveSearch; $k = 0; foreach($ids as $id){ $setting = (array)$AjaxyLiveSearch->get_setting($id, $public); $setting['show'] = 1; $AjaxyLiveSearch->set_setting($id, $setting); $k ++; } $message = sprintf(_('%s templates shown'), $k); } } elseif(isset($_GET['show']) && isset($_GET['name'])){ global $AjaxyLiveSearch; if($tab == 'author'){ $setting = (array)$AjaxyLiveSearch->get_setting('role_'.$_GET['name'], $public); $setting['show'] = (int)$_GET['show']; $AjaxyLiveSearch->set_setting('role_'.$_GET['name'], $setting); }else{ $setting = (array)$AjaxyLiveSearch->get_setting($_GET['name'], $public); $setting['show'] = (int)$_GET['show']; $AjaxyLiveSearch->set_setting($_GET['name'], $setting); } $message = _('Template modified'); } break; case 'themes': if(isset($_GET['theme']) && isset($_GET['apply'])){ global $AjaxyLiveSearch; $AjaxyLiveSearch->set_style_setting('theme', $_GET['theme']); $message = $_GET['theme'].' theme applied'; } break; default: } ?> <style type="text/css"> .column-order, .column-limit_results, .column-show_on_search { text-align: center !important; width: 75px; } </style> <div class="wrap"> <div id="icon-edit" class="icon32 icon32-posts-post"><br></div> <h2><?php _e('Ajaxy Live Search'); ?></h2> <ul class="subsubsub"> <li class="active"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false); ?>" class="<?php echo (!$tab ? 'current' : ''); ?>"><?php _e('General settings'); ?><span class="count"></span></a> |</li> <li class="active"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false).'&tab=post_type'; ?>" class="<?php echo ($tab == 'post_type' ? 'current' : ''); ?>"><?php _e('Post type Search'); ?><span class="count"></span></a> |</li> <li class="active"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false).'&tab=taxonomy'; ?>" class="<?php echo ($tab == 'taxonomy' ? 'current' : ''); ?>"><?php _e('Taxonomy Search'); ?><span class="count"></span></a> |</li> <li class="active"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false).'&tab=author'; ?>" class="<?php echo ($tab == 'author' ? 'current' : ''); ?>"><?php _e('Author Search'); ?><span class="count"></span></a> |</li> <li class="active ajaxy-sf-new"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false).'&tab=woocommerce'; ?>" class="<?php echo ($tab == 'woocommerce' ? 'current' : ''); ?>"><?php _e('WooCommerce'); ?><span class="count-new">New *</span></a> |</li> <!--<li class="active ajaxy-sf-new pro"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false).'&tab=selective'; ?>" class="<?php echo ($tab == 'selective' ? 'current' : ''); ?>"><?php _e('Selective Search'); ?><span class="count-new">New *</span></a> |</li>--> <li class="active"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false).'&tab=themes'; ?>" class="<?php echo ($tab == 'themes' ? 'current' : ''); ?>"><?php _e('Themes'); ?><span class="count"></span></a> |</li> <li class="active"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false).'&tab=shortcode'; ?>" class="<?php echo ($tab == 'shortcode' ? 'current' : ''); ?>"><?php _e('Shortcodes'); ?><span class="count"></span></a> |</li> <li class="active"><a href="<?php echo menu_page_url('ajaxy_sf_admin', false).'&tab=preview'; ?>" class="<?php echo ($tab == 'preview' ? 'current' : ''); ?>"><?php _e('Preview'); ?><span class="count"></span></a></li> </ul> <hr style="clear:both; display:block"/> <div id="message-bottom" class="updated"> <table> <tr> <td> <p> <?php printf(__('please donate some dollars for this project development and themes to be created, we are trying to make this project better, if you think it is worth it then u should support it. contact me at %s for support and development, please include your paypal id or donation id in your message.'), '<a href="mailto:icu090@gmail.com">icu090@gmail.com</a>');?> </p> </td> <td> <a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QDDZQHHCPUDDG"><img class="aligncenter size-full wp-image-180" title="btn_donateCC_LG" alt="" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" width="147" height="47"></a> </td> </tr> </table> </div> <form id="ajaxy-form" action="" method="post"> <?php wp_nonce_field(); ?> <?php if($tab == 'post_type'): ?> <?php $list_table = new WP_SF_List_Table($this->get_search_objects(true, 'post_type')); ?> <div> <?php if ( $message ) : ?> <div id="message" class="updated"><p><?php echo $message; ?></p></div> <?php endif; ?> <?php $list_table->display(); ?> </div> <?php elseif($tab == 'taxonomy'): ?> <?php $list_table = new WP_SF_List_Table($this->get_search_objects(true, 'taxonomy')); ?> <div> <?php if ( $message ) : ?> <div id="message" class="updated"><p><?php echo $message; ?></p></div> <?php endif; ?> <?php $list_table->display(); ?> </div> <?php elseif($tab == 'author'): ?> <?php $list_table = new WP_SF_List_Table($this->get_search_objects(true, 'author'), false, 'role_'); ?> <div> <?php if ( $message ) : ?> <div id="message" class="updated"><p><?php echo $message; ?></p></div> <?php endif; ?> <?php $list_table->display(); ?> </div> <?php elseif($tab == 'themes'): ?> <?php $list_table = new WP_SF_THEMES_List_Table(); ?> <div> <?php if ( $message ) : ?> <div id="message" class="updated"><p><?php echo $message; ?></p></div> <?php endif; ?> <?php $list_table->display(); ?> </div> <?php elseif($tab == 'preview'): ?> <br class="clear" /> <hr style="margin-bottom:20px"/> <div class="wrap"> <?php ajaxy_search_form(); ?> </div> <hr style="margin:20px 0 10px 0"/> <p class="description"><?php _e('Use the form above to preview theme changes and settings, please note that the changes could vary from one theme to another, please contact the author of this plugin for more help'); ?></p> <hr style="margin:10px 0"/> <?php elseif($tab == 'selective'): ?> <?php elseif($tab == 'woocommerce'): $list_table = new WP_SF_List_Table($this->get_search_objects(true, 'taxonomy', array(), self::$woocommerce_taxonomies)); ?> <h3><?php _e('WooCommerce Taxonomies'); ?></h3> <div class="ajaxy-form-table ajaxy-form-nowrap"> <?php if ( $message ) : ?> <div id="message" class="updated"><p><?php echo $message; ?></p></div> <?php endif; ?> <?php $list_table->display(); ?> </div> <h3><?php _e('WooCommerce Post Types'); ?></h3> <?php $list_table = new WP_SF_List_Table($this->get_search_objects(true, 'post_type', self::$woocommerce_post_types, array())); ?> <div class="ajaxy-form-table ajaxy-form-nowrap"> <?php if ( $message ) : ?> <div id="message" class="updated"><p><?php echo $message; ?></p></div> <?php endif; ?> <?php $list_table->display(); ?> </div> <?php elseif($tab == 'author'): $list_table = new WP_SF_List_Table($this->get_search_objects(false, 'author'), true, 'role_'); ?> <h3><?php _e('WooCommerce Taxonomies'); ?></h3> <div class="ajaxy-form-table ajaxy-form-nowrap"> <?php if ( $message ) : ?> <div id="message" class="updated"><p><?php echo $message; ?></p></div> <?php endif; ?> <?php $list_table->display(); ?> </div> <h3><?php _e('WooCommerce Post Types'); ?></h3> <?php $list_table = new WP_SF_List_Table($this->get_search_objects(true, 'post_type', self::$woocommerce_post_types, array())); ?> <div class="ajaxy-form-table ajaxy-form-nowrap"> <?php if ( $message ) : ?> <div id="message" class="updated"><p><?php echo $message; ?></p></div> <?php endif; ?> <?php $list_table->display(); ?> </div> <?php elseif($tab == 'shortcode'): include_once('admin/admin-shortcodes.php'); else: include_once('admin/admin-settings.php'); endif; ?> </form> </div> <?php } function get_image_from_content($content, $width_max, $height_max){ //return false; $theImageSrc = false; preg_match_all ('/<img[^>]+>/i', $content, $matches); $imageCount = count ($matches); if ($imageCount >= 1) { if (isset ($matches[0][0])) { preg_match_all('/src=("[^"]*")/i', $matches[0][0], $src); if (isset ($src[1][0])) { $theImageSrc = str_replace('"', '', $src[1][0]); } } } if($this->get_style_setting('aspect_ratio', 0 ) > 0){ set_time_limit(0); try{ set_time_limit(1); list($width, $height, $type, $attr) = @getimagesize( $theImageSrc ); if($width > 0 && $height > 0){ if($width < $width_max && $height < $height_max){ return array('src' => $theImageSrc, 'width' => $width, 'height' => $height); } elseif($width > $width_max && $height > $height_max){ $percent_width = $width_max * 100/$width; $percent_height = $height_max * 100/$height; $percent = ($percent_height < $percent_width ? $percent_height : $percent_width); return array('src' => $theImageSrc, 'width' => intval($width * $percent / 100), 'height' => intval($height * $percent / 100)); } elseif($width < $width_max && $height > $height_max){ $percent = $height * 100/$height_max; return array('src' => $theImageSrc, 'width' => intval($width * $percent / 100), 'height' => intval($height * $percent / 100)); } else{ $percent = $width * 100/$width_max; return array('src' => $theImageSrc, 'width' => intval($width * $percent / 100), 'height' => intval($height * $percent / 100)); } } } catch(Exception $e){ set_time_limit(60); return array('src' => $theImageSrc, 'width' => $this->get_style_setting('thumb_width', 50 ) , 'height' => $this->get_style_setting('thumb_height', 50 ) ); } } else{ return array('src' => $theImageSrc, 'width' => $this->get_style_setting('thumb_width', 50 ) , 'height' => $this->get_style_setting('thumb_height', 50 ) ); } return false; } function get_post_types() { $post_types = get_post_types(array('_builtin' => false),'objects'); $post_types['post'] = get_post_type_object('post'); $post_types['page'] = get_post_type_object('page'); unset($post_types['wpsc-product-file']); return $post_types; } function get_excerpt_count() { return $this->get_style_setting('excerpt', 10); } function get_taxonomies() { $args = array( 'public' => true, '_builtin' => false ); $output = 'objects'; // or objects $operator = 'or'; // 'and' or 'or' $taxonomies = get_taxonomies( $args, $output, $operator ); if ( $taxonomies ) { return $taxonomies; } return null; } function get_search_objects($all = false, $objects = false, $specific_post_types = array(), $specific_taxonomies = array(), $specific_roles = array()) { $search = array(); $scat = (array)$this->get_setting('category'); $arg_category_show = isset($_POST['show_category']) ? $_POST['show_category'] : 1; $search_taxonomies = false; if($scat['show'] == 1 && $arg_category_show == 1){ $search_taxonomies = true; } $arg_post_category_show = isset($_POST['show_post_category']) ? $_POST['show_post_category'] : 1; $show_post_category = false; if($scat['ushow'] == 1 && $arg_post_category_show == 1){ $show_post_category = true; } $arg_authors_show = isset($_POST['show_authors']) ? $_POST['show_authors'] : 1; $show_authors = false; if($show_authors == 1){ $show_authors = true; } if(!$objects || $objects == 'post_type') { // get all post types that are ready for search $post_types = $this->get_post_types(); foreach($post_types as $post_type) { if(sizeof($specific_post_types) == 0) { $setting = $this->get_setting($post_type->name); if($setting -> show == 1 || $all){ $search[] = array( 'order' => $setting->order, 'name' => $post_type->name, 'label' => (empty($setting->title) ? $post_type->label : $setting->title), 'type' => 'post_type' ); } } elseif(in_array($post_type->name, $specific_post_types)) { $setting = $this->get_setting($post_type->name); $search[] = array( 'order' => $setting->order, 'name' => $post_type->name, 'label' => (empty($setting->title) ? $post_type->label : $setting->title), 'type' => 'post_type' ); } } } if((!$objects || $objects == 'taxonomy') && $search_taxonomies) { // override post_types from input $taxonomies = $this->get_taxonomies(); foreach($taxonomies as $taxonomy) { if(sizeof($specific_taxonomies) == 0) { $setting = $this->get_setting($taxonomy->name); if($setting -> show == 1 || $all){ $search[] = array( 'order' => $setting->order, 'name' => $taxonomy->name, 'label' => (empty($setting->title) ? $taxonomy->label : $setting->title), 'type' => 'taxonomy', 'show_posts' => $show_post_category ); } } elseif(in_array($taxonomy->name, $specific_taxonomies)) { $setting = $this->get_setting($taxonomy->name); $search[] = array( 'order' => $setting->order, 'name' => $taxonomy->name, 'label' => (empty($setting->title) ? $taxonomy->label : $setting->title), 'type' => 'taxonomy', 'show_posts' => $show_post_category ); } } }elseif((!$objects || $objects == 'taxonomy')) { // override post_types from input $taxonomies = $this->get_taxonomies(); foreach($taxonomies as $taxonomy) { if(sizeof($specific_taxonomies) == 0) { $setting = $this->get_setting($taxonomy->name); if($setting -> show == 1 || $all){ $search[] = array( 'order' => $setting->order, 'name' => $taxonomy->name, 'label' => (empty($setting->title) ? $taxonomy->label : $setting->title), 'type' => 'taxonomy', 'show_posts' => $show_post_category ); } } elseif(in_array($taxonomy->name, $specific_taxonomies)) { $setting = $this->get_setting($taxonomy->name); $search[] = array( 'order' => $setting->order, 'name' => $taxonomy->name, 'label' => (empty($setting->title) ? $taxonomy->label : $setting->title), 'type' => 'taxonomy', 'show_posts' => $show_post_category ); } } } if(!$objects || $objects == 'author') { global $wp_roles; $roles = $wp_roles->get_names(); foreach($roles as $role => $label) { if(sizeof($specific_roles) == 0) { $setting = $this->get_setting('role_'.$role, false); if($setting -> show == 1 || $all){ $search[] = array( 'order' => $setting->order, 'name' => $role, 'label' => (empty($setting->title) ? $label : $setting->title), 'type' => 'role' ); } } elseif(in_array($role, $specific_roles)) { $setting = $this->get_setting('role_'.$role, false); $search[] = array( 'order' => $setting->order, 'name' => $role, 'label' => (empty($setting->title) ? $label : $setting->title), 'type' => 'role' ); } } } uasort($search, array(&$this, 'sort_search_objects')); return $search; } function sort_search_objects($a, $b) { if ($a['order'] == $b['order']) { return 0; } return ($a['order'] < $b['order']) ? -1 : 1; } function set_templates($template, $html) { if(get_option('sf_template_'.$template) !== false) { update_option('sf_template_'.$template, stripslashes($html)); } else { add_option('sf_template_'.$template, stripslashes($html)); } } function set_setting($name, $value) { if(get_option('sf_setting_'.$name) !== false) { update_option('sf_setting_'.$name, json_encode($value)); } else { add_option('sf_setting_'.$name, json_encode($value)); } } function remove_setting($name){ delete_option('sf_setting_'.$name); } function get_setting($name, $public = true) { $defaults = array( 'title' => '', 'show' => 1, 'ushow' => 0, 'search_content' => 0, 'limit' => 5, 'order' => 0, 'order_results' => false ); if(!$public) { $defaults['show'] = 0; } if(get_option('sf_setting_'.$name) !== false) { $settings = json_decode(get_option('sf_setting_'.$name)); foreach($defaults as $key => $value) { if(!isset($settings->{$key})){ $settings->{$key} = $value; } } return $settings; } else { return (object)$defaults; } } function set_style_setting($name, $value) { update_option('sf_style_'.$name, $value); } function get_style_setting($name, $default = '') { if(get_option('sf_style_'.$name) !== false) { return get_option('sf_style_'.$name, $default); } else { return $default; } } function remove_style_setting($name) { return delete_option('sf_style_'.$name); } function remove_template($template) { delete_option('sf_template_'.$template); } function get_templates($template, $type='') { $template_post = ""; switch($type) { case 'more': $template_post = get_option('sf_template_more'); if(!$template_post) { $template_post = '<a href="{search_url_escaped}"><span class="sf_text">See more results for "{search_value}"</span><span class="sf_small">Displaying top {total} results</span></a>'; } break; case 'taxonomy': $template_post = get_option('sf_template_'.$template); if(!$template_post) { $template_post = '<a href="{category_link}">{name}</a>'; } break; case 'author': case 'role': $template_post = get_option('sf_template_'.$template); if(!$template_post) { $template_post = '<a href="{author_link}">{user_nicename}</a>'; } break; case 'post_type': $template_post = get_option('sf_template_'.$template); if(!$template_post && in_array($template, self::$woocommerce_post_types)) { $template_post = '<a href="{post_link}">{post_image_html}<span class="sf_text">{post_title} - {price}</span><span class="sf_small">Posted by {post_author} on {post_date_formatted}</span></a>'; }elseif(!$template_post){ $template_post = '<a href="{post_link}">{post_image_html}<span class="sf_text">{post_title} </span><span class="sf_small">Posted by {post_author} on {post_date_formatted}</span></a>'; } break; default: $template_post = get_option('sf_template_'.$template); if(!$template_post) { $template_post = '<a href="{post_link}">{post_image_html}<span class="sf_text">{post_title} </span><span class="sf_small">Posted by {post_author} on {post_date_formatted}</span></a>'; } break; } return $template_post; } function category($name, $taxonomy = 'category', $show_category_posts = false, $limit = 5) { global $wpdb; $categories = array(); $setting = (object)$this->get_setting($taxonomy); $excludes = ""; $excludes_array = array(); if(isset($setting->excludes) && sizeof($setting->excludes) > 0 && is_array($setting->excludes)){ $excludes = " AND $wpdb->terms.term_id NOT IN (".implode(',', $setting->excludes).")"; $excludes_array = $setting->excludes; } $results = null; $query = " SELECT distinct($wpdb->terms.name) , $wpdb->terms.term_id , $wpdb->term_taxonomy.taxonomy FROM $wpdb->terms , $wpdb->term_taxonomy WHERE name LIKE '%%%s%%' AND $wpdb->term_taxonomy.taxonomy = '$taxonomy' AND $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id $excludes LIMIT 0, %d"; $query = apply_filters("sf_category_query", $wpdb->prepare($query, $name, $setting->limit), $name, $excludes_array, $setting->limit); $results = $wpdb->get_results($query); if(sizeof($results) > 0 && is_array($results) && !is_wp_error($results)) { $unset_array = array('term_group', 'term_taxonomy_id', 'taxonomy', 'parent', 'count', 'cat_ID', 'cat_name', 'category_parent'); foreach($results as $result) { $cat = get_term($result->term_id, $result->taxonomy); if($cat != null && !is_wp_error($cat)) { $cat_object = new stdclass(); $category_link = get_term_link($cat); $cat_object->category_link = $category_link; $matches = array(); $template = $this->get_templates( $taxonomy, 'taxonomy' ); preg_match_all ("/\{.*?\}/", $template, $matches); foreach($matches[0] as $match){ $match = str_replace(array('{', '}'), '', $match); if(isset($cat->{$match})) { $cat_object->{$match} = $cat->{$match}; } } if($show_category_posts) { $limit = isset($setting->limit_posts) ? $setting->limit_posts : 5; $psts = $this->posts_by_term($cat->term_id, $taxonomy, $limit); if(sizeof($psts) > 0) { $categories[$cat->term_id] = array('name' => $cat->name,'posts' => $this->posts_by_term($cat->term_id, $limit)); } } else { $categories[] = $cat_object; } } } } return $categories; } function author($name, $show_author_posts = false, $limit = 5) { global $wpdb; $authors = array(); $results = null; $query = " SELECT * FROM $wpdb->users WHERE ID IN ( SELECT ID FROM $wpdb->usermeta WHERE (meta_key = 'first_name' AND meta_value LIKE '%%%s%%') OR (meta_key = 'last_name' AND meta_value LIKE '%%%s%%' ) OR (meta_key = 'nickname' AND meta_value LIKE '%%%s%%' ) ) "; $query = apply_filters("sf_authors_query", $wpdb->prepare($query, $name, $name, $name), $name); $results = $wpdb->get_results($query); if(sizeof($results) > 0 && is_array($results) && !is_wp_error($results)) { foreach($results as $result) { $authors[] = new WP_User($result->ID); } } return $authors; } function filter_authors_by_role($authors, $role) { $users = array(); $setting = (object)$this->get_setting('role_'.$role, false); $excludes = ""; $excludes_array = array(); if(isset($setting->excludes) && sizeof($setting->excludes) > 0 && is_array($setting->excludes)){ $excludes_array = $setting->excludes; } $template = $this->get_templates( 'role_'.$role, 'author' ); $matches = array(); preg_match_all ("/\{.*?\}/", $template, $matches); if(sizeof($matches) > 0) { foreach($authors as $author) { if(in_array($role, $author->roles) && !in_array($author->ID,$excludes_array)) { $user = new stdClass(); foreach($matches[0] as $match) { $match = str_replace(array('{', '}'), '', $match); $method = "get_".$match; if(method_exists ($author->data, $method)){ $user->{$match} = call_user_func(array($author->data,$method)); }elseif(method_exists ($author, $match)){ $user->{$match} = call_user_func(array($author->data,$match)); }elseif(property_exists ($author->data, $match)){ $user->{$match} = $author->data->{$match}; } } if(in_array('{author_link}', $matches[0])){ $user->author_link = get_author_posts_url($author->ID); } $users[] = $user; } } } return $users; } function posts($name, $post_type='post', $term_id = false) { global $wpdb; $posts = array(); $setting = (object)$this->get_setting($post_type); $excludes = ""; $excludes_array = array(); if(isset($setting->excludes) && sizeof($setting->excludes) > 0 && is_array($setting->excludes)){ $excludes = " AND ID NOT IN (".implode(',', $setting->excludes).")"; $excludes_array = $setting->excludes; } $order_results = ($setting->order_results ? " ORDER BY ".$setting->order_results : ""); $results = array(); $query = " SELECT $wpdb->posts.ID FROM $wpdb->posts WHERE (post_title LIKE '%%%s%%' ".($setting->search_content == 1 ? "or post_content LIKE '%%%s%%')":")")." AND post_status='publish' AND post_type='".$post_type."' $excludes $order_results LIMIT 0, %d"; /* $meta_query = " SELECT project_id.post_id , height.height , width.width FROM $wpdb->postmeta WHERE meta_key = '$meta_key' AND meta_value LIKE '$meta_value' "; */ $query = apply_filters("sf_posts_query", ($setting->search_content == 1 ? $wpdb->prepare($query, $name, $name, $setting->limit) :$wpdb->prepare($query, $name, $setting->limit)), $name, $post_type, $excludes_array, $setting->search_content, $order_results, $setting->limit); $results = $wpdb->get_results( $query ); if(sizeof($results) > 0 && is_array($results) && !is_wp_error($results)) { $template = $this->get_templates( $post_type, 'post_type' ); $matches = array(); preg_match_all ("/\{.*?\}/", $template, $matches); if(sizeof($matches) > 0) { foreach($results as $result) { $pst = $this->post_object($result->ID, $term_id, $matches[0]); if($pst){ $posts[] = $pst; } } } } return $posts; } function posts_by_term($term_id, $taxonomy, $limit = 5){ $posts = array(); $args = array( 'showposts' => $limit, 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'terms' => $term_id, 'field' => 'term_id', ) ), 'orderby' => 'date', 'order' => 'DESC' ); $term_query = new WP_Query( $args ); if($term_query->have_posts()) : $psts = apply_filters('sf_pre_term_posts', $term_query->posts); if(sizeof($psts) > 0) { foreach($psts as $p) { $matches = array(); $template = $this->get_templates( $p->post_type, 'post_type' ); preg_match_all ("/\{.*?\}/", $template, $matches); $posts[] = $this->post_object($p->ID, false, $matches[0]); } } $posts = apply_filters('sf_term_posts', $posts); endif; return $posts; } function post_object($id, $term_id = false, $matches = false) { $unset_array = array('post_date_gmt', 'post_status', 'comment_status', 'ping_status', 'post_password', 'post_content_filtered', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'guid', 'menu_order', 'post_mime_type', 'comment_count', 'ancestors', 'filter'); global $post; $date_format = get_option( 'date_format' ); $post = get_post($id); if($term_id) { if(!in_category($term_id, $post->ID)){ return false; } } $size = array('height' => $this->get_style_setting('thumb_height' , 50), 'width' => $this->get_style_setting('thumb_weight' , 50)); if($post != null) { $post_object = new stdclass(); $post_link = get_permalink($post->ID); if(in_array('{post_image}', $matches) || in_array('{post_image_html}', $matches)) { $post_thumbnail_id = get_post_thumbnail_id( $post->ID); if( $post_thumbnail_id > 0) { $thumb = wp_get_attachment_image_src( $post_thumbnail_id, array($size['height'], $size['width']) ); $post_object->post_image = (trim($thumb[0]) == "" ? AJAXY_SF_NO_IMAGE : $thumb[0]); if(in_array('{post_image_html}', $matches)) { $post_object->post_image_html = '<img src="'.$post_object->post_image.'" width="'.$size['width'].'" height="'.$size['height'].'"/>'; } } else { if($src = $this->get_image_from_content($post->post_content, $size['height'], $size['width'])){ $post_object->post_image = $src['src'] ? $src['src'] : AJAXY_SF_NO_IMAGE; if(in_array('{post_image_html}', $matches)) { $post_object->post_image_html = '<img src="'.$post_object->post_image.'" width="'.$src['width'].'" height="'.$src['height'].'" />'; } } else{ $post_object->post_image = AJAXY_SF_NO_IMAGE; if(in_array('{post_image_html}', $matches)) { $post_object->post_image_html = ''; } } } } if($post->post_type == "wpsc-product"){ if(function_exists('wpsc_calculate_price')){ if(in_array('{wpsc_price}', $matches)){ $post_object->wpsc_price = wpsc_the_product_price(); }if(in_array('{wpsc_shipping}', $matches)){ $post_object->wpsc_shipping = strip_tags(wpsc_product_postage_and_packaging()); }if(in_array('{wpsc_image}', $matches)){ $post_object->wpsc_image = wpsc_the_product_image($size['height'], $size['width']); } } } if($post->post_type == 'product' && class_exists('WC_Product_Factory')) { $product_factory = new WC_Product_Factory(); global $product; $product = $product_factory->get_product($post); if($product->is_visible()) { foreach($matches as $match) { $match = str_replace(array('{', '}'), '', $match); if(in_array($match, array('categories', 'tags'))) { $method = "get_".$match; if(method_exists ($product, $method)){ $term_list = call_user_func(array($product, $method), ''); if($term_list){ $post_object->{$match} = '<span class="sf_list sf_'.$match.'">'.$term_list.'</span>'; }else{ $post_object->{$match} = ""; } } }elseif($match == 'add_to_cart_button'){ ob_start(); do_action( 'woocommerce_' . $product->product_type . '_add_to_cart' ); $post_object->{$match} = '<div class="product">'.ob_get_contents().'</div>'; ob_end_clean(); }else{ $method = "get_".$match; if(method_exists ($product, $method)){ $post_object->{$match} = call_user_func(array($product, $method)); }elseif(method_exists ($product, $match)){ $post_object->{$match} = call_user_func(array($product, $match)); } } } } /* $post->sku = $product->get_sku(); $post->sale_price = $product->get_sale_price(); $post->regular_price = $product->get_regular_price(); $post->price = $product->get_price(); $post->price_including_tax = $product->get_price_including_tax(); $post->price_excluding_tax = $product->get_price_excluding_tax(); $post->price_suffix = $product->get_price_suffix(); $post->price_html = $product->get_price_html(); $post->price_html_from_text = $product->get_price_html_from_text(); $post->average_rating = $product->get_average_rating(); $post->rating_count = $product->get_rating_count(); $post->rating_html = $product->get_rating_html(); $post->dimensions = $product->get_dimensions(); $post->shipping_class = $product->get_shipping_class(); $post->add_to_cart_text = $product->add_to_cart_text(); $post->single_add_to_cart_text = $product->single_add_to_cart_text(); $post->add_to_cart_url = $product->add_to_cart_url(); $post->title = $product->get_title(); */ } $post_object->ID = $post->ID; $post_object->post_title = get_the_title($post->ID); if(in_array('{post_excerpt}', $matches)) { $post_object->post_excerpt = $post->post_excerpt; }if(in_array('{post_author}', $matches)) { $post_object->post_author = get_the_author_meta('display_name', $post->post_author); }if(in_array('{post_link}', $matches)) { $post_object->post_link = $post_link; }if(in_array('{post_content}', $matches)) { $post_object->post_content = $this->get_text_words(apply_filters('the_content', $post->post_content) ,(int)$this->get_excerpt_count()); }if(in_array('{post_date_formatted}', $matches)) { $post_object->post_date_formatted = date($date_format, strtotime( $post->post_date) ); } foreach($matches as $match) { $match = str_replace(array('{', '}'), '', $match); if(strpos($match, 'custom_field_') !== false){ $key = str_replace('custom_field_', '', $match); $custom_field = get_post_meta($post->ID, $key, true); if ( is_array($custom_field) ) { $cf_name = 'custom_field_'.$key; $post_object->{$cf_name} = apply_filters('sf_post_custom_field', $custom_field[0], $key, $post); }else{ $cf_name = 'custom_field_'.$key; $post_object->{$cf_name} = apply_filters('sf_post_custom_field', $custom_field, $key, $post); } } } $post_object = apply_filters('sf_post', $post_object); return $post_object; } return false; } function get_text_words($text, $count) { $tr = explode(' ', strip_tags(strip_shortcodes($text))); $s = ""; for($i = 0; $i < $count && $i < sizeof($tr); $i++) { $s[] = $tr[$i]; } return implode(' ', $s); } function enqueue_scripts() { wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'ajaxy-sf-search', AJAXY_SF_PLUGIN_URL."js/sf.js", array('jquery'), '1.0.1', true ); wp_enqueue_script( 'ajaxy-sf-selective', AJAXY_SF_PLUGIN_URL."js/sf_selective.js", array('jquery'), '1.0.0', true ); $this->enqueue_styles(); } function enqueue_styles() { $themes = $this->get_installed_themes(AJAXY_THEMES_DIR, 'themes'); $style = AJAXY_SF_PLUGIN_URL."themes/default/style.css"; $theme = $this->get_style_setting('theme'); if(isset($themes[$theme])){ $style = $themes[$theme]['stylesheet_url']; } if($theme != 'blank') { if($this->get_style_setting('rtl_theme', 0) == 1) { wp_enqueue_style( 'ajaxy-sf-common', AJAXY_SF_PLUGIN_URL."themes/common-rtl.css" ); }else{ wp_enqueue_style( 'ajaxy-sf-common', AJAXY_SF_PLUGIN_URL."themes/common.css" ); } wp_enqueue_style( 'ajaxy-sf-selective', AJAXY_SF_PLUGIN_URL."themes/selective.css" ); wp_enqueue_style( 'ajaxy-sf-theme', $style ); } } function head() { $css = $this->get_style_setting('css'); ?> <!-- AJAXY SEARCH V <?php echo AJAXY_SF_VERSION; ?>--> <?php if(trim($css) != ''): ?> <style type="text/css"><?php echo $css; ?></style> <?php endif; if(is_admin()) {?> <link rel="stylesheet" type="text/css" href="<?php echo AJAXY_SF_PLUGIN_URL; ?>/admin/css/styles.css" /> <?php } $settings = array( 'label' => $this->get_style_setting('search_label', 'Search'), 'expand' => $this->get_style_setting('expand', false) ); $live_search_settings = json_encode( array( 'expand' => $settings['expand'] ,'searchUrl' => $this->get_style_setting('search_url', home_url().'/?s=%s') ,'text' => $settings['label'] ,'delay' => $this->get_style_setting('delay', 500) ,'iwidth' => $this->get_style_setting('width', 180) ,'width' => $this->get_style_setting('results_width', 315) ,'ajaxUrl' => $this->get_ajax_url() ,'rtl' => $this->get_style_setting('rtl_theme', 0) ) ); ?> <script type="text/javascript"> /* <![CDATA[ */ var sf_position = '<?php echo $this->get_style_setting('results_position', 0); ?>'; var sf_templates = <?php echo json_encode($this->get_templates('more', 'more')); ?>; var sf_input = '<?php echo (trim($this->get_style_setting('input_id', '.sf_input')) == "" ? '.sf_input' : $this->get_style_setting('input_id', '.sf_input')); ?>'; jQuery(document).ready(function(){ jQuery(sf_input).ajaxyLiveSearch(<?php echo $live_search_settings; ?>); jQuery(".sf_ajaxy-selective-input").keyup(function() { var width = jQuery(this).val().length * 8; if(width < 50) { width = 50; } jQuery(this).width(width); }); jQuery(".sf_ajaxy-selective-search").click(function() { jQuery(this).find(".sf_ajaxy-selective-input").focus(); }); jQuery(".sf_ajaxy-selective-close").click(function() { jQuery(this).parent().remove(); }); }); /* ]]> */ </script> <?php } function get_ajax_url(){ if(defined('ICL_LANGUAGE_CODE')){ return admin_url('admin-ajax.php').'?lang='.ICL_LANGUAGE_CODE; } if(function_exists('qtrans_getLanguage')){ return admin_url('admin-ajax.php').'?lang='.qtrans_getLanguage(); } return admin_url('admin-ajax.php'); } function footer(){ //echo $script; } function get_shortcode() { if(isset($_POST['sf'])) { $postData = $_POST['sf']['style']; $m = array(); $border = ""; foreach($postData as $key => $value) { if(!empty($value)) { switch($key) { case "b_width": $border = $value."px "; break; case "b_type" : $border .= $value." "; break; case "b_color" : $border .= "#".$value." "; break; case "width" : $m[] = 'iwidth="'.$value.'"'; break; case "results_width" : $m[] = 'width="'.$value.'"'; break; case "post_types" : $m[] = 'post_types="'.implode(',', $value).'"'; break; default: $m[] = $key.'="'.$value.'"'; } } } if($border != ""){ $m[] = 'border="'.trim($border).'"'; } echo '[ajaxy-live-search '.implode(' ', $m).']'; } //print_r($_POST); exit; } function get_search_results() { $results = array(); $sf_value = apply_filters('sf_value', $_POST['sf_value']); if(!empty($sf_value)) { //filter taxonomies if set $arg_taxonomies = isset($_POST['taxonomies']) && trim($_POST['taxonomies']) != "" ? explode(',', trim($_POST['taxonomies'])) : array(); // override post_types from input $arg_post_types = isset($_POST['post_types']) && trim($_POST['post_types']) != "" ? explode(',', trim($_POST['post_types'])) : array(); $search = $this->get_search_objects(false, false, $arg_post_types, $arg_taxonomies); $author_searched = false; $authors = array(); foreach($search as $key => $object) { if($object['type'] == 'post_type') { $posts_result = $this->posts($sf_value, $object['name']); if(sizeof($posts_result) > 0) { $results[$object['name']][0]['all'] = $posts_result; $results[$object['name']][0]['template'] = $this->get_templates($object['name'], 'post_type'); $results[$object['name']][0]['title'] = $object['label']; $results[$object['name']][0]['class_name'] = 'sf_item'.(in_array($object['name'], self::$woocommerce_post_types) ? ' woocommerce': ''); } } elseif($object['type'] == 'taxonomy') { if($object['show_posts']) { $taxonomy_result = $this->category($sf_value, $object['name'], $object['show_posts']); if(sizeof($taxonomy_result) > 0) { $cnt = 0; foreach($taxonomy_result as $key => $val) { if(sizeof($val['posts']) > 0) { $results[$object['name']][$cnt]['all'] = $val['posts']; $results[$object['name']][$cnt]['template'] = $this->get_templates($object['name'], 'taxonomy'); $results[$object['name']][$cnt]['title'] = $object['label']; $results[$object['name']][$cnt]['class_name'] = 'sf_category'; $cnt ++; } } } }else{ $taxonomy_result = $this->category($sf_value, $object['name']); if(sizeof($taxonomy_result) > 0) { $results[$object['name']][0]['all'] = $taxonomy_result; $results[$object['name']][0]['template'] = $this->get_templates($object['name'], 'taxonomy'); $results[$object['name']][0]['title'] = $object['label']; $results[$object['name']][0]['class_name'] = 'sf_category'; } } }elseif($object['type'] == 'role') { $users = array(); if(!$author_searched) { $authors = $this->author($sf_value, $object['name']); $users = $this->filter_authors_by_role($authors, $object['name']); $author_searched = true; }else{ $users = $this->filter_authors_by_role($authors, $object['name']); } if(sizeof($users) > 0) { $results[$object['name']][0]['all'] = $users; $results[$object['name']][0]['template'] = $this->get_templates($object['name'], 'author'); $results[$object['name']][0]['title'] = $object['label']; $results[$object['name']][0]['class_name'] = 'sf_category'; } } } $results = apply_filters('sf_results', $results); echo json_encode($results); } do_action( 'sf_value_results', $sf_value, $results); exit; } function get_installed_themes($themeDir, $themeFolder){ $dirs = array(); if ($handle = opendir($themeDir)) { while (($file = readdir($handle)) !== false) { if('dir' == filetype($themeDir.$file) ){ if(trim($file) != '.' && trim($file) != '..'){ $dirs[] = $file; } } } closedir($handle); } $themes = array(); if(sizeof($dirs) > 0){ foreach($dirs as $dir){ if(file_exists($themeDir.$dir.'/style.css')){ $themes[$dir] = array( 'title' => $dir, 'stylesheet_dir' => $themeDir.$dir.'/style.css', 'stylesheet_url' => plugins_url( $themeFolder.'/'.$dir.'/style.css', __FILE__), 'dir' => $themeDir.$dir, 'url' => plugins_url( $themeFolder.'/'.$dir , __FILE__ ) ); } } } return $themes; } function admin_notice() { global $current_screen; if($current_screen->parent_base == 'ajaxy-page' && isset($_GET['ajaxy-tdismiss'])) { update_option('ajaxy-tdismiss', 2); } elseif(isset($_GET['ajaxy-tdismiss'])){ update_option('ajaxy-tdismiss', 1); } $dismiss = (int)get_option('ajaxy-tdismiss'); if(!class_exists ( 'AjaxyTracker' ) && (($dismiss != 1 && $dismiss != 2) || ($current_screen->parent_base == 'ajaxy-page' && $dismiss != 2))) { echo '<div class="updated"><p><b>Ajaxy:</b> Track your live search and improve your website search with live search keyword tracker - <a href="'.get_admin_url().'plugin-install.php?tab=search&s=ajaxy+live+search+tracker&plugin-search-input=Search+Plugins">Download</a> | <a href="'.(strpos( $_SERVER['REQUEST_URI'], '?') !== false ? $_SERVER['REQUEST_URI'].'&ajaxy-tdismiss=1' : $_SERVER['REQUEST_URI'].'?ajaxy-tdismiss=1').'">No Thanks - Dismiss</a></p></div>'; } } function form($settings) { $form = ' <!-- Ajaxy Search Form v'.AJAXY_SF_VERSION.' --> <div id="'.$settings['id'].'" class="sf_container"> <form role="search" method="get" class="searchform" action="' . home_url( '/' ) . '" > <div> <label class="screen-reader-text" for="s">' . __('Search for:') . '</label> <div class="sf_search" style="border:'.$settings['border'].'"> <span class="sf_block"> <input style="width:'.($settings['width']).'px;" class="sf_input" autocomplete="off" type="text" value="' . (get_search_query() == '' ? $settings['label'] : get_search_query()). '" name="s"/> <button class="sf_button searchsubmit" type="submit"><span class="sf_hidden">'. esc_attr__(__('Search')) .'</span></button> </span> </div> </div> </form> </div>'; if($settings['credits'] == 1) { $form = $form.'<a style="display:none" href="http://www.ajaxy.org">Powered by Ajaxy</a>'; } return $form; } function selective_input($settings) { $selective_input = ' <!-- Ajaxy Selective Search Input v'.AJAXY_SF_VERSION.' --> <div id="'.$settings['id'].'" class="sf_ajaxy-selective-search" style="border:'.$settings['border'].';width:'.($settings['width']).'px;"> <input class="sf_ajaxy-selective-input" type="text" placeholder="'.$settings['label'].'" value=""/> </div>'; if(isset($settings['credits']) && $settings['credits'] == 1) { $selective_input = $selective_input.'<a style="display:none" href="http://www.ajaxy.org">Powered by Ajaxy</a>'; } return $selective_input; } function form_shortcode($atts = array()) { $m = uniqid(); $scat = (array)$this->get_setting('category'); $settings = array( 'id' => $m, 'label' => $this->get_style_setting('search_label', 'Search'), 'expand' => $this->get_style_setting('expand', 0), 'width' => $this->get_style_setting('width', 180), 'border' => $this->get_style_setting('border-width', '1') . "px " . $this->get_style_setting('border-type', 'solid') . " #" .$this->get_style_setting('border-color', 'dddddd'), 'credits' => $this->get_style_setting('credits', 1 ), 'show_category' => $scat['show'], 'show_post_category' => $scat['ushow'], 'post_types' => '' ); if($settings['expand'] == 1){ $settings['width'] = $settings['expand']; } $settings = shortcode_atts( $settings, $atts, 'ajaxy-live-search-layout' ) ; $form = $this->form($settings); $live_search_settings = array( 'expand' => $settings['expand'] ,'searchUrl' => $this->get_style_setting('search_url', home_url().'/?s=%s') ,'text' => $settings['label'] ,'delay' => $this->get_style_setting('delay', 500) ,'iwidth' => $this->get_style_setting('width', 180) ,'width' => $this->get_style_setting('results_width', 315) ,'ajaxUrl' => $this->get_ajax_url() ,'ajaxData' => 'sf_custom_data_'.$m ,'search' => false ,'rtl' => $this->get_style_setting('rtl_theme', 0) ); $live_search_settings = shortcode_atts( $live_search_settings, $atts, 'ajaxy-live-search' ) ; $script = ' <script type="text/javascript"> /* <![CDATA[ */ function sf_custom_data_'.$m.'(data){ data.show_category = "'.$settings['show_category'].'"; data.show_post_category = "'.$settings['show_post_category'].'"; data.post_types = "'.$settings['post_types'].'"; return data; } jQuery(document).ready(function(){ jQuery("#'.$m.' .sf_input").ajaxyLiveSearch('.json_encode($live_search_settings).'); }); /* ]]> */ </script>'; return $form.$script; } function selective_input_shortcode($atts = array()) { $m = uniqid(); $scat = (array)$this->get_setting('category'); $settings = array( 'id' => $m, 'label' => $this->get_style_setting('search_label', 'Search'), 'expand' => $this->get_style_setting('expand', 0), 'width' => $this->get_style_setting('width', 180), 'border' => $this->get_style_setting('border-width', '1') . "px " . $this->get_style_setting('border-type', 'solid') . " #" .$this->get_style_setting('border-color', 'dddddd'), 'credits' => $this->get_style_setting('credits', 0 ), 'show_category' => $scat['show'], 'show_post_category' => $scat['ushow'], 'post_types' => '', 'name' => 'selective_search', 'name-type' => 'array', 'value' => '{post_type}' ); if($settings['expand'] == 1){ $settings['width'] = $settings['expand']; } $settings = shortcode_atts( $settings, $atts, 'ajaxy-selective-search-layout' ) ; $selective_input = $this->selective_input((array)$settings); $live_search_settings = array( 'expand' => $settings['expand'] ,'searchUrl' => $this->get_style_setting('search_url', home_url().'/?s=%s') ,'text' => $settings['label'] ,'delay' => $this->get_style_setting('delay', 500) ,'iwidth' => $this->get_style_setting('width', 180) ,'width' => $this->get_style_setting('results_width', 315) ,'ajaxUrl' => $this->get_ajax_url() ,'ajaxData' => 'sf_custom_data_'.$m ,'callback' => 'sf_load_data_'.$m ,'search' => '' ,'rtl' => $this->get_style_setting('rtl_theme', 0) ); $live_search_settings = shortcode_atts( $live_search_settings, $atts, 'ajaxy-live-search' ) ; $script = ' <script type="text/javascript"> /* <![CDATA[ */ function sf_custom_data_'.$m.'(data){ data.show_category = "'.$settings['show_category'].'"; data.show_post_category = "'.$settings['show_post_category'].'"; data.post_types = "'.$settings['post_types'].'"; return data; }function sf_load_data_'.$m.'(object, item){ var data = jQuery("body").data("sf_results"); var rType = jQuery(item).attr("result-type"); var name_type = "'.$settings['name-type'].'"; var name_value = "'.$settings['value'].'"; if(rType == "object") { var iType = jQuery(item).attr("index-type"); var iArray = jQuery(item).attr("index-array"); var index = jQuery(item).attr("index"); var itemObject = data[iType][iArray]; for (var key in itemObject.all[index]) { var reg = new RegExp("{"+key+"}","gi"); name_value = name_value.replace(reg, itemObject.all[index][key]); } sf_addItem(jQuery(object.element).parent(), itemObject.all[index].post_title, "'.$settings['name'].($settings['name-type'] == 'array' ? '[]':'').'", name_type, name_value); }else if(rType == "array") { var index = jQuery(item).attr("index"); var itemObject = data[index]; sf_addItem(jQuery(object.element).parent(), itemObject, "'.$settings['name'].($settings['name-type'] == 'array' ? '[]':'').'", name_type, itemObject); } } jQuery(document).ready(function(){ jQuery("#'.$m.' .sf_ajaxy-selective-input").ajaxyLiveSearch('.json_encode($live_search_settings).'); }); /* ]]> */ </script>'; return $selective_input.$script; } } add_filter('sf_category_query', 'sf_category_query', 4, 10); function sf_category_query($query, $search, $excludes, $limit){ global $wpdb; $wpml_lang_code = (defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE: false); if( $wpml_lang_code ) { if(sizeof($excludes) > 0){ $excludes = " AND $wpdb->terms.term_id NOT IN (".implode(",", $excludes).")"; } else{ $excludes = ""; } $query = "select * from (select distinct($wpdb->terms.name), $wpdb->terms.term_id, $wpdb->term_taxonomy.taxonomy, $wpdb->term_taxonomy.term_taxonomy_id from $wpdb->terms, $wpdb->term_taxonomy where name like '%%%s%%' and $wpdb->term_taxonomy.taxonomy<>'link_category' and $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id $excludes limit 0, ".$limit.") as c, ".$wpdb->prefix."icl_translations as i where c.term_taxonomy_id = i.element_id and i.language_code = %s and SUBSTR(i.element_type, 1, 4)='tax_' group by c.term_id"; $query = $wpdb->prepare($query, $search, $wpml_lang_code); return $query; } return $query; } add_filter('sf_posts_query', 'sf_posts_query', 5, 10); function sf_posts_query($query, $search, $post_type, $excludes, $search_content, $order_results, $limit){ global $wpdb; $wpml_lang_code = (defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE: false); if( $wpml_lang_code ) { if(sizeof($excludes) > 0){ $excludes = " AND $wpdb->posts.ID NOT IN (".implode(",", $excludes).")"; } else{ $excludes = ""; } //$order_results = (!empty($order_results) ? " order by ".$order_results : ""); $query = $wpdb->prepare("select * from (select $wpdb->posts.ID from $wpdb->posts where (post_title like '%%%s%%' ".($search_content == true ? "or post_content like '%%%s%%')":")")." and post_status='publish' and post_type='".$post_type."' $excludes $order_results limit 0,".$limit.") as p, ".$wpdb->prefix."icl_translations as i where p.ID = i.element_id and i.language_code = %s group by p.ID", ($search_content == true ? array($search, $search, $wpml_lang_code): array($search, $wpml_lang_code))); return $query; } return $query; } function ajaxy_search_form($settings = array()) { global $AjaxyLiveSearch; echo $AjaxyLiveSearch->form_shortcode($settings); } global $AjaxyLiveSearch; $AjaxyLiveSearch = new AjaxyLiveSearch(); ?>
booklein/wpbookle
wp-content/plugins/ajaxy-search-form/sf.php
PHP
gpl-2.0
56,836
EasyBlog.module("composer/blocks/handlers/liveleak", function($) { var module = this; EasyBlog.Controller("Composer.Blocks.Handlers.Liveleak", { elements: [ '[data-liveleak-fieldset-{url|fluid|width-fieldset|height-fieldset|width|height|update-url}]' ], defaultOptions: $.extend({ // Form "{form}": "> [data-liveleak-form]", "{insert}": "[data-liveleak-insert]", "{source}": "[data-liveleak-source]", "{loader}": "> [data-liveleak-loader]", // Error message "{errorMessage}": "[data-liveleak-error]", // video player "{player}": "iframe", // Template wrapper. "{wrapper}": "[data-liveleak-wrapper]" }, EBD.selectors) }, function(self, opts, base, composer, blocks, meta, currentBlock) { return { init: function() { blocks = self.blocks; composer = blocks.composer; meta = opts.meta; currentBlock = $(); }, toData: function(block) { var data = blocks.data(block); var overlay = block.data('overlay'); // The overlay might not be there if the user did not enter any urls if (!overlay) { return data; } // Get the iframe url var player = self.player.inside(overlay.element()); // We need to get the source of the iframe so we can generate our own html codes during the display data.source = player.attr('src'); return data; }, toText: function(block) { var data = blocks.data(block); return data.source; }, toHTML: function(block) { // We need to get the data from the overlay instead var data = blocks.data(block); var overlay = block.data('overlay'); if (overlay) { return overlay.element().html(); } }, activate: function(block) { var content = blocks.getBlockContent(block); var data = blocks.data(block); // Set as current block currentBlock = block; // Populate fieldset self.populate(block); }, deactivate: function(block) { }, construct: function(block) { }, getWrapper: function(block) { var wrapper = $(meta.wrapper); return wrapper; }, getPlayer: function(url) { var player = $(meta.player); player.attr('src', url); return player; }, reconstruct: function(block) { var data = blocks.data(block); var overlay = block.data('overlay'); var content = blocks.getBlockContent(block); // If this is an edited post which has url to the gist, we need to attach the overlay again if it doesn't exist yet. if (data.source && !overlay) { self.setOverlay(block); } else { content.html(meta.html); } // So redactor won't receive it. block.find(self.source.selector).off("paste").on("paste", function(event){ event.stopPropagation(); }); }, deconstruct: function(block) { }, refocus: function(block) { }, reset: function(block) { }, populate: function(block) { // When populating the fieldset for a block, reset the values // var data = blocks.data(block); // Update the url in fieldset self.updateFieldset(block); }, updateFieldset: function(block) { var data = blocks.data(block); // If there's no url at all, we don't need to do anything if (!data.url) { return; } // Update the url self.url().val(data.url); // Update the width self.width().val(data.width); // Update the height self.height().val(data.height); // Update the fluid settings self.fluid().val(data.fluid ? '1' : '0') .trigger('change'); }, getOverlay: function(block) { var overlay = block.data('overlay'); var data = blocks.data(block); var content = blocks.getBlockContent(block); if (!overlay) { overlay = composer.document.overlay.create(block); var wrapper = self.getWrapper(); // Insert placeholder inside wrapper overlay.placeholder() .appendTo(wrapper); // Insert wrapper inside block content content.empty() .append(wrapper); // Attach the overlay items on the dom overlay.attach(); } return overlay; }, setWrapperLayout: function(block) { var wrapper = self.wrapper.inside(block); var data = blocks.data(block); // If it's a fluid width, append the is-responsive class to it if (data.fluid) { wrapper .addClass("is-responsive") .css({ width: "", height: "" }); } else { // If this was switch from fluid to non fluid, we need to update with the appropriate width / height so video doesn't go crazy if (wrapper.hasClass('is-responsive')) { data.width = wrapper.width(); data.height = wrapper.outerHeight(); } self.width().val(data.width); self.height().val(data.height); // If this is not a fluid layout, we should set a width / height of the wrapper wrapper .css({ width: data.width, height: data.height }) .removeClass("is-responsive"); } }, setOverlay: function(block) { var data = blocks.data(block); var overlay = self.getOverlay(block); // Clear the element if necessary if (overlay.element().length > 0) { overlay.element().empty(); } // Set the wrapper layout self.setWrapperLayout(block); // Append the embed codes overlay.element().append(data.embed); // Refresh the overlay overlay.refresh(); // Set the overlay data so we don't create overlays all the time block.data('overlay', overlay); }, isUrlValid: function(url) { if (url == '') { return false; } // http://www.liveleak.com/view?i=963_1425404509 var regex = /^(http|https):\/\/www\.liveleak\.com\/view\?i=(.*)$/ var valid = regex.test(url); return valid; }, loading: function() { var content = blocks.getBlockContent(currentBlock); var loader = self.loader.inside(content); var form = self.form.inside(content); if (!self.isLoading) { loader.removeClass('hidden'); form.addClass('hidden'); self.isLoading = true; } else { loader.addClass('hidden'); form.removeClass('hidden'); self.isLoading = false; } }, crawl: function(url, block) { var data = blocks.data(block); var content = blocks.getBlockContent(block); // If there's an overlay hide it var overlay = block.data('overlay'); if (overlay) { overlay.element().empty(); } var regex = /www\.liveleak\.com\/view\?i=(.*)$/ var matches = url.match(regex); var code = matches[1]; // lets rebuild the url var source = 'http://www.liveleak.com/e/' + code; // Display the loader and hide the form self.loading(); EasyBlog.ajax('site/views/crawler/crawl', { "url": url }).done(function(results) { var result = results[url]; // console.log(result); // return; // Set block's data here data.url = url; data.source = source; // data.width = result.video.width; // data.height = result.video.height; data.title = result.opengraph.title; data.description = result.opengraph.desc; var player = self.getPlayer(data.source); data.embed = player.prop('outerHTML'); // Set the overlay self.setOverlay(block); // Update fieldset attributes self.updateFieldset(block); }).fail(function(message) { self.errorMessage().removeClass('hide').html(message); }).always(function() { // When it's done trigger the loading again self.loading(); // Hide the form and loader self.form.inside(content).addClass('hidden'); }); }, "{insert} click": function(button) { if (currentBlock.length < 1) { var block = self.block.of(button); blocks.activateBlock(block); } // Add overlay when the user add's a new link. var content = blocks.getBlockContent(currentBlock); var url = self.source.inside(content).val(); var data = blocks.data(currentBlock); // Ensure that the url is valid if (!self.isUrlValid(url)) { self.errorMessage().removeClass('hide'); return; } // Create an iframe, append it to this document where specified self.crawl(url, currentBlock); }, "{fluid} change": function(el, event) { var enabled = el.val() == 1 ? true : false; var data = blocks.data(currentBlock); data.fluid = enabled; self.setWrapperLayout(currentBlock); // If this is using a fluid layout, do not allow them to set the width and height self.widthFieldset() .toggleClass('hide', enabled); self.heightFieldset() .toggleClass('hide', enabled); // Refresh the overlay var overlay = self.getOverlay(currentBlock); overlay.refresh(); }, "{width} keyup": $.debounce(function(el, event){ var data = blocks.data(currentBlock); var width = el.val(); // If there's no value at all, don't resize the video's width if (width == 0) { return; } // Set the width data.width = width; // Get the overlay var overlay = self.getOverlay(currentBlock); // Update the wrapper's width var wrapper = self.wrapper.inside(currentBlock); wrapper.css('width', width); // Refresh the overlay var overlay = self.getOverlay(currentBlock); overlay.refresh(); }, 250), "{height} keyup": $.debounce(function(el, event){ var data = blocks.data(currentBlock); var height = el.val(); // If there's no value at all, don't resize the video's width if (height == 0) { return; } // Set the height data.height = height; // Update the placeholder's width var wrapper = self.wrapper.inside(currentBlock); wrapper.css('height', height); // Refresh the overlay var overlay = self.getOverlay(currentBlock); overlay.refresh(); }, 250), "{updateUrl} click": function(el, event) { var url = self.url().val(); var data = blocks.data(currentBlock); var content = blocks.getBlockContent(currentBlock); // Verify the source url if (!self.isUrlValid(url)) { self.errorMessage.inside(content).removeClass('hide'); return; } // Crawl and inject contents self.crawl(url, currentBlock); } } }); module.resolve(); });
quanghung0404/it2tech
media/com_easyblog/scripts/composer/blocks/handlers/liveleak.js
JavaScript
gpl-2.0
14,216
// add_meta.cpp // // Add a Rivendell RDCatch Event // // (C) Copyright 2002-2004 Fred Gleason <fredg@paravelsystems.com> // // $Id: add_meta.cpp,v 1.9 2010/07/29 19:32:37 cvs Exp $ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // #include <qdialog.h> #include <qstring.h> #include <qpushbutton.h> #include <qlistbox.h> #include <qtextedit.h> #include <qpainter.h> #include <qevent.h> #include <qmessagebox.h> #include <qcheckbox.h> #include <qsqldatabase.h> #include <rd.h> #include <rdlog_line.h> #include <add_meta.h> AddMeta::AddMeta(QWidget *parent,const char *name) : QDialog(parent,name,true,Qt::WStyle_Customize|Qt::WStyle_DialogBorder) { setCaption(""); // // Fix the Window Size // setMinimumWidth(sizeHint().width()); setMaximumWidth(sizeHint().width()); setMinimumHeight(sizeHint().height()); setMaximumHeight(sizeHint().height()); // // Generate Fonts // QFont button_font=QFont("Helvetica",12,QFont::Bold); button_font.setPixelSize(12); QFont label_font=QFont("Helvetica",12,QFont::Bold); label_font.setPixelSize(12); QFont day_font=QFont("Helvetica",12,QFont::Normal); day_font.setPixelSize(12); // // Title Label // QLabel *label=new QLabel(tr("Insert a:"),this,"title_label"); label->setGeometry(0,0,sizeHint().width(),30); label->setFont(label_font); label->setAlignment(AlignCenter); // // Marker Button // QPushButton *button=new QPushButton(this,"marker_button"); button->setGeometry(10,30,sizeHint().width()-20,50); button->setFont(button_font); button->setText(tr("&Marker")); connect(button,SIGNAL(clicked()),this,SLOT(markerData())); // // Voice Track Button // button=new QPushButton(this,"track_button"); button->setGeometry(10,80,sizeHint().width()-20,50); button->setFont(button_font); button->setText(tr("Voice &Track")); connect(button,SIGNAL(clicked()),this,SLOT(trackData())); // // Chain Button // button=new QPushButton(this,"chain_button"); button->setGeometry(10,130,sizeHint().width()-20,50); button->setFont(button_font); button->setText(tr("Log C&hain")); connect(button,SIGNAL(clicked()),this,SLOT(chainData())); // // Cancel Button // button=new QPushButton(this,"cancel_button"); button->setGeometry(10,sizeHint().height()-60,sizeHint().width()-20,50); button->setFont(button_font); button->setText(tr("&Cancel")); button->setDefault(true); connect(button,SIGNAL(clicked()),this,SLOT(cancelData())); } AddMeta::~AddMeta() { } QSize AddMeta::sizeHint() const { return QSize(200,240); } QSizePolicy AddMeta::sizePolicy() const { return QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); } void AddMeta::closeEvent(QCloseEvent *e) { cancelData(); } void AddMeta::markerData() { done(RDLogLine::Marker); } void AddMeta::chainData() { done(RDLogLine::Chain); } void AddMeta::trackData() { done(RDLogLine::Track); } void AddMeta::cancelData() { done(-1); }
validmirror/rivendell
rdlogedit/add_meta.cpp
C++
gpl-2.0
3,571
<?php /** * @package SP Page Builder * @author JoomShaper http://www.joomshaper.com * @copyright Copyright (c) 2010 - 2016 JoomShaper * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later */ //no direct accees defined ('_JEXEC') or die ('restricted aceess'); $addon = $displayData['addon']; $inlineCSS = ''; $addon_css = ''; $addon_link_css = ''; $addon_link_hover_css = ''; $addon_id = "#sppb-addon-". $addon->id; // Color if(isset($addon->settings->global_text_color) && $addon->settings->global_text_color) { $addon_css .= "\tcolor: " . $addon->settings->global_text_color . ";\n"; } if(isset($addon->settings->global_link_color) && $addon->settings->global_link_color) { $addon_link_css .= "\tcolor: " . $addon->settings->global_link_color . ";\n"; } if(isset($addon->settings->global_link_hover_color) && $addon->settings->global_link_hover_color) { $addon_link_hover_css .= "\tcolor: " . $addon->settings->global_link_hover_color . ";\n"; } // Background if(isset($addon->settings->global_use_background) && $addon->settings->global_use_background) { if(isset($addon->settings->global_background_color) && $addon->settings->global_background_color) { $addon_css .= "\tbackground-color: " . $addon->settings->global_background_color . ";\n"; } if(isset($addon->settings->global_background_image) && $addon->settings->global_background_image) { $addon_css .= "\tbackground-image: url(" . JURI::base(true) . '/' . $addon->settings->global_background_image . ");\n"; if(isset($addon->settings->global_background_repeat) && $addon->settings->global_background_repeat) { $addon_css .= "\tbackground-repeat: " . $addon->settings->global_background_repeat . ";\n"; } if(isset($addon->settings->global_background_size) && $addon->settings->global_background_size) { $addon_css .= "\tbackground-size: " . $addon->settings->global_background_size . ";\n"; } if(isset($addon->settings->global_background_attachment) && $addon->settings->global_background_attachment) { $addon_css .= "\tbackground-attachment: " . $addon->settings->global_background_attachment . ";\n"; } } } // Border if(isset($addon->settings->global_user_border) && $addon->settings->global_user_border) { if(isset($addon->settings->global_border_width) && $addon->settings->global_border_width) { $addon_css .= "border-width: " . $addon->settings->global_border_width . "px;\n"; } if(isset($addon->settings->global_border_color) && $addon->settings->global_border_color) { $addon_css .= "border-color: " . $addon->settings->global_border_color . ";\n"; } if(isset($addon->settings->global_boder_style) && $addon->settings->global_boder_style) { $addon_css .= "border-style: " . $addon->settings->global_boder_style . ";\n"; } } // Border radius if(isset($addon->settings->global_border_radius) && $addon->settings->global_border_radius) { $addon_css .= "border-radius: " . $addon->settings->global_border_radius . "px;\n"; } // Padding & Margin if(isset($addon->settings->global_margin) && $addon->settings->global_margin) { $addon_css .= "margin: " . $addon->settings->global_margin . ";\n"; } if(isset($addon->settings->global_padding) && $addon->settings->global_padding) { $addon_css .= "padding: " . $addon->settings->global_padding . ";\n"; } if($addon_css) { $inlineCSS .= $addon_id ." {\n" . $addon_css . "}\n"; } if($addon_link_css) { $inlineCSS .= $addon_id ." a {\n" . $addon_link_css . "}\n"; } if($addon_link_hover_css) { $inlineCSS .= $addon_id ." a:hover,\n#sppb-addon-". $addon->id ." a:focus,\n#sppb-addon-". $addon->id ." a:active {\n" . $addon_link_hover_css . "}\n"; } //Addon Title if(isset($addon->settings->title) && $addon->settings->title) { $title_style = (isset($addon->settings->title_margin_top) && $addon->settings->title_margin_top != '') ? 'margin-top:' . (int) $addon->settings->title_margin_top . 'px;' : ''; $title_style .= (isset($addon->settings->title_margin_bottom) && $addon->settings->title_margin_bottom != '') ? 'margin-bottom:' . (int) $addon->settings->title_margin_bottom . 'px;' : ''; $title_style .= (isset($addon->settings->title_text_color) && $addon->settings->title_text_color) ? 'color:' . $addon->settings->title_text_color . ';' : ''; $title_style .= (isset($addon->settings->title_fontsize) && $addon->settings->title_fontsize) ? 'font-size:' . $addon->settings->title_fontsize . 'px;line-height:' . $addon->settings->title_fontsize . 'px;' : ''; $title_style .= (isset($addon->settings->title_lineheight) && $addon->settings->title_lineheight) ? 'line-height:' . $addon->settings->title_lineheight . 'px;' : ''; $title_style .= (isset($addon->settings->title_fontweight) && $addon->settings->title_fontweight) ? 'font-weight:' . $addon->settings->title_fontweight . ';' : ''; $title_style .= (isset($addon->settings->title_letterspace) && $addon->settings->title_letterspace) ? 'letter-spacing:' . $addon->settings->title_letterspace . ';' : ''; $title_font_style = (isset($addon->settings->title_fontstyle) && $addon->settings->title_fontstyle) ? $addon->settings->title_fontstyle : ''; if(is_array($title_font_style) && count($title_font_style)) { if(in_array('underline', $title_font_style)) { $title_style .= 'text-decoration: underline;'; } if(in_array('uppercase', $title_font_style)) { $title_style .= 'text-transform: uppercase;'; } if(in_array('italic', $title_font_style)) { $title_style .= 'font-style: italic;'; } if(in_array('lighter', $title_font_style)) { $title_style .= 'font-weight: lighter;'; } else if(in_array('normal', $title_font_style)) { $title_style .= 'font-weight: normal;'; } else if(in_array('bold', $title_font_style)) { $title_style .= 'font-weight: bold;'; } else if(in_array('bolder', $title_font_style)) { $title_style .= 'font-weight: bolder;'; } } if($title_style) { $inlineCSS .= $addon_id ." .sppb-addon-title {\n" . $title_style . "}\n"; } } echo $inlineCSS;
bmacenbacher/multison
components/com_sppagebuilder/layouts/addon/css.php
PHP
gpl-2.0
6,247
package com.offsec.nethunter; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.List; /** * Fragment used for managing interactions for and presentation of a navigation drawer. * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"> * design guidelines</a> for a complete explanation of the behaviors implemented here. */ public class SideMenu extends Fragment { /** * Remember the position of the selected item. */ private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; /** * Per the design guidelines, you should show the drawer on launch until the user manually * expands it. This shared preference tracks this. */ private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; /** * A pointer to the current callbacks instance (the Activity). */ private NavigationDrawerCallbacks mCallbacks; /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int mCurrentSelectedPosition = 0; private boolean mFromSavedInstanceState; private boolean mUserLearnedDrawer; private String[][] activitiesInfo; private String[] activityNames; private String[] activityIntents; public SideMenu() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activitiesInfo = querySampleActivities(); activityNames = activitiesInfo[0]; activityIntents = activitiesInfo[1]; // Read in the flag indicating whether or not the user has demonstrated awareness of the // drawer. See PREF_USER_LEARNED_DRAWER for details. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } // Select either the default item (0) or the last selected item. selectItem(mCurrentSelectedPosition); } public String[][] getMenuInfo() { // expose the activitiesInfo to the main class return activitiesInfo; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.side_menu, container, false); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); mDrawerLayout.closeDrawer(mDrawerListView); } }); mDrawerListView.setAdapter(new ArrayAdapter<String>( getActionBar().getThemedContext(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, activityNames )); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); return mDrawerListView; } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } public void closeDrawer() { mDrawerLayout.closeDrawer(mFragmentContainerView); } /** * Users of this fragment must call this method to set up the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up/back' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { // The user manually opened the drawer; store this flag to prevent auto-showing // the navigation drawer automatically in the future. mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } /*@Override public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, slideOffset); mainView.setTranslationX(slideOffset * drawerView.getWidth()); mDrawerLayout.bringChildToFront(drawerView); mDrawerLayout.requestLayout(); }*/ }; // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, // per the navigation drawer design guidelines. if (!mUserLearnedDrawer && !mFromSavedInstanceState) { mDrawerLayout.openDrawer(mFragmentContainerView); } // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void selectItem(int position) { // Log.d("select", String.valueOf(position)); mCurrentSelectedPosition = position; if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position, activityIntents[position]); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // If the drawer is open, show the global app actions in the action bar. See also // showGlobalContextActionBar, which controls the top-left area of the action bar. if (mDrawerLayout != null && isDrawerOpen()) { inflater.inflate(R.menu.global, menu); showGlobalContextActionBar(); } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } if (item.getItemId() == R.id.closeApp) { getActivity().finish(); } return super.onOptionsItemSelected(item); } /** * Per the navigation drawer design guidelines, updates the action bar to show the global app * 'context', rather than just what's in the current screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return getActivity().getActionBar(); } /** * Callbacks interface that all activities using this fragment must implement. */ public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position, String activity); } public String[][] querySampleActivities() { Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.setPackage(getActivity().getPackageName()); intent.addCategory(Intent.CATEGORY_SAMPLE_CODE); PackageManager pm = getActivity().getPackageManager(); List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0); final int count = infos.size(); int total = count; if (Build.VERSION.SDK_INT >= 21) { total = count-1; } String[] activityNames = new String[total]; String[] activityActions = new String[total]; for (int i = 0; i < count; i++) { final ResolveInfo info = infos.get(i); final CharSequence labelSeq = info.loadLabel(pm); if (!labelSeq.toString().equals("Iptables Configuration") || Build.VERSION.SDK_INT < 21) { String label = labelSeq != null ? labelSeq.toString() : info.activityInfo.name; activityNames[i] = label; activityActions[i] = info.activityInfo.name; } } return new String[][]{activityNames, activityActions}; } }
jorik041/nethunter-app
src/com/offsec/nethunter/SideMenu.java
Java
gpl-2.0
12,600
/* * e_trans.cpp * * Copyright (c) 2008, eFTE SF Group (see AUTHORS file) * Copyright (c) 1994-1996, Marko Macek * * You may distribute under the terms of either the GNU General Public * License or the Artistic License, as specified in the README file. * */ #include "fte.h" #include <ctype.h> // FLAW: NULL characters can not be translated, need escaping int ParseTrans(unsigned char *S, unsigned char *D, TransTable tab) { unsigned char Dest[512]; unsigned char A, B; unsigned int i; if (S == 0 || D == 0) return 0; strncpy((char *)Dest, (char *)D, sizeof(Dest) - 1); Dest[sizeof(Dest) - 1] = 0; D = Dest; // no translation for (i = 0; i < 256; i++) tab[i] = (unsigned char)i; while (*S && *D) { if (S[0] && S[1] == '-' && S[2]) { if (S[0] <= S[2]) { A = (*S)++; if (S[0] >= S[2]) S += 2; } else { A = (*S)--; if (S[0] <= S[2]) S += 2; } } else { A = *S++; } if (D[0] && D[1] == '-' && D[2]) { if (D[0] <= D[2]) { B = (*D)++; if (D[0] >= D[2]) D += 2; } else { B = (*D)--; if (D[0] <= D[2]) D += 2; } } else { B = *D++; } tab[A] = B; } if (*S != *D) // one was too short return 0; return 1; } int MakeTrans(TransTable tab, int What) { int i; // no translation for (i = 0; i <= 255; i++) tab[i] = (unsigned char)i; switch (What) { case ccToggle: case ccUp: for (i = 33; i <= 255; i++) if (isalpha(i) && (toupper(i) != i)) tab[i] = (unsigned char) toupper(i); if (What != ccToggle) break; case ccDown: for (i = 33; i <= 255; i++) if (isalpha(i) && (i == tab[i]) && (tolower(i) != i)) tab[i] = (unsigned char) tolower(i); break; default: return 0; } return 1; } int EBuffer::BlockTrans(TransTable tab) { int L, I, B, E; PELine LL; if (CheckBlock() == 0) return 0; if (RCount == 0) return 0; for (L = BB.Row; L <= BE.Row; L++) { LL = RLine(L); B = 0; E = 0; switch (BlockMode) { case bmLine: if (L == BE.Row) E = 0; else E = LL->Count; break; case bmColumn: if (L == BE.Row) E = 0; else { B = CharOffset(LL, BB.Col); E = CharOffset(LL, BE.Col); } break; case bmStream: if (L == BB.Row && L == BE.Row) { B = CharOffset(LL, BB.Col); E = CharOffset(LL, BE.Col); } else if (L == BB.Row) { B = CharOffset(LL, BB.Col); E = LL->Count; } else if (L == BE.Row) { B = 0; E = CharOffset(LL, BE.Col); } else { B = 0; E = LL->Count; } break; } if (B > LL->Count) B = LL->Count; if (E > LL->Count) E = LL->Count; if (E > B) { if (ChgChars(L, B, E - B, 0) == 0) return 0; for (I = B; I < E; I++) LL->Chars[I] = tab[(unsigned char)LL->Chars[I]]; } } Draw(BB.Row, BE.Row); return 1; } int EBuffer::CharTrans(TransTable tab) { PELine L = VLine(CP.Row); unsigned int P = CharOffset(L, CP.Col); if (P >= (unsigned int)L->Count) return 0; if (ChgChars(CP.Row, P, 1, 0) == 0) return 0; L->Chars[P] = tab[(unsigned char)L->Chars[P]]; return 1; } int EBuffer::LineTrans(TransTable tab) { PELine L = VLine(CP.Row); int I; if (L->Count > 0) { if (ChgChars(CP.Row, 0, L->Count, 0) == 0) return 0; for (I = 0; I < L->Count; I++) L->Chars[I] = tab[(unsigned char)L->Chars[I]]; } return 1; } int EBuffer::CharCaseUp() { TransTable tab; MakeTrans(tab, ccUp); return CharTrans(tab); } int EBuffer::CharCaseDown() { TransTable tab; MakeTrans(tab, ccDown); return CharTrans(tab); } int EBuffer::CharCaseToggle() { TransTable tab; MakeTrans(tab, ccToggle); return CharTrans(tab); } int EBuffer::LineCaseUp() { TransTable tab; MakeTrans(tab, ccUp); return LineTrans(tab); } int EBuffer::LineCaseDown() { TransTable tab; MakeTrans(tab, ccDown); return LineTrans(tab); } int EBuffer::LineCaseToggle() { TransTable tab; MakeTrans(tab, ccToggle); return LineTrans(tab); } int EBuffer::BlockCaseUp() { TransTable tab; MakeTrans(tab, ccUp); return BlockTrans(tab); } int EBuffer::BlockCaseDown() { TransTable tab; MakeTrans(tab, ccDown); return BlockTrans(tab); } int EBuffer::BlockCaseToggle() { TransTable tab; MakeTrans(tab, ccToggle); return BlockTrans(tab); } int EBuffer::GetTrans(ExState &State, TransTable tab) { unsigned char TrS[512] = ""; unsigned char TrD[512] = ""; if (State.GetStrParam(View, (char *)TrS, sizeof(TrS)) == 0) if (View->MView->Win->GetStr("Trans From", sizeof(TrS), (char *)TrS, HIST_TRANS) == 0) return 0; if (State.GetStrParam(View, (char *)TrD, sizeof(TrD)) == 0) if (View->MView->Win->GetStr("Trans To", sizeof(TrS), (char *)TrD, HIST_TRANS) == 0) return 0; if (ParseTrans(TrS, TrD, tab) == 0) { Msg(S_ERROR, "Bad Trans Arguments %s %s.", TrS, TrD); return 0; } return 1; } int EBuffer::CharTrans(ExState &State) { TransTable tab; if (GetTrans(State, tab) == 0) return 0; return CharTrans(tab); } int EBuffer::LineTrans(ExState &State) { TransTable tab; if (GetTrans(State, tab) == 0) return 0; return LineTrans(tab); } int EBuffer::BlockTrans(ExState &State) { TransTable tab; if (GetTrans(State, tab) == 0) return 0; return BlockTrans(tab); }
lanurmi/efte
src/e_trans.cpp
C++
gpl-2.0
6,273
<?php /** * Media Library Assistant extended List Table class * * @package Media Library Assistant * @since 1.40 */ /* * The WP_List_Table class isn't automatically available to plugins */ if ( !class_exists( 'WP_List_Table' ) ) { require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } /** * Class MLA (Media Library Assistant) View List Table implements the "Views" admin settings tab * * Extends the core WP_List_Table class. * * @package Media Library Assistant * @since 1.40 */ class MLA_View_List_Table extends WP_List_Table { /* * These arrays define the table columns. */ /** * Table column definitions * * This array defines table columns and titles where the key is the column slug (and class) * and the value is the column's title text. * * @since 1.40 * * @var array */ private static $default_columns = array( 'cb' => '<input type="checkbox" />', //Render a checkbox instead of text 'name' => 'Slug', 'specification' => 'Specification', 'post_mime_type' => 'Post Mime', 'table_view' => 'Table View', 'singular' => 'Singular Name', 'plural' => 'Plural Name', 'menu_order' => 'Order', 'description' => 'Description' ); /** * Default values for hidden columns * * This array is used when the user-level option is not set, i.e., * the user has not altered the selection of hidden columns. * * The value on the right-hand side must match the column slug, e.g., * array(0 => 'ID_parent, 1 => 'title_name'). * * @since 1.40 * * @var array */ private static $default_hidden_columns = array( // 'name', // 'specification', // 'post_mime_type', // 'table_view', 'singular', // 'plural', 'menu_order', 'description' ); /** * Sortable column definitions * * This array defines the table columns that can be sorted. The array key * is the column slug that needs to be sortable, and the value is database column * to sort by. Often, the key and value will be the same, but this is not always * the case (as the value is a column name from the database, not the list table). * * The array value also contains a boolean which is 'true' if the data is currently * sorted by that column. This is computed each time the table is displayed. * * @since 1.40 * * @var array */ private static $default_sortable_columns = array( 'name' => array('slug',false), 'specification' => array('specification',false), 'post_mime_type' => array('post_mime_type',false), 'table_view' => array('table_view',false), 'singular' => array('singular',false), 'plural' => array('plural',false), 'menu_order' => array('menu_order',false), 'description' => array('description',false) ); /** * Access the default list of hidden columns * * @since 1.40 * * @return array default list of hidden columns */ private static function _default_hidden_columns( ) { return self::$default_hidden_columns; } /** * Return the names and display values of the sortable columns * * @since 1.40 * * @return array name => array( orderby value, heading ) for sortable columns */ public static function mla_get_sortable_columns( ) { $results = array() ; foreach ( self::$default_sortable_columns as $key => $value ) { $value[1] = self::$default_columns[ $key ]; $results[ $key ] = $value; } return $results; } /** * Handler for filter 'get_user_option_managesettings_page_mla-settings-menu-viewcolumnshidden' * * Required because the screen.php get_hidden_columns function only uses * the get_user_option result. Set when the file is loaded because the object * is not created in time for the call from screen.php. * * @since 1.40 * * @param mixed false or array with current list of hidden columns, if any * @param string 'managesettings_page_mla-settings-menucolumnshidden' * @param object WP_User object, if logged in * * @return array updated list of hidden columns */ public static function mla_manage_hidden_columns_filter( $result, $option, $user_data ) { if ( $result ) return $result; else return self::_default_hidden_columns(); } /** * Handler for filter 'manage_settings_page_mla-settings-menu_columns' * * This required filter dictates the table's columns and titles. Set when the * file is loaded because the list_table object isn't created in time * to affect the "screen options" setup. * * @since 1.40 * * @return array list of table columns */ public static function mla_manage_columns_filter( ) { return self::$default_columns; } /** * Called in the admin_init action because the list_table object isn't * created in time to affect the "screen options" setup. * * @since 1.40 * * @return void */ public static function mla_admin_init_action( ) { if ( isset( $_REQUEST['mla_tab'] ) && $_REQUEST['mla_tab'] == 'view' ) { add_filter( 'get_user_option_managesettings_page_' . MLASettings::MLA_SETTINGS_SLUG . '-viewcolumnshidden', 'MLA_View_List_Table::mla_manage_hidden_columns_filter', 10, 3 ); add_filter( 'manage_settings_page_' . MLASettings::MLA_SETTINGS_SLUG . '-view_columns', 'MLA_View_List_Table::mla_manage_columns_filter', 10, 0 ); } } /** * Initializes some properties from $_REQUEST variables, then * calls the parent constructor to set some default configs. * * @since 1.40 * * @return void */ function __construct( ) { //Set parent defaults parent::__construct( array( 'singular' => 'post_mime_type', //singular name of the listed records 'plural' => 'post_mime_types', //plural name of the listed records 'ajax' => true, //does this table support ajax? 'screen' => 'settings_page_' . MLASettings::MLA_SETTINGS_SLUG . '-view' ) ); /* * NOTE: There is one add_action call at the end of this source file. * NOTE: There are two add_filter calls at the end of this source file. */ } /** * Supply a column value if no column-specific function has been defined * * Called when the parent class can't find a method specifically built for a * given column. All columns should have a specific method, so this function * returns a troubleshooting message. * * @since 1.40 * * @param array A singular item (one full row's worth of data) * @param array The name/slug of the column to be processed * @return string Text or HTML to be placed inside the column */ function column_default( $item, $column_name ) { //Show the whole array for troubleshooting purposes return 'column_default: ' . $column_name . ', ' . print_r( $item, true ); } /** * Displays checkboxes for using bulk actions. The 'cb' column * is given special treatment when columns are processed. * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_cb( $item ) { return sprintf( '<input type="checkbox" name="cb_mla_item_ID[]" value="%1$s" />', /*%1$s*/ $item->post_ID ); } /** * Add rollover actions to a table column * * @since 1.40 * * @param object An MLA post_mime_type object * @param string Current column name * * @return array Names and URLs of row-level actions */ private function _build_rollover_actions( $item, $column ) { $actions = array(); /* * Compose view arguments */ $view_args = array( 'page' => MLASettings::MLA_SETTINGS_SLUG . '-view', 'mla_tab' => 'view', 'mla_item_slug' => urlencode( $item->slug ) ); if ( isset( $_REQUEST['paged'] ) ) $view_args['paged'] = $_REQUEST['paged']; if ( isset( $_REQUEST['order'] ) ) $view_args['order'] = $_REQUEST['order']; if ( isset( $_REQUEST['orderby'] ) ) $view_args['orderby'] = $_REQUEST['orderby']; /* * Get the standard and custom types */ $mla_types = MLAOptions::mla_get_option( MLAOptions::MLA_POST_MIME_TYPES, true ); if ( ! is_array( $mla_types ) ) $mla_types = array (); $custom_types = MLAOptions::mla_get_option( MLAOptions::MLA_POST_MIME_TYPES, false, true ); if ( ! is_array( $custom_types ) ) $custom_types = array (); $actions['edit'] = '<a href="' . add_query_arg( $view_args, wp_nonce_url( '?mla_admin_action=' . MLA::MLA_ADMIN_SINGLE_EDIT_DISPLAY, MLA::MLA_ADMIN_NONCE ) ) . '" title="Edit this item">Edit</a>'; $actions['inline hide-if-no-js'] = '<a class="editinline" href="#" title="Edit this item inline">Quick Edit</a>'; if ( isset( $custom_types[ $item->slug ] ) ) { if ( isset( $mla_types[ $item->slug ] ) ) $actions['delete'] = '<a class="delete-tag"' . ' href="' . add_query_arg( $view_args, wp_nonce_url( '?mla_admin_action=' . MLA::MLA_ADMIN_SINGLE_DELETE, MLA::MLA_ADMIN_NONCE ) ) . '" title="Revert to standard item">Revert to Standard</a>'; else $actions['delete'] = '<a class="delete-tag"' . ' href="' . add_query_arg( $view_args, wp_nonce_url( '?mla_admin_action=' . MLA::MLA_ADMIN_SINGLE_DELETE, MLA::MLA_ADMIN_NONCE ) ) . '" title="Delete this item permanently">Delete Permanently</a>'; } // custom type return $actions; } /** * Add hidden fields with the data for use in the inline editor * * @since 1.40 * * @param object An MLA post_mime_type object * * @return string HTML <div> with row data */ private function _build_inline_data( $item ) { $inline_data = "\r\n" . '<div class="hidden" id="inline_' . $item->post_ID . "\">\r\n"; $inline_data .= ' <div class="original_slug">' . esc_attr( $item->slug ) . "</div>\r\n"; $inline_data .= ' <div class="slug">' . esc_attr( $item->slug ) . "</div>\r\n"; $inline_data .= ' <div class="singular">' . esc_attr( $item->singular ) . "</div>\r\n"; $inline_data .= ' <div class="plural">' . esc_attr( $item->plural ) . "</div>\r\n"; $inline_data .= ' <div class="specification">' . esc_attr( $item->specification ) . "</div>\r\n"; $inline_data .= ' <div class="post_mime_type">' . esc_attr( $item->post_mime_type ) . "</div>\r\n"; $inline_data .= ' <div class="table_view">' . esc_attr( $item->table_view ) . "</div>\r\n"; $inline_data .= ' <div class="menu_order">' . esc_attr( $item->menu_order ) . "</div>\r\n"; $inline_data .= ' <div class="description">' . esc_attr( $item->description ) . "</div>\r\n"; $inline_data .= "</div>\r\n"; return $inline_data; } /** * Supply the content for a custom column * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_name( $item ) { $row_actions = self::_build_rollover_actions( $item, 'name' ); $slug = esc_attr( $item->slug ); return sprintf( '%1$s<br>%2$s%3$s', /*%1$s*/ $slug, /*%2$s*/ $this->row_actions( $row_actions ), /*%3$s*/ $this->_build_inline_data( $item ) ); } /** * Supply the content for a custom column * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_specification( $item ) { return esc_attr( $item->specification ); } /** * Supply the content for a custom column * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_post_mime_type( $item ) { if ( $item->post_mime_type ) return 'yes'; else return 'no'; } /** * Supply the content for a custom column * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_table_view( $item ) { if ( $item->table_view ) return 'yes'; else return 'no'; } /** * Supply the content for a custom column * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_singular( $item ) { return esc_attr( $item->singular ); } /** * Supply the content for a custom column * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_plural( $item ) { return esc_attr( $item->plural ); } /** * Supply the content for a custom column * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_menu_order( $item ) { return (string) $item->menu_order; } /** * Supply the content for a custom column * * @since 1.40 * * @param object An MLA post_mime_type object * @return string HTML markup to be placed inside the column */ function column_description( $item ) { return esc_attr( $item->description ); } /** * This method dictates the table's columns and titles * * @since 1.40 * * @return array Column information: 'slugs'=>'Visible Titles' */ function get_columns( ) { return $columns = MLA_View_List_Table::mla_manage_columns_filter(); } /** * Returns the list of currently hidden columns from a user option or * from default values if the option is not set * * @since 1.40 * * @return array Column information,e.g., array(0 => 'ID_parent, 1 => 'title_name') */ function get_hidden_columns( ) { $columns = get_user_option( 'managesettings_page_' . MLASettings::MLA_SETTINGS_SLUG . '-viewcolumnshidden' ); if ( is_array( $columns ) ) { return $columns; } else return self::_default_hidden_columns(); } /** * Returns an array where the key is the column that needs to be sortable * and the value is db column to sort by. Also notes the current sort column, * if set. * * @since 1.40 * * @return array Sortable column information,e.g., * 'slugs'=>array('data_values',boolean) */ function get_sortable_columns( ) { $columns = self::$default_sortable_columns; if ( isset( $_REQUEST['orderby'] ) ) { $needle = array( $_REQUEST['orderby'], false ); $key = array_search( $needle, $columns ); if ( $key ) $columns[ $key ][ 1 ] = true; } else { $columns['menu_order'][ 1 ] = true; } return $columns; } /** * Get an associative array ( option_name => option_title ) with the list * of bulk actions available on this table. * * @since 1.40 * * @return array Contains all the bulk actions: 'slugs'=>'Visible Titles' */ function get_bulk_actions( ) { $actions = array(); $actions['edit'] = 'Edit'; $actions['delete'] = 'Delete Permanently'; return $actions; } /** * Prepares the list of items for displaying * * This is where you prepare your data for display. This method will usually * be used to query the database, sort and filter the data, and generally * get it ready to be displayed. At a minimum, we should set $this->items and * $this->set_pagination_args(). * * @since 1.40 * * @return void */ function prepare_items( ) { $this->_column_headers = array( $this->get_columns(), $this->get_hidden_columns(), $this->get_sortable_columns() ); /* * REQUIRED for pagination. */ $total_items = MLAMime::mla_count_view_items( $_REQUEST ); $user = get_current_user_id(); $screen = get_current_screen(); $option = $screen->get_option( 'per_page', 'option' ); if ( is_string( $option ) ) $per_page = get_user_meta( $user, $option, true ); else $per_page = 10; if ( empty( $per_page ) || $per_page < 1 ) $per_page = $screen->get_option( 'per_page', 'default' ); /* * REQUIRED. We also have to register our pagination options & calculations. */ $this->set_pagination_args( array( 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil( $total_items / $per_page ) ) ); $current_page = $this->get_pagenum(); /* * REQUIRED. Assign sorted and paginated data to the items property, where * it can be used by the rest of the class. */ $this->items = MLAMime::mla_query_view_items( $_REQUEST, ( ( $current_page - 1 ) * $per_page ), $per_page ); } /** * Generates (echoes) content for a single row of the table * * @since 1.40 * * @param object the current item * * @return void Echoes the row HTML */ function single_row( $item ) { static $row_class = ''; $row_class = ( $row_class == '' ? ' class="alternate"' : '' ); echo '<tr id="view-' . $item->post_ID . '"' . $row_class . '>'; echo parent::single_row_columns( $item ); echo '</tr>'; } } // class MLA_View_List_Table /* * Actions are added here, when the source file is loaded, because the MLA_View_List_Table * object is created too late to be useful. */ add_action( 'admin_init', 'MLA_View_List_Table::mla_admin_init_action' ); ?>
sontv1003/best-picture
wp-content/plugins/media-library-assistant/includes/class-mla-view-list-table.php
PHP
gpl-2.0
17,378
/* * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <winsock2.h> #include "FontCache.h" #include "Font.h" #include "SimpleFontData.h" #include "StringHash.h" #include "UnicodeRange.h" #include <mlang.h> #include <windows.h> #include <wtf/StdLibExtras.h> #if PLATFORM(CG) #include <ApplicationServices/ApplicationServices.h> #include <WebKitSystemInterface/WebKitSystemInterface.h> #endif using std::min; namespace WebCore { void FontCache::platformInit() { #if PLATFORM(CG) wkSetUpFontCache(1536 * 1024 * 4); // This size matches Mac. #endif } IMLangFontLink2* FontCache::getFontLinkInterface() { static IMultiLanguage *multiLanguage; if (!multiLanguage) { if (CoCreateInstance(CLSID_CMultiLanguage, 0, CLSCTX_ALL, IID_IMultiLanguage, (void**)&multiLanguage) != S_OK) return 0; } static IMLangFontLink2* langFontLink; if (!langFontLink) { if (multiLanguage->QueryInterface(&langFontLink) != S_OK) return 0; } return langFontLink; } static int CALLBACK metaFileEnumProc(HDC hdc, HANDLETABLE* table, CONST ENHMETARECORD* record, int tableEntries, LPARAM logFont) { if (record->iType == EMR_EXTCREATEFONTINDIRECTW) { const EMREXTCREATEFONTINDIRECTW* createFontRecord = reinterpret_cast<const EMREXTCREATEFONTINDIRECTW*>(record); *reinterpret_cast<LOGFONT*>(logFont) = createFontRecord->elfw.elfLogFont; } return true; } static int CALLBACK linkedFontEnumProc(CONST LOGFONT* logFont, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM hfont) { *reinterpret_cast<HFONT*>(hfont) = CreateFontIndirect(logFont); return false; } static const Vector<String>* getLinkedFonts(String& family) { static HashMap<String, Vector<String>*> systemLinkMap; Vector<String>* result = systemLinkMap.get(family); if (result) return result; result = new Vector<String>; systemLinkMap.set(family, result); HKEY fontLinkKey; if (FAILED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontLink\\SystemLink", 0, KEY_READ, &fontLinkKey))) return result; DWORD linkedFontsBufferSize = 0; RegQueryValueEx(fontLinkKey, family.charactersWithNullTermination(), 0, NULL, NULL, &linkedFontsBufferSize); WCHAR* linkedFonts = reinterpret_cast<WCHAR*>(malloc(linkedFontsBufferSize)); if (SUCCEEDED(RegQueryValueEx(fontLinkKey, family.charactersWithNullTermination(), 0, NULL, reinterpret_cast<BYTE*>(linkedFonts), &linkedFontsBufferSize))) { unsigned i = 0; unsigned length = linkedFontsBufferSize / sizeof(*linkedFonts); while (i < length) { while (i < length && linkedFonts[i] != ',') i++; i++; unsigned j = i; while (j < length && linkedFonts[j]) j++; result->append(String(linkedFonts + i, j - i)); i = j + 1; } } free(linkedFonts); RegCloseKey(fontLinkKey); return result; } static const Vector<DWORD, 4>& getCJKCodePageMasks() { // The default order in which we look for a font for a CJK character. If the user's default code page is // one of these, we will use it first. static const UINT CJKCodePages[] = { 932, /* Japanese */ 936, /* Simplified Chinese */ 950, /* Traditional Chinese */ 949 /* Korean */ }; static Vector<DWORD, 4> codePageMasks; static bool initialized; if (!initialized) { initialized = true; IMLangFontLink2* langFontLink = fontCache()->getFontLinkInterface(); if (!langFontLink) return codePageMasks; UINT defaultCodePage; DWORD defaultCodePageMask = 0; if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE, reinterpret_cast<LPWSTR>(&defaultCodePage), sizeof(defaultCodePage))) langFontLink->CodePageToCodePages(defaultCodePage, &defaultCodePageMask); if (defaultCodePage == CJKCodePages[0] || defaultCodePage == CJKCodePages[1] || defaultCodePage == CJKCodePages[2] || defaultCodePage == CJKCodePages[3]) codePageMasks.append(defaultCodePageMask); for (unsigned i = 0; i < 4; ++i) { if (defaultCodePage != CJKCodePages[i]) { DWORD codePageMask; langFontLink->CodePageToCodePages(CJKCodePages[i], &codePageMask); codePageMasks.append(codePageMask); } } } return codePageMasks; } static bool currentFontContainsCharacter(HDC hdc, UChar character) { static Vector<char, 512> glyphsetBuffer; glyphsetBuffer.resize(GetFontUnicodeRanges(hdc, 0)); GLYPHSET* glyphset = reinterpret_cast<GLYPHSET*>(glyphsetBuffer.data()); GetFontUnicodeRanges(hdc, glyphset); // FIXME: Change this to a binary search. unsigned i = 0; while (i < glyphset->cRanges && glyphset->ranges[i].wcLow <= character) i++; return i && glyphset->ranges[i - 1].wcLow + glyphset->ranges[i - 1].cGlyphs > character; } static HFONT createMLangFont(IMLangFontLink2* langFontLink, HDC hdc, DWORD codePageMask, UChar character = 0) { HFONT MLangFont; HFONT hfont = 0; if (SUCCEEDED(langFontLink->MapFont(hdc, codePageMask, character, &MLangFont)) && MLangFont) { LOGFONT lf; GetObject(MLangFont, sizeof(LOGFONT), &lf); langFontLink->ReleaseFont(MLangFont); hfont = CreateFontIndirect(&lf); } return hfont; } const SimpleFontData* FontCache::getFontDataForCharacters(const Font& font, const UChar* characters, int length) { UChar character = characters[0]; SimpleFontData* fontData = 0; HDC hdc = GetDC(0); HFONT primaryFont = font.primaryFont()->fontDataForCharacter(character)->platformData().hfont(); HGDIOBJ oldFont = SelectObject(hdc, primaryFont); HFONT hfont = 0; if (IMLangFontLink2* langFontLink = getFontLinkInterface()) { // Try MLang font linking first. DWORD codePages = 0; langFontLink->GetCharCodePages(character, &codePages); if (codePages && findCharUnicodeRange(character) == cRangeSetCJK) { // The CJK character may belong to multiple code pages. We want to // do font linking against a single one of them, preferring the default // code page for the user's locale. const Vector<DWORD, 4>& CJKCodePageMasks = getCJKCodePageMasks(); unsigned numCodePages = CJKCodePageMasks.size(); for (unsigned i = 0; i < numCodePages && !hfont; ++i) { hfont = createMLangFont(langFontLink, hdc, CJKCodePageMasks[i]); if (hfont && !(codePages & CJKCodePageMasks[i])) { // We asked about a code page that is not one of the code pages // returned by MLang, so the font might not contain the character. SelectObject(hdc, hfont); if (!currentFontContainsCharacter(hdc, character)) { DeleteObject(hfont); hfont = 0; } SelectObject(hdc, primaryFont); } } } else hfont = createMLangFont(langFontLink, hdc, codePages, character); } // A font returned from MLang is trusted to contain the character. bool containsCharacter = hfont; if (!hfont) { // To find out what font Uniscribe would use, we make it draw into a metafile and intercept // calls to CreateFontIndirect(). HDC metaFileDc = CreateEnhMetaFile(hdc, NULL, NULL, NULL); SelectObject(metaFileDc, primaryFont); bool scriptStringOutSucceeded = false; SCRIPT_STRING_ANALYSIS ssa; // FIXME: If length is greater than 1, we actually return the font for the last character. // This function should be renamed getFontDataForCharacter and take a single 32-bit character. if (SUCCEEDED(ScriptStringAnalyse(metaFileDc, characters, length, 0, -1, SSA_METAFILE | SSA_FALLBACK | SSA_GLYPHS | SSA_LINK, 0, NULL, NULL, NULL, NULL, NULL, &ssa))) { scriptStringOutSucceeded = SUCCEEDED(ScriptStringOut(ssa, 0, 0, 0, NULL, 0, 0, FALSE)); ScriptStringFree(&ssa); } HENHMETAFILE metaFile = CloseEnhMetaFile(metaFileDc); if (scriptStringOutSucceeded) { LOGFONT logFont; logFont.lfFaceName[0] = 0; EnumEnhMetaFile(0, metaFile, metaFileEnumProc, &logFont, NULL); if (logFont.lfFaceName[0]) hfont = CreateFontIndirect(&logFont); } DeleteEnhMetaFile(metaFile); } String familyName; const Vector<String>* linkedFonts = 0; unsigned linkedFontIndex = 0; while (hfont) { SelectObject(hdc, hfont); WCHAR name[LF_FACESIZE]; GetTextFace(hdc, LF_FACESIZE, name); familyName = name; if (containsCharacter || currentFontContainsCharacter(hdc, character)) break; if (!linkedFonts) linkedFonts = getLinkedFonts(familyName); SelectObject(hdc, oldFont); DeleteObject(hfont); hfont = 0; if (linkedFonts->size() <= linkedFontIndex) break; LOGFONT logFont; logFont.lfCharSet = DEFAULT_CHARSET; memcpy(logFont.lfFaceName, linkedFonts->at(linkedFontIndex).characters(), linkedFonts->at(linkedFontIndex).length() * sizeof(WCHAR)); logFont.lfFaceName[linkedFonts->at(linkedFontIndex).length()] = 0; EnumFontFamiliesEx(hdc, &logFont, linkedFontEnumProc, reinterpret_cast<LPARAM>(&hfont), 0); linkedFontIndex++; } if (hfont) { if (!familyName.isEmpty()) { FontPlatformData* result = getCachedFontPlatformData(font.fontDescription(), familyName); if (result) fontData = getCachedFontData(result); } SelectObject(hdc, oldFont); DeleteObject(hfont); } ReleaseDC(0, hdc); return fontData; } SimpleFontData* FontCache::getSimilarFontPlatformData(const Font& font) { return 0; } SimpleFontData* FontCache::getLastResortFallbackFont(const FontDescription& fontDescription) { // FIXME: Would be even better to somehow get the user's default font here. For now we'll pick // the default that the user would get without changing any prefs. static AtomicString timesStr("Times New Roman"); if (SimpleFontData* simpleFont = getCachedFontData(fontDescription, timesStr)) return simpleFont; DEFINE_STATIC_LOCAL(String, defaultGUIFontFamily, ()); if (defaultGUIFontFamily.isEmpty()) { HFONT defaultGUIFont = static_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT)); LOGFONT logFont; GetObject(defaultGUIFont, sizeof(logFont), &logFont); defaultGUIFontFamily = String(logFont.lfFaceName, wcsnlen(logFont.lfFaceName, LF_FACESIZE)); } return getCachedFontData(fontDescription, defaultGUIFontFamily); } static LONG toGDIFontWeight(FontWeight fontWeight) { static LONG gdiFontWeights[] = { FW_THIN, // FontWeight100 FW_EXTRALIGHT, // FontWeight200 FW_LIGHT, // FontWeight300 FW_NORMAL, // FontWeight400 FW_MEDIUM, // FontWeight500 FW_SEMIBOLD, // FontWeight600 FW_BOLD, // FontWeight700 FW_EXTRABOLD, // FontWeight800 FW_HEAVY // FontWeight900 }; return gdiFontWeights[fontWeight]; } static inline bool isGDIFontWeightBold(LONG gdiFontWeight) { return gdiFontWeight >= FW_SEMIBOLD; } static LONG adjustedGDIFontWeight(LONG gdiFontWeight, const String& family) { static AtomicString lucidaStr("Lucida Grande"); if (equalIgnoringCase(family, lucidaStr)) { if (gdiFontWeight == FW_NORMAL) return FW_MEDIUM; if (gdiFontWeight == FW_BOLD) return FW_SEMIBOLD; } return gdiFontWeight; } struct MatchImprovingProcData { MatchImprovingProcData(LONG desiredWeight, bool desiredItalic) : m_desiredWeight(desiredWeight) , m_desiredItalic(desiredItalic) , m_hasMatched(false) { } LONG m_desiredWeight; bool m_desiredItalic; bool m_hasMatched; LOGFONT m_chosen; }; static int CALLBACK matchImprovingEnumProc(CONST LOGFONT* candidate, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM lParam) { MatchImprovingProcData* matchData = reinterpret_cast<MatchImprovingProcData*>(lParam); if (!matchData->m_hasMatched) { matchData->m_hasMatched = true; matchData->m_chosen = *candidate; return 1; } if (!candidate->lfItalic != !matchData->m_chosen.lfItalic) { if (!candidate->lfItalic == !matchData->m_desiredItalic) matchData->m_chosen = *candidate; return 1; } unsigned chosenWeightDeltaMagnitude = abs(matchData->m_chosen.lfWeight - matchData->m_desiredWeight); unsigned candidateWeightDeltaMagnitude = abs(candidate->lfWeight - matchData->m_desiredWeight); // If both are the same distance from the desired weight, prefer the candidate if it is further from regular. if (chosenWeightDeltaMagnitude == candidateWeightDeltaMagnitude && abs(candidate->lfWeight - FW_NORMAL) > abs(matchData->m_chosen.lfWeight - FW_NORMAL)) { matchData->m_chosen = *candidate; return 1; } // Otherwise, prefer the one closer to the desired weight. if (candidateWeightDeltaMagnitude < chosenWeightDeltaMagnitude) matchData->m_chosen = *candidate; return 1; } static HFONT createGDIFont(const AtomicString& family, LONG desiredWeight, bool desiredItalic, int size, bool synthesizeItalic) { HDC hdc = GetDC(0); LOGFONT logFont; logFont.lfCharSet = DEFAULT_CHARSET; unsigned familyLength = min(family.length(), static_cast<unsigned>(LF_FACESIZE - 1)); memcpy(logFont.lfFaceName, family.characters(), familyLength * sizeof(UChar)); logFont.lfFaceName[familyLength] = 0; logFont.lfPitchAndFamily = 0; MatchImprovingProcData matchData(desiredWeight, desiredItalic); EnumFontFamiliesEx(hdc, &logFont, matchImprovingEnumProc, reinterpret_cast<LPARAM>(&matchData), 0); ReleaseDC(0, hdc); if (!matchData.m_hasMatched) return 0; matchData.m_chosen.lfHeight = -size; matchData.m_chosen.lfWidth = 0; matchData.m_chosen.lfEscapement = 0; matchData.m_chosen.lfOrientation = 0; matchData.m_chosen.lfUnderline = false; matchData.m_chosen.lfStrikeOut = false; matchData.m_chosen.lfCharSet = DEFAULT_CHARSET; #if PLATFORM(CG) || PLATFORM(CAIRO) matchData.m_chosen.lfOutPrecision = OUT_TT_ONLY_PRECIS; #else matchData.m_chosen.lfOutPrecision = OUT_TT_PRECIS; #endif matchData.m_chosen.lfQuality = DEFAULT_QUALITY; matchData.m_chosen.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; if (desiredItalic && !matchData.m_chosen.lfItalic && synthesizeItalic) matchData.m_chosen.lfItalic = 1; HFONT result = CreateFontIndirect(&matchData.m_chosen); if (!result) return 0; HDC dc = GetDC(0); SaveDC(dc); SelectObject(dc, result); WCHAR actualName[LF_FACESIZE]; GetTextFace(dc, LF_FACESIZE, actualName); RestoreDC(dc, -1); ReleaseDC(0, dc); if (wcsicmp(matchData.m_chosen.lfFaceName, actualName)) { DeleteObject(result); result = 0; } return result; } struct TraitsInFamilyProcData { TraitsInFamilyProcData(const AtomicString& familyName) : m_familyName(familyName) { } const AtomicString& m_familyName; HashSet<unsigned> m_traitsMasks; }; static int CALLBACK traitsInFamilyEnumProc(CONST LOGFONT* logFont, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM lParam) { TraitsInFamilyProcData* procData = reinterpret_cast<TraitsInFamilyProcData*>(lParam); unsigned traitsMask = 0; traitsMask |= logFont->lfItalic ? FontStyleItalicMask : FontStyleNormalMask; traitsMask |= FontVariantNormalMask; LONG weight = adjustedGDIFontWeight(logFont->lfWeight, procData->m_familyName); traitsMask |= weight == FW_THIN ? FontWeight100Mask : weight == FW_EXTRALIGHT ? FontWeight200Mask : weight == FW_LIGHT ? FontWeight300Mask : weight == FW_NORMAL ? FontWeight400Mask : weight == FW_MEDIUM ? FontWeight500Mask : weight == FW_SEMIBOLD ? FontWeight600Mask : weight == FW_BOLD ? FontWeight700Mask : weight == FW_EXTRABOLD ? FontWeight800Mask : FontWeight900Mask; procData->m_traitsMasks.add(traitsMask); return 1; } void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks) { HDC hdc = GetDC(0); LOGFONT logFont; logFont.lfCharSet = DEFAULT_CHARSET; unsigned familyLength = min(familyName.length(), static_cast<unsigned>(LF_FACESIZE - 1)); memcpy(logFont.lfFaceName, familyName.characters(), familyLength * sizeof(UChar)); logFont.lfFaceName[familyLength] = 0; logFont.lfPitchAndFamily = 0; TraitsInFamilyProcData procData(familyName); EnumFontFamiliesEx(hdc, &logFont, traitsInFamilyEnumProc, reinterpret_cast<LPARAM>(&procData), 0); copyToVector(procData.m_traitsMasks, traitsMasks); ReleaseDC(0, hdc); } FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family) { bool isLucidaGrande = false; static AtomicString lucidaStr("Lucida Grande"); if (equalIgnoringCase(family, lucidaStr)) isLucidaGrande = true; bool useGDI = fontDescription.renderingMode() == AlternateRenderingMode && !isLucidaGrande; // The logical size constant is 32. We do this for subpixel precision when rendering using Uniscribe. // This masks rounding errors related to the HFONT metrics being different from the CGFont metrics. // FIXME: We will eventually want subpixel precision for GDI mode, but the scaled rendering doesn't // look as nice. That may be solvable though. #if PLATFORM(CG) bool canCreateCGFontWithLOGFONT = wkCanCreateCGFontWithLOGFONT(); #else bool canCreateCGFontWithLOGFONT = true; #endif LONG weight = adjustedGDIFontWeight(toGDIFontWeight(fontDescription.weight()), family); HFONT hfont = createGDIFont(family, weight, fontDescription.italic(), fontDescription.computedPixelSize() * (useGDI ? 1 : 32), useGDI && canCreateCGFontWithLOGFONT); if (!hfont) return 0; if (isLucidaGrande) useGDI = false; // Never use GDI for Lucida Grande. LOGFONT logFont; GetObject(hfont, sizeof(LOGFONT), &logFont); bool synthesizeBold = isGDIFontWeightBold(weight) && !isGDIFontWeightBold(logFont.lfWeight); bool synthesizeItalic = fontDescription.italic() && !logFont.lfItalic; FontPlatformData* result = new FontPlatformData(hfont, fontDescription.computedPixelSize(), synthesizeBold, synthesizeItalic, useGDI); #if PLATFORM(CG) bool fontCreationFailed = !result->cgFont(); #elif PLATFORM(CAIRO) bool fontCreationFailed = !result->fontFace(); #endif if (fontCreationFailed) { // The creation of the CGFontRef failed for some reason. We already asserted in debug builds, but to make // absolutely sure that we don't use this font, go ahead and return 0 so that we can fall back to the next // font. delete result; DeleteObject(hfont); return 0; } return result; } }
asoneofus/v350
FADG_4.39A/external/webkit/WebCore/platform/graphics/win/FontCacheWin.cpp
C++
gpl-2.0
21,172
/** @file Crypto_md5.cpp @author Morgan McGuire, http://graphics.cs.williams.edu Copyright 2006-2007, Morgan McGuire. All rights reserved. @created 2006-03-28 @edited 2006-04-06 */ #include "G3D/platform.h" #include "G3D/Crypto.h" #include "G3D/BinaryInput.h" #include "G3D/BinaryOutput.h" #include <cstring> namespace G3D { MD5Hash::MD5Hash(class BinaryInput& b) { deserialize(b); } void MD5Hash::deserialize(class BinaryInput& b) { b.readBytes(value, 16); } void MD5Hash::serialize(class BinaryOutput& b) const { b.writeBytes(value, 16); } typedef unsigned char md5_byte_t; /* 8-bit byte */ typedef unsigned int md5_word_t; /* 32-bit word */ /* Define the state of the MD5 Algorithm. */ typedef struct md5_state_s { md5_word_t count[2]; /* message length in bits, lsw first */ md5_word_t abcd[4]; /* digest buffer */ md5_byte_t buf[64]; /* accumulate block */ } md5_state_t; #ifdef __cplusplus extern "C" { #endif /* Initialize the algorithm. */ static void md5_init(md5_state_t *pms); /* Append a string to the message. */ static void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes); /* Finish the message and return the digest. */ static void md5_finish(md5_state_t *pms, md5_byte_t digest[16]); #ifdef __cplusplus } #endif MD5Hash Crypto::md5(const void* data, size_t n) { md5_state_t state; md5_init(&state); md5_append(&state, (const uint8*)data, (int)n); MD5Hash h; md5_finish(&state, &(h[0])); return h; } /* Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. L. Peter Deutsch ghost@aladdin.com */ /* Independent implementation of MD5 (RFC 1321). This code implements the MD5 Algorithm defined in RFC 1321, whose text is available at http://www.ietf.org/rfc/rfc1321.txt The code is derived from the text of the RFC, including the test suite (section A.5) but excluding the rest of Appendix A. It does not include any code or documentation that is identified in the RFC as being copyrighted. The original and principal author of md5.c is L. Peter Deutsch <ghost@aladdin.com>. Other authors are noted in the change history that follows (in reverse chronological order): 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order either statically or dynamically; added missing #include <string.h> in library. 2002-03-11 lpd Corrected argument list for main(), and added int return type, in test program and T value program. 2002-02-21 lpd Added missing #include <stdio.h> in test program. 2000-07-03 lpd Patched to eliminate warnings about "constant is unsigned in ANSI C, signed in traditional"; made test program self-checking. 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). 1999-05-03 lpd Original version. */ /* * This package supports both compile-time and run-time determination of CPU * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is * defined as non-zero, the code will be compiled to run only on big-endian * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to * run on either big- or little-endian CPUs, but will run slightly less * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined. */ #if defined(G3D_LINUX) || defined(G3D_OSX) # if defined(G3D_OSX_PPC) # include <ppc/endian.h> # elif defined(G3D_OSX_INTEL) # include <i386/endian.h> # elif defined(__linux__) # include <endian.h> # elif defined(__FreeBSD__) # include <sys/endian.h> # endif #else # define BYTE_ORDER 0 #endif #define T_MASK ((md5_word_t)~0) #define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) #define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) #define T3 0x242070db #define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) #define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) #define T6 0x4787c62a #define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) #define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) #define T9 0x698098d8 #define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) #define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) #define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) #define T13 0x6b901122 #define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) #define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) #define T16 0x49b40821 #define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) #define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) #define T19 0x265e5a51 #define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) #define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) #define T22 0x02441453 #define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) #define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) #define T25 0x21e1cde6 #define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) #define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) #define T28 0x455a14ed #define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) #define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) #define T31 0x676f02d9 #define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) #define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) #define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) #define T35 0x6d9d6122 #define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) #define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) #define T38 0x4bdecfa9 #define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) #define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) #define T41 0x289b7ec6 #define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) #define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) #define T44 0x04881d05 #define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) #define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) #define T47 0x1fa27cf8 #define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) #define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) #define T50 0x432aff97 #define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) #define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) #define T53 0x655b59c3 #define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) #define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) #define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) #define T57 0x6fa87e4f #define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) #define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) #define T60 0x4e0811a1 #define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) #define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) #define T63 0x2ad7d2bb #define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) static void md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) { md5_word_t a = pms->abcd[0], b = pms->abcd[1], c = pms->abcd[2], d = pms->abcd[3]; md5_word_t t; #if BYTE_ORDER > 0 /* Define storage only for big-endian CPUs. */ md5_word_t X[16]; #else /* Define storage for little-endian or both types of CPUs. */ md5_word_t xbuf[16]; const md5_word_t *X; #endif { #if BYTE_ORDER == 0 /* * Determine dynamically whether this is a big-endian or * little-endian machine, since we can use a more efficient * algorithm on the latter. */ static const int w = 1; if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ #endif #if BYTE_ORDER <= 0 /* little-endian */ { /* * On little-endian machines, we can process properly aligned * data without copying it. */ if (!((data - (const md5_byte_t *)0) & 3)) { /* data are properly aligned */ X = (const md5_word_t *)data; } else { /* not aligned */ memcpy(xbuf, data, 64); X = xbuf; } } #endif #if BYTE_ORDER == 0 else /* dynamic big-endian */ #endif #if BYTE_ORDER >= 0 /* big-endian */ { /* * On big-endian machines, we must arrange the bytes in the * right order. */ const md5_byte_t *xp = data; int i; # if BYTE_ORDER == 0 X = xbuf; /* (dynamic only) */ # else # define xbuf X /* (static only) */ # endif for (i = 0; i < 16; ++i, xp += 4) xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); } #endif } #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) /* Round 1. */ /* Let [abcd k s i] denote the operation a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ #define F(x, y, z) (((x) & (y)) | (~(x) & (z))) #define SET(a, b, c, d, k, s, Ti)\ t = a + F(b,c,d) + X[k] + Ti;\ a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ SET(a, b, c, d, 0, 7, T1); SET(d, a, b, c, 1, 12, T2); SET(c, d, a, b, 2, 17, T3); SET(b, c, d, a, 3, 22, T4); SET(a, b, c, d, 4, 7, T5); SET(d, a, b, c, 5, 12, T6); SET(c, d, a, b, 6, 17, T7); SET(b, c, d, a, 7, 22, T8); SET(a, b, c, d, 8, 7, T9); SET(d, a, b, c, 9, 12, T10); SET(c, d, a, b, 10, 17, T11); SET(b, c, d, a, 11, 22, T12); SET(a, b, c, d, 12, 7, T13); SET(d, a, b, c, 13, 12, T14); SET(c, d, a, b, 14, 17, T15); SET(b, c, d, a, 15, 22, T16); #undef SET /* Round 2. */ /* Let [abcd k s i] denote the operation a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ #define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) #define SET(a, b, c, d, k, s, Ti)\ t = a + G(b,c,d) + X[k] + Ti;\ a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ SET(a, b, c, d, 1, 5, T17); SET(d, a, b, c, 6, 9, T18); SET(c, d, a, b, 11, 14, T19); SET(b, c, d, a, 0, 20, T20); SET(a, b, c, d, 5, 5, T21); SET(d, a, b, c, 10, 9, T22); SET(c, d, a, b, 15, 14, T23); SET(b, c, d, a, 4, 20, T24); SET(a, b, c, d, 9, 5, T25); SET(d, a, b, c, 14, 9, T26); SET(c, d, a, b, 3, 14, T27); SET(b, c, d, a, 8, 20, T28); SET(a, b, c, d, 13, 5, T29); SET(d, a, b, c, 2, 9, T30); SET(c, d, a, b, 7, 14, T31); SET(b, c, d, a, 12, 20, T32); #undef SET /* Round 3. */ /* Let [abcd k s t] denote the operation a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ #define H(x, y, z) ((x) ^ (y) ^ (z)) #define SET(a, b, c, d, k, s, Ti)\ t = a + H(b,c,d) + X[k] + Ti;\ a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ SET(a, b, c, d, 5, 4, T33); SET(d, a, b, c, 8, 11, T34); SET(c, d, a, b, 11, 16, T35); SET(b, c, d, a, 14, 23, T36); SET(a, b, c, d, 1, 4, T37); SET(d, a, b, c, 4, 11, T38); SET(c, d, a, b, 7, 16, T39); SET(b, c, d, a, 10, 23, T40); SET(a, b, c, d, 13, 4, T41); SET(d, a, b, c, 0, 11, T42); SET(c, d, a, b, 3, 16, T43); SET(b, c, d, a, 6, 23, T44); SET(a, b, c, d, 9, 4, T45); SET(d, a, b, c, 12, 11, T46); SET(c, d, a, b, 15, 16, T47); SET(b, c, d, a, 2, 23, T48); #undef SET /* Round 4. */ /* Let [abcd k s t] denote the operation a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ #define I(x, y, z) ((y) ^ ((x) | ~(z))) #define SET(a, b, c, d, k, s, Ti)\ t = a + I(b,c,d) + X[k] + Ti;\ a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ SET(a, b, c, d, 0, 6, T49); SET(d, a, b, c, 7, 10, T50); SET(c, d, a, b, 14, 15, T51); SET(b, c, d, a, 5, 21, T52); SET(a, b, c, d, 12, 6, T53); SET(d, a, b, c, 3, 10, T54); SET(c, d, a, b, 10, 15, T55); SET(b, c, d, a, 1, 21, T56); SET(a, b, c, d, 8, 6, T57); SET(d, a, b, c, 15, 10, T58); SET(c, d, a, b, 6, 15, T59); SET(b, c, d, a, 13, 21, T60); SET(a, b, c, d, 4, 6, T61); SET(d, a, b, c, 11, 10, T62); SET(c, d, a, b, 2, 15, T63); SET(b, c, d, a, 9, 21, T64); #undef SET /* Then perform the following additions. (That is increment each of the four registers by the value it had before this block was started.) */ pms->abcd[0] += a; pms->abcd[1] += b; pms->abcd[2] += c; pms->abcd[3] += d; } void md5_init(md5_state_t *pms) { pms->count[0] = pms->count[1] = 0; pms->abcd[0] = 0x67452301; pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; pms->abcd[3] = 0x10325476; } void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) { const md5_byte_t *p = data; int left = nbytes; int offset = (pms->count[0] >> 3) & 63; md5_word_t nbits = (md5_word_t)(nbytes << 3); if (nbytes <= 0) return; /* Update the message length. */ pms->count[1] += nbytes >> 29; pms->count[0] += nbits; if (pms->count[0] < nbits) pms->count[1]++; /* Process an initial partial block. */ if (offset) { int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); memcpy(pms->buf + offset, p, copy); if (offset + copy < 64) return; p += copy; left -= copy; md5_process(pms, pms->buf); } /* Process full blocks. */ for (; left >= 64; p += 64, left -= 64) md5_process(pms, p); /* Process a final partial block. */ if (left) memcpy(pms->buf, p, left); } void md5_finish(md5_state_t *pms, md5_byte_t digest[16]) { static const md5_byte_t pad[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; md5_byte_t data[8]; int i; /* Save the length before padding. */ for (i = 0; i < 8; ++i) data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); /* Pad to 56 bytes mod 64. */ md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); /* Append the length. */ md5_append(pms, data, 8); for (i = 0; i < 16; ++i) digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); } }
hktari/TrinityCore
dep/g3dlite/source/Crypto_md5.cpp
C++
gpl-2.0
14,762
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * This code is partially based on the Rack-Cache library by Ryan Tomayko, * which is released under the MIT license. * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\HttpCache; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\TerminableInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Cache provides HTTP caching. * * @author Fabien Potencier <fabien@symfony.com> */ class HttpCache implements HttpKernelInterface, TerminableInterface { private $kernel; private $store; private $request; private $surrogate; private $surrogateCacheStrategy; private $options = array(); private $traces = array(); /** * Constructor. * * The available options are: * * * debug: If true, the traces are added as a HTTP header to ease debugging * * * default_ttl The number of seconds that a cache entry should be considered * fresh when no explicit freshness information is provided in * a response. Explicit Cache-Control or Expires headers * override this value. (default: 0) * * * private_headers Set of request headers that trigger "private" cache-control behavior * on responses that don't explicitly state whether the response is * public or private via a Cache-Control directive. (default: Authorization and Cookie) * * * allow_reload Specifies whether the client can force a cache reload by including a * Cache-Control "no-cache" directive in the request. Set it to ``true`` * for compliance with RFC 2616. (default: false) * * * allow_revalidate Specifies whether the client can force a cache revalidate by including * a Cache-Control "max-age=0" directive in the request. Set it to ``true`` * for compliance with RFC 2616. (default: false) * * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the * Response TTL precision is a second) during which the cache can immediately return * a stale response while it revalidates it in the background (default: 2). * This setting is overridden by the stale-while-revalidate HTTP Cache-Control * extension (see RFC 5861). * * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which * the cache can serve a stale response when an error is encountered (default: 60). * This setting is overridden by the stale-if-error HTTP Cache-Control extension * (see RFC 5861). * * @param HttpKernelInterface $kernel An HttpKernelInterface instance * @param StoreInterface $store A Store instance * @param SurrogateInterface $surrogate A SurrogateInterface instance * @param array $options An array of options */ public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array()) { $this->store = $store; $this->kernel = $kernel; $this->surrogate = $surrogate; // needed in case there is a fatal error because the backend is too slow to respond register_shutdown_function(array($this->store, 'cleanup')); $this->options = array_merge(array( 'debug' => false, 'default_ttl' => 0, 'private_headers' => array('Authorization', 'Cookie'), 'allow_reload' => false, 'allow_revalidate' => false, 'stale_while_revalidate' => 2, 'stale_if_error' => 60, ), $options); } /** * Gets the current store. * * @return StoreInterface $store A StoreInterface instance */ public function getStore() { return $this->store; } /** * Returns an array of events that took place during processing of the last request. * * @return array An array of events */ public function getTraces() { return $this->traces; } /** * Returns a log message for the events of the last request processing. * * @return string A log message */ public function getLog() { $log = array(); foreach ($this->traces as $request => $traces) { $log[] = sprintf('%s: %s', $request, implode(', ', $traces)); } return implode('; ', $log); } /** * Gets the Request instance associated with the master request. * * @return Request A Request instance */ public function getRequest() { return $this->request; } /** * Gets the Kernel instance. * * @return HttpKernelInterface An HttpKernelInterface instance */ public function getKernel() { return $this->kernel; } /** * Gets the Surrogate instance. * * @throws \LogicException * * @return SurrogateInterface A Surrogate instance */ public function getSurrogate() { if (!$this->surrogate instanceof Esi) { throw new \LogicException('This instance of HttpCache was not set up to use ESI as surrogate handler. You must overwrite and use createSurrogate'); } return $this->surrogate; } /** * Gets the Esi instance. * * @throws \LogicException * * @return Esi An Esi instance * * @deprecated since version 2.6, to be removed in 3.0. Use getSurrogate() instead */ public function getEsi() { @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the getSurrogate() method instead.', E_USER_DEPRECATED); return $this->getSurrogate(); } /** * {@inheritdoc} */ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism if (HttpKernelInterface::MASTER_REQUEST === $type) { $this->traces = array(); $this->request = $request; if (null !== $this->surrogate) { $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy(); } } $path = $request->getPathInfo(); if ($qs = $request->getQueryString()) { $path .= '?'.$qs; } $this->traces[$request->getMethod().' '.$path] = array(); if (!$request->isMethodSafe()) { $response = $this->invalidate($request, $catch); } elseif ($request->headers->has('expect')) { $response = $this->pass($request, $catch); } else { $response = $this->lookup($request, $catch); } $this->restoreResponseBody($request, $response); $response->setDate(\DateTime::createFromFormat('U', time(), new \DateTimeZone('UTC'))); if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) { $response->headers->set('X-Symfony-Cache', $this->getLog()); } if (null !== $this->surrogate) { if (HttpKernelInterface::MASTER_REQUEST === $type) { $this->surrogateCacheStrategy->update($response); } else { $this->surrogateCacheStrategy->add($response); } } $response->prepare($request); $response->isNotModified($request); return $response; } /** * {@inheritdoc} */ public function terminate(Request $request, Response $response) { if ($this->getKernel() instanceof TerminableInterface) { $this->getKernel()->terminate($request, $response); } } /** * Forwards the Request to the backend without storing the Response in the cache. * * @param Request $request A Request instance * @param bool $catch Whether to process exceptions * * @return Response A Response instance */ protected function pass(Request $request, $catch = false) { $this->record($request, 'pass'); return $this->forward($request, $catch); } /** * Invalidates non-safe methods (like POST, PUT, and DELETE). * * @param Request $request A Request instance * @param bool $catch Whether to process exceptions * * @return Response A Response instance * * @throws \Exception * * @see RFC2616 13.10 */ protected function invalidate(Request $request, $catch = false) { $response = $this->pass($request, $catch); // invalidate only when the response is successful if ($response->isSuccessful() || $response->isRedirect()) { try { $this->store->invalidate($request, $catch); // As per the RFC, invalidate Location and Content-Location URLs if present foreach (array('Location', 'Content-Location') as $header) { if ($uri = $response->headers->get($header)) { $subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all()); $this->store->invalidate($subRequest); } } $this->record($request, 'invalidate'); } catch (\Exception $e) { $this->record($request, 'invalidate-failed'); if ($this->options['debug']) { throw $e; } } } return $response; } /** * Lookups a Response from the cache for the given Request. * * When a matching cache entry is found and is fresh, it uses it as the * response without forwarding any request to the backend. When a matching * cache entry is found but is stale, it attempts to "validate" the entry with * the backend using conditional GET. When no matching cache entry is found, * it triggers "miss" processing. * * @param Request $request A Request instance * @param bool $catch whether to process exceptions * * @return Response A Response instance * * @throws \Exception */ protected function lookup(Request $request, $catch = false) { // if allow_reload and no-cache Cache-Control, allow a cache reload if ($this->options['allow_reload'] && $request->isNoCache()) { $this->record($request, 'reload'); return $this->fetch($request, $catch); } try { $entry = $this->store->lookup($request); } catch (\Exception $e) { $this->record($request, 'lookup-failed'); if ($this->options['debug']) { throw $e; } return $this->pass($request, $catch); } if (null === $entry) { $this->record($request, 'miss'); return $this->fetch($request, $catch); } if (!$this->isFreshEnough($request, $entry)) { $this->record($request, 'stale'); return $this->validate($request, $entry, $catch); } $this->record($request, 'fresh'); $entry->headers->set('Age', $entry->getAge()); return $entry; } /** * Validates that a cache entry is fresh. * * The original request is used as a template for a conditional * GET request with the backend. * * @param Request $request A Request instance * @param Response $entry A Response instance to validate * @param bool $catch Whether to process exceptions * * @return Response A Response instance */ protected function validate(Request $request, Response $entry, $catch = false) { $subRequest = clone $request; // send no head requests because we want content $subRequest->setMethod('GET'); // add our cached last-modified validator $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified')); // Add our cached etag validator to the environment. // We keep the etags from the client to handle the case when the client // has a different private valid entry which is not cached here. $cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array(); $requestEtags = $request->getETags(); if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) { $subRequest->headers->set('if_none_match', implode(', ', $etags)); } $response = $this->forward($subRequest, $catch, $entry); if (304 == $response->getStatusCode()) { $this->record($request, 'valid'); // return the response and not the cache entry if the response is valid but not cached $etag = $response->getEtag(); if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) { return $response; } $entry = clone $entry; $entry->headers->remove('Date'); foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) { if ($response->headers->has($name)) { $entry->headers->set($name, $response->headers->get($name)); } } $response = $entry; } else { $this->record($request, 'invalid'); } if ($response->isCacheable()) { $this->store($request, $response); } return $response; } /** * Forwards the Request to the backend and determines whether the response should be stored. * * This methods is triggered when the cache missed or a reload is required. * * @param Request $request A Request instance * @param bool $catch whether to process exceptions * * @return Response A Response instance */ protected function fetch(Request $request, $catch = false) { $subRequest = clone $request; // send no head requests because we want content $subRequest->setMethod('GET'); // avoid that the backend sends no content $subRequest->headers->remove('if_modified_since'); $subRequest->headers->remove('if_none_match'); $response = $this->forward($subRequest, $catch); if ($response->isCacheable()) { $this->store($request, $response); } return $response; } /** * Forwards the Request to the backend and returns the Response. * * @param Request $request A Request instance * @param bool $catch Whether to catch exceptions or not * @param Response $entry A Response instance (the stale entry if present, null otherwise) * * @return Response A Response instance */ protected function forward(Request $request, $catch = false, Response $entry = null) { if ($this->surrogate) { $this->surrogate->addSurrogateCapability($request); } // modify the X-Forwarded-For header if needed $forwardedFor = $request->headers->get('X-Forwarded-For'); if ($forwardedFor) { $request->headers->set('X-Forwarded-For', $forwardedFor.', '.$request->server->get('REMOTE_ADDR')); } else { $request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR')); } // fix the client IP address by setting it to 127.0.0.1 as HttpCache // is always called from the same process as the backend. $request->server->set('REMOTE_ADDR', '127.0.0.1'); // make sure HttpCache is a trusted proxy if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) { $trustedProxies[] = '127.0.0.1'; Request::setTrustedProxies($trustedProxies); } // always a "master" request (as the real master request can be in cache) $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch); // FIXME: we probably need to also catch exceptions if raw === true // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) { if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) { $age = $this->options['stale_if_error']; } if (abs($entry->getTtl()) < $age) { $this->record($request, 'stale-if-error'); return $entry; } } $this->processResponseBody($request, $response); if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) { $response->setPrivate(true); } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) { $response->setTtl($this->options['default_ttl']); } return $response; } /** * Checks whether the cache entry is "fresh enough" to satisfy the Request. * * @param Request $request A Request instance * @param Response $entry A Response instance * * @return bool true if the cache entry if fresh enough, false otherwise */ protected function isFreshEnough(Request $request, Response $entry) { if (!$entry->isFresh()) { return $this->lock($request, $entry); } if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) { return $maxAge > 0 && $maxAge >= $entry->getAge(); } return true; } /** * Locks a Request during the call to the backend. * * @param Request $request A Request instance * @param Response $entry A Response instance * * @return bool true if the cache entry can be returned even if it is staled, false otherwise */ protected function lock(Request $request, Response $entry) { // try to acquire a lock to call the backend $lock = $this->store->lock($request); // there is already another process calling the backend if (true !== $lock) { // check if we can serve the stale entry if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) { $age = $this->options['stale_while_revalidate']; } if (abs($entry->getTtl()) < $age) { $this->record($request, 'stale-while-revalidate'); // server the stale response while there is a revalidation return true; } // wait for the lock to be released $wait = 0; while ($this->store->isLocked($request) && $wait < 5000000) { usleep(50000); $wait += 50000; } if ($wait < 2000000) { // replace the current entry with the fresh one $new = $this->lookup($request); $entry->headers = $new->headers; $entry->setContent($new->getContent()); $entry->setStatusCode($new->getStatusCode()); $entry->setProtocolVersion($new->getProtocolVersion()); foreach ($new->headers->getCookies() as $cookie) { $entry->headers->setCookie($cookie); } } else { // backend is slow as hell, send a 503 response (to avoid the dog pile effect) $entry->setStatusCode(503); $entry->setContent('503 Service Unavailable'); $entry->headers->set('Retry-After', 10); } return true; } // we have the lock, call the backend return false; } /** * Writes the Response to the cache. * * @param Request $request A Request instance * @param Response $response A Response instance * * @throws \Exception */ protected function store(Request $request, Response $response) { try { $this->store->write($request, $response); $this->record($request, 'store'); $response->headers->set('Age', $response->getAge()); } catch (\Exception $e) { $this->record($request, 'store-failed'); if ($this->options['debug']) { throw $e; } } // now that the response is cached, release the lock $this->store->unlock($request); } /** * Restores the Response body. * * @param Request $request A Request instance * @param Response $response A Response instance */ private function restoreResponseBody(Request $request, Response $response) { if ($request->isMethod('HEAD') || 304 === $response->getStatusCode()) { $response->setContent(null); $response->headers->remove('X-Body-Eval'); $response->headers->remove('X-Body-File'); return; } if ($response->headers->has('X-Body-Eval')) { ob_start(); if ($response->headers->has('X-Body-File')) { include $response->headers->get('X-Body-File'); } else { eval('; ?>'.$response->getContent().'<?php ;'); } $response->setContent(ob_get_clean()); $response->headers->remove('X-Body-Eval'); if (!$response->headers->has('Transfer-Encoding')) { $response->headers->set('Content-Length', strlen($response->getContent())); } } elseif ($response->headers->has('X-Body-File')) { $response->setContent(file_get_contents($response->headers->get('X-Body-File'))); } else { return; } $response->headers->remove('X-Body-File'); } protected function processResponseBody(Request $request, Response $response) { if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) { $this->surrogate->process($request, $response); } } /** * Checks if the Request includes authorization or other sensitive information * that should cause the Response to be considered private by default. * * @param Request $request A Request instance * * @return bool true if the Request is private, false otherwise */ private function isPrivateRequest(Request $request) { foreach ($this->options['private_headers'] as $key) { $key = strtolower(str_replace('HTTP_', '', $key)); if ('cookie' === $key) { if (count($request->cookies->all())) { return true; } } elseif ($request->headers->has($key)) { return true; } } return false; } /** * Records that an event took place. * * @param Request $request A Request instance * @param string $event The event name */ private function record(Request $request, $event) { $path = $request->getPathInfo(); if ($qs = $request->getQueryString()) { $path .= '?'.$qs; } $this->traces[$request->getMethod().' '.$path][] = $event; } }
namquy/websitegomsu
vendor/symfony/http-kernel/HttpCache/HttpCache.php
PHP
gpl-2.0
24,522
#include <linux/kernel.h> #include <linux/init.h> #include <linux/types.h> #include <linux/module.h> #include <linux/list.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/pagemap.h> #include <linux/sched.h> #include <linux/dmapool.h> #include <linux/mempool.h> #include <linux/spinlock.h> #include <linux/kthread.h> #include <linux/interrupt.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <net/ipv6.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/skbuff.h> #include <linux/rtnetlink.h> #include <linux/if_vlan.h> #include <linux/delay.h> #include <linux/mm.h> #include <linux/vmalloc.h> #include "qlge.h" static const char ql_gstrings_test[][ETH_GSTRING_LEN] = { "Loopback test (offline)" }; #define QLGE_TEST_LEN (sizeof(ql_gstrings_test) / ETH_GSTRING_LEN) static int ql_update_ring_coalescing(struct ql_adapter *qdev) { int i, status = 0; struct rx_ring *rx_ring; struct cqicb *cqicb; if (!netif_running(qdev->ndev)) return status; /* Skip the default queue, and update the outbound handler * queues if they changed. */ cqicb = (struct cqicb *)&qdev->rx_ring[qdev->rss_ring_count]; if (le16_to_cpu(cqicb->irq_delay) != qdev->tx_coalesce_usecs || le16_to_cpu(cqicb->pkt_delay) != qdev->tx_max_coalesced_frames) { for (i = qdev->rss_ring_count; i < qdev->rx_ring_count; i++) { rx_ring = &qdev->rx_ring[i]; cqicb = (struct cqicb *)rx_ring; cqicb->irq_delay = cpu_to_le16(qdev->tx_coalesce_usecs); cqicb->pkt_delay = cpu_to_le16(qdev->tx_max_coalesced_frames); cqicb->flags = FLAGS_LI; status = ql_write_cfg(qdev, cqicb, sizeof(*cqicb), CFG_LCQ, rx_ring->cq_id); if (status) { netif_err(qdev, ifup, qdev->ndev, "Failed to load CQICB.\n"); goto exit; } } } /* Update the inbound (RSS) handler queues if they changed. */ cqicb = (struct cqicb *)&qdev->rx_ring[0]; if (le16_to_cpu(cqicb->irq_delay) != qdev->rx_coalesce_usecs || le16_to_cpu(cqicb->pkt_delay) != qdev->rx_max_coalesced_frames) { for (i = 0; i < qdev->rss_ring_count; i++, rx_ring++) { rx_ring = &qdev->rx_ring[i]; cqicb = (struct cqicb *)rx_ring; cqicb->irq_delay = cpu_to_le16(qdev->rx_coalesce_usecs); cqicb->pkt_delay = cpu_to_le16(qdev->rx_max_coalesced_frames); cqicb->flags = FLAGS_LI; status = ql_write_cfg(qdev, cqicb, sizeof(*cqicb), CFG_LCQ, rx_ring->cq_id); if (status) { netif_err(qdev, ifup, qdev->ndev, "Failed to load CQICB.\n"); goto exit; } } } exit: return status; } static void ql_update_stats(struct ql_adapter *qdev) { u32 i; u64 data; u64 *iter = &qdev->nic_stats.tx_pkts; spin_lock(&qdev->stats_lock); if (ql_sem_spinlock(qdev, qdev->xg_sem_mask)) { netif_err(qdev, drv, qdev->ndev, "Couldn't get xgmac sem.\n"); goto quit; } /* * Get TX statistics. */ for (i = 0x200; i < 0x280; i += 8) { if (ql_read_xgmac_reg64(qdev, i, &data)) { netif_err(qdev, drv, qdev->ndev, "Error reading status register 0x%.04x.\n", i); goto end; } else *iter = data; iter++; } /* * Get RX statistics. */ for (i = 0x300; i < 0x3d0; i += 8) { if (ql_read_xgmac_reg64(qdev, i, &data)) { netif_err(qdev, drv, qdev->ndev, "Error reading status register 0x%.04x.\n", i); goto end; } else *iter = data; iter++; } /* * Get Per-priority TX pause frame counter statistics. */ for (i = 0x500; i < 0x540; i += 8) { if (ql_read_xgmac_reg64(qdev, i, &data)) { netif_err(qdev, drv, qdev->ndev, "Error reading status register 0x%.04x.\n", i); goto end; } else *iter = data; iter++; } /* * Get Per-priority RX pause frame counter statistics. */ for (i = 0x568; i < 0x5a8; i += 8) { if (ql_read_xgmac_reg64(qdev, i, &data)) { netif_err(qdev, drv, qdev->ndev, "Error reading status register 0x%.04x.\n", i); goto end; } else *iter = data; iter++; } /* * Get RX NIC FIFO DROP statistics. */ if (ql_read_xgmac_reg64(qdev, 0x5b8, &data)) { netif_err(qdev, drv, qdev->ndev, "Error reading status register 0x%.04x.\n", i); goto end; } else *iter = data; end: ql_sem_unlock(qdev, qdev->xg_sem_mask); quit: spin_unlock(&qdev->stats_lock); QL_DUMP_STAT(qdev); } static char ql_stats_str_arr[][ETH_GSTRING_LEN] = { {"tx_pkts"}, {"tx_bytes"}, {"tx_mcast_pkts"}, {"tx_bcast_pkts"}, {"tx_ucast_pkts"}, {"tx_ctl_pkts"}, {"tx_pause_pkts"}, {"tx_64_pkts"}, {"tx_65_to_127_pkts"}, {"tx_128_to_255_pkts"}, {"tx_256_511_pkts"}, {"tx_512_to_1023_pkts"}, {"tx_1024_to_1518_pkts"}, {"tx_1519_to_max_pkts"}, {"tx_undersize_pkts"}, {"tx_oversize_pkts"}, {"rx_bytes"}, {"rx_bytes_ok"}, {"rx_pkts"}, {"rx_pkts_ok"}, {"rx_bcast_pkts"}, {"rx_mcast_pkts"}, {"rx_ucast_pkts"}, {"rx_undersize_pkts"}, {"rx_oversize_pkts"}, {"rx_jabber_pkts"}, {"rx_undersize_fcerr_pkts"}, {"rx_drop_events"}, {"rx_fcerr_pkts"}, {"rx_align_err"}, {"rx_symbol_err"}, {"rx_mac_err"}, {"rx_ctl_pkts"}, {"rx_pause_pkts"}, {"rx_64_pkts"}, {"rx_65_to_127_pkts"}, {"rx_128_255_pkts"}, {"rx_256_511_pkts"}, {"rx_512_to_1023_pkts"}, {"rx_1024_to_1518_pkts"}, {"rx_1519_to_max_pkts"}, {"rx_len_err_pkts"}, {"tx_cbfc_pause_frames0"}, {"tx_cbfc_pause_frames1"}, {"tx_cbfc_pause_frames2"}, {"tx_cbfc_pause_frames3"}, {"tx_cbfc_pause_frames4"}, {"tx_cbfc_pause_frames5"}, {"tx_cbfc_pause_frames6"}, {"tx_cbfc_pause_frames7"}, {"rx_cbfc_pause_frames0"}, {"rx_cbfc_pause_frames1"}, {"rx_cbfc_pause_frames2"}, {"rx_cbfc_pause_frames3"}, {"rx_cbfc_pause_frames4"}, {"rx_cbfc_pause_frames5"}, {"rx_cbfc_pause_frames6"}, {"rx_cbfc_pause_frames7"}, {"rx_nic_fifo_drop"}, }; static void ql_get_strings(struct net_device *dev, u32 stringset, u8 *buf) { switch (stringset) { case ETH_SS_STATS: memcpy(buf, ql_stats_str_arr, sizeof(ql_stats_str_arr)); break; } } static int ql_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_TEST: return QLGE_TEST_LEN; case ETH_SS_STATS: return ARRAY_SIZE(ql_stats_str_arr); default: return -EOPNOTSUPP; } } static void ql_get_ethtool_stats(struct net_device *ndev, struct ethtool_stats *stats, u64 *data) { struct ql_adapter *qdev = netdev_priv(ndev); struct nic_stats *s = &qdev->nic_stats; ql_update_stats(qdev); *data++ = s->tx_pkts; *data++ = s->tx_bytes; *data++ = s->tx_mcast_pkts; *data++ = s->tx_bcast_pkts; *data++ = s->tx_ucast_pkts; *data++ = s->tx_ctl_pkts; *data++ = s->tx_pause_pkts; *data++ = s->tx_64_pkt; *data++ = s->tx_65_to_127_pkt; *data++ = s->tx_128_to_255_pkt; *data++ = s->tx_256_511_pkt; *data++ = s->tx_512_to_1023_pkt; *data++ = s->tx_1024_to_1518_pkt; *data++ = s->tx_1519_to_max_pkt; *data++ = s->tx_undersize_pkt; *data++ = s->tx_oversize_pkt; *data++ = s->rx_bytes; *data++ = s->rx_bytes_ok; *data++ = s->rx_pkts; *data++ = s->rx_pkts_ok; *data++ = s->rx_bcast_pkts; *data++ = s->rx_mcast_pkts; *data++ = s->rx_ucast_pkts; *data++ = s->rx_undersize_pkts; *data++ = s->rx_oversize_pkts; *data++ = s->rx_jabber_pkts; *data++ = s->rx_undersize_fcerr_pkts; *data++ = s->rx_drop_events; *data++ = s->rx_fcerr_pkts; *data++ = s->rx_align_err; *data++ = s->rx_symbol_err; *data++ = s->rx_mac_err; *data++ = s->rx_ctl_pkts; *data++ = s->rx_pause_pkts; *data++ = s->rx_64_pkts; *data++ = s->rx_65_to_127_pkts; *data++ = s->rx_128_255_pkts; *data++ = s->rx_256_511_pkts; *data++ = s->rx_512_to_1023_pkts; *data++ = s->rx_1024_to_1518_pkts; *data++ = s->rx_1519_to_max_pkts; *data++ = s->rx_len_err_pkts; *data++ = s->tx_cbfc_pause_frames0; *data++ = s->tx_cbfc_pause_frames1; *data++ = s->tx_cbfc_pause_frames2; *data++ = s->tx_cbfc_pause_frames3; *data++ = s->tx_cbfc_pause_frames4; *data++ = s->tx_cbfc_pause_frames5; *data++ = s->tx_cbfc_pause_frames6; *data++ = s->tx_cbfc_pause_frames7; *data++ = s->rx_cbfc_pause_frames0; *data++ = s->rx_cbfc_pause_frames1; *data++ = s->rx_cbfc_pause_frames2; *data++ = s->rx_cbfc_pause_frames3; *data++ = s->rx_cbfc_pause_frames4; *data++ = s->rx_cbfc_pause_frames5; *data++ = s->rx_cbfc_pause_frames6; *data++ = s->rx_cbfc_pause_frames7; *data++ = s->rx_nic_fifo_drop; } static int ql_get_settings(struct net_device *ndev, struct ethtool_cmd *ecmd) { struct ql_adapter *qdev = netdev_priv(ndev); ecmd->supported = SUPPORTED_10000baseT_Full; ecmd->advertising = ADVERTISED_10000baseT_Full; ecmd->autoneg = AUTONEG_ENABLE; ecmd->transceiver = XCVR_EXTERNAL; if ((qdev->link_status & STS_LINK_TYPE_MASK) == STS_LINK_TYPE_10GBASET) { ecmd->supported |= (SUPPORTED_TP | SUPPORTED_Autoneg); ecmd->advertising |= (ADVERTISED_TP | ADVERTISED_Autoneg); ecmd->port = PORT_TP; } else { ecmd->supported |= SUPPORTED_FIBRE; ecmd->advertising |= ADVERTISED_FIBRE; ecmd->port = PORT_FIBRE; } ecmd->speed = SPEED_10000; ecmd->duplex = DUPLEX_FULL; return 0; } static void ql_get_drvinfo(struct net_device *ndev, struct ethtool_drvinfo *drvinfo) { struct ql_adapter *qdev = netdev_priv(ndev); strncpy(drvinfo->driver, qlge_driver_name, 32); strncpy(drvinfo->version, qlge_driver_version, 32); snprintf(drvinfo->fw_version, 32, "v%d.%d.%d", (qdev->fw_rev_id & 0x00ff0000) >> 16, (qdev->fw_rev_id & 0x0000ff00) >> 8, (qdev->fw_rev_id & 0x000000ff)); strncpy(drvinfo->bus_info, pci_name(qdev->pdev), 32); drvinfo->n_stats = 0; drvinfo->testinfo_len = 0; if (!test_bit(QL_FRC_COREDUMP, &qdev->flags)) drvinfo->regdump_len = sizeof(struct ql_mpi_coredump); else drvinfo->regdump_len = sizeof(struct ql_reg_dump); drvinfo->eedump_len = 0; } static void ql_get_wol(struct net_device *ndev, struct ethtool_wolinfo *wol) { struct ql_adapter *qdev = netdev_priv(ndev); /* What we support. */ wol->supported = WAKE_MAGIC; /* What we've currently got set. */ wol->wolopts = qdev->wol; } static int ql_set_wol(struct net_device *ndev, struct ethtool_wolinfo *wol) { struct ql_adapter *qdev = netdev_priv(ndev); int status; if (wol->wolopts & ~WAKE_MAGIC) return -EINVAL; qdev->wol = wol->wolopts; netif_info(qdev, drv, qdev->ndev, "Set wol option 0x%x\n", qdev->wol); if (!qdev->wol) { u32 wol = 0; status = ql_mb_wol_mode(qdev, wol); netif_err(qdev, drv, qdev->ndev, "WOL %s (wol code 0x%x)\n", status == 0 ? "cleared successfully" : "clear failed", wol); } return 0; } static int ql_phys_id(struct net_device *ndev, u32 data) { struct ql_adapter *qdev = netdev_priv(ndev); u32 led_reg, i; int status; /* Save the current LED settings */ status = ql_mb_get_led_cfg(qdev); if (status) return status; led_reg = qdev->led_config; /* Start blinking the led */ if (!data || data > 300) data = 300; for (i = 0; i < (data * 10); i++) ql_mb_set_led_cfg(qdev, QL_LED_BLINK); /* Restore LED settings */ status = ql_mb_set_led_cfg(qdev, led_reg); if (status) return status; return 0; } static int ql_start_loopback(struct ql_adapter *qdev) { if (netif_carrier_ok(qdev->ndev)) { set_bit(QL_LB_LINK_UP, &qdev->flags); netif_carrier_off(qdev->ndev); } else clear_bit(QL_LB_LINK_UP, &qdev->flags); qdev->link_config |= CFG_LOOPBACK_PCS; return ql_mb_set_port_cfg(qdev); } static void ql_stop_loopback(struct ql_adapter *qdev) { qdev->link_config &= ~CFG_LOOPBACK_PCS; ql_mb_set_port_cfg(qdev); if (test_bit(QL_LB_LINK_UP, &qdev->flags)) { netif_carrier_on(qdev->ndev); clear_bit(QL_LB_LINK_UP, &qdev->flags); } } static void ql_create_lb_frame(struct sk_buff *skb, unsigned int frame_size) { memset(skb->data, 0xFF, frame_size); frame_size &= ~1; memset(&skb->data[frame_size / 2], 0xAA, frame_size / 2 - 1); memset(&skb->data[frame_size / 2 + 10], 0xBE, 1); memset(&skb->data[frame_size / 2 + 12], 0xAF, 1); } void ql_check_lb_frame(struct ql_adapter *qdev, struct sk_buff *skb) { unsigned int frame_size = skb->len; if ((*(skb->data + 3) == 0xFF) && (*(skb->data + frame_size / 2 + 10) == 0xBE) && (*(skb->data + frame_size / 2 + 12) == 0xAF)) { atomic_dec(&qdev->lb_count); return; } } static int ql_run_loopback_test(struct ql_adapter *qdev) { int i; netdev_tx_t rc; struct sk_buff *skb; unsigned int size = SMALL_BUF_MAP_SIZE; for (i = 0; i < 64; i++) { skb = netdev_alloc_skb(qdev->ndev, size); if (!skb) return -ENOMEM; skb->queue_mapping = 0; skb_put(skb, size); ql_create_lb_frame(skb, size); rc = ql_lb_send(skb, qdev->ndev); if (rc != NETDEV_TX_OK) return -EPIPE; atomic_inc(&qdev->lb_count); } /* Give queue time to settle before testing results. */ msleep(2); ql_clean_lb_rx_ring(&qdev->rx_ring[0], 128); return atomic_read(&qdev->lb_count) ? -EIO : 0; } static int ql_loopback_test(struct ql_adapter *qdev, u64 *data) { *data = ql_start_loopback(qdev); if (*data) goto out; *data = ql_run_loopback_test(qdev); out: ql_stop_loopback(qdev); return *data; } static void ql_self_test(struct net_device *ndev, struct ethtool_test *eth_test, u64 *data) { struct ql_adapter *qdev = netdev_priv(ndev); if (netif_running(ndev)) { set_bit(QL_SELFTEST, &qdev->flags); if (eth_test->flags == ETH_TEST_FL_OFFLINE) { /* Offline tests */ if (ql_loopback_test(qdev, &data[0])) eth_test->flags |= ETH_TEST_FL_FAILED; } else { /* Online tests */ data[0] = 0; } clear_bit(QL_SELFTEST, &qdev->flags); /* Give link time to come up after * port configuration changes. */ msleep_interruptible(4 * 1000); } else { netif_err(qdev, drv, qdev->ndev, "is down, Loopback test will fail.\n"); eth_test->flags |= ETH_TEST_FL_FAILED; } } static int ql_get_regs_len(struct net_device *ndev) { struct ql_adapter *qdev = netdev_priv(ndev); if (!test_bit(QL_FRC_COREDUMP, &qdev->flags)) return sizeof(struct ql_mpi_coredump); else return sizeof(struct ql_reg_dump); } static void ql_get_regs(struct net_device *ndev, struct ethtool_regs *regs, void *p) { struct ql_adapter *qdev = netdev_priv(ndev); ql_get_dump(qdev, p); qdev->core_is_dumped = 0; if (!test_bit(QL_FRC_COREDUMP, &qdev->flags)) regs->len = sizeof(struct ql_mpi_coredump); else regs->len = sizeof(struct ql_reg_dump); } static int ql_get_coalesce(struct net_device *dev, struct ethtool_coalesce *c) { struct ql_adapter *qdev = netdev_priv(dev); c->rx_coalesce_usecs = qdev->rx_coalesce_usecs; c->tx_coalesce_usecs = qdev->tx_coalesce_usecs; /* This chip coalesces as follows: * If a packet arrives, hold off interrupts until * cqicb->int_delay expires, but if no other packets arrive don't * wait longer than cqicb->pkt_int_delay. But ethtool doesn't use a * timer to coalesce on a frame basis. So, we have to take ethtool's * max_coalesced_frames value and convert it to a delay in microseconds. * We do this by using a basic thoughput of 1,000,000 frames per * second @ (1024 bytes). This means one frame per usec. So it's a * simple one to one ratio. */ c->rx_max_coalesced_frames = qdev->rx_max_coalesced_frames; c->tx_max_coalesced_frames = qdev->tx_max_coalesced_frames; return 0; } static int ql_set_coalesce(struct net_device *ndev, struct ethtool_coalesce *c) { struct ql_adapter *qdev = netdev_priv(ndev); /* Validate user parameters. */ if (c->rx_coalesce_usecs > qdev->rx_ring_size / 2) return -EINVAL; /* Don't wait more than 10 usec. */ if (c->rx_max_coalesced_frames > MAX_INTER_FRAME_WAIT) return -EINVAL; if (c->tx_coalesce_usecs > qdev->tx_ring_size / 2) return -EINVAL; if (c->tx_max_coalesced_frames > MAX_INTER_FRAME_WAIT) return -EINVAL; /* Verify a change took place before updating the hardware. */ if (qdev->rx_coalesce_usecs == c->rx_coalesce_usecs && qdev->tx_coalesce_usecs == c->tx_coalesce_usecs && qdev->rx_max_coalesced_frames == c->rx_max_coalesced_frames && qdev->tx_max_coalesced_frames == c->tx_max_coalesced_frames) return 0; qdev->rx_coalesce_usecs = c->rx_coalesce_usecs; qdev->tx_coalesce_usecs = c->tx_coalesce_usecs; qdev->rx_max_coalesced_frames = c->rx_max_coalesced_frames; qdev->tx_max_coalesced_frames = c->tx_max_coalesced_frames; return ql_update_ring_coalescing(qdev); } static void ql_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct ql_adapter *qdev = netdev_priv(netdev); ql_mb_get_port_cfg(qdev); if (qdev->link_config & CFG_PAUSE_STD) { pause->rx_pause = 1; pause->tx_pause = 1; } } static int ql_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct ql_adapter *qdev = netdev_priv(netdev); int status = 0; if ((pause->rx_pause) && (pause->tx_pause)) qdev->link_config |= CFG_PAUSE_STD; else if (!pause->rx_pause && !pause->tx_pause) qdev->link_config &= ~CFG_PAUSE_STD; else return -EINVAL; status = ql_mb_set_port_cfg(qdev); if (status) return status; return status; } static u32 ql_get_rx_csum(struct net_device *netdev) { struct ql_adapter *qdev = netdev_priv(netdev); return qdev->rx_csum; } static int ql_set_rx_csum(struct net_device *netdev, uint32_t data) { struct ql_adapter *qdev = netdev_priv(netdev); qdev->rx_csum = data; return 0; } static int ql_set_tso(struct net_device *ndev, uint32_t data) { if (data) { ndev->features |= NETIF_F_TSO; ndev->features |= NETIF_F_TSO6; } else { ndev->features &= ~NETIF_F_TSO; ndev->features &= ~NETIF_F_TSO6; } return 0; } static u32 ql_get_msglevel(struct net_device *ndev) { struct ql_adapter *qdev = netdev_priv(ndev); return qdev->msg_enable; } static void ql_set_msglevel(struct net_device *ndev, u32 value) { struct ql_adapter *qdev = netdev_priv(ndev); qdev->msg_enable = value; } const struct ethtool_ops qlge_ethtool_ops = { .get_settings = ql_get_settings, .get_drvinfo = ql_get_drvinfo, .get_wol = ql_get_wol, .set_wol = ql_set_wol, .get_regs_len = ql_get_regs_len, .get_regs = ql_get_regs, .get_msglevel = ql_get_msglevel, .set_msglevel = ql_set_msglevel, .get_link = ethtool_op_get_link, .phys_id = ql_phys_id, .self_test = ql_self_test, .get_pauseparam = ql_get_pauseparam, .set_pauseparam = ql_set_pauseparam, .get_rx_csum = ql_get_rx_csum, .set_rx_csum = ql_set_rx_csum, .get_tx_csum = ethtool_op_get_tx_csum, .set_tx_csum = ethtool_op_set_tx_csum, .get_sg = ethtool_op_get_sg, .set_sg = ethtool_op_set_sg, .get_tso = ethtool_op_get_tso, .set_tso = ql_set_tso, .get_coalesce = ql_get_coalesce, .set_coalesce = ql_set_coalesce, .get_sset_count = ql_get_sset_count, .get_strings = ql_get_strings, .get_ethtool_stats = ql_get_ethtool_stats, };
getitnowmarketing/iconia-ics
drivers/net/qlge/qlge_ethtool.c
C
gpl-2.0
18,769
/** \file G3D/Image1.cpp \maintainer Morgan McGuire, http://graphics.cs.williams.edu \created 2007-01-31 \edited 2012-12-25 */ #include "G3D/Image1.h" #include "G3D/Image1unorm8.h" #include "G3D/Image.h" #include "G3D/Color4.h" #include "G3D/Color4unorm8.h" #include "G3D/Color1.h" #include "G3D/Color1unorm8.h" #include "G3D/ImageFormat.h" #include "G3D/PixelTransferBuffer.h" #include "G3D/CPUPixelTransferBuffer.h" namespace G3D { Image1::Image1(int w, int h, WrapMode wrap) : Map2D<Color1, Color1>(w, h, wrap) { setAll(Color1(0.0f)); } Image1::Ref Image1::fromImage1unorm8(const shared_ptr<Image1unorm8>& im) { Ref out = createEmpty(static_cast<WrapMode>(im->wrapMode())); out->resize(im->width(), im->height()); int N = im->width() * im->height(); const Color1unorm8* src = reinterpret_cast<Color1unorm8*>(im->getCArray()); for (int i = 0; i < N; ++i) { out->data[i] = Color1(src[i]); } return out; } Image1::Ref Image1::createEmpty(int width, int height, WrapMode wrap) { return Image1::Ref(new Type(width, height, wrap)); } Image1::Ref Image1::createEmpty(WrapMode wrap) { return createEmpty(0, 0, wrap); } Image1::Ref Image1::fromFile(const std::string& filename, WrapMode wrap) { Ref out = createEmpty(wrap); out->load(filename); return out; } void Image1::load(const std::string& filename) { shared_ptr<Image> image = Image::fromFile(filename); if (image->format() != ImageFormat::L32F()) { image->convertToL8(); } switch (image->format()->code) { case ImageFormat::CODE_L8: copyArray(static_cast<const Color1unorm8*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_L32F: copyArray(static_cast<const Color1*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_RGB8: copyArray(static_cast<const Color3unorm8*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_RGB32F: copyArray(static_cast<const Color3*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_RGBA8: copyArray(static_cast<const Color4unorm8*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_RGBA32F: copyArray(static_cast<const Color4*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; default: debugAssertM(false, "Trying to load unsupported image format"); break; } setChanged(true); } Image1::Ref Image1::fromArray(const class Color3unorm8* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color1* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color1unorm8* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color3* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color4unorm8* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color4* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } void Image1::copyArray(const Color3unorm8* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = data.getCArray(); // Convert int8 -> float for (int i = 0; i < N; ++i) { dst[i] = Color1(Color3(src[i]).average()); } } void Image1::copyArray(const Color4unorm8* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = data.getCArray(); // Strip alpha and convert for (int i = 0; i < N; ++i) { dst[i] = Color1(Color3(src[i].rgb()).average()); } } void Image1::copyArray(const Color1* src, int w, int h) { resize(w, h); System::memcpy(getCArray(), src, w * h * sizeof(Color1)); } void Image1::copyArray(const Color4* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = data.getCArray(); // Strip alpha for (int i = 0; i < N; ++i) { dst[i] = Color1(src[i].rgb().average()); } } void Image1::copyArray(const Color1unorm8* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = getCArray(); for (int i = 0; i < N; ++i) { dst[i]= Color1(src[i]); } } void Image1::copyArray(const Color3* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = getCArray(); for (int i = 0; i < N; ++i) { dst[i] = Color1(src[i].average()); } } void Image1::save(const std::string& filename) { // To avoid saving as floating point image. FreeImage cannot convert floating point to L8. Image1unorm8::Ref unorm8 = Image1unorm8::fromImage1(dynamic_pointer_cast<Image1>(shared_from_this())); unorm8->save(filename); } const ImageFormat* Image1::format() const { return ImageFormat::L32F(); } } // G3D
trinityclassic/trinityone
dep/g3dlite/source/Image1.cpp
C++
gpl-2.0
5,593
/* * Copyright (C) 2001, 2002 Sistina Software (UK) Limited. * Copyright (C) 2004 - 2006 Red Hat, Inc. All rights reserved. * * This file is released under the GPL. */ #include "dm.h" #include <linux/module.h> #include <linux/vmalloc.h> #include <linux/miscdevice.h> #include <linux/init.h> #include <linux/wait.h> #include <linux/slab.h> #include <linux/dm-ioctl.h> #include <linux/hdreg.h> #include <linux/compat.h> #include <asm/uaccess.h> #define DM_MSG_PREFIX "ioctl" #define DM_DRIVER_EMAIL "dm-devel@redhat.com" /*----------------------------------------------------------------- * The ioctl interface needs to be able to look up devices by * name or uuid. *---------------------------------------------------------------*/ struct hash_cell { struct list_head name_list; struct list_head uuid_list; char *name; char *uuid; struct mapped_device *md; struct dm_table *new_map; }; /* * A dummy definition to make RCU happy. * struct dm_table should never be dereferenced in this file. */ struct dm_table { int undefined__; }; struct vers_iter { size_t param_size; struct dm_target_versions *vers, *old_vers; char *end; uint32_t flags; }; #define NUM_BUCKETS 64 #define MASK_BUCKETS (NUM_BUCKETS - 1) static struct list_head _name_buckets[NUM_BUCKETS]; static struct list_head _uuid_buckets[NUM_BUCKETS]; static void dm_hash_remove_all(bool keep_open_devices, bool mark_deferred, bool only_deferred); /* * Guards access to both hash tables. */ static DECLARE_RWSEM(_hash_lock); /* * Protects use of mdptr to obtain hash cell name and uuid from mapped device. */ static DEFINE_MUTEX(dm_hash_cells_mutex); static void init_buckets(struct list_head *buckets) { unsigned int i; for (i = 0; i < NUM_BUCKETS; i++) INIT_LIST_HEAD(buckets + i); } static int dm_hash_init(void) { init_buckets(_name_buckets); init_buckets(_uuid_buckets); return 0; } static void dm_hash_exit(void) { dm_hash_remove_all(false, false, false); } /*----------------------------------------------------------------- * Hash function: * We're not really concerned with the str hash function being * fast since it's only used by the ioctl interface. *---------------------------------------------------------------*/ static unsigned int hash_str(const char *str) { const unsigned int hash_mult = 2654435387U; unsigned int h = 0; while (*str) h = (h + (unsigned int) *str++) * hash_mult; return h & MASK_BUCKETS; } /*----------------------------------------------------------------- * Code for looking up a device by name *---------------------------------------------------------------*/ static struct hash_cell *__get_name_cell(const char *str) { struct hash_cell *hc; unsigned int h = hash_str(str); list_for_each_entry (hc, _name_buckets + h, name_list) if (!strcmp(hc->name, str)) { dm_get(hc->md); return hc; } return NULL; } static struct hash_cell *__get_uuid_cell(const char *str) { struct hash_cell *hc; unsigned int h = hash_str(str); list_for_each_entry (hc, _uuid_buckets + h, uuid_list) if (!strcmp(hc->uuid, str)) { dm_get(hc->md); return hc; } return NULL; } static struct hash_cell *__get_dev_cell(uint64_t dev) { struct mapped_device *md; struct hash_cell *hc; md = dm_get_md(huge_decode_dev(dev)); if (!md) return NULL; hc = dm_get_mdptr(md); if (!hc) { dm_put(md); return NULL; } return hc; } /*----------------------------------------------------------------- * Inserting, removing and renaming a device. *---------------------------------------------------------------*/ static struct hash_cell *alloc_cell(const char *name, const char *uuid, struct mapped_device *md) { struct hash_cell *hc; hc = kmalloc(sizeof(*hc), GFP_KERNEL); if (!hc) return NULL; hc->name = kstrdup(name, GFP_KERNEL); if (!hc->name) { kfree(hc); return NULL; } if (!uuid) hc->uuid = NULL; else { hc->uuid = kstrdup(uuid, GFP_KERNEL); if (!hc->uuid) { kfree(hc->name); kfree(hc); return NULL; } } INIT_LIST_HEAD(&hc->name_list); INIT_LIST_HEAD(&hc->uuid_list); hc->md = md; hc->new_map = NULL; return hc; } static void free_cell(struct hash_cell *hc) { if (hc) { kfree(hc->name); kfree(hc->uuid); kfree(hc); } } /* * The kdev_t and uuid of a device can never change once it is * initially inserted. */ static int dm_hash_insert(const char *name, const char *uuid, struct mapped_device *md) { struct hash_cell *cell, *hc; /* * Allocate the new cells. */ cell = alloc_cell(name, uuid, md); if (!cell) return -ENOMEM; /* * Insert the cell into both hash tables. */ down_write(&_hash_lock); hc = __get_name_cell(name); if (hc) { dm_put(hc->md); goto bad; } list_add(&cell->name_list, _name_buckets + hash_str(name)); if (uuid) { hc = __get_uuid_cell(uuid); if (hc) { list_del(&cell->name_list); dm_put(hc->md); goto bad; } list_add(&cell->uuid_list, _uuid_buckets + hash_str(uuid)); } dm_get(md); mutex_lock(&dm_hash_cells_mutex); dm_set_mdptr(md, cell); mutex_unlock(&dm_hash_cells_mutex); up_write(&_hash_lock); return 0; bad: up_write(&_hash_lock); free_cell(cell); return -EBUSY; } static struct dm_table *__hash_remove(struct hash_cell *hc) { struct dm_table *table; int srcu_idx; /* remove from the dev hash */ list_del(&hc->uuid_list); list_del(&hc->name_list); mutex_lock(&dm_hash_cells_mutex); dm_set_mdptr(hc->md, NULL); mutex_unlock(&dm_hash_cells_mutex); table = dm_get_live_table(hc->md, &srcu_idx); if (table) dm_table_event(table); dm_put_live_table(hc->md, srcu_idx); table = NULL; if (hc->new_map) table = hc->new_map; dm_put(hc->md); free_cell(hc); return table; } static void dm_hash_remove_all(bool keep_open_devices, bool mark_deferred, bool only_deferred) { int i, dev_skipped; struct hash_cell *hc; struct mapped_device *md; struct dm_table *t; retry: dev_skipped = 0; down_write(&_hash_lock); for (i = 0; i < NUM_BUCKETS; i++) { list_for_each_entry(hc, _name_buckets + i, name_list) { md = hc->md; dm_get(md); if (keep_open_devices && dm_lock_for_deletion(md, mark_deferred, only_deferred)) { dm_put(md); dev_skipped++; continue; } t = __hash_remove(hc); up_write(&_hash_lock); if (t) { dm_sync_table(md); dm_table_destroy(t); } dm_put(md); if (likely(keep_open_devices)) dm_destroy(md); else dm_destroy_immediate(md); /* * Some mapped devices may be using other mapped * devices, so repeat until we make no further * progress. If a new mapped device is created * here it will also get removed. */ goto retry; } } up_write(&_hash_lock); if (dev_skipped) DMWARN("remove_all left %d open device(s)", dev_skipped); } /* * Set the uuid of a hash_cell that isn't already set. */ static void __set_cell_uuid(struct hash_cell *hc, char *new_uuid) { mutex_lock(&dm_hash_cells_mutex); hc->uuid = new_uuid; mutex_unlock(&dm_hash_cells_mutex); list_add(&hc->uuid_list, _uuid_buckets + hash_str(new_uuid)); } /* * Changes the name of a hash_cell and returns the old name for * the caller to free. */ static char *__change_cell_name(struct hash_cell *hc, char *new_name) { char *old_name; /* * Rename and move the name cell. */ list_del(&hc->name_list); old_name = hc->name; mutex_lock(&dm_hash_cells_mutex); hc->name = new_name; mutex_unlock(&dm_hash_cells_mutex); list_add(&hc->name_list, _name_buckets + hash_str(new_name)); return old_name; } static struct mapped_device *dm_hash_rename(struct dm_ioctl *param, const char *new) { char *new_data, *old_name = NULL; struct hash_cell *hc; struct dm_table *table; struct mapped_device *md; unsigned change_uuid = (param->flags & DM_UUID_FLAG) ? 1 : 0; int srcu_idx; /* * duplicate new. */ new_data = kstrdup(new, GFP_KERNEL); if (!new_data) return ERR_PTR(-ENOMEM); down_write(&_hash_lock); /* * Is new free ? */ if (change_uuid) hc = __get_uuid_cell(new); else hc = __get_name_cell(new); if (hc) { DMWARN("Unable to change %s on mapped device %s to one that " "already exists: %s", change_uuid ? "uuid" : "name", param->name, new); dm_put(hc->md); up_write(&_hash_lock); kfree(new_data); return ERR_PTR(-EBUSY); } /* * Is there such a device as 'old' ? */ hc = __get_name_cell(param->name); if (!hc) { DMWARN("Unable to rename non-existent device, %s to %s%s", param->name, change_uuid ? "uuid " : "", new); up_write(&_hash_lock); kfree(new_data); return ERR_PTR(-ENXIO); } /* * Does this device already have a uuid? */ if (change_uuid && hc->uuid) { DMWARN("Unable to change uuid of mapped device %s to %s " "because uuid is already set to %s", param->name, new, hc->uuid); dm_put(hc->md); up_write(&_hash_lock); kfree(new_data); return ERR_PTR(-EINVAL); } if (change_uuid) __set_cell_uuid(hc, new_data); else old_name = __change_cell_name(hc, new_data); /* * Wake up any dm event waiters. */ table = dm_get_live_table(hc->md, &srcu_idx); if (table) dm_table_event(table); dm_put_live_table(hc->md, srcu_idx); if (!dm_kobject_uevent(hc->md, KOBJ_CHANGE, param->event_nr)) param->flags |= DM_UEVENT_GENERATED_FLAG; md = hc->md; up_write(&_hash_lock); kfree(old_name); return md; } void dm_deferred_remove(void) { dm_hash_remove_all(true, false, true); } /*----------------------------------------------------------------- * Implementation of the ioctl commands *---------------------------------------------------------------*/ /* * All the ioctl commands get dispatched to functions with this * prototype. */ typedef int (*ioctl_fn)(struct dm_ioctl *param, size_t param_size); static int remove_all(struct dm_ioctl *param, size_t param_size) { dm_hash_remove_all(true, !!(param->flags & DM_DEFERRED_REMOVE), false); param->data_size = 0; return 0; } /* * Round up the ptr to an 8-byte boundary. */ #define ALIGN_MASK 7 static inline void *align_ptr(void *ptr) { return (void *) (((size_t) (ptr + ALIGN_MASK)) & ~ALIGN_MASK); } /* * Retrieves the data payload buffer from an already allocated * struct dm_ioctl. */ static void *get_result_buffer(struct dm_ioctl *param, size_t param_size, size_t *len) { param->data_start = align_ptr(param + 1) - (void *) param; if (param->data_start < param_size) *len = param_size - param->data_start; else *len = 0; return ((void *) param) + param->data_start; } static int list_devices(struct dm_ioctl *param, size_t param_size) { unsigned int i; struct hash_cell *hc; size_t len, needed = 0; struct gendisk *disk; struct dm_name_list *nl, *old_nl = NULL; down_write(&_hash_lock); /* * Loop through all the devices working out how much * space we need. */ for (i = 0; i < NUM_BUCKETS; i++) { list_for_each_entry (hc, _name_buckets + i, name_list) { needed += sizeof(struct dm_name_list); needed += strlen(hc->name) + 1; needed += ALIGN_MASK; } } /* * Grab our output buffer. */ nl = get_result_buffer(param, param_size, &len); if (len < needed) { param->flags |= DM_BUFFER_FULL_FLAG; goto out; } param->data_size = param->data_start + needed; nl->dev = 0; /* Flags no data */ /* * Now loop through filling out the names. */ for (i = 0; i < NUM_BUCKETS; i++) { list_for_each_entry (hc, _name_buckets + i, name_list) { if (old_nl) old_nl->next = (uint32_t) ((void *) nl - (void *) old_nl); disk = dm_disk(hc->md); nl->dev = huge_encode_dev(disk_devt(disk)); nl->next = 0; strcpy(nl->name, hc->name); old_nl = nl; nl = align_ptr(((void *) ++nl) + strlen(hc->name) + 1); } } out: up_write(&_hash_lock); return 0; } static void list_version_get_needed(struct target_type *tt, void *needed_param) { size_t *needed = needed_param; *needed += sizeof(struct dm_target_versions); *needed += strlen(tt->name); *needed += ALIGN_MASK; } static void list_version_get_info(struct target_type *tt, void *param) { struct vers_iter *info = param; /* Check space - it might have changed since the first iteration */ if ((char *)info->vers + sizeof(tt->version) + strlen(tt->name) + 1 > info->end) { info->flags = DM_BUFFER_FULL_FLAG; return; } if (info->old_vers) info->old_vers->next = (uint32_t) ((void *)info->vers - (void *)info->old_vers); info->vers->version[0] = tt->version[0]; info->vers->version[1] = tt->version[1]; info->vers->version[2] = tt->version[2]; info->vers->next = 0; strcpy(info->vers->name, tt->name); info->old_vers = info->vers; info->vers = align_ptr(((void *) ++info->vers) + strlen(tt->name) + 1); } static int list_versions(struct dm_ioctl *param, size_t param_size) { size_t len, needed = 0; struct dm_target_versions *vers; struct vers_iter iter_info; /* * Loop through all the devices working out how much * space we need. */ dm_target_iterate(list_version_get_needed, &needed); /* * Grab our output buffer. */ vers = get_result_buffer(param, param_size, &len); if (len < needed) { param->flags |= DM_BUFFER_FULL_FLAG; goto out; } param->data_size = param->data_start + needed; iter_info.param_size = param_size; iter_info.old_vers = NULL; iter_info.vers = vers; iter_info.flags = 0; iter_info.end = (char *)vers+len; /* * Now loop through filling out the names & versions. */ dm_target_iterate(list_version_get_info, &iter_info); param->flags |= iter_info.flags; out: return 0; } static int check_name(const char *name) { if (strchr(name, '/')) { DMWARN("invalid device name"); return -EINVAL; } return 0; } /* * On successful return, the caller must not attempt to acquire * _hash_lock without first calling dm_table_put, because dm_table_destroy * waits for this dm_table_put and could be called under this lock. */ static struct dm_table *dm_get_inactive_table(struct mapped_device *md, int *srcu_idx) { struct hash_cell *hc; struct dm_table *table = NULL; /* increment rcu count, we don't care about the table pointer */ dm_get_live_table(md, srcu_idx); down_read(&_hash_lock); hc = dm_get_mdptr(md); if (!hc || hc->md != md) { DMWARN("device has been removed from the dev hash table."); goto out; } table = hc->new_map; out: up_read(&_hash_lock); return table; } static struct dm_table *dm_get_live_or_inactive_table(struct mapped_device *md, struct dm_ioctl *param, int *srcu_idx) { return (param->flags & DM_QUERY_INACTIVE_TABLE_FLAG) ? dm_get_inactive_table(md, srcu_idx) : dm_get_live_table(md, srcu_idx); } /* * Fills in a dm_ioctl structure, ready for sending back to * userland. */ static void __dev_status(struct mapped_device *md, struct dm_ioctl *param) { struct gendisk *disk = dm_disk(md); struct dm_table *table; int srcu_idx; param->flags &= ~(DM_SUSPEND_FLAG | DM_READONLY_FLAG | DM_ACTIVE_PRESENT_FLAG); if (dm_suspended_md(md)) param->flags |= DM_SUSPEND_FLAG; if (dm_test_deferred_remove_flag(md)) param->flags |= DM_DEFERRED_REMOVE; param->dev = huge_encode_dev(disk_devt(disk)); /* * Yes, this will be out of date by the time it gets back * to userland, but it is still very useful for * debugging. */ param->open_count = dm_open_count(md); param->event_nr = dm_get_event_nr(md); param->target_count = 0; table = dm_get_live_table(md, &srcu_idx); if (table) { if (!(param->flags & DM_QUERY_INACTIVE_TABLE_FLAG)) { if (get_disk_ro(disk)) param->flags |= DM_READONLY_FLAG; param->target_count = dm_table_get_num_targets(table); } param->flags |= DM_ACTIVE_PRESENT_FLAG; } dm_put_live_table(md, srcu_idx); if (param->flags & DM_QUERY_INACTIVE_TABLE_FLAG) { int srcu_idx; table = dm_get_inactive_table(md, &srcu_idx); if (table) { if (!(dm_table_get_mode(table) & FMODE_WRITE)) param->flags |= DM_READONLY_FLAG; param->target_count = dm_table_get_num_targets(table); } dm_put_live_table(md, srcu_idx); } } static int dev_create(struct dm_ioctl *param, size_t param_size) { int r, m = DM_ANY_MINOR; struct mapped_device *md; r = check_name(param->name); if (r) return r; if (param->flags & DM_PERSISTENT_DEV_FLAG) m = MINOR(huge_decode_dev(param->dev)); r = dm_create(m, &md); if (r) return r; r = dm_hash_insert(param->name, *param->uuid ? param->uuid : NULL, md); if (r) { dm_put(md); dm_destroy(md); return r; } param->flags &= ~DM_INACTIVE_PRESENT_FLAG; __dev_status(md, param); dm_put(md); return 0; } /* * Always use UUID for lookups if it's present, otherwise use name or dev. */ static struct hash_cell *__find_device_hash_cell(struct dm_ioctl *param) { struct hash_cell *hc = NULL; if (*param->uuid) { if (*param->name || param->dev) return NULL; hc = __get_uuid_cell(param->uuid); if (!hc) return NULL; } else if (*param->name) { if (param->dev) return NULL; hc = __get_name_cell(param->name); if (!hc) return NULL; } else if (param->dev) { hc = __get_dev_cell(param->dev); if (!hc) return NULL; } else return NULL; /* * Sneakily write in both the name and the uuid * while we have the cell. */ strlcpy(param->name, hc->name, sizeof(param->name)); if (hc->uuid) strlcpy(param->uuid, hc->uuid, sizeof(param->uuid)); else param->uuid[0] = '\0'; if (hc->new_map) param->flags |= DM_INACTIVE_PRESENT_FLAG; else param->flags &= ~DM_INACTIVE_PRESENT_FLAG; return hc; } static struct mapped_device *find_device(struct dm_ioctl *param) { struct hash_cell *hc; struct mapped_device *md = NULL; down_read(&_hash_lock); hc = __find_device_hash_cell(param); if (hc) md = hc->md; up_read(&_hash_lock); return md; } static int dev_remove(struct dm_ioctl *param, size_t param_size) { struct hash_cell *hc; struct mapped_device *md; int r; struct dm_table *t; down_write(&_hash_lock); hc = __find_device_hash_cell(param); if (!hc) { DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table."); up_write(&_hash_lock); return -ENXIO; } md = hc->md; /* * Ensure the device is not open and nothing further can open it. */ r = dm_lock_for_deletion(md, !!(param->flags & DM_DEFERRED_REMOVE), false); if (r) { if (r == -EBUSY && param->flags & DM_DEFERRED_REMOVE) { up_write(&_hash_lock); dm_put(md); return 0; } DMDEBUG_LIMIT("unable to remove open device %s", hc->name); up_write(&_hash_lock); dm_put(md); return r; } t = __hash_remove(hc); up_write(&_hash_lock); if (t) { dm_sync_table(md); dm_table_destroy(t); } param->flags &= ~DM_DEFERRED_REMOVE; if (!dm_kobject_uevent(md, KOBJ_REMOVE, param->event_nr)) param->flags |= DM_UEVENT_GENERATED_FLAG; dm_put(md); dm_destroy(md); return 0; } /* * Check a string doesn't overrun the chunk of * memory we copied from userland. */ static int invalid_str(char *str, void *end) { while ((void *) str < end) if (!*str++) return 0; return -EINVAL; } static int dev_rename(struct dm_ioctl *param, size_t param_size) { int r; char *new_data = (char *) param + param->data_start; struct mapped_device *md; unsigned change_uuid = (param->flags & DM_UUID_FLAG) ? 1 : 0; if (new_data < param->data || invalid_str(new_data, (void *) param + param_size) || !*new_data || strlen(new_data) > (change_uuid ? DM_UUID_LEN - 1 : DM_NAME_LEN - 1)) { DMWARN("Invalid new mapped device name or uuid string supplied."); return -EINVAL; } if (!change_uuid) { r = check_name(new_data); if (r) return r; } md = dm_hash_rename(param, new_data); if (IS_ERR(md)) return PTR_ERR(md); __dev_status(md, param); dm_put(md); return 0; } static int dev_set_geometry(struct dm_ioctl *param, size_t param_size) { int r = -EINVAL, x; struct mapped_device *md; struct hd_geometry geometry; unsigned long indata[4]; char *geostr = (char *) param + param->data_start; char dummy; md = find_device(param); if (!md) return -ENXIO; if (geostr < param->data || invalid_str(geostr, (void *) param + param_size)) { DMWARN("Invalid geometry supplied."); goto out; } x = sscanf(geostr, "%lu %lu %lu %lu%c", indata, indata + 1, indata + 2, indata + 3, &dummy); if (x != 4) { DMWARN("Unable to interpret geometry settings."); goto out; } if (indata[0] > 65535 || indata[1] > 255 || indata[2] > 255 || indata[3] > ULONG_MAX) { DMWARN("Geometry exceeds range limits."); goto out; } geometry.cylinders = indata[0]; geometry.heads = indata[1]; geometry.sectors = indata[2]; geometry.start = indata[3]; r = dm_set_geometry(md, &geometry); param->data_size = 0; out: dm_put(md); return r; } static int do_suspend(struct dm_ioctl *param) { int r = 0; unsigned suspend_flags = DM_SUSPEND_LOCKFS_FLAG; struct mapped_device *md; md = find_device(param); if (!md) return -ENXIO; if (param->flags & DM_SKIP_LOCKFS_FLAG) suspend_flags &= ~DM_SUSPEND_LOCKFS_FLAG; if (param->flags & DM_NOFLUSH_FLAG) suspend_flags |= DM_SUSPEND_NOFLUSH_FLAG; if (!dm_suspended_md(md)) { r = dm_suspend(md, suspend_flags); if (r) goto out; } __dev_status(md, param); out: dm_put(md); return r; } static int do_resume(struct dm_ioctl *param) { int r = 0; unsigned suspend_flags = DM_SUSPEND_LOCKFS_FLAG; struct hash_cell *hc; struct mapped_device *md; struct dm_table *new_map, *old_map = NULL; down_write(&_hash_lock); hc = __find_device_hash_cell(param); if (!hc) { DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table."); up_write(&_hash_lock); return -ENXIO; } md = hc->md; new_map = hc->new_map; hc->new_map = NULL; param->flags &= ~DM_INACTIVE_PRESENT_FLAG; up_write(&_hash_lock); /* Do we need to load a new map ? */ if (new_map) { /* Suspend if it isn't already suspended */ if (param->flags & DM_SKIP_LOCKFS_FLAG) suspend_flags &= ~DM_SUSPEND_LOCKFS_FLAG; if (param->flags & DM_NOFLUSH_FLAG) suspend_flags |= DM_SUSPEND_NOFLUSH_FLAG; if (!dm_suspended_md(md)) dm_suspend(md, suspend_flags); old_map = dm_swap_table(md, new_map); if (IS_ERR(old_map)) { dm_sync_table(md); dm_table_destroy(new_map); dm_put(md); return PTR_ERR(old_map); } if (dm_table_get_mode(new_map) & FMODE_WRITE) set_disk_ro(dm_disk(md), 0); else set_disk_ro(dm_disk(md), 1); } if (dm_suspended_md(md)) { r = dm_resume(md); if (!r && !dm_kobject_uevent(md, KOBJ_CHANGE, param->event_nr)) param->flags |= DM_UEVENT_GENERATED_FLAG; } /* * Since dm_swap_table synchronizes RCU, nobody should be in * read-side critical section already. */ if (old_map) dm_table_destroy(old_map); if (!r) __dev_status(md, param); dm_put(md); return r; } /* * Set or unset the suspension state of a device. * If the device already is in the requested state we just return its status. */ static int dev_suspend(struct dm_ioctl *param, size_t param_size) { if (param->flags & DM_SUSPEND_FLAG) return do_suspend(param); return do_resume(param); } /* * Copies device info back to user space, used by * the create and info ioctls. */ static int dev_status(struct dm_ioctl *param, size_t param_size) { struct mapped_device *md; md = find_device(param); if (!md) return -ENXIO; __dev_status(md, param); dm_put(md); return 0; } /* * Build up the status struct for each target */ static void retrieve_status(struct dm_table *table, struct dm_ioctl *param, size_t param_size) { unsigned int i, num_targets; struct dm_target_spec *spec; char *outbuf, *outptr; status_type_t type; size_t remaining, len, used = 0; unsigned status_flags = 0; outptr = outbuf = get_result_buffer(param, param_size, &len); if (param->flags & DM_STATUS_TABLE_FLAG) type = STATUSTYPE_TABLE; else type = STATUSTYPE_INFO; /* Get all the target info */ num_targets = dm_table_get_num_targets(table); for (i = 0; i < num_targets; i++) { struct dm_target *ti = dm_table_get_target(table, i); size_t l; remaining = len - (outptr - outbuf); if (remaining <= sizeof(struct dm_target_spec)) { param->flags |= DM_BUFFER_FULL_FLAG; break; } spec = (struct dm_target_spec *) outptr; spec->status = 0; spec->sector_start = ti->begin; spec->length = ti->len; strncpy(spec->target_type, ti->type->name, sizeof(spec->target_type)); outptr += sizeof(struct dm_target_spec); remaining = len - (outptr - outbuf); if (remaining <= 0) { param->flags |= DM_BUFFER_FULL_FLAG; break; } /* Get the status/table string from the target driver */ if (ti->type->status) { if (param->flags & DM_NOFLUSH_FLAG) status_flags |= DM_STATUS_NOFLUSH_FLAG; ti->type->status(ti, type, status_flags, outptr, remaining); } else outptr[0] = '\0'; l = strlen(outptr) + 1; if (l == remaining) { param->flags |= DM_BUFFER_FULL_FLAG; break; } outptr += l; used = param->data_start + (outptr - outbuf); outptr = align_ptr(outptr); spec->next = outptr - outbuf; } if (used) param->data_size = used; param->target_count = num_targets; } /* * Wait for a device to report an event */ static int dev_wait(struct dm_ioctl *param, size_t param_size) { int r = 0; struct mapped_device *md; struct dm_table *table; int srcu_idx; md = find_device(param); if (!md) return -ENXIO; /* * Wait for a notification event */ if (dm_wait_event(md, param->event_nr)) { r = -ERESTARTSYS; goto out; } /* * The userland program is going to want to know what * changed to trigger the event, so we may as well tell * him and save an ioctl. */ __dev_status(md, param); table = dm_get_live_or_inactive_table(md, param, &srcu_idx); if (table) retrieve_status(table, param, param_size); dm_put_live_table(md, srcu_idx); out: dm_put(md); return r; } static inline fmode_t get_mode(struct dm_ioctl *param) { fmode_t mode = FMODE_READ | FMODE_WRITE; if (param->flags & DM_READONLY_FLAG) mode = FMODE_READ; return mode; } static int next_target(struct dm_target_spec *last, uint32_t next, void *end, struct dm_target_spec **spec, char **target_params) { *spec = (struct dm_target_spec *) ((unsigned char *) last + next); *target_params = (char *) (*spec + 1); if (*spec < (last + 1)) return -EINVAL; return invalid_str(*target_params, end); } static int populate_table(struct dm_table *table, struct dm_ioctl *param, size_t param_size) { int r; unsigned int i = 0; struct dm_target_spec *spec = (struct dm_target_spec *) param; uint32_t next = param->data_start; void *end = (void *) param + param_size; char *target_params; if (!param->target_count) { DMWARN("populate_table: no targets specified"); return -EINVAL; } for (i = 0; i < param->target_count; i++) { r = next_target(spec, next, end, &spec, &target_params); if (r) { DMWARN("unable to find target"); return r; } r = dm_table_add_target(table, spec->target_type, (sector_t) spec->sector_start, (sector_t) spec->length, target_params); if (r) { DMWARN("error adding target to table"); return r; } next = spec->next; } return dm_table_complete(table); } static int table_load(struct dm_ioctl *param, size_t param_size) { int r; struct hash_cell *hc; struct dm_table *t, *old_map = NULL; struct mapped_device *md; struct target_type *immutable_target_type; md = find_device(param); if (!md) return -ENXIO; r = dm_table_create(&t, get_mode(param), param->target_count, md); if (r) goto err; /* Protect md->type and md->queue against concurrent table loads. */ dm_lock_md_type(md); r = populate_table(t, param, param_size); if (r) goto err_unlock_md_type; immutable_target_type = dm_get_immutable_target_type(md); if (immutable_target_type && (immutable_target_type != dm_table_get_immutable_target_type(t))) { DMWARN("can't replace immutable target type %s", immutable_target_type->name); r = -EINVAL; goto err_unlock_md_type; } if (dm_get_md_type(md) == DM_TYPE_NONE) /* Initial table load: acquire type of table. */ dm_set_md_type(md, dm_table_get_type(t)); else if (dm_get_md_type(md) != dm_table_get_type(t)) { DMWARN("can't change device type after initial table load."); r = -EINVAL; goto err_unlock_md_type; } /* setup md->queue to reflect md's type (may block) */ r = dm_setup_md_queue(md); if (r) { DMWARN("unable to set up device queue for new table."); goto err_unlock_md_type; } dm_unlock_md_type(md); /* stage inactive table */ down_write(&_hash_lock); hc = dm_get_mdptr(md); if (!hc || hc->md != md) { DMWARN("device has been removed from the dev hash table."); up_write(&_hash_lock); r = -ENXIO; goto err_destroy_table; } if (hc->new_map) old_map = hc->new_map; hc->new_map = t; up_write(&_hash_lock); param->flags |= DM_INACTIVE_PRESENT_FLAG; __dev_status(md, param); if (old_map) { dm_sync_table(md); dm_table_destroy(old_map); } dm_put(md); return 0; err_unlock_md_type: dm_unlock_md_type(md); err_destroy_table: dm_table_destroy(t); err: dm_put(md); return r; } static int table_clear(struct dm_ioctl *param, size_t param_size) { struct hash_cell *hc; struct mapped_device *md; struct dm_table *old_map = NULL; down_write(&_hash_lock); hc = __find_device_hash_cell(param); if (!hc) { DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table."); up_write(&_hash_lock); return -ENXIO; } if (hc->new_map) { old_map = hc->new_map; hc->new_map = NULL; } param->flags &= ~DM_INACTIVE_PRESENT_FLAG; __dev_status(hc->md, param); md = hc->md; up_write(&_hash_lock); if (old_map) { dm_sync_table(md); dm_table_destroy(old_map); } dm_put(md); return 0; } /* * Retrieves a list of devices used by a particular dm device. */ static void retrieve_deps(struct dm_table *table, struct dm_ioctl *param, size_t param_size) { unsigned int count = 0; struct list_head *tmp; size_t len, needed; struct dm_dev_internal *dd; struct dm_target_deps *deps; deps = get_result_buffer(param, param_size, &len); /* * Count the devices. */ list_for_each (tmp, dm_table_get_devices(table)) count++; /* * Check we have enough space. */ needed = sizeof(*deps) + (sizeof(*deps->dev) * count); if (len < needed) { param->flags |= DM_BUFFER_FULL_FLAG; return; } /* * Fill in the devices. */ deps->count = count; count = 0; list_for_each_entry (dd, dm_table_get_devices(table), list) deps->dev[count++] = huge_encode_dev(dd->dm_dev.bdev->bd_dev); param->data_size = param->data_start + needed; } static int table_deps(struct dm_ioctl *param, size_t param_size) { struct mapped_device *md; struct dm_table *table; int srcu_idx; md = find_device(param); if (!md) return -ENXIO; __dev_status(md, param); table = dm_get_live_or_inactive_table(md, param, &srcu_idx); if (table) retrieve_deps(table, param, param_size); dm_put_live_table(md, srcu_idx); dm_put(md); return 0; } /* * Return the status of a device as a text string for each * target. */ static int table_status(struct dm_ioctl *param, size_t param_size) { struct mapped_device *md; struct dm_table *table; int srcu_idx; md = find_device(param); if (!md) return -ENXIO; __dev_status(md, param); table = dm_get_live_or_inactive_table(md, param, &srcu_idx); if (table) retrieve_status(table, param, param_size); dm_put_live_table(md, srcu_idx); dm_put(md); return 0; } /* * Process device-mapper dependent messages. Messages prefixed with '@' * are processed by the DM core. All others are delivered to the target. * Returns a number <= 1 if message was processed by device mapper. * Returns 2 if message should be delivered to the target. */ static int message_for_md(struct mapped_device *md, unsigned argc, char **argv, char *result, unsigned maxlen) { int r; if (**argv != '@') return 2; /* no '@' prefix, deliver to target */ if (!strcasecmp(argv[0], "@cancel_deferred_remove")) { if (argc != 1) { DMERR("Invalid arguments for @cancel_deferred_remove"); return -EINVAL; } return dm_cancel_deferred_remove(md); } r = dm_stats_message(md, argc, argv, result, maxlen); if (r < 2) return r; DMERR("Unsupported message sent to DM core: %s", argv[0]); return -EINVAL; } /* * Pass a message to the target that's at the supplied device offset. */ static int target_message(struct dm_ioctl *param, size_t param_size) { int r, argc; char **argv; struct mapped_device *md; struct dm_table *table; struct dm_target *ti; struct dm_target_msg *tmsg = (void *) param + param->data_start; size_t maxlen; char *result = get_result_buffer(param, param_size, &maxlen); int srcu_idx; md = find_device(param); if (!md) return -ENXIO; if (tmsg < (struct dm_target_msg *) param->data || invalid_str(tmsg->message, (void *) param + param_size)) { DMWARN("Invalid target message parameters."); r = -EINVAL; goto out; } r = dm_split_args(&argc, &argv, tmsg->message); if (r) { DMWARN("Failed to split target message parameters"); goto out; } if (!argc) { DMWARN("Empty message received."); goto out_argv; } r = message_for_md(md, argc, argv, result, maxlen); if (r <= 1) goto out_argv; table = dm_get_live_table(md, &srcu_idx); if (!table) goto out_table; if (dm_deleting_md(md)) { r = -ENXIO; goto out_table; } ti = dm_table_find_target(table, tmsg->sector); if (!dm_target_is_valid(ti)) { DMWARN("Target message sector outside device."); r = -EINVAL; } else if (ti->type->message) r = ti->type->message(ti, argc, argv); else { DMWARN("Target type does not support messages"); r = -EINVAL; } out_table: dm_put_live_table(md, srcu_idx); out_argv: kfree(argv); out: if (r >= 0) __dev_status(md, param); if (r == 1) { param->flags |= DM_DATA_OUT_FLAG; if (dm_message_test_buffer_overflow(result, maxlen)) param->flags |= DM_BUFFER_FULL_FLAG; else param->data_size = param->data_start + strlen(result) + 1; r = 0; } dm_put(md); return r; } /* * The ioctl parameter block consists of two parts, a dm_ioctl struct * followed by a data buffer. This flag is set if the second part, * which has a variable size, is not used by the function processing * the ioctl. */ #define IOCTL_FLAGS_NO_PARAMS 1 /*----------------------------------------------------------------- * Implementation of open/close/ioctl on the special char * device. *---------------------------------------------------------------*/ static ioctl_fn lookup_ioctl(unsigned int cmd, int *ioctl_flags) { static struct { int cmd; int flags; ioctl_fn fn; } _ioctls[] = { {DM_VERSION_CMD, 0, NULL}, /* version is dealt with elsewhere */ {DM_REMOVE_ALL_CMD, IOCTL_FLAGS_NO_PARAMS, remove_all}, {DM_LIST_DEVICES_CMD, 0, list_devices}, {DM_DEV_CREATE_CMD, IOCTL_FLAGS_NO_PARAMS, dev_create}, {DM_DEV_REMOVE_CMD, IOCTL_FLAGS_NO_PARAMS, dev_remove}, {DM_DEV_RENAME_CMD, 0, dev_rename}, {DM_DEV_SUSPEND_CMD, IOCTL_FLAGS_NO_PARAMS, dev_suspend}, {DM_DEV_STATUS_CMD, IOCTL_FLAGS_NO_PARAMS, dev_status}, {DM_DEV_WAIT_CMD, 0, dev_wait}, {DM_TABLE_LOAD_CMD, 0, table_load}, {DM_TABLE_CLEAR_CMD, IOCTL_FLAGS_NO_PARAMS, table_clear}, {DM_TABLE_DEPS_CMD, 0, table_deps}, {DM_TABLE_STATUS_CMD, 0, table_status}, {DM_LIST_VERSIONS_CMD, 0, list_versions}, {DM_TARGET_MSG_CMD, 0, target_message}, {DM_DEV_SET_GEOMETRY_CMD, 0, dev_set_geometry} }; if (unlikely(cmd >= ARRAY_SIZE(_ioctls))) return NULL; *ioctl_flags = _ioctls[cmd].flags; return _ioctls[cmd].fn; } /* * As well as checking the version compatibility this always * copies the kernel interface version out. */ static int check_version(unsigned int cmd, struct dm_ioctl __user *user) { uint32_t version[3]; int r = 0; if (copy_from_user(version, user->version, sizeof(version))) return -EFAULT; if ((DM_VERSION_MAJOR != version[0]) || (DM_VERSION_MINOR < version[1])) { DMWARN("ioctl interface mismatch: " "kernel(%u.%u.%u), user(%u.%u.%u), cmd(%d)", DM_VERSION_MAJOR, DM_VERSION_MINOR, DM_VERSION_PATCHLEVEL, version[0], version[1], version[2], cmd); r = -EINVAL; } /* * Fill in the kernel version. */ version[0] = DM_VERSION_MAJOR; version[1] = DM_VERSION_MINOR; version[2] = DM_VERSION_PATCHLEVEL; if (copy_to_user(user->version, version, sizeof(version))) return -EFAULT; return r; } #define DM_PARAMS_KMALLOC 0x0001 /* Params alloced with kmalloc */ #define DM_PARAMS_VMALLOC 0x0002 /* Params alloced with vmalloc */ #define DM_WIPE_BUFFER 0x0010 /* Wipe input buffer before returning from ioctl */ static void free_params(struct dm_ioctl *param, size_t param_size, int param_flags) { if (param_flags & DM_WIPE_BUFFER) memset(param, 0, param_size); if (param_flags & DM_PARAMS_KMALLOC) kfree(param); if (param_flags & DM_PARAMS_VMALLOC) vfree(param); } static int copy_params(struct dm_ioctl __user *user, struct dm_ioctl *param_kernel, int ioctl_flags, struct dm_ioctl **param, int *param_flags) { struct dm_ioctl *dmi; int secure_data; const size_t minimum_data_size = sizeof(*param_kernel) - sizeof(param_kernel->data); if (copy_from_user(param_kernel, user, minimum_data_size)) return -EFAULT; if (param_kernel->data_size < minimum_data_size) return -EINVAL; secure_data = param_kernel->flags & DM_SECURE_DATA_FLAG; *param_flags = secure_data ? DM_WIPE_BUFFER : 0; if (ioctl_flags & IOCTL_FLAGS_NO_PARAMS) { dmi = param_kernel; dmi->data_size = minimum_data_size; goto data_copied; } /* * Try to avoid low memory issues when a device is suspended. * Use kmalloc() rather than vmalloc() when we can. */ dmi = NULL; if (param_kernel->data_size <= KMALLOC_MAX_SIZE) { dmi = kmalloc(param_kernel->data_size, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN); if (dmi) *param_flags |= DM_PARAMS_KMALLOC; } if (!dmi) { unsigned noio_flag; noio_flag = memalloc_noio_save(); dmi = __vmalloc(param_kernel->data_size, GFP_NOIO | __GFP_REPEAT | __GFP_HIGH | __GFP_HIGHMEM, PAGE_KERNEL); memalloc_noio_restore(noio_flag); if (dmi) *param_flags |= DM_PARAMS_VMALLOC; } if (!dmi) { if (secure_data && clear_user(user, param_kernel->data_size)) return -EFAULT; return -ENOMEM; } if (copy_from_user(dmi, user, param_kernel->data_size)) goto bad; data_copied: /* * Abort if something changed the ioctl data while it was being copied. */ if (dmi->data_size != param_kernel->data_size) { DMERR("rejecting ioctl: data size modified while processing parameters"); goto bad; } /* Wipe the user buffer so we do not return it to userspace */ if (secure_data && clear_user(user, param_kernel->data_size)) goto bad; *param = dmi; return 0; bad: free_params(dmi, param_kernel->data_size, *param_flags); return -EFAULT; } static int validate_params(uint cmd, struct dm_ioctl *param) { /* Always clear this flag */ param->flags &= ~DM_BUFFER_FULL_FLAG; param->flags &= ~DM_UEVENT_GENERATED_FLAG; param->flags &= ~DM_SECURE_DATA_FLAG; param->flags &= ~DM_DATA_OUT_FLAG; /* Ignores parameters */ if (cmd == DM_REMOVE_ALL_CMD || cmd == DM_LIST_DEVICES_CMD || cmd == DM_LIST_VERSIONS_CMD) return 0; if ((cmd == DM_DEV_CREATE_CMD)) { if (!*param->name) { DMWARN("name not supplied when creating device"); return -EINVAL; } } else if ((*param->uuid && *param->name)) { DMWARN("only supply one of name or uuid, cmd(%u)", cmd); return -EINVAL; } /* Ensure strings are terminated */ param->name[DM_NAME_LEN - 1] = '\0'; param->uuid[DM_UUID_LEN - 1] = '\0'; return 0; } static int ctl_ioctl(uint command, struct dm_ioctl __user *user) { int r = 0; int ioctl_flags; int param_flags; unsigned int cmd; struct dm_ioctl *uninitialized_var(param); ioctl_fn fn = NULL; size_t input_param_size; struct dm_ioctl param_kernel; /* only root can play with this */ if (!capable(CAP_SYS_ADMIN)) return -EACCES; if (_IOC_TYPE(command) != DM_IOCTL) return -ENOTTY; cmd = _IOC_NR(command); /* * Check the interface version passed in. This also * writes out the kernel's interface version. */ r = check_version(cmd, user); if (r) return r; /* * Nothing more to do for the version command. */ if (cmd == DM_VERSION_CMD) return 0; fn = lookup_ioctl(cmd, &ioctl_flags); if (!fn) { DMWARN("dm_ctl_ioctl: unknown command 0x%x", command); return -ENOTTY; } /* * Copy the parameters into kernel space. */ r = copy_params(user, &param_kernel, ioctl_flags, &param, &param_flags); if (r) return r; input_param_size = param->data_size; r = validate_params(cmd, param); if (r) goto out; param->data_size = sizeof(*param); r = fn(param, input_param_size); if (unlikely(param->flags & DM_BUFFER_FULL_FLAG) && unlikely(ioctl_flags & IOCTL_FLAGS_NO_PARAMS)) DMERR("ioctl %d tried to output some data but has IOCTL_FLAGS_NO_PARAMS set", cmd); /* * Copy the results back to userland. */ if (!r && copy_to_user(user, param, param->data_size)) r = -EFAULT; out: free_params(param, input_param_size, param_flags); return r; } static long dm_ctl_ioctl(struct file *file, uint command, ulong u) { return (long)ctl_ioctl(command, (struct dm_ioctl __user *)u); } #ifdef CONFIG_COMPAT static long dm_compat_ctl_ioctl(struct file *file, uint command, ulong u) { return (long)dm_ctl_ioctl(file, command, (ulong) compat_ptr(u)); } #else #define dm_compat_ctl_ioctl NULL #endif static const struct file_operations _ctl_fops = { .open = nonseekable_open, .unlocked_ioctl = dm_ctl_ioctl, .compat_ioctl = dm_compat_ctl_ioctl, .owner = THIS_MODULE, .llseek = noop_llseek, }; static struct miscdevice _dm_misc = { .minor = MAPPER_CTRL_MINOR, .name = DM_NAME, .nodename = DM_DIR "/" DM_CONTROL_NODE, .fops = &_ctl_fops }; MODULE_ALIAS_MISCDEV(MAPPER_CTRL_MINOR); MODULE_ALIAS("devname:" DM_DIR "/" DM_CONTROL_NODE); /* * Create misc character device and link to DM_DIR/control. */ int __init dm_interface_init(void) { int r; r = dm_hash_init(); if (r) return r; r = misc_register(&_dm_misc); if (r) { DMERR("misc_register failed for control device"); dm_hash_exit(); return r; } DMINFO("%d.%d.%d%s initialised: %s", DM_VERSION_MAJOR, DM_VERSION_MINOR, DM_VERSION_PATCHLEVEL, DM_VERSION_EXTRA, DM_DRIVER_EMAIL); return 0; } void dm_interface_exit(void) { if (misc_deregister(&_dm_misc) < 0) DMERR("misc_deregister failed for control device"); dm_hash_exit(); } /** * dm_copy_name_and_uuid - Copy mapped device name & uuid into supplied buffers * @md: Pointer to mapped_device * @name: Buffer (size DM_NAME_LEN) for name * @uuid: Buffer (size DM_UUID_LEN) for uuid or empty string if uuid not defined */ int dm_copy_name_and_uuid(struct mapped_device *md, char *name, char *uuid) { int r = 0; struct hash_cell *hc; if (!md) return -ENXIO; mutex_lock(&dm_hash_cells_mutex); hc = dm_get_mdptr(md); if (!hc || hc->md != md) { r = -ENXIO; goto out; } if (name) strcpy(name, hc->name); if (uuid) strcpy(uuid, hc->uuid ? : ""); out: mutex_unlock(&dm_hash_cells_mutex); return r; }
coreos/linux-deprecated
drivers/md/dm-ioctl.c
C
gpl-2.0
43,318
/* * Shared interrupt handling code for IPR and INTC2 types of IRQs. * * Copyright (C) 2007, 2008 Magnus Damm * Copyright (C) 2009 - 2012 Paul Mundt * * Based on intc2.c and ipr.c * * Copyright (C) 1999 Niibe Yutaka & Takeshi Yaegashi * Copyright (C) 2000 Kazumoto Kojima * Copyright (C) 2001 David J. Mckay (david.mckay@st.com) * Copyright (C) 2003 Takashi Kusuda <kusuda-takashi@hitachi-ul.co.jp> * Copyright (C) 2005, 2006 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #define pr_fmt(fmt) "intc: " fmt #include <linux/init.h> #include <linux/irq.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/stat.h> #include <linux/interrupt.h> #include <linux/sh_intc.h> #include <linux/irqdomain.h> #include <linux/device.h> #include <linux/syscore_ops.h> #include <linux/list.h> #include <linux/spinlock.h> #include <linux/radix-tree.h> #include <linux/export.h> #include <linux/sort.h> #include "internals.h" LIST_HEAD(intc_list); DEFINE_RAW_SPINLOCK(intc_big_lock); static unsigned int nr_intc_controllers; /* * Default priority level * - this needs to be at least 2 for 5-bit priorities on 7780 */ static unsigned int default_prio_level = 2; /* 2 - 16 */ static unsigned int intc_prio_level[INTC_NR_IRQS]; /* for now */ unsigned int intc_get_dfl_prio_level(void) { return default_prio_level; } unsigned int intc_get_prio_level(unsigned int irq) { return intc_prio_level[irq]; } void intc_set_prio_level(unsigned int irq, unsigned int level) { unsigned long flags; raw_spin_lock_irqsave(&intc_big_lock, flags); intc_prio_level[irq] = level; raw_spin_unlock_irqrestore(&intc_big_lock, flags); } static void intc_redirect_irq(struct irq_desc *desc) { generic_handle_irq((unsigned int)irq_desc_get_handler_data(desc)); } static void __init intc_register_irq(struct intc_desc *desc, struct intc_desc_int *d, intc_enum enum_id, unsigned int irq) { struct intc_handle_int *hp; struct irq_data *irq_data; unsigned int data[2], primary; unsigned long flags; raw_spin_lock_irqsave(&intc_big_lock, flags); radix_tree_insert(&d->tree, enum_id, intc_irq_xlate_get(irq)); raw_spin_unlock_irqrestore(&intc_big_lock, flags); /* * Prefer single interrupt source bitmap over other combinations: * * 1. bitmap, single interrupt source * 2. priority, single interrupt source * 3. bitmap, multiple interrupt sources (groups) * 4. priority, multiple interrupt sources (groups) */ data[0] = intc_get_mask_handle(desc, d, enum_id, 0); data[1] = intc_get_prio_handle(desc, d, enum_id, 0); primary = 0; if (!data[0] && data[1]) primary = 1; if (!data[0] && !data[1]) pr_warning("missing unique irq mask for irq %d (vect 0x%04x)\n", irq, irq2evt(irq)); data[0] = data[0] ? data[0] : intc_get_mask_handle(desc, d, enum_id, 1); data[1] = data[1] ? data[1] : intc_get_prio_handle(desc, d, enum_id, 1); if (!data[primary]) primary ^= 1; BUG_ON(!data[primary]); /* must have primary masking method */ irq_data = irq_get_irq_data(irq); disable_irq_nosync(irq); irq_set_chip_and_handler_name(irq, &d->chip, handle_level_irq, "level"); irq_set_chip_data(irq, (void *)data[primary]); /* * set priority level */ intc_set_prio_level(irq, intc_get_dfl_prio_level()); /* enable secondary masking method if present */ if (data[!primary]) _intc_enable(irq_data, data[!primary]); /* add irq to d->prio list if priority is available */ if (data[1]) { hp = d->prio + d->nr_prio; hp->irq = irq; hp->handle = data[1]; if (primary) { /* * only secondary priority should access registers, so * set _INTC_FN(h) = REG_FN_ERR for intc_set_priority() */ hp->handle &= ~_INTC_MK(0x0f, 0, 0, 0, 0, 0); hp->handle |= _INTC_MK(REG_FN_ERR, 0, 0, 0, 0, 0); } d->nr_prio++; } /* add irq to d->sense list if sense is available */ data[0] = intc_get_sense_handle(desc, d, enum_id); if (data[0]) { (d->sense + d->nr_sense)->irq = irq; (d->sense + d->nr_sense)->handle = data[0]; d->nr_sense++; } /* irq should be disabled by default */ d->chip.irq_mask(irq_data); intc_set_ack_handle(irq, desc, d, enum_id); intc_set_dist_handle(irq, desc, d, enum_id); activate_irq(irq); } static unsigned int __init save_reg(struct intc_desc_int *d, unsigned int cnt, unsigned long value, unsigned int smp) { if (value) { value = intc_phys_to_virt(d, value); d->reg[cnt] = value; #ifdef CONFIG_SMP d->smp[cnt] = smp; #endif return 1; } return 0; } int __init register_intc_controller(struct intc_desc *desc) { unsigned int i, k, smp; struct intc_hw_desc *hw = &desc->hw; struct intc_desc_int *d; struct resource *res; pr_info("Registered controller '%s' with %u IRQs\n", desc->name, hw->nr_vectors); d = kzalloc(sizeof(*d), GFP_NOWAIT); if (!d) goto err0; INIT_LIST_HEAD(&d->list); list_add_tail(&d->list, &intc_list); raw_spin_lock_init(&d->lock); INIT_RADIX_TREE(&d->tree, GFP_ATOMIC); d->index = nr_intc_controllers; if (desc->num_resources) { d->nr_windows = desc->num_resources; d->window = kzalloc(d->nr_windows * sizeof(*d->window), GFP_NOWAIT); if (!d->window) goto err1; for (k = 0; k < d->nr_windows; k++) { res = desc->resource + k; WARN_ON(resource_type(res) != IORESOURCE_MEM); d->window[k].phys = res->start; d->window[k].size = resource_size(res); d->window[k].virt = ioremap_nocache(res->start, resource_size(res)); if (!d->window[k].virt) goto err2; } } d->nr_reg = hw->mask_regs ? hw->nr_mask_regs * 2 : 0; #ifdef CONFIG_INTC_BALANCING if (d->nr_reg) d->nr_reg += hw->nr_mask_regs; #endif d->nr_reg += hw->prio_regs ? hw->nr_prio_regs * 2 : 0; d->nr_reg += hw->sense_regs ? hw->nr_sense_regs : 0; d->nr_reg += hw->ack_regs ? hw->nr_ack_regs : 0; d->nr_reg += hw->subgroups ? hw->nr_subgroups : 0; d->reg = kzalloc(d->nr_reg * sizeof(*d->reg), GFP_NOWAIT); if (!d->reg) goto err2; #ifdef CONFIG_SMP d->smp = kzalloc(d->nr_reg * sizeof(*d->smp), GFP_NOWAIT); if (!d->smp) goto err3; #endif k = 0; if (hw->mask_regs) { for (i = 0; i < hw->nr_mask_regs; i++) { smp = IS_SMP(hw->mask_regs[i]); k += save_reg(d, k, hw->mask_regs[i].set_reg, smp); k += save_reg(d, k, hw->mask_regs[i].clr_reg, smp); #ifdef CONFIG_INTC_BALANCING k += save_reg(d, k, hw->mask_regs[i].dist_reg, 0); #endif } } if (hw->prio_regs) { d->prio = kzalloc(hw->nr_vectors * sizeof(*d->prio), GFP_NOWAIT); if (!d->prio) goto err4; for (i = 0; i < hw->nr_prio_regs; i++) { smp = IS_SMP(hw->prio_regs[i]); k += save_reg(d, k, hw->prio_regs[i].set_reg, smp); k += save_reg(d, k, hw->prio_regs[i].clr_reg, smp); } sort(d->prio, hw->nr_prio_regs, sizeof(*d->prio), intc_handle_int_cmp, NULL); } if (hw->sense_regs) { d->sense = kzalloc(hw->nr_vectors * sizeof(*d->sense), GFP_NOWAIT); if (!d->sense) goto err5; for (i = 0; i < hw->nr_sense_regs; i++) k += save_reg(d, k, hw->sense_regs[i].reg, 0); sort(d->sense, hw->nr_sense_regs, sizeof(*d->sense), intc_handle_int_cmp, NULL); } if (hw->subgroups) for (i = 0; i < hw->nr_subgroups; i++) if (hw->subgroups[i].reg) k+= save_reg(d, k, hw->subgroups[i].reg, 0); memcpy(&d->chip, &intc_irq_chip, sizeof(struct irq_chip)); d->chip.name = desc->name; if (hw->ack_regs) for (i = 0; i < hw->nr_ack_regs; i++) k += save_reg(d, k, hw->ack_regs[i].set_reg, 0); else d->chip.irq_mask_ack = d->chip.irq_disable; /* disable bits matching force_disable before registering irqs */ if (desc->force_disable) intc_enable_disable_enum(desc, d, desc->force_disable, 0); /* disable bits matching force_enable before registering irqs */ if (desc->force_enable) intc_enable_disable_enum(desc, d, desc->force_enable, 0); BUG_ON(k > 256); /* _INTC_ADDR_E() and _INTC_ADDR_D() are 8 bits */ intc_irq_domain_init(d, hw); /* register the vectors one by one */ for (i = 0; i < hw->nr_vectors; i++) { struct intc_vect *vect = hw->vectors + i; unsigned int irq = evt2irq(vect->vect); int res; if (!vect->enum_id) continue; res = irq_create_identity_mapping(d->domain, irq); if (unlikely(res)) { if (res == -EEXIST) { res = irq_domain_associate(d->domain, irq, irq); if (unlikely(res)) { pr_err("domain association failure\n"); continue; } } else { pr_err("can't identity map IRQ %d\n", irq); continue; } } intc_irq_xlate_set(irq, vect->enum_id, d); intc_register_irq(desc, d, vect->enum_id, irq); for (k = i + 1; k < hw->nr_vectors; k++) { struct intc_vect *vect2 = hw->vectors + k; unsigned int irq2 = evt2irq(vect2->vect); if (vect->enum_id != vect2->enum_id) continue; /* * In the case of multi-evt handling and sparse * IRQ support, each vector still needs to have * its own backing irq_desc. */ res = irq_create_identity_mapping(d->domain, irq2); if (unlikely(res)) { if (res == -EEXIST) { res = irq_domain_associate(d->domain, irq2, irq2); if (unlikely(res)) { pr_err("domain association " "failure\n"); continue; } } else { pr_err("can't identity map IRQ %d\n", irq); continue; } } vect2->enum_id = 0; /* redirect this interrupts to the first one */ irq_set_chip(irq2, &dummy_irq_chip); irq_set_chained_handler_and_data(irq2, intc_redirect_irq, (void *)irq); } } intc_subgroup_init(desc, d); /* enable bits matching force_enable after registering irqs */ if (desc->force_enable) intc_enable_disable_enum(desc, d, desc->force_enable, 1); d->skip_suspend = desc->skip_syscore_suspend; nr_intc_controllers++; return 0; err5: kfree(d->prio); err4: #ifdef CONFIG_SMP kfree(d->smp); err3: #endif kfree(d->reg); err2: for (k = 0; k < d->nr_windows; k++) if (d->window[k].virt) iounmap(d->window[k].virt); kfree(d->window); err1: kfree(d); err0: pr_err("unable to allocate INTC memory\n"); return -ENOMEM; } static int intc_suspend(void) { struct intc_desc_int *d; list_for_each_entry(d, &intc_list, list) { int irq; if (d->skip_suspend) continue; /* enable wakeup irqs belonging to this intc controller */ for_each_active_irq(irq) { struct irq_data *data; struct irq_chip *chip; data = irq_get_irq_data(irq); chip = irq_data_get_irq_chip(data); if (chip != &d->chip) continue; if (irqd_is_wakeup_set(data)) chip->irq_enable(data); } } return 0; } static void intc_resume(void) { struct intc_desc_int *d; list_for_each_entry(d, &intc_list, list) { int irq; if (d->skip_suspend) continue; for_each_active_irq(irq) { struct irq_data *data; struct irq_chip *chip; data = irq_get_irq_data(irq); chip = irq_data_get_irq_chip(data); /* * This will catch the redirect and VIRQ cases * due to the dummy_irq_chip being inserted. */ if (chip != &d->chip) continue; if (irqd_irq_disabled(data)) chip->irq_disable(data); else chip->irq_enable(data); } } } struct syscore_ops intc_syscore_ops = { .suspend = intc_suspend, .resume = intc_resume, }; struct bus_type intc_subsys = { .name = "intc", .dev_name = "intc", }; static ssize_t show_intc_name(struct device *dev, struct device_attribute *attr, char *buf) { struct intc_desc_int *d; d = container_of(dev, struct intc_desc_int, dev); return sprintf(buf, "%s\n", d->chip.name); } static DEVICE_ATTR(name, S_IRUGO, show_intc_name, NULL); static int __init register_intc_devs(void) { struct intc_desc_int *d; int error; register_syscore_ops(&intc_syscore_ops); error = subsys_system_register(&intc_subsys, NULL); if (!error) { list_for_each_entry(d, &intc_list, list) { d->dev.id = d->index; d->dev.bus = &intc_subsys; error = device_register(&d->dev); if (error == 0) error = device_create_file(&d->dev, &dev_attr_name); if (error) break; } } if (error) pr_err("device registration error\n"); return error; } device_initcall(register_intc_devs);
rhtu/linux
drivers/sh/intc/core.c
C
gpl-2.0
12,263
/* Driver for USB Mass Storage compliant devices * Debugging Functions Source Code File * * Current development and maintenance by: * (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net) * * Developed with the assistance of: * (c) 2002 Alan Stern <stern@rowland.org> * * Initial work by: * (c) 1999 Michael Gee (michael@linuxspecific.com) * * This driver is based on the 'USB Mass Storage Class' document. This * describes in detail the protocol used to communicate with such * devices. Clearly, the designers had SCSI and ATAPI commands in * mind when they created this document. The commands are all very * similar to commands in the SCSI-II and ATAPI specifications. * * It is important to note that in a number of cases this class * exhibits class-specific exemptions from the USB specification. * Notably the usage of NAK, STALL and ACK differs from the norm, in * that they are used to communicate wait, failed and OK on commands. * * Also, for certain devices, the interrupt endpoint is used to convey * status of a command. * * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more * information about this driver. * * 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., * 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/device.h> #include <linux/cdrom.h> #include <linux/export.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_dbg.h> #include "usb.h" #include "debug.h" #include "scsi.h" void usb_stor_show_command(const struct us_data *us, struct scsi_cmnd *srb) { char *what = NULL; int i; switch (srb->cmnd[0]) { case TEST_UNIT_READY: what = "TEST_UNIT_READY"; break; case REZERO_UNIT: what = "REZERO_UNIT"; break; case REQUEST_SENSE: what = "REQUEST_SENSE"; break; case FORMAT_UNIT: what = "FORMAT_UNIT"; break; case READ_BLOCK_LIMITS: what = "READ_BLOCK_LIMITS"; break; case REASSIGN_BLOCKS: what = "REASSIGN_BLOCKS"; break; case READ_6: what = "READ_6"; break; case WRITE_6: what = "WRITE_6"; break; case SEEK_6: what = "SEEK_6"; break; case READ_REVERSE: what = "READ_REVERSE"; break; case WRITE_FILEMARKS: what = "WRITE_FILEMARKS"; break; case SPACE: what = "SPACE"; break; case INQUIRY: what = "INQUIRY"; break; case RECOVER_BUFFERED_DATA: what = "RECOVER_BUFFERED_DATA"; break; case MODE_SELECT: what = "MODE_SELECT"; break; case RESERVE: what = "RESERVE"; break; case RELEASE: what = "RELEASE"; break; case COPY: what = "COPY"; break; case ERASE: what = "ERASE"; break; case MODE_SENSE: what = "MODE_SENSE"; break; case START_STOP: what = "START_STOP"; break; case RECEIVE_DIAGNOSTIC: what = "RECEIVE_DIAGNOSTIC"; break; case SEND_DIAGNOSTIC: what = "SEND_DIAGNOSTIC"; break; case ALLOW_MEDIUM_REMOVAL: what = "ALLOW_MEDIUM_REMOVAL"; break; case SET_WINDOW: what = "SET_WINDOW"; break; case READ_CAPACITY: what = "READ_CAPACITY"; break; case READ_10: what = "READ_10"; break; case WRITE_10: what = "WRITE_10"; break; case SEEK_10: what = "SEEK_10"; break; case WRITE_VERIFY: what = "WRITE_VERIFY"; break; case VERIFY: what = "VERIFY"; break; case SEARCH_HIGH: what = "SEARCH_HIGH"; break; case SEARCH_EQUAL: what = "SEARCH_EQUAL"; break; case SEARCH_LOW: what = "SEARCH_LOW"; break; case SET_LIMITS: what = "SET_LIMITS"; break; case READ_POSITION: what = "READ_POSITION"; break; case SYNCHRONIZE_CACHE: what = "SYNCHRONIZE_CACHE"; break; case LOCK_UNLOCK_CACHE: what = "LOCK_UNLOCK_CACHE"; break; case READ_DEFECT_DATA: what = "READ_DEFECT_DATA"; break; case MEDIUM_SCAN: what = "MEDIUM_SCAN"; break; case COMPARE: what = "COMPARE"; break; case COPY_VERIFY: what = "COPY_VERIFY"; break; case WRITE_BUFFER: what = "WRITE_BUFFER"; break; case READ_BUFFER: what = "READ_BUFFER"; break; case UPDATE_BLOCK: what = "UPDATE_BLOCK"; break; case READ_LONG: what = "READ_LONG"; break; case WRITE_LONG: what = "WRITE_LONG"; break; case CHANGE_DEFINITION: what = "CHANGE_DEFINITION"; break; case WRITE_SAME: what = "WRITE_SAME"; break; case GPCMD_READ_SUBCHANNEL: what = "READ SUBCHANNEL"; break; case READ_TOC: what = "READ_TOC"; break; case GPCMD_READ_HEADER: what = "READ HEADER"; break; case GPCMD_PLAY_AUDIO_10: what = "PLAY AUDIO (10)"; break; case GPCMD_PLAY_AUDIO_MSF: what = "PLAY AUDIO MSF"; break; case GPCMD_GET_EVENT_STATUS_NOTIFICATION: what = "GET EVENT/STATUS NOTIFICATION"; break; case GPCMD_PAUSE_RESUME: what = "PAUSE/RESUME"; break; case LOG_SELECT: what = "LOG_SELECT"; break; case LOG_SENSE: what = "LOG_SENSE"; break; case GPCMD_STOP_PLAY_SCAN: what = "STOP PLAY/SCAN"; break; case GPCMD_READ_DISC_INFO: what = "READ DISC INFORMATION"; break; case GPCMD_READ_TRACK_RZONE_INFO: what = "READ TRACK INFORMATION"; break; case GPCMD_RESERVE_RZONE_TRACK: what = "RESERVE TRACK"; break; case GPCMD_SEND_OPC: what = "SEND OPC"; break; case MODE_SELECT_10: what = "MODE_SELECT_10"; break; case GPCMD_REPAIR_RZONE_TRACK: what = "REPAIR TRACK"; break; case 0x59: what = "READ MASTER CUE"; break; case MODE_SENSE_10: what = "MODE_SENSE_10"; break; case GPCMD_CLOSE_TRACK: what = "CLOSE TRACK/SESSION"; break; case 0x5C: what = "READ BUFFER CAPACITY"; break; case 0x5D: what = "SEND CUE SHEET"; break; case GPCMD_BLANK: what = "BLANK"; break; case REPORT_LUNS: what = "REPORT LUNS"; break; case MOVE_MEDIUM: what = "MOVE_MEDIUM or PLAY AUDIO (12)"; break; case READ_12: what = "READ_12"; break; case WRITE_12: what = "WRITE_12"; break; case WRITE_VERIFY_12: what = "WRITE_VERIFY_12"; break; case SEARCH_HIGH_12: what = "SEARCH_HIGH_12"; break; case SEARCH_EQUAL_12: what = "SEARCH_EQUAL_12"; break; case SEARCH_LOW_12: what = "SEARCH_LOW_12"; break; case SEND_VOLUME_TAG: what = "SEND_VOLUME_TAG"; break; case READ_ELEMENT_STATUS: what = "READ_ELEMENT_STATUS"; break; case GPCMD_READ_CD_MSF: what = "READ CD MSF"; break; case GPCMD_SCAN: what = "SCAN"; break; case GPCMD_SET_SPEED: what = "SET CD SPEED"; break; case GPCMD_MECHANISM_STATUS: what = "MECHANISM STATUS"; break; case GPCMD_READ_CD: what = "READ CD"; break; case 0xE1: what = "WRITE CONTINUE"; break; case WRITE_LONG_2: what = "WRITE_LONG_2"; break; default: what = "(unknown command)"; break; } usb_stor_dbg(us, "Command %s (%d bytes)\n", what, srb->cmd_len); usb_stor_dbg(us, "bytes: "); for (i = 0; i < srb->cmd_len && i < 16; i++) US_DEBUGPX(" %02x", srb->cmnd[i]); US_DEBUGPX("\n"); } void usb_stor_show_sense(const struct us_data *us, unsigned char key, unsigned char asc, unsigned char ascq) { const char *what, *keystr, *fmt; keystr = scsi_sense_key_string(key); what = scsi_extd_sense_format(asc, ascq, &fmt); if (keystr == NULL) keystr = "(Unknown Key)"; if (what == NULL) what = "(unknown ASC/ASCQ)"; usb_stor_dbg(us, "%s: ", keystr); if (fmt) US_DEBUGPX("%s (%s%x)\n", what, fmt, ascq); else US_DEBUGPX("%s\n", what); } void usb_stor_dbg(const struct us_data *us, const char *fmt, ...) { va_list args; va_start(args, fmt); dev_vprintk_emit(LOGLEVEL_DEBUG, &us->pusb_dev->dev, fmt, args); va_end(args); } EXPORT_SYMBOL_GPL(usb_stor_dbg);
krzk/tizen-tv-rpi-linux
drivers/usb/storage/debug.c
C
gpl-2.0
7,657
/* SCTP kernel implementation * Copyright (c) 2003 International Business Machines, Corp. * * This file is part of the SCTP kernel implementation * * These functions manipulate sctp SSN tracker. * * This SCTP implementation 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 SCTP implementation 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 GNU CC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <linux-sctp@vger.kernel.org> * * Written or modified by: * Jon Grimm <jgrimm@us.ibm.com> */ #include <linux/types.h> #include <linux/slab.h> #include <net/sctp/sctp.h> #include <net/sctp/sm.h> static struct sctp_ssnmap *sctp_ssnmap_init(struct sctp_ssnmap *map, __u16 in, __u16 out); /* Storage size needed for map includes 2 headers and then the * specific needs of in or out streams. */ static inline size_t sctp_ssnmap_size(__u16 in, __u16 out) { return sizeof(struct sctp_ssnmap) + (in + out) * sizeof(__u16); } /* Create a new sctp_ssnmap. * Allocate room to store at least 'len' contiguous TSNs. */ struct sctp_ssnmap *sctp_ssnmap_new(__u16 in, __u16 out, gfp_t gfp) { struct sctp_ssnmap *retval; int size; size = sctp_ssnmap_size(in, out); if (size <= KMALLOC_MAX_SIZE) retval = kmalloc(size, gfp); else retval = (struct sctp_ssnmap *) __get_free_pages(gfp, get_order(size)); if (!retval) goto fail; if (!sctp_ssnmap_init(retval, in, out)) goto fail_map; SCTP_DBG_OBJCNT_INC(ssnmap); return retval; fail_map: if (size <= KMALLOC_MAX_SIZE) kfree(retval); else free_pages((unsigned long)retval, get_order(size)); fail: return NULL; } /* Initialize a block of memory as a ssnmap. */ static struct sctp_ssnmap *sctp_ssnmap_init(struct sctp_ssnmap *map, __u16 in, __u16 out) { memset(map, 0x00, sctp_ssnmap_size(in, out)); /* Start 'in' stream just after the map header. */ map->in.ssn = (__u16 *)&map[1]; map->in.len = in; /* Start 'out' stream just after 'in'. */ map->out.ssn = &map->in.ssn[in]; map->out.len = out; return map; } /* Clear out the ssnmap streams. */ void sctp_ssnmap_clear(struct sctp_ssnmap *map) { size_t size; size = (map->in.len + map->out.len) * sizeof(__u16); memset(map->in.ssn, 0x00, size); } /* Dispose of a ssnmap. */ void sctp_ssnmap_free(struct sctp_ssnmap *map) { int size; if (unlikely(!map)) return; size = sctp_ssnmap_size(map->in.len, map->out.len); if (size <= KMALLOC_MAX_SIZE) kfree(map); else free_pages((unsigned long)map, get_order(size)); SCTP_DBG_OBJCNT_DEC(ssnmap); }
omor1/linux-430
net/sctp/ssnmap.c
C
gpl-2.0
3,169
/* SCTP kernel implementation * Copyright (c) 2003 International Business Machines, Corp. * * This file is part of the SCTP kernel implementation * * These functions manipulate sctp SSN tracker. * * This SCTP implementation 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 SCTP implementation 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 GNU CC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <linux-sctp@vger.kernel.org> * * Written or modified by: * Jon Grimm <jgrimm@us.ibm.com> */ #include <linux/types.h> #include <linux/slab.h> #include <net/sctp/sctp.h> #include <net/sctp/sm.h> static struct sctp_ssnmap *sctp_ssnmap_init(struct sctp_ssnmap *map, __u16 in, __u16 out); /* Storage size needed for map includes 2 headers and then the * specific needs of in or out streams. */ static inline size_t sctp_ssnmap_size(__u16 in, __u16 out) { return sizeof(struct sctp_ssnmap) + (in + out) * sizeof(__u16); } /* Create a new sctp_ssnmap. * Allocate room to store at least 'len' contiguous TSNs. */ struct sctp_ssnmap *sctp_ssnmap_new(__u16 in, __u16 out, gfp_t gfp) { struct sctp_ssnmap *retval; int size; size = sctp_ssnmap_size(in, out); if (size <= KMALLOC_MAX_SIZE) retval = kmalloc(size, gfp); else retval = (struct sctp_ssnmap *) __get_free_pages(gfp, get_order(size)); if (!retval) goto fail; if (!sctp_ssnmap_init(retval, in, out)) goto fail_map; SCTP_DBG_OBJCNT_INC(ssnmap); return retval; fail_map: if (size <= KMALLOC_MAX_SIZE) kfree(retval); else free_pages((unsigned long)retval, get_order(size)); fail: return NULL; } /* Initialize a block of memory as a ssnmap. */ static struct sctp_ssnmap *sctp_ssnmap_init(struct sctp_ssnmap *map, __u16 in, __u16 out) { memset(map, 0x00, sctp_ssnmap_size(in, out)); /* Start 'in' stream just after the map header. */ map->in.ssn = (__u16 *)&map[1]; map->in.len = in; /* Start 'out' stream just after 'in'. */ map->out.ssn = &map->in.ssn[in]; map->out.len = out; return map; } /* Clear out the ssnmap streams. */ void sctp_ssnmap_clear(struct sctp_ssnmap *map) { size_t size; size = (map->in.len + map->out.len) * sizeof(__u16); memset(map->in.ssn, 0x00, size); } /* Dispose of a ssnmap. */ void sctp_ssnmap_free(struct sctp_ssnmap *map) { int size; if (unlikely(!map)) return; size = sctp_ssnmap_size(map->in.len, map->out.len); if (size <= KMALLOC_MAX_SIZE) kfree(map); else free_pages((unsigned long)map, get_order(size)); SCTP_DBG_OBJCNT_DEC(ssnmap); }
MojieBuddhist/linux-1
net/sctp/ssnmap.c
C
gpl-2.0
3,169
/* * Simple "CDC Subset" USB Networking Links * Copyright (C) 2000-2005 by David Brownell * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/module.h> #include <linux/kmod.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/workqueue.h> #include <linux/mii.h> #include <linux/usb.h> #include <linux/usb/usbnet.h> /* * This supports simple USB network links that don't require any special * framing or hardware control operations. The protocol used here is a * strict subset of CDC Ethernet, with three basic differences reflecting * the goal that almost any hardware should run it: * * - Minimal runtime control: one interface, no altsettings, and * no vendor or class specific control requests. If a device is * configured, it is allowed to exchange packets with the host. * Fancier models would mean not working on some hardware. * * - Minimal manufacturing control: no IEEE "Organizationally * Unique ID" required, or an EEPROMs to store one. Each host uses * one random "locally assigned" Ethernet address instead, which can * of course be overridden using standard tools like "ifconfig". * (With 2^46 such addresses, same-net collisions are quite rare.) * * - There is no additional framing data for USB. Packets are written * exactly as in CDC Ethernet, starting with an Ethernet header and * terminated by a short packet. However, the host will never send a * zero length packet; some systems can't handle those robustly. * * Anything that can transmit and receive USB bulk packets can implement * this protocol. That includes both smart peripherals and quite a lot * of "host-to-host" USB cables (which embed two devices back-to-back). * * Note that although Linux may use many of those host-to-host links * with this "cdc_subset" framing, that doesn't mean there may not be a * better approach. Handling the "other end unplugs/replugs" scenario * well tends to require chip-specific vendor requests. Also, Windows * peers at the other end of host-to-host cables may expect their own * framing to be used rather than this "cdc_subset" model. */ #if defined(CONFIG_USB_EPSON2888) || defined(CONFIG_USB_ARMLINUX) /* PDA style devices are always connected if present */ static int always_connected (struct usbnet *dev) { return 0; } #endif #ifdef CONFIG_USB_ALI_M5632 #define HAVE_HARDWARE /*------------------------------------------------------------------------- * * ALi M5632 driver ... does high speed * * NOTE that the MS-Windows drivers for this chip use some funky and * (naturally) undocumented 7-byte prefix to each packet, so this is a * case where we don't currently interoperate. Also, once you unplug * one end of the cable, you need to replug the other end too ... since * chip docs are unavailable, there's no way to reset the relevant state * short of a power cycle. * *-------------------------------------------------------------------------*/ static const struct driver_info ali_m5632_info = { .description = "ALi M5632", .flags = FLAG_POINTTOPOINT, }; #endif #ifdef CONFIG_USB_AN2720 #define HAVE_HARDWARE /*------------------------------------------------------------------------- * * AnchorChips 2720 driver ... http://www.cypress.com * * This doesn't seem to have a way to detect whether the peer is * connected, or need any reset handshaking. It's got pretty big * internal buffers (handles most of a frame's worth of data). * Chip data sheets don't describe any vendor control messages. * *-------------------------------------------------------------------------*/ static const struct driver_info an2720_info = { .description = "AnchorChips/Cypress 2720", .flags = FLAG_POINTTOPOINT, // no reset available! // no check_connect available! .in = 2, .out = 2, // direction distinguishes these }; #endif /* CONFIG_USB_AN2720 */ #ifdef CONFIG_USB_BELKIN #define HAVE_HARDWARE /*------------------------------------------------------------------------- * * Belkin F5U104 ... two NetChip 2280 devices + Atmel AVR microcontroller * * ... also two eTEK designs, including one sold as "Advance USBNET" * *-------------------------------------------------------------------------*/ static const struct driver_info belkin_info = { .description = "Belkin, eTEK, or compatible", .flags = FLAG_POINTTOPOINT, }; #endif /* CONFIG_USB_BELKIN */ #ifdef CONFIG_USB_EPSON2888 #define HAVE_HARDWARE /*------------------------------------------------------------------------- * * EPSON USB clients * * This is the same idea as Linux PDAs (below) except the firmware in the * device might not be Tux-powered. Epson provides reference firmware that * implements this interface. Product developers can reuse or modify that * code, such as by using their own product and vendor codes. * * Support was from Juro Bystricky <bystricky.juro@erd.epson.com> * *-------------------------------------------------------------------------*/ static const struct driver_info epson2888_info = { .description = "Epson USB Device", .check_connect = always_connected, .flags = FLAG_POINTTOPOINT, .in = 4, .out = 3, }; #endif /* CONFIG_USB_EPSON2888 */ /*------------------------------------------------------------------------- * * info from Jonathan McDowell <noodles@earth.li> * *-------------------------------------------------------------------------*/ #ifdef CONFIG_USB_KC2190 #define HAVE_HARDWARE static const struct driver_info kc2190_info = { .description = "KC Technology KC-190", .flags = FLAG_POINTTOPOINT, }; #endif /* CONFIG_USB_KC2190 */ #ifdef CONFIG_USB_ARMLINUX #define HAVE_HARDWARE /*------------------------------------------------------------------------- * * Intel's SA-1100 chip integrates basic USB support, and is used * in PDAs like some iPaqs, the Yopy, some Zaurus models, and more. * When they run Linux, arch/arm/mach-sa1100/usb-eth.c may be used to * network using minimal USB framing data. * * This describes the driver currently in standard ARM Linux kernels. * The Zaurus uses a different driver (see later). * * PXA25x and PXA210 use XScale cores (ARM v5TE) with better USB support * and different USB endpoint numbering than the SA1100 devices. The * mach-pxa/usb-eth.c driver re-uses the device ids from mach-sa1100 * so we rely on the endpoint descriptors. * *-------------------------------------------------------------------------*/ static const struct driver_info linuxdev_info = { .description = "Linux Device", .check_connect = always_connected, .flags = FLAG_POINTTOPOINT, }; static const struct driver_info yopy_info = { .description = "Yopy", .check_connect = always_connected, .flags = FLAG_POINTTOPOINT, }; static const struct driver_info blob_info = { .description = "Boot Loader OBject", .check_connect = always_connected, .flags = FLAG_POINTTOPOINT, }; #endif /* CONFIG_USB_ARMLINUX */ /*-------------------------------------------------------------------------*/ #ifndef HAVE_HARDWARE #warning You need to configure some hardware for this driver #endif /* * chip vendor names won't normally be on the cables, and * may not be on the device. */ static const struct usb_device_id products [] = { #ifdef CONFIG_USB_ALI_M5632 { USB_DEVICE (0x0402, 0x5632), // ALi defaults .driver_info = (unsigned long) &ali_m5632_info, }, { USB_DEVICE (0x182d,0x207c), // SiteCom CN-124 .driver_info = (unsigned long) &ali_m5632_info, }, #endif #ifdef CONFIG_USB_AN2720 { USB_DEVICE (0x0547, 0x2720), // AnchorChips defaults .driver_info = (unsigned long) &an2720_info, }, { USB_DEVICE (0x0547, 0x2727), // Xircom PGUNET .driver_info = (unsigned long) &an2720_info, }, #endif #ifdef CONFIG_USB_BELKIN { USB_DEVICE (0x050d, 0x0004), // Belkin .driver_info = (unsigned long) &belkin_info, }, { USB_DEVICE (0x056c, 0x8100), // eTEK .driver_info = (unsigned long) &belkin_info, }, { USB_DEVICE (0x0525, 0x9901), // Advance USBNET (eTEK) .driver_info = (unsigned long) &belkin_info, }, #endif #ifdef CONFIG_USB_EPSON2888 { USB_DEVICE (0x0525, 0x2888), // EPSON USB client .driver_info = (unsigned long) &epson2888_info, }, #endif #ifdef CONFIG_USB_KC2190 { USB_DEVICE (0x050f, 0x0190), // KC-190 .driver_info = (unsigned long) &kc2190_info, }, #endif #ifdef CONFIG_USB_ARMLINUX /* * SA-1100 using standard ARM Linux kernels, or compatible. * Often used when talking to Linux PDAs (iPaq, Yopy, etc). * The sa-1100 "usb-eth" driver handles the basic framing. * * PXA25x or PXA210 ... these use a "usb-eth" driver much like * the sa1100 one, but hardware uses different endpoint numbers. * * Or the Linux "Ethernet" gadget on hardware that can't talk * CDC Ethernet (e.g., no altsettings), in either of two modes: * - acting just like the old "usb-eth" firmware, though * the implementation is different * - supporting RNDIS as the first/default configuration for * MS-Windows interop; Linux needs to use the other config */ { // 1183 = 0x049F, both used as hex values? // Compaq "Itsy" vendor/product id USB_DEVICE (0x049F, 0x505A), // usb-eth, or compatible .driver_info = (unsigned long) &linuxdev_info, }, { USB_DEVICE (0x0E7E, 0x1001), // G.Mate "Yopy" .driver_info = (unsigned long) &yopy_info, }, { USB_DEVICE (0x8086, 0x07d3), // "blob" bootloader .driver_info = (unsigned long) &blob_info, }, { USB_DEVICE (0x1286, 0x8001), // "blob" bootloader .driver_info = (unsigned long) &blob_info, }, { // Linux Ethernet/RNDIS gadget, mostly on PXA, second config // e.g. Gumstix, current OpenZaurus, ... or anything else // that just enables this gadget option. USB_DEVICE (0x0525, 0xa4a2), .driver_info = (unsigned long) &linuxdev_info, }, #endif { }, // END }; MODULE_DEVICE_TABLE(usb, products); /*-------------------------------------------------------------------------*/ static struct usb_driver cdc_subset_driver = { .name = "cdc_subset", .probe = usbnet_probe, .suspend = usbnet_suspend, .resume = usbnet_resume, .disconnect = usbnet_disconnect, .id_table = products, .disable_hub_initiated_lpm = 1, }; module_usb_driver(cdc_subset_driver); MODULE_AUTHOR("David Brownell"); MODULE_DESCRIPTION("Simple 'CDC Subset' USB networking links"); MODULE_LICENSE("GPL");
mukulsoni/android_kernel_cyanogen_msm8916
drivers/net/usb/cdc_subset.c
C
gpl-2.0
11,062
<?php /** * Comment Management Screen * * @package WordPress * @subpackage Administration */ /** Load WordPress Bootstrap */ require_once( dirname( __FILE__ ) . '/admin.php' ); $parent_file = 'edit-comments.php'; $submenu_file = 'edit-comments.php'; wp_reset_vars( array('action') ); if ( isset( $_POST['deletecomment'] ) ) $action = 'deletecomment'; if ( 'cdc' == $action ) $action = 'delete'; elseif ( 'mac' == $action ) $action = 'approve'; if ( isset( $_GET['dt'] ) ) { if ( 'spam' == $_GET['dt'] ) $action = 'spam'; elseif ( 'trash' == $_GET['dt'] ) $action = 'trash'; } /** * Display error message at bottom of comments. * * @param string $msg Error Message. Assumed to contain HTML and be sanitized. */ function comment_footer_die( $msg ) { echo "<div class='wrap'><p>$msg</p></div>"; include( ABSPATH . 'wp-admin/admin-footer.php' ); die; } switch( $action ) { case 'editcomment' : $title = __('Edit Comment'); get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __( 'You can edit the information left in a comment if needed. This is often useful when you notice that a commenter has made a typographical error.' ) . '</p>' . '<p>' . __( 'You can also moderate the comment from this screen using the Status box, where you can also change the timestamp of the comment.' ) . '</p>' ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __( 'For more information:' ) . '</strong></p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Administration_Screens#Comments" target="_blank">Documentation on Comments</a>' ) . '</p>' . '<p>' . __( '<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>' ) . '</p>' ); wp_enqueue_script('comment'); require_once( ABSPATH . 'wp-admin/admin-header.php' ); $comment_id = absint( $_GET['c'] ); if ( !$comment = get_comment( $comment_id ) ) comment_footer_die( __('Oops, no comment with this ID.') . sprintf(' <a href="%s">' . __('Go back') . '</a>.', 'javascript:history.go(-1)') ); if ( !current_user_can( 'edit_comment', $comment_id ) ) comment_footer_die( __('You are not allowed to edit this comment.') ); if ( 'trash' == $comment->comment_approved ) comment_footer_die( __('This comment is in the Trash. Please move it out of the Trash if you want to edit it.') ); $comment = get_comment_to_edit( $comment_id ); include( ABSPATH . 'wp-admin/edit-form-comment.php' ); break; case 'delete' : case 'approve' : case 'trash' : case 'spam' : $title = __('Moderate Comment'); $comment_id = absint( $_GET['c'] ); if ( !$comment = get_comment_to_edit( $comment_id ) ) { wp_redirect( admin_url('edit-comments.php?error=1') ); die(); } if ( !current_user_can( 'edit_comment', $comment->comment_ID ) ) { wp_redirect( admin_url('edit-comments.php?error=2') ); die(); } // No need to re-approve/re-trash/re-spam a comment. if ( $action == str_replace( '1', 'approve', $comment->comment_approved ) ) { wp_redirect( admin_url( 'edit-comments.php?same=' . $comment_id ) ); die(); } require_once( ABSPATH . 'wp-admin/admin-header.php' ); $formaction = $action . 'comment'; $nonce_action = 'approve' == $action ? 'approve-comment_' : 'delete-comment_'; $nonce_action .= $comment_id; ?> <div class="wrap"> <div class="narrow"> <h2><?php echo esc_html( $title ); ?></h2> <?php switch ( $action ) { case 'spam' : $caution_msg = __('You are about to mark the following comment as spam:'); $button = __('Spam Comment'); break; case 'trash' : $caution_msg = __('You are about to move the following comment to the Trash:'); $button = __('Trash Comment'); break; case 'delete' : $caution_msg = __('You are about to delete the following comment:'); $button = __('Permanently Delete Comment'); break; default : $caution_msg = __('You are about to approve the following comment:'); $button = __('Approve Comment'); break; } if ( $comment->comment_approved != '0' ) { // if not unapproved $message = ''; switch ( $comment->comment_approved ) { case '1' : $message = __('This comment is currently approved.'); break; case 'spam' : $message = __('This comment is currently marked as spam.'); break; case 'trash' : $message = __('This comment is currently in the Trash.'); break; } if ( $message ) echo '<div class="updated"><p>' . $message . '</p></div>'; } ?> <p><strong><?php _e('Caution:'); ?></strong> <?php echo $caution_msg; ?></p> <table class="form-table comment-ays"> <tr class="alt"> <th scope="row"><?php _e('Author'); ?></th> <td><?php echo $comment->comment_author; ?></td> </tr> <?php if ( $comment->comment_author_email ) { ?> <tr> <th scope="row"><?php _e('E-mail'); ?></th> <td><?php echo $comment->comment_author_email; ?></td> </tr> <?php } ?> <?php if ( $comment->comment_author_url ) { ?> <tr> <th scope="row"><?php _e('URL'); ?></th> <td><a href="<?php echo $comment->comment_author_url; ?>"><?php echo $comment->comment_author_url; ?></a></td> </tr> <?php } ?> <tr> <th scope="row"><?php /* translators: field name in comment form */ _ex('Comment', 'noun'); ?></th> <td><?php echo $comment->comment_content; ?></td> </tr> </table> <p><?php _e('Are you sure you want to do this?'); ?></p> <form action="comment.php" method="get"> <table width="100%"> <tr> <td><a class="button" href="<?php echo admin_url('edit-comments.php'); ?>"><?php esc_attr_e('No'); ?></a></td> <td class="textright"><?php submit_button( $button, 'button' ); ?></td> </tr> </table> <?php wp_nonce_field( $nonce_action ); ?> <input type="hidden" name="action" value="<?php echo esc_attr($formaction); ?>" /> <input type="hidden" name="c" value="<?php echo esc_attr($comment->comment_ID); ?>" /> <input type="hidden" name="noredir" value="1" /> </form> </div> </div> <?php break; case 'deletecomment' : case 'trashcomment' : case 'untrashcomment' : case 'spamcomment' : case 'unspamcomment' : case 'approvecomment' : case 'unapprovecomment' : $comment_id = absint( $_REQUEST['c'] ); if ( in_array( $action, array( 'approvecomment', 'unapprovecomment' ) ) ) check_admin_referer( 'approve-comment_' . $comment_id ); else check_admin_referer( 'delete-comment_' . $comment_id ); $noredir = isset($_REQUEST['noredir']); if ( !$comment = get_comment($comment_id) ) comment_footer_die( __('Oops, no comment with this ID.') . sprintf(' <a href="%s">' . __('Go back') . '</a>.', 'edit-comments.php') ); if ( !current_user_can( 'edit_comment', $comment->comment_ID ) ) comment_footer_die( __('You are not allowed to edit comments on this post.') ); if ( '' != wp_get_referer() && ! $noredir && false === strpos(wp_get_referer(), 'comment.php') ) $redir = wp_get_referer(); elseif ( '' != wp_get_original_referer() && ! $noredir ) $redir = wp_get_original_referer(); elseif ( in_array( $action, array( 'approvecomment', 'unapprovecomment' ) ) ) $redir = admin_url('edit-comments.php?p=' . absint( $comment->comment_post_ID ) ); else $redir = admin_url('edit-comments.php'); $redir = remove_query_arg( array('spammed', 'unspammed', 'trashed', 'untrashed', 'deleted', 'ids', 'approved', 'unapproved'), $redir ); switch ( $action ) { case 'deletecomment' : wp_delete_comment( $comment_id ); $redir = add_query_arg( array('deleted' => '1'), $redir ); break; case 'trashcomment' : wp_trash_comment($comment_id); $redir = add_query_arg( array('trashed' => '1', 'ids' => $comment_id), $redir ); break; case 'untrashcomment' : wp_untrash_comment($comment_id); $redir = add_query_arg( array('untrashed' => '1'), $redir ); break; case 'spamcomment' : wp_spam_comment($comment_id); $redir = add_query_arg( array('spammed' => '1', 'ids' => $comment_id), $redir ); break; case 'unspamcomment' : wp_unspam_comment($comment_id); $redir = add_query_arg( array('unspammed' => '1'), $redir ); break; case 'approvecomment' : wp_set_comment_status( $comment_id, 'approve' ); $redir = add_query_arg( array( 'approved' => 1 ), $redir ); break; case 'unapprovecomment' : wp_set_comment_status( $comment_id, 'hold' ); $redir = add_query_arg( array( 'unapproved' => 1 ), $redir ); break; } wp_redirect( $redir ); die; case 'editedcomment' : $comment_id = absint( $_POST['comment_ID'] ); $comment_post_id = absint( $_POST['comment_post_ID'] ); check_admin_referer( 'update-comment_' . $comment_id ); edit_comment(); $location = ( empty( $_POST['referredby'] ) ? "edit-comments.php?p=$comment_post_id" : $_POST['referredby'] ) . '#comment-' . $comment_id; /** * Filter the URI the user is redirected to after editing a comment in the admin. * * @since 2.1.0 * * @param string $location The URI the user will be redirected to. * @param int $comment_id The ID of the comment being edited. */ $location = apply_filters( 'comment_edit_redirect', $location, $comment_id ); wp_redirect( $location ); exit(); default: wp_die( __('Unknown action.') ); } // end switch include( ABSPATH . 'wp-admin/admin-footer.php' );
jaamejam/SuperDome
wp-admin/comment.php
PHP
gpl-2.0
9,154
/* * Ram backed block device driver. * * Copyright (C) 2007 Nick Piggin * Copyright (C) 2007 Novell Inc. * * Parts derived from drivers/block/rd.c, and drivers/block/loop.c, copyright * of their respective owners. */ #include <linux/init.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/major.h> #include <linux/blkdev.h> #include <linux/bio.h> #include <linux/highmem.h> #include <linux/mutex.h> #include <linux/radix-tree.h> #include <linux/fs.h> #include <linux/slab.h> #include <asm/uaccess.h> #define SECTOR_SHIFT 9 #define PAGE_SECTORS_SHIFT (PAGE_SHIFT - SECTOR_SHIFT) #define PAGE_SECTORS (1 << PAGE_SECTORS_SHIFT) /* * Each block ramdisk device has a radix_tree brd_pages of pages that stores * the pages containing the block device's contents. A brd page's ->index is * its offset in PAGE_SIZE units. This is similar to, but in no way connected * with, the kernel's pagecache or buffer cache (which sit above our block * device). */ struct brd_device { int brd_number; struct request_queue *brd_queue; struct gendisk *brd_disk; struct list_head brd_list; /* * Backing store of pages and lock to protect it. This is the contents * of the block device. */ spinlock_t brd_lock; struct radix_tree_root brd_pages; }; /* * Look up and return a brd's page for a given sector. */ static DEFINE_MUTEX(brd_mutex); static struct page *brd_lookup_page(struct brd_device *brd, sector_t sector) { pgoff_t idx; struct page *page; /* * The page lifetime is protected by the fact that we have opened the * device node -- brd pages will never be deleted under us, so we * don't need any further locking or refcounting. * * This is strictly true for the radix-tree nodes as well (ie. we * don't actually need the rcu_read_lock()), however that is not a * documented feature of the radix-tree API so it is better to be * safe here (we don't have total exclusion from radix tree updates * here, only deletes). */ rcu_read_lock(); idx = sector >> PAGE_SECTORS_SHIFT; /* sector to page index */ page = radix_tree_lookup(&brd->brd_pages, idx); rcu_read_unlock(); BUG_ON(page && page->index != idx); return page; } /* * Look up and return a brd's page for a given sector. * If one does not exist, allocate an empty page, and insert that. Then * return it. */ static struct page *brd_insert_page(struct brd_device *brd, sector_t sector) { pgoff_t idx; struct page *page; gfp_t gfp_flags; page = brd_lookup_page(brd, sector); if (page) return page; /* * Must use NOIO because we don't want to recurse back into the * block or filesystem layers from page reclaim. * * Cannot support XIP and highmem, because our ->direct_access * routine for XIP must return memory that is always addressable. * If XIP was reworked to use pfns and kmap throughout, this * restriction might be able to be lifted. */ gfp_flags = GFP_NOIO | __GFP_ZERO; #ifndef CONFIG_BLK_DEV_XIP gfp_flags |= __GFP_HIGHMEM; #endif page = alloc_page(gfp_flags); if (!page) return NULL; if (radix_tree_preload(GFP_NOIO)) { __free_page(page); return NULL; } spin_lock(&brd->brd_lock); idx = sector >> PAGE_SECTORS_SHIFT; if (radix_tree_insert(&brd->brd_pages, idx, page)) { __free_page(page); page = radix_tree_lookup(&brd->brd_pages, idx); BUG_ON(!page); BUG_ON(page->index != idx); } else page->index = idx; spin_unlock(&brd->brd_lock); radix_tree_preload_end(); return page; } static void brd_free_page(struct brd_device *brd, sector_t sector) { struct page *page; pgoff_t idx; spin_lock(&brd->brd_lock); idx = sector >> PAGE_SECTORS_SHIFT; page = radix_tree_delete(&brd->brd_pages, idx); spin_unlock(&brd->brd_lock); if (page) __free_page(page); } static void brd_zero_page(struct brd_device *brd, sector_t sector) { struct page *page; page = brd_lookup_page(brd, sector); if (page) clear_highpage(page); } /* * Free all backing store pages and radix tree. This must only be called when * there are no other users of the device. */ #define FREE_BATCH 16 static void brd_free_pages(struct brd_device *brd) { unsigned long pos = 0; struct page *pages[FREE_BATCH]; int nr_pages; do { int i; nr_pages = radix_tree_gang_lookup(&brd->brd_pages, (void **)pages, pos, FREE_BATCH); for (i = 0; i < nr_pages; i++) { void *ret; BUG_ON(pages[i]->index < pos); pos = pages[i]->index; ret = radix_tree_delete(&brd->brd_pages, pos); BUG_ON(!ret || ret != pages[i]); __free_page(pages[i]); } pos++; /* * This assumes radix_tree_gang_lookup always returns as * many pages as possible. If the radix-tree code changes, * so will this have to. */ } while (nr_pages == FREE_BATCH); } /* * copy_to_brd_setup must be called before copy_to_brd. It may sleep. */ static int copy_to_brd_setup(struct brd_device *brd, sector_t sector, size_t n) { unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT; size_t copy; copy = min_t(size_t, n, PAGE_SIZE - offset); if (!brd_insert_page(brd, sector)) return -ENOMEM; if (copy < n) { sector += copy >> SECTOR_SHIFT; if (!brd_insert_page(brd, sector)) return -ENOMEM; } return 0; } static void discard_from_brd(struct brd_device *brd, sector_t sector, size_t n) { while (n >= PAGE_SIZE) { /* * Don't want to actually discard pages here because * re-allocating the pages can result in writeback * deadlocks under heavy load. */ if (0) brd_free_page(brd, sector); else brd_zero_page(brd, sector); sector += PAGE_SIZE >> SECTOR_SHIFT; n -= PAGE_SIZE; } } /* * Copy n bytes from src to the brd starting at sector. Does not sleep. */ static void copy_to_brd(struct brd_device *brd, const void *src, sector_t sector, size_t n) { struct page *page; void *dst; unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT; size_t copy; copy = min_t(size_t, n, PAGE_SIZE - offset); page = brd_lookup_page(brd, sector); BUG_ON(!page); dst = kmap_atomic(page); memcpy(dst + offset, src, copy); kunmap_atomic(dst); if (copy < n) { src += copy; sector += copy >> SECTOR_SHIFT; copy = n - copy; page = brd_lookup_page(brd, sector); BUG_ON(!page); dst = kmap_atomic(page); memcpy(dst, src, copy); kunmap_atomic(dst); } } /* * Copy n bytes to dst from the brd starting at sector. Does not sleep. */ static void copy_from_brd(void *dst, struct brd_device *brd, sector_t sector, size_t n) { struct page *page; void *src; unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT; size_t copy; copy = min_t(size_t, n, PAGE_SIZE - offset); page = brd_lookup_page(brd, sector); if (page) { src = kmap_atomic(page); memcpy(dst, src + offset, copy); kunmap_atomic(src); } else memset(dst, 0, copy); if (copy < n) { dst += copy; sector += copy >> SECTOR_SHIFT; copy = n - copy; page = brd_lookup_page(brd, sector); if (page) { src = kmap_atomic(page); memcpy(dst, src, copy); kunmap_atomic(src); } else memset(dst, 0, copy); } } /* * Process a single bvec of a bio. */ static int brd_do_bvec(struct brd_device *brd, struct page *page, unsigned int len, unsigned int off, int rw, sector_t sector) { void *mem; int err = 0; if (rw != READ) { err = copy_to_brd_setup(brd, sector, len); if (err) goto out; } mem = kmap_atomic(page); if (rw == READ) { copy_from_brd(mem + off, brd, sector, len); flush_dcache_page(page); } else { flush_dcache_page(page); copy_to_brd(brd, mem + off, sector, len); } kunmap_atomic(mem); out: return err; } static void brd_make_request(struct request_queue *q, struct bio *bio) { struct block_device *bdev = bio->bi_bdev; struct brd_device *brd = bdev->bd_disk->private_data; int rw; struct bio_vec *bvec; sector_t sector; int i; int err = -EIO; sector = bio->bi_sector; if (sector + (bio->bi_size >> SECTOR_SHIFT) > get_capacity(bdev->bd_disk)) goto out; if (unlikely(bio->bi_rw & REQ_DISCARD)) { err = 0; discard_from_brd(brd, sector, bio->bi_size); goto out; } rw = bio_rw(bio); if (rw == READA) rw = READ; bio_for_each_segment(bvec, bio, i) { unsigned int len = bvec->bv_len; err = brd_do_bvec(brd, bvec->bv_page, len, bvec->bv_offset, rw, sector); if (err) break; sector += len >> SECTOR_SHIFT; } out: bio_endio(bio, err); } #ifdef CONFIG_BLK_DEV_XIP static int brd_direct_access(struct block_device *bdev, sector_t sector, void **kaddr, unsigned long *pfn) { struct brd_device *brd = bdev->bd_disk->private_data; struct page *page; if (!brd) return -ENODEV; if (sector & (PAGE_SECTORS-1)) return -EINVAL; if (sector + PAGE_SECTORS > get_capacity(bdev->bd_disk)) return -ERANGE; page = brd_insert_page(brd, sector); if (!page) return -ENOMEM; *kaddr = page_address(page); *pfn = page_to_pfn(page); return 0; } #endif static int brd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { int error; struct brd_device *brd = bdev->bd_disk->private_data; if (cmd != BLKFLSBUF) return -ENOTTY; /* * ram device BLKFLSBUF has special semantics, we want to actually * release and destroy the ramdisk data. */ mutex_lock(&brd_mutex); mutex_lock(&bdev->bd_mutex); error = -EBUSY; if (bdev->bd_openers <= 1) { /* * Kill the cache first, so it isn't written back to the * device. * * Another thread might instantiate more buffercache here, * but there is not much we can do to close that race. */ kill_bdev(bdev); brd_free_pages(brd); error = 0; } mutex_unlock(&bdev->bd_mutex); mutex_unlock(&brd_mutex); return error; } static const struct block_device_operations brd_fops = { .owner = THIS_MODULE, .ioctl = brd_ioctl, #ifdef CONFIG_BLK_DEV_XIP .direct_access = brd_direct_access, #endif }; /* * And now the modules code and kernel interface. */ static int rd_nr; int rd_size = CONFIG_BLK_DEV_RAM_SIZE; static int max_part; static int part_shift; module_param(rd_nr, int, S_IRUGO); MODULE_PARM_DESC(rd_nr, "Maximum number of brd devices"); module_param(rd_size, int, S_IRUGO); MODULE_PARM_DESC(rd_size, "Size of each RAM disk in kbytes."); module_param(max_part, int, S_IRUGO); MODULE_PARM_DESC(max_part, "Maximum number of partitions per RAM disk"); MODULE_LICENSE("GPL"); MODULE_ALIAS_BLOCKDEV_MAJOR(RAMDISK_MAJOR); MODULE_ALIAS("rd"); #ifndef MODULE /* Legacy boot options - nonmodular */ static int __init ramdisk_size(char *str) { rd_size = simple_strtol(str, NULL, 0); return 1; } __setup("ramdisk_size=", ramdisk_size); #endif /* * The device scheme is derived from loop.c. Keep them in synch where possible * (should share code eventually). */ static LIST_HEAD(brd_devices); static DEFINE_MUTEX(brd_devices_mutex); static struct brd_device *brd_alloc(int i) { struct brd_device *brd; struct gendisk *disk; brd = kzalloc(sizeof(*brd), GFP_KERNEL); if (!brd) goto out; brd->brd_number = i; spin_lock_init(&brd->brd_lock); INIT_RADIX_TREE(&brd->brd_pages, GFP_ATOMIC); brd->brd_queue = blk_alloc_queue(GFP_KERNEL); if (!brd->brd_queue) goto out_free_dev; blk_queue_make_request(brd->brd_queue, brd_make_request); blk_queue_max_hw_sectors(brd->brd_queue, 1024); blk_queue_bounce_limit(brd->brd_queue, BLK_BOUNCE_ANY); brd->brd_queue->limits.discard_granularity = PAGE_SIZE; brd->brd_queue->limits.max_discard_sectors = UINT_MAX; brd->brd_queue->limits.discard_zeroes_data = 1; queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, brd->brd_queue); disk = brd->brd_disk = alloc_disk(1 << part_shift); if (!disk) goto out_free_queue; disk->major = RAMDISK_MAJOR; disk->first_minor = i << part_shift; disk->fops = &brd_fops; disk->private_data = brd; disk->queue = brd->brd_queue; disk->flags |= GENHD_FL_SUPPRESS_PARTITION_INFO; sprintf(disk->disk_name, "ram%d", i); set_capacity(disk, rd_size * 2); return brd; out_free_queue: blk_cleanup_queue(brd->brd_queue); out_free_dev: kfree(brd); out: return NULL; } static void brd_free(struct brd_device *brd) { put_disk(brd->brd_disk); blk_cleanup_queue(brd->brd_queue); brd_free_pages(brd); kfree(brd); } static struct brd_device *brd_init_one(int i) { struct brd_device *brd; list_for_each_entry(brd, &brd_devices, brd_list) { if (brd->brd_number == i) goto out; } brd = brd_alloc(i); if (brd) { add_disk(brd->brd_disk); list_add_tail(&brd->brd_list, &brd_devices); } out: return brd; } static void brd_del_one(struct brd_device *brd) { list_del(&brd->brd_list); del_gendisk(brd->brd_disk); brd_free(brd); } static struct kobject *brd_probe(dev_t dev, int *part, void *data) { struct brd_device *brd; struct kobject *kobj; mutex_lock(&brd_devices_mutex); brd = brd_init_one(MINOR(dev) >> part_shift); kobj = brd ? get_disk(brd->brd_disk) : ERR_PTR(-ENOMEM); mutex_unlock(&brd_devices_mutex); *part = 0; return kobj; } static int __init brd_init(void) { int i, nr; unsigned long range; struct brd_device *brd, *next; /* * brd module now has a feature to instantiate underlying device * structure on-demand, provided that there is an access dev node. * However, this will not work well with user space tool that doesn't * know about such "feature". In order to not break any existing * tool, we do the following: * * (1) if rd_nr is specified, create that many upfront, and this * also becomes a hard limit. * (2) if rd_nr is not specified, create CONFIG_BLK_DEV_RAM_COUNT * (default 16) rd device on module load, user can further * extend brd device by create dev node themselves and have * kernel automatically instantiate actual device on-demand. */ part_shift = 0; if (max_part > 0) { part_shift = fls(max_part); /* * Adjust max_part according to part_shift as it is exported * to user space so that user can decide correct minor number * if [s]he want to create more devices. * * Note that -1 is required because partition 0 is reserved * for the whole disk. */ max_part = (1UL << part_shift) - 1; } if ((1UL << part_shift) > DISK_MAX_PARTS) return -EINVAL; if (rd_nr > 1UL << (MINORBITS - part_shift)) return -EINVAL; if (rd_nr) { nr = rd_nr; range = rd_nr << part_shift; } else { nr = CONFIG_BLK_DEV_RAM_COUNT; range = 1UL << MINORBITS; } if (register_blkdev(RAMDISK_MAJOR, "ramdisk")) return -EIO; for (i = 0; i < nr; i++) { brd = brd_alloc(i); if (!brd) goto out_free; list_add_tail(&brd->brd_list, &brd_devices); } /* point of no return */ list_for_each_entry(brd, &brd_devices, brd_list) add_disk(brd->brd_disk); blk_register_region(MKDEV(RAMDISK_MAJOR, 0), range, THIS_MODULE, brd_probe, NULL, NULL); printk(KERN_INFO "brd: module loaded\n"); return 0; out_free: list_for_each_entry_safe(brd, next, &brd_devices, brd_list) { list_del(&brd->brd_list); brd_free(brd); } unregister_blkdev(RAMDISK_MAJOR, "ramdisk"); return -ENOMEM; } static void __exit brd_exit(void) { unsigned long range; struct brd_device *brd, *next; range = rd_nr ? rd_nr << part_shift : 1UL << MINORBITS; list_for_each_entry_safe(brd, next, &brd_devices, brd_list) brd_del_one(brd); blk_unregister_region(MKDEV(RAMDISK_MAJOR, 0), range); unregister_blkdev(RAMDISK_MAJOR, "ramdisk"); } module_init(brd_init); module_exit(brd_exit);
sub77/kernel_msm
drivers/block/brd.c
C
gpl-2.0
15,378
/* * drivers/net/netx-eth.c * * Copyright (c) 2005 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix * * 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 */ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/platform_device.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/mii.h> #include <asm/io.h> #include <mach/hardware.h> #include <mach/netx-regs.h> #include <mach/pfifo.h> #include <mach/xc.h> #include <mach/eth.h> /* XC Fifo Offsets */ #define EMPTY_PTR_FIFO(xcno) (0 + ((xcno) << 3)) /* Index of the empty pointer FIFO */ #define IND_FIFO_PORT_HI(xcno) (1 + ((xcno) << 3)) /* Index of the FIFO where received */ /* Data packages are indicated by XC */ #define IND_FIFO_PORT_LO(xcno) (2 + ((xcno) << 3)) /* Index of the FIFO where received */ /* Data packages are indicated by XC */ #define REQ_FIFO_PORT_HI(xcno) (3 + ((xcno) << 3)) /* Index of the FIFO where Data packages */ /* have to be indicated by ARM which */ /* shall be sent */ #define REQ_FIFO_PORT_LO(xcno) (4 + ((xcno) << 3)) /* Index of the FIFO where Data packages */ /* have to be indicated by ARM which shall */ /* be sent */ #define CON_FIFO_PORT_HI(xcno) (5 + ((xcno) << 3)) /* Index of the FIFO where sent Data packages */ /* are confirmed */ #define CON_FIFO_PORT_LO(xcno) (6 + ((xcno) << 3)) /* Index of the FIFO where sent Data */ /* packages are confirmed */ #define PFIFO_MASK(xcno) (0x7f << (xcno*8)) #define FIFO_PTR_FRAMELEN_SHIFT 0 #define FIFO_PTR_FRAMELEN_MASK (0x7ff << 0) #define FIFO_PTR_FRAMELEN(len) (((len) << 0) & FIFO_PTR_FRAMELEN_MASK) #define FIFO_PTR_TIMETRIG (1<<11) #define FIFO_PTR_MULTI_REQ #define FIFO_PTR_ORIGIN (1<<14) #define FIFO_PTR_VLAN (1<<15) #define FIFO_PTR_FRAMENO_SHIFT 16 #define FIFO_PTR_FRAMENO_MASK (0x3f << 16) #define FIFO_PTR_FRAMENO(no) (((no) << 16) & FIFO_PTR_FRAMENO_MASK) #define FIFO_PTR_SEGMENT_SHIFT 22 #define FIFO_PTR_SEGMENT_MASK (0xf << 22) #define FIFO_PTR_SEGMENT(seg) (((seg) & 0xf) << 22) #define FIFO_PTR_ERROR_SHIFT 28 #define FIFO_PTR_ERROR_MASK (0xf << 28) #define ISR_LINK_STATUS_CHANGE (1<<4) #define ISR_IND_LO (1<<3) #define ISR_CON_LO (1<<2) #define ISR_IND_HI (1<<1) #define ISR_CON_HI (1<<0) #define ETH_MAC_LOCAL_CONFIG 0x1560 #define ETH_MAC_4321 0x1564 #define ETH_MAC_65 0x1568 #define MAC_TRAFFIC_CLASS_ARRANGEMENT_SHIFT 16 #define MAC_TRAFFIC_CLASS_ARRANGEMENT_MASK (0xf<<MAC_TRAFFIC_CLASS_ARRANGEMENT_SHIFT) #define MAC_TRAFFIC_CLASS_ARRANGEMENT(x) (((x)<<MAC_TRAFFIC_CLASS_ARRANGEMENT_SHIFT) & MAC_TRAFFIC_CLASS_ARRANGEMENT_MASK) #define LOCAL_CONFIG_LINK_STATUS_IRQ_EN (1<<24) #define LOCAL_CONFIG_CON_LO_IRQ_EN (1<<23) #define LOCAL_CONFIG_CON_HI_IRQ_EN (1<<22) #define LOCAL_CONFIG_IND_LO_IRQ_EN (1<<21) #define LOCAL_CONFIG_IND_HI_IRQ_EN (1<<20) #define CARDNAME "netx-eth" /* LSB must be zero */ #define INTERNAL_PHY_ADR 0x1c struct netx_eth_priv { void __iomem *sram_base, *xpec_base, *xmac_base; int id; struct mii_if_info mii; u32 msg_enable; struct xc *xc; spinlock_t lock; }; static void netx_eth_set_multicast_list(struct net_device *ndev) { /* implement me */ } static int netx_eth_hard_start_xmit(struct sk_buff *skb, struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); unsigned char *buf = skb->data; unsigned int len = skb->len; spin_lock_irq(&priv->lock); memcpy_toio(priv->sram_base + 1560, (void *)buf, len); if (len < 60) { memset_io(priv->sram_base + 1560 + len, 0, 60 - len); len = 60; } pfifo_push(REQ_FIFO_PORT_LO(priv->id), FIFO_PTR_SEGMENT(priv->id) | FIFO_PTR_FRAMENO(1) | FIFO_PTR_FRAMELEN(len)); ndev->stats.tx_packets++; ndev->stats.tx_bytes += skb->len; netif_stop_queue(ndev); spin_unlock_irq(&priv->lock); dev_kfree_skb(skb); return NETDEV_TX_OK; } static void netx_eth_receive(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); unsigned int val, frameno, seg, len; unsigned char *data; struct sk_buff *skb; val = pfifo_pop(IND_FIFO_PORT_LO(priv->id)); frameno = (val & FIFO_PTR_FRAMENO_MASK) >> FIFO_PTR_FRAMENO_SHIFT; seg = (val & FIFO_PTR_SEGMENT_MASK) >> FIFO_PTR_SEGMENT_SHIFT; len = (val & FIFO_PTR_FRAMELEN_MASK) >> FIFO_PTR_FRAMELEN_SHIFT; skb = dev_alloc_skb(len); if (unlikely(skb == NULL)) { printk(KERN_NOTICE "%s: Low memory, packet dropped.\n", ndev->name); ndev->stats.rx_dropped++; return; } data = skb_put(skb, len); memcpy_fromio(data, priv->sram_base + frameno * 1560, len); pfifo_push(EMPTY_PTR_FIFO(priv->id), FIFO_PTR_SEGMENT(seg) | FIFO_PTR_FRAMENO(frameno)); skb->protocol = eth_type_trans(skb, ndev); netif_rx(skb); ndev->stats.rx_packets++; ndev->stats.rx_bytes += len; } static irqreturn_t netx_eth_interrupt(int irq, void *dev_id) { struct net_device *ndev = dev_id; struct netx_eth_priv *priv = netdev_priv(ndev); int status; unsigned long flags; spin_lock_irqsave(&priv->lock, flags); status = readl(NETX_PFIFO_XPEC_ISR(priv->id)); while (status) { int fill_level; writel(status, NETX_PFIFO_XPEC_ISR(priv->id)); if ((status & ISR_CON_HI) || (status & ISR_IND_HI)) printk("%s: unexpected status: 0x%08x\n", __func__, status); fill_level = readl(NETX_PFIFO_FILL_LEVEL(IND_FIFO_PORT_LO(priv->id))); while (fill_level--) netx_eth_receive(ndev); if (status & ISR_CON_LO) netif_wake_queue(ndev); if (status & ISR_LINK_STATUS_CHANGE) mii_check_media(&priv->mii, netif_msg_link(priv), 1); status = readl(NETX_PFIFO_XPEC_ISR(priv->id)); } spin_unlock_irqrestore(&priv->lock, flags); return IRQ_HANDLED; } static int netx_eth_open(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); if (request_irq (ndev->irq, netx_eth_interrupt, IRQF_SHARED, ndev->name, ndev)) return -EAGAIN; writel(ndev->dev_addr[0] | ndev->dev_addr[1]<<8 | ndev->dev_addr[2]<<16 | ndev->dev_addr[3]<<24, priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_4321); writel(ndev->dev_addr[4] | ndev->dev_addr[5]<<8, priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_65); writel(LOCAL_CONFIG_LINK_STATUS_IRQ_EN | LOCAL_CONFIG_CON_LO_IRQ_EN | LOCAL_CONFIG_CON_HI_IRQ_EN | LOCAL_CONFIG_IND_LO_IRQ_EN | LOCAL_CONFIG_IND_HI_IRQ_EN, priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_LOCAL_CONFIG); mii_check_media(&priv->mii, netif_msg_link(priv), 1); netif_start_queue(ndev); return 0; } static int netx_eth_close(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); netif_stop_queue(ndev); writel(0, priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_LOCAL_CONFIG); free_irq(ndev->irq, ndev); return 0; } static void netx_eth_timeout(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); int i; printk(KERN_ERR "%s: transmit timed out, resetting\n", ndev->name); spin_lock_irq(&priv->lock); xc_reset(priv->xc); xc_start(priv->xc); for (i=2; i<=18; i++) pfifo_push(EMPTY_PTR_FIFO(priv->id), FIFO_PTR_FRAMENO(i) | FIFO_PTR_SEGMENT(priv->id)); spin_unlock_irq(&priv->lock); netif_wake_queue(ndev); } static int netx_eth_phy_read(struct net_device *ndev, int phy_id, int reg) { unsigned int val; val = MIIMU_SNRDY | MIIMU_PREAMBLE | MIIMU_PHYADDR(phy_id) | MIIMU_REGADDR(reg) | MIIMU_PHY_NRES; writel(val, NETX_MIIMU); while (readl(NETX_MIIMU) & MIIMU_SNRDY); return readl(NETX_MIIMU) >> 16; } static void netx_eth_phy_write(struct net_device *ndev, int phy_id, int reg, int value) { unsigned int val; val = MIIMU_SNRDY | MIIMU_PREAMBLE | MIIMU_PHYADDR(phy_id) | MIIMU_REGADDR(reg) | MIIMU_PHY_NRES | MIIMU_OPMODE_WRITE | MIIMU_DATA(value); writel(val, NETX_MIIMU); while (readl(NETX_MIIMU) & MIIMU_SNRDY); } static const struct net_device_ops netx_eth_netdev_ops = { .ndo_open = netx_eth_open, .ndo_stop = netx_eth_close, .ndo_start_xmit = netx_eth_hard_start_xmit, .ndo_tx_timeout = netx_eth_timeout, .ndo_set_multicast_list = netx_eth_set_multicast_list, .ndo_change_mtu = eth_change_mtu, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = eth_mac_addr, }; static int netx_eth_enable(struct net_device *ndev) { struct netx_eth_priv *priv = netdev_priv(ndev); unsigned int mac4321, mac65; int running, i; ether_setup(ndev); ndev->netdev_ops = &netx_eth_netdev_ops; ndev->watchdog_timeo = msecs_to_jiffies(5000); priv->msg_enable = NETIF_MSG_LINK; priv->mii.phy_id_mask = 0x1f; priv->mii.reg_num_mask = 0x1f; priv->mii.force_media = 0; priv->mii.full_duplex = 0; priv->mii.dev = ndev; priv->mii.mdio_read = netx_eth_phy_read; priv->mii.mdio_write = netx_eth_phy_write; priv->mii.phy_id = INTERNAL_PHY_ADR + priv->id; running = xc_running(priv->xc); xc_stop(priv->xc); /* if the xc engine is already running, assume the bootloader has * loaded the firmware for us */ if (running) { /* get Node Address from hardware */ mac4321 = readl(priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_4321); mac65 = readl(priv->xpec_base + NETX_XPEC_RAM_START_OFS + ETH_MAC_65); ndev->dev_addr[0] = mac4321 & 0xff; ndev->dev_addr[1] = (mac4321 >> 8) & 0xff; ndev->dev_addr[2] = (mac4321 >> 16) & 0xff; ndev->dev_addr[3] = (mac4321 >> 24) & 0xff; ndev->dev_addr[4] = mac65 & 0xff; ndev->dev_addr[5] = (mac65 >> 8) & 0xff; } else { if (xc_request_firmware(priv->xc)) { printk(CARDNAME ": requesting firmware failed\n"); return -ENODEV; } } xc_reset(priv->xc); xc_start(priv->xc); if (!is_valid_ether_addr(ndev->dev_addr)) printk("%s: Invalid ethernet MAC address. Please " "set using ifconfig\n", ndev->name); for (i=2; i<=18; i++) pfifo_push(EMPTY_PTR_FIFO(priv->id), FIFO_PTR_FRAMENO(i) | FIFO_PTR_SEGMENT(priv->id)); return register_netdev(ndev); } static int netx_eth_drv_probe(struct platform_device *pdev) { struct netx_eth_priv *priv; struct net_device *ndev; struct netxeth_platform_data *pdata; int ret; ndev = alloc_etherdev(sizeof (struct netx_eth_priv)); if (!ndev) { printk("%s: could not allocate device.\n", CARDNAME); ret = -ENOMEM; goto exit; } SET_NETDEV_DEV(ndev, &pdev->dev); platform_set_drvdata(pdev, ndev); priv = netdev_priv(ndev); pdata = (struct netxeth_platform_data *)pdev->dev.platform_data; priv->xc = request_xc(pdata->xcno, &pdev->dev); if (!priv->xc) { dev_err(&pdev->dev, "unable to request xc engine\n"); ret = -ENODEV; goto exit_free_netdev; } ndev->irq = priv->xc->irq; priv->id = pdev->id; priv->xpec_base = priv->xc->xpec_base; priv->xmac_base = priv->xc->xmac_base; priv->sram_base = priv->xc->sram_base; spin_lock_init(&priv->lock); ret = pfifo_request(PFIFO_MASK(priv->id)); if (ret) { printk("unable to request PFIFO\n"); goto exit_free_xc; } ret = netx_eth_enable(ndev); if (ret) goto exit_free_pfifo; return 0; exit_free_pfifo: pfifo_free(PFIFO_MASK(priv->id)); exit_free_xc: free_xc(priv->xc); exit_free_netdev: platform_set_drvdata(pdev, NULL); free_netdev(ndev); exit: return ret; } static int netx_eth_drv_remove(struct platform_device *pdev) { struct net_device *ndev = dev_get_drvdata(&pdev->dev); struct netx_eth_priv *priv = netdev_priv(ndev); platform_set_drvdata(pdev, NULL); unregister_netdev(ndev); xc_stop(priv->xc); free_xc(priv->xc); free_netdev(ndev); pfifo_free(PFIFO_MASK(priv->id)); return 0; } static int netx_eth_drv_suspend(struct platform_device *pdev, pm_message_t state) { dev_err(&pdev->dev, "suspend not implemented\n"); return 0; } static int netx_eth_drv_resume(struct platform_device *pdev) { dev_err(&pdev->dev, "resume not implemented\n"); return 0; } static struct platform_driver netx_eth_driver = { .probe = netx_eth_drv_probe, .remove = netx_eth_drv_remove, .suspend = netx_eth_drv_suspend, .resume = netx_eth_drv_resume, .driver = { .name = CARDNAME, .owner = THIS_MODULE, }, }; static int __init netx_eth_init(void) { unsigned int phy_control, val; printk("NetX Ethernet driver\n"); phy_control = PHY_CONTROL_PHY_ADDRESS(INTERNAL_PHY_ADR>>1) | PHY_CONTROL_PHY1_MODE(PHY_MODE_ALL) | PHY_CONTROL_PHY1_AUTOMDIX | PHY_CONTROL_PHY1_EN | PHY_CONTROL_PHY0_MODE(PHY_MODE_ALL) | PHY_CONTROL_PHY0_AUTOMDIX | PHY_CONTROL_PHY0_EN | PHY_CONTROL_CLK_XLATIN; val = readl(NETX_SYSTEM_IOC_ACCESS_KEY); writel(val, NETX_SYSTEM_IOC_ACCESS_KEY); writel(phy_control | PHY_CONTROL_RESET, NETX_SYSTEM_PHY_CONTROL); udelay(100); val = readl(NETX_SYSTEM_IOC_ACCESS_KEY); writel(val, NETX_SYSTEM_IOC_ACCESS_KEY); writel(phy_control, NETX_SYSTEM_PHY_CONTROL); return platform_driver_register(&netx_eth_driver); } static void __exit netx_eth_cleanup(void) { platform_driver_unregister(&netx_eth_driver); } module_init(netx_eth_init); module_exit(netx_eth_cleanup); MODULE_AUTHOR("Sascha Hauer, Pengutronix"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" CARDNAME); MODULE_FIRMWARE("xc0.bin"); MODULE_FIRMWARE("xc1.bin"); MODULE_FIRMWARE("xc2.bin");
rukin5197/android_kernel_lge_m3s
drivers/net/netx-eth.c
C
gpl-2.0
14,019
/* * pata_atp867x.c - ARTOP 867X 64bit 4-channel UDMA133 ATA controller driver * * (C) 2009 Google Inc. John(Jung-Ik) Lee <jilee@google.com> * * Per Atp867 data sheet rev 1.2, Acard. * Based in part on early ide code from * 2003-2004 by Eric Uhrhane, Google, 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. * * 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 * * * TODO: * 1. RAID features [comparison, XOR, striping, mirroring, etc.] */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/gfp.h> #include <scsi/scsi_host.h> #include <linux/libata.h> #define DRV_NAME "pata_atp867x" #define DRV_VERSION "0.7.5" /* * IO Registers * Note that all runtime hot priv ports are cached in ap private_data */ enum { ATP867X_IO_CHANNEL_OFFSET = 0x10, /* * IO Register Bitfields */ ATP867X_IO_PIOSPD_ACTIVE_SHIFT = 4, ATP867X_IO_PIOSPD_RECOVER_SHIFT = 0, ATP867X_IO_DMAMODE_MSTR_SHIFT = 0, ATP867X_IO_DMAMODE_MSTR_MASK = 0x07, ATP867X_IO_DMAMODE_SLAVE_SHIFT = 4, ATP867X_IO_DMAMODE_SLAVE_MASK = 0x70, ATP867X_IO_DMAMODE_UDMA_6 = 0x07, ATP867X_IO_DMAMODE_UDMA_5 = 0x06, ATP867X_IO_DMAMODE_UDMA_4 = 0x05, ATP867X_IO_DMAMODE_UDMA_3 = 0x04, ATP867X_IO_DMAMODE_UDMA_2 = 0x03, ATP867X_IO_DMAMODE_UDMA_1 = 0x02, ATP867X_IO_DMAMODE_UDMA_0 = 0x01, ATP867X_IO_DMAMODE_DISABLE = 0x00, ATP867X_IO_SYS_INFO_66MHZ = 0x04, ATP867X_IO_SYS_INFO_SLOW_UDMA5 = 0x02, ATP867X_IO_SYS_MASK_RESERVED = (~0xf1), ATP867X_IO_PORTSPD_VAL = 0x1143, ATP867X_PREREAD_VAL = 0x0200, ATP867X_NUM_PORTS = 4, ATP867X_BAR_IOBASE = 0, ATP867X_BAR_ROMBASE = 6, }; #define ATP867X_IOBASE(ap) ((ap)->host->iomap[0]) #define ATP867X_SYS_INFO(ap) (0x3F + ATP867X_IOBASE(ap)) #define ATP867X_IO_PORTBASE(ap, port) (0x00 + ATP867X_IOBASE(ap) + \ (port) * ATP867X_IO_CHANNEL_OFFSET) #define ATP867X_IO_DMABASE(ap, port) (0x40 + \ ATP867X_IO_PORTBASE((ap), (port))) #define ATP867X_IO_STATUS(ap, port) (0x07 + \ ATP867X_IO_PORTBASE((ap), (port))) #define ATP867X_IO_ALTSTATUS(ap, port) (0x0E + \ ATP867X_IO_PORTBASE((ap), (port))) /* * hot priv ports */ #define ATP867X_IO_MSTRPIOSPD(ap, port) (0x08 + \ ATP867X_IO_DMABASE((ap), (port))) #define ATP867X_IO_SLAVPIOSPD(ap, port) (0x09 + \ ATP867X_IO_DMABASE((ap), (port))) #define ATP867X_IO_8BPIOSPD(ap, port) (0x0A + \ ATP867X_IO_DMABASE((ap), (port))) #define ATP867X_IO_DMAMODE(ap, port) (0x0B + \ ATP867X_IO_DMABASE((ap), (port))) #define ATP867X_IO_PORTSPD(ap, port) (0x4A + \ ATP867X_IO_PORTBASE((ap), (port))) #define ATP867X_IO_PREREAD(ap, port) (0x4C + \ ATP867X_IO_PORTBASE((ap), (port))) struct atp867x_priv { void __iomem *dma_mode; void __iomem *mstr_piospd; void __iomem *slave_piospd; void __iomem *eightb_piospd; int pci66mhz; }; static void atp867x_set_dmamode(struct ata_port *ap, struct ata_device *adev) { struct pci_dev *pdev = to_pci_dev(ap->host->dev); struct atp867x_priv *dp = ap->private_data; u8 speed = adev->dma_mode; u8 b; u8 mode = speed - XFER_UDMA_0 + 1; /* * Doc 6.6.9: decrease the udma mode value by 1 for safer UDMA speed * on 66MHz bus * rev-A: UDMA_1~4 (5, 6 no change) * rev-B: all UDMA modes * UDMA_0 stays not to disable UDMA */ if (dp->pci66mhz && mode > ATP867X_IO_DMAMODE_UDMA_0 && (pdev->device == PCI_DEVICE_ID_ARTOP_ATP867B || mode < ATP867X_IO_DMAMODE_UDMA_5)) mode--; b = ioread8(dp->dma_mode); if (adev->devno & 1) { b = (b & ~ATP867X_IO_DMAMODE_SLAVE_MASK) | (mode << ATP867X_IO_DMAMODE_SLAVE_SHIFT); } else { b = (b & ~ATP867X_IO_DMAMODE_MSTR_MASK) | (mode << ATP867X_IO_DMAMODE_MSTR_SHIFT); } iowrite8(b, dp->dma_mode); } static int atp867x_get_active_clocks_shifted(struct ata_port *ap, unsigned int clk) { struct atp867x_priv *dp = ap->private_data; unsigned char clocks = clk; /* * Doc 6.6.9: increase the clock value by 1 for safer PIO speed * on 66MHz bus */ if (dp->pci66mhz) clocks++; switch (clocks) { case 0: clocks = 1; break; case 1 ... 6: break; default: printk(KERN_WARNING "ATP867X: active %dclk is invalid. " "Using 12clk.\n", clk); case 9 ... 12: clocks = 7; /* 12 clk */ break; case 7: case 8: /* default 8 clk */ clocks = 0; goto active_clock_shift_done; } active_clock_shift_done: return clocks << ATP867X_IO_PIOSPD_ACTIVE_SHIFT; } static int atp867x_get_recover_clocks_shifted(unsigned int clk) { unsigned char clocks = clk; switch (clocks) { case 0: clocks = 1; break; case 1 ... 11: break; case 13: case 14: --clocks; /* by the spec */ break; case 15: break; default: printk(KERN_WARNING "ATP867X: recover %dclk is invalid. " "Using default 12clk.\n", clk); case 12: /* default 12 clk */ clocks = 0; break; } return clocks << ATP867X_IO_PIOSPD_RECOVER_SHIFT; } static void atp867x_set_piomode(struct ata_port *ap, struct ata_device *adev) { struct ata_device *peer = ata_dev_pair(adev); struct atp867x_priv *dp = ap->private_data; u8 speed = adev->pio_mode; struct ata_timing t, p; int T, UT; u8 b; T = 1000000000 / 33333; UT = T / 4; ata_timing_compute(adev, speed, &t, T, UT); if (peer && peer->pio_mode) { ata_timing_compute(peer, peer->pio_mode, &p, T, UT); ata_timing_merge(&p, &t, &t, ATA_TIMING_8BIT); } b = ioread8(dp->dma_mode); if (adev->devno & 1) b = (b & ~ATP867X_IO_DMAMODE_SLAVE_MASK); else b = (b & ~ATP867X_IO_DMAMODE_MSTR_MASK); iowrite8(b, dp->dma_mode); b = atp867x_get_active_clocks_shifted(ap, t.active) | atp867x_get_recover_clocks_shifted(t.recover); if (adev->devno & 1) iowrite8(b, dp->slave_piospd); else iowrite8(b, dp->mstr_piospd); b = atp867x_get_active_clocks_shifted(ap, t.act8b) | atp867x_get_recover_clocks_shifted(t.rec8b); iowrite8(b, dp->eightb_piospd); } static int atp867x_cable_override(struct pci_dev *pdev) { if (pdev->subsystem_vendor == PCI_VENDOR_ID_ARTOP && (pdev->subsystem_device == PCI_DEVICE_ID_ARTOP_ATP867A || pdev->subsystem_device == PCI_DEVICE_ID_ARTOP_ATP867B)) { return 1; } return 0; } static int atp867x_cable_detect(struct ata_port *ap) { struct pci_dev *pdev = to_pci_dev(ap->host->dev); if (atp867x_cable_override(pdev)) return ATA_CBL_PATA40_SHORT; return ATA_CBL_PATA_UNK; } static struct scsi_host_template atp867x_sht = { ATA_BMDMA_SHT(DRV_NAME), }; static struct ata_port_operations atp867x_ops = { .inherits = &ata_bmdma_port_ops, .cable_detect = atp867x_cable_detect, .set_piomode = atp867x_set_piomode, .set_dmamode = atp867x_set_dmamode, }; #ifdef ATP867X_DEBUG static void atp867x_check_res(struct pci_dev *pdev) { int i; unsigned long start, len; /* Check the PCI resources for this channel are enabled */ for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) { start = pci_resource_start(pdev, i); len = pci_resource_len(pdev, i); printk(KERN_DEBUG "ATP867X: resource start:len=%lx:%lx\n", start, len); } } static void atp867x_check_ports(struct ata_port *ap, int port) { struct ata_ioports *ioaddr = &ap->ioaddr; struct atp867x_priv *dp = ap->private_data; printk(KERN_DEBUG "ATP867X: port[%d] addresses\n" " cmd_addr =0x%llx, 0x%llx\n" " ctl_addr =0x%llx, 0x%llx\n" " bmdma_addr =0x%llx, 0x%llx\n" " data_addr =0x%llx\n" " error_addr =0x%llx\n" " feature_addr =0x%llx\n" " nsect_addr =0x%llx\n" " lbal_addr =0x%llx\n" " lbam_addr =0x%llx\n" " lbah_addr =0x%llx\n" " device_addr =0x%llx\n" " status_addr =0x%llx\n" " command_addr =0x%llx\n" " dp->dma_mode =0x%llx\n" " dp->mstr_piospd =0x%llx\n" " dp->slave_piospd =0x%llx\n" " dp->eightb_piospd =0x%llx\n" " dp->pci66mhz =0x%lx\n", port, (unsigned long long)ioaddr->cmd_addr, (unsigned long long)ATP867X_IO_PORTBASE(ap, port), (unsigned long long)ioaddr->ctl_addr, (unsigned long long)ATP867X_IO_ALTSTATUS(ap, port), (unsigned long long)ioaddr->bmdma_addr, (unsigned long long)ATP867X_IO_DMABASE(ap, port), (unsigned long long)ioaddr->data_addr, (unsigned long long)ioaddr->error_addr, (unsigned long long)ioaddr->feature_addr, (unsigned long long)ioaddr->nsect_addr, (unsigned long long)ioaddr->lbal_addr, (unsigned long long)ioaddr->lbam_addr, (unsigned long long)ioaddr->lbah_addr, (unsigned long long)ioaddr->device_addr, (unsigned long long)ioaddr->status_addr, (unsigned long long)ioaddr->command_addr, (unsigned long long)dp->dma_mode, (unsigned long long)dp->mstr_piospd, (unsigned long long)dp->slave_piospd, (unsigned long long)dp->eightb_piospd, (unsigned long)dp->pci66mhz); } #endif static int atp867x_set_priv(struct ata_port *ap) { struct pci_dev *pdev = to_pci_dev(ap->host->dev); struct atp867x_priv *dp; int port = ap->port_no; dp = ap->private_data = devm_kzalloc(&pdev->dev, sizeof(*dp), GFP_KERNEL); if (dp == NULL) return -ENOMEM; dp->dma_mode = ATP867X_IO_DMAMODE(ap, port); dp->mstr_piospd = ATP867X_IO_MSTRPIOSPD(ap, port); dp->slave_piospd = ATP867X_IO_SLAVPIOSPD(ap, port); dp->eightb_piospd = ATP867X_IO_8BPIOSPD(ap, port); dp->pci66mhz = ioread8(ATP867X_SYS_INFO(ap)) & ATP867X_IO_SYS_INFO_66MHZ; return 0; } static void atp867x_fixup(struct ata_host *host) { struct pci_dev *pdev = to_pci_dev(host->dev); struct ata_port *ap = host->ports[0]; int i; u8 v; /* * Broken BIOS might not set latency high enough */ pci_read_config_byte(pdev, PCI_LATENCY_TIMER, &v); if (v < 0x80) { v = 0x80; pci_write_config_byte(pdev, PCI_LATENCY_TIMER, v); printk(KERN_DEBUG "ATP867X: set latency timer of device %s" " to %d\n", pci_name(pdev), v); } /* * init 8bit io ports speed(0aaarrrr) to 43h and * init udma modes of master/slave to 0/0(11h) */ for (i = 0; i < ATP867X_NUM_PORTS; i++) iowrite16(ATP867X_IO_PORTSPD_VAL, ATP867X_IO_PORTSPD(ap, i)); /* * init PreREAD counts */ for (i = 0; i < ATP867X_NUM_PORTS; i++) iowrite16(ATP867X_PREREAD_VAL, ATP867X_IO_PREREAD(ap, i)); v = ioread8(ATP867X_IOBASE(ap) + 0x28); v &= 0xcf; /* Enable INTA#: bit4=0 means enable */ v |= 0xc0; /* Enable PCI burst, MRM & not immediate interrupts */ iowrite8(v, ATP867X_IOBASE(ap) + 0x28); /* * Turn off the over clocked udma5 mode, only for Rev-B */ v = ioread8(ATP867X_SYS_INFO(ap)); v &= ATP867X_IO_SYS_MASK_RESERVED; if (pdev->device == PCI_DEVICE_ID_ARTOP_ATP867B) v |= ATP867X_IO_SYS_INFO_SLOW_UDMA5; iowrite8(v, ATP867X_SYS_INFO(ap)); } static int atp867x_ata_pci_sff_init_host(struct ata_host *host) { struct device *gdev = host->dev; struct pci_dev *pdev = to_pci_dev(gdev); unsigned int mask = 0; int i, rc; /* * do not map rombase */ rc = pcim_iomap_regions(pdev, 1 << ATP867X_BAR_IOBASE, DRV_NAME); if (rc == -EBUSY) pcim_pin_device(pdev); if (rc) return rc; host->iomap = pcim_iomap_table(pdev); #ifdef ATP867X_DEBUG atp867x_check_res(pdev); for (i = 0; i < PCI_ROM_RESOURCE; i++) printk(KERN_DEBUG "ATP867X: iomap[%d]=0x%llx\n", i, (unsigned long long)(host->iomap[i])); #endif /* * request, iomap BARs and init port addresses accordingly */ for (i = 0; i < host->n_ports; i++) { struct ata_port *ap = host->ports[i]; struct ata_ioports *ioaddr = &ap->ioaddr; ioaddr->cmd_addr = ATP867X_IO_PORTBASE(ap, i); ioaddr->ctl_addr = ioaddr->altstatus_addr = ATP867X_IO_ALTSTATUS(ap, i); ioaddr->bmdma_addr = ATP867X_IO_DMABASE(ap, i); ata_sff_std_ports(ioaddr); rc = atp867x_set_priv(ap); if (rc) return rc; #ifdef ATP867X_DEBUG atp867x_check_ports(ap, i); #endif ata_port_desc(ap, "cmd 0x%lx ctl 0x%lx", (unsigned long)ioaddr->cmd_addr, (unsigned long)ioaddr->ctl_addr); ata_port_desc(ap, "bmdma 0x%lx", (unsigned long)ioaddr->bmdma_addr); mask |= 1 << i; } if (!mask) { dev_printk(KERN_ERR, gdev, "no available native port\n"); return -ENODEV; } atp867x_fixup(host); rc = pci_set_dma_mask(pdev, ATA_DMA_MASK); if (rc) return rc; rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK); return rc; } static int atp867x_init_one(struct pci_dev *pdev, const struct pci_device_id *id) { static int printed_version; static const struct ata_port_info info_867x = { .flags = ATA_FLAG_SLAVE_POSS, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &atp867x_ops, }; struct ata_host *host; const struct ata_port_info *ppi[] = { &info_867x, NULL }; int rc; if (!printed_version++) dev_printk(KERN_INFO, &pdev->dev, "version " DRV_VERSION "\n"); rc = pcim_enable_device(pdev); if (rc) return rc; printk(KERN_INFO "ATP867X: ATP867 ATA UDMA133 controller (rev %02X)", pdev->device); host = ata_host_alloc_pinfo(&pdev->dev, ppi, ATP867X_NUM_PORTS); if (!host) { dev_printk(KERN_ERR, &pdev->dev, "failed to allocate ATA host\n"); rc = -ENOMEM; goto err_out; } rc = atp867x_ata_pci_sff_init_host(host); if (rc) { dev_printk(KERN_ERR, &pdev->dev, "failed to init host\n"); goto err_out; } pci_set_master(pdev); rc = ata_host_activate(host, pdev->irq, ata_bmdma_interrupt, IRQF_SHARED, &atp867x_sht); if (rc) dev_printk(KERN_ERR, &pdev->dev, "failed to activate host\n"); err_out: return rc; } #ifdef CONFIG_PM static int atp867x_reinit_one(struct pci_dev *pdev) { struct ata_host *host = dev_get_drvdata(&pdev->dev); int rc; rc = ata_pci_device_do_resume(pdev); if (rc) return rc; atp867x_fixup(host); ata_host_resume(host); return 0; } #endif static struct pci_device_id atp867x_pci_tbl[] = { { PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP867A), 0 }, { PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP867B), 0 }, { }, }; static struct pci_driver atp867x_driver = { .name = DRV_NAME, .id_table = atp867x_pci_tbl, .probe = atp867x_init_one, .remove = ata_pci_remove_one, #ifdef CONFIG_PM .suspend = ata_pci_device_suspend, .resume = atp867x_reinit_one, #endif }; static int __init atp867x_init(void) { return pci_register_driver(&atp867x_driver); } static void __exit atp867x_exit(void) { pci_unregister_driver(&atp867x_driver); } MODULE_AUTHOR("John(Jung-Ik) Lee, Google Inc."); MODULE_DESCRIPTION("low level driver for Artop/Acard 867x ATA controller"); MODULE_LICENSE("GPL"); MODULE_DEVICE_TABLE(pci, atp867x_pci_tbl); MODULE_VERSION(DRV_VERSION); module_init(atp867x_init); module_exit(atp867x_exit);
jamison904/T989_TW_JB
drivers/ata/pata_atp867x.c
C
gpl-2.0
14,984
/* * CS4271 ASoC codec driver * * Copyright (c) 2010 Alexander Sverdlin <subaparts@yandex.ru> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This driver support CS4271 codec being master or slave, working * in control port mode, connected either via SPI or I2C. * The data format accepted is I2S or left-justified. * DAPM support not implemented. */ #include <linux/module.h> #include <linux/slab.h> #include <linux/delay.h> #include <sound/pcm.h> #include <sound/soc.h> #include <sound/tlv.h> #include <linux/gpio.h> #include <linux/i2c.h> #include <linux/spi/spi.h> #include <sound/cs4271.h> #define CS4271_PCM_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | \ SNDRV_PCM_FMTBIT_S24_LE | \ SNDRV_PCM_FMTBIT_S32_LE) #define CS4271_PCM_RATES SNDRV_PCM_RATE_8000_192000 /* * CS4271 registers * High byte represents SPI chip address (0x10) + write command (0) * Low byte - codec register address */ #define CS4271_MODE1 0x2001 /* Mode Control 1 */ #define CS4271_DACCTL 0x2002 /* DAC Control */ #define CS4271_DACVOL 0x2003 /* DAC Volume & Mixing Control */ #define CS4271_VOLA 0x2004 /* DAC Channel A Volume Control */ #define CS4271_VOLB 0x2005 /* DAC Channel B Volume Control */ #define CS4271_ADCCTL 0x2006 /* ADC Control */ #define CS4271_MODE2 0x2007 /* Mode Control 2 */ #define CS4271_CHIPID 0x2008 /* Chip ID */ #define CS4271_FIRSTREG CS4271_MODE1 #define CS4271_LASTREG CS4271_MODE2 #define CS4271_NR_REGS ((CS4271_LASTREG & 0xFF) + 1) /* Bit masks for the CS4271 registers */ #define CS4271_MODE1_MODE_MASK 0xC0 #define CS4271_MODE1_MODE_1X 0x00 #define CS4271_MODE1_MODE_2X 0x80 #define CS4271_MODE1_MODE_4X 0xC0 #define CS4271_MODE1_DIV_MASK 0x30 #define CS4271_MODE1_DIV_1 0x00 #define CS4271_MODE1_DIV_15 0x10 #define CS4271_MODE1_DIV_2 0x20 #define CS4271_MODE1_DIV_3 0x30 #define CS4271_MODE1_MASTER 0x08 #define CS4271_MODE1_DAC_DIF_MASK 0x07 #define CS4271_MODE1_DAC_DIF_LJ 0x00 #define CS4271_MODE1_DAC_DIF_I2S 0x01 #define CS4271_MODE1_DAC_DIF_RJ16 0x02 #define CS4271_MODE1_DAC_DIF_RJ24 0x03 #define CS4271_MODE1_DAC_DIF_RJ20 0x04 #define CS4271_MODE1_DAC_DIF_RJ18 0x05 #define CS4271_DACCTL_AMUTE 0x80 #define CS4271_DACCTL_IF_SLOW 0x40 #define CS4271_DACCTL_DEM_MASK 0x30 #define CS4271_DACCTL_DEM_DIS 0x00 #define CS4271_DACCTL_DEM_441 0x10 #define CS4271_DACCTL_DEM_48 0x20 #define CS4271_DACCTL_DEM_32 0x30 #define CS4271_DACCTL_SVRU 0x08 #define CS4271_DACCTL_SRD 0x04 #define CS4271_DACCTL_INVA 0x02 #define CS4271_DACCTL_INVB 0x01 #define CS4271_DACVOL_BEQUA 0x40 #define CS4271_DACVOL_SOFT 0x20 #define CS4271_DACVOL_ZEROC 0x10 #define CS4271_DACVOL_ATAPI_MASK 0x0F #define CS4271_DACVOL_ATAPI_M_M 0x00 #define CS4271_DACVOL_ATAPI_M_BR 0x01 #define CS4271_DACVOL_ATAPI_M_BL 0x02 #define CS4271_DACVOL_ATAPI_M_BLR2 0x03 #define CS4271_DACVOL_ATAPI_AR_M 0x04 #define CS4271_DACVOL_ATAPI_AR_BR 0x05 #define CS4271_DACVOL_ATAPI_AR_BL 0x06 #define CS4271_DACVOL_ATAPI_AR_BLR2 0x07 #define CS4271_DACVOL_ATAPI_AL_M 0x08 #define CS4271_DACVOL_ATAPI_AL_BR 0x09 #define CS4271_DACVOL_ATAPI_AL_BL 0x0A #define CS4271_DACVOL_ATAPI_AL_BLR2 0x0B #define CS4271_DACVOL_ATAPI_ALR2_M 0x0C #define CS4271_DACVOL_ATAPI_ALR2_BR 0x0D #define CS4271_DACVOL_ATAPI_ALR2_BL 0x0E #define CS4271_DACVOL_ATAPI_ALR2_BLR2 0x0F #define CS4271_VOLA_MUTE 0x80 #define CS4271_VOLA_VOL_MASK 0x7F #define CS4271_VOLB_MUTE 0x80 #define CS4271_VOLB_VOL_MASK 0x7F #define CS4271_ADCCTL_DITHER16 0x20 #define CS4271_ADCCTL_ADC_DIF_MASK 0x10 #define CS4271_ADCCTL_ADC_DIF_LJ 0x00 #define CS4271_ADCCTL_ADC_DIF_I2S 0x10 #define CS4271_ADCCTL_MUTEA 0x08 #define CS4271_ADCCTL_MUTEB 0x04 #define CS4271_ADCCTL_HPFDA 0x02 #define CS4271_ADCCTL_HPFDB 0x01 #define CS4271_MODE2_LOOP 0x10 #define CS4271_MODE2_MUTECAEQUB 0x08 #define CS4271_MODE2_FREEZE 0x04 #define CS4271_MODE2_CPEN 0x02 #define CS4271_MODE2_PDN 0x01 #define CS4271_CHIPID_PART_MASK 0xF0 #define CS4271_CHIPID_REV_MASK 0x0F /* * Default CS4271 power-up configuration * Array contains non-existing in hw register at address 0 * Array do not include Chip ID, as codec driver does not use * registers read operations at all */ static const u8 cs4271_dflt_reg[CS4271_NR_REGS] = { 0, 0, CS4271_DACCTL_AMUTE, CS4271_DACVOL_SOFT | CS4271_DACVOL_ATAPI_AL_BR, 0, 0, 0, 0, }; struct cs4271_private { /* SND_SOC_I2C or SND_SOC_SPI */ enum snd_soc_control_type bus_type; unsigned int mclk; bool master; bool deemph; /* Current sample rate for de-emphasis control */ int rate; /* GPIO driving Reset pin, if any */ int gpio_nreset; /* GPIO that disable serial bus, if any */ int gpio_disable; }; /* * @freq is the desired MCLK rate * MCLK rate should (c) be the sample rate, multiplied by one of the * ratios listed in cs4271_mclk_fs_ratios table */ static int cs4271_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = codec_dai->codec; struct cs4271_private *cs4271 = snd_soc_codec_get_drvdata(codec); cs4271->mclk = freq; return 0; } static int cs4271_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int format) { struct snd_soc_codec *codec = codec_dai->codec; struct cs4271_private *cs4271 = snd_soc_codec_get_drvdata(codec); unsigned int val = 0; int ret; switch (format & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: cs4271->master = 0; break; case SND_SOC_DAIFMT_CBM_CFM: cs4271->master = 1; val |= CS4271_MODE1_MASTER; break; default: dev_err(codec->dev, "Invalid DAI format\n"); return -EINVAL; } switch (format & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_LEFT_J: val |= CS4271_MODE1_DAC_DIF_LJ; ret = snd_soc_update_bits(codec, CS4271_ADCCTL, CS4271_ADCCTL_ADC_DIF_MASK, CS4271_ADCCTL_ADC_DIF_LJ); if (ret < 0) return ret; break; case SND_SOC_DAIFMT_I2S: val |= CS4271_MODE1_DAC_DIF_I2S; ret = snd_soc_update_bits(codec, CS4271_ADCCTL, CS4271_ADCCTL_ADC_DIF_MASK, CS4271_ADCCTL_ADC_DIF_I2S); if (ret < 0) return ret; break; default: dev_err(codec->dev, "Invalid DAI format\n"); return -EINVAL; } ret = snd_soc_update_bits(codec, CS4271_MODE1, CS4271_MODE1_DAC_DIF_MASK | CS4271_MODE1_MASTER, val); if (ret < 0) return ret; return 0; } static int cs4271_deemph[] = {0, 44100, 48000, 32000}; static int cs4271_set_deemph(struct snd_soc_codec *codec) { struct cs4271_private *cs4271 = snd_soc_codec_get_drvdata(codec); int i, ret; int val = CS4271_DACCTL_DEM_DIS; if (cs4271->deemph) { /* Find closest de-emphasis freq */ val = 1; for (i = 2; i < ARRAY_SIZE(cs4271_deemph); i++) if (abs(cs4271_deemph[i] - cs4271->rate) < abs(cs4271_deemph[val] - cs4271->rate)) val = i; val <<= 4; } ret = snd_soc_update_bits(codec, CS4271_DACCTL, CS4271_DACCTL_DEM_MASK, val); if (ret < 0) return ret; return 0; } static int cs4271_get_deemph(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct cs4271_private *cs4271 = snd_soc_codec_get_drvdata(codec); ucontrol->value.enumerated.item[0] = cs4271->deemph; return 0; } static int cs4271_put_deemph(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct cs4271_private *cs4271 = snd_soc_codec_get_drvdata(codec); cs4271->deemph = ucontrol->value.enumerated.item[0]; return cs4271_set_deemph(codec); } struct cs4271_clk_cfg { bool master; /* codec mode */ u8 speed_mode; /* codec speed mode: 1x, 2x, 4x */ unsigned short ratio; /* MCLK / sample rate */ u8 ratio_mask; /* ratio bit mask for Master mode */ }; static struct cs4271_clk_cfg cs4271_clk_tab[] = { {1, CS4271_MODE1_MODE_1X, 256, CS4271_MODE1_DIV_1}, {1, CS4271_MODE1_MODE_1X, 384, CS4271_MODE1_DIV_15}, {1, CS4271_MODE1_MODE_1X, 512, CS4271_MODE1_DIV_2}, {1, CS4271_MODE1_MODE_1X, 768, CS4271_MODE1_DIV_3}, {1, CS4271_MODE1_MODE_2X, 128, CS4271_MODE1_DIV_1}, {1, CS4271_MODE1_MODE_2X, 192, CS4271_MODE1_DIV_15}, {1, CS4271_MODE1_MODE_2X, 256, CS4271_MODE1_DIV_2}, {1, CS4271_MODE1_MODE_2X, 384, CS4271_MODE1_DIV_3}, {1, CS4271_MODE1_MODE_4X, 64, CS4271_MODE1_DIV_1}, {1, CS4271_MODE1_MODE_4X, 96, CS4271_MODE1_DIV_15}, {1, CS4271_MODE1_MODE_4X, 128, CS4271_MODE1_DIV_2}, {1, CS4271_MODE1_MODE_4X, 192, CS4271_MODE1_DIV_3}, {0, CS4271_MODE1_MODE_1X, 256, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_1X, 384, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_1X, 512, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_1X, 768, CS4271_MODE1_DIV_2}, {0, CS4271_MODE1_MODE_1X, 1024, CS4271_MODE1_DIV_2}, {0, CS4271_MODE1_MODE_2X, 128, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_2X, 192, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_2X, 256, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_2X, 384, CS4271_MODE1_DIV_2}, {0, CS4271_MODE1_MODE_2X, 512, CS4271_MODE1_DIV_2}, {0, CS4271_MODE1_MODE_4X, 64, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_4X, 96, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_4X, 128, CS4271_MODE1_DIV_1}, {0, CS4271_MODE1_MODE_4X, 192, CS4271_MODE1_DIV_2}, {0, CS4271_MODE1_MODE_4X, 256, CS4271_MODE1_DIV_2}, }; #define CS4171_NR_RATIOS ARRAY_SIZE(cs4271_clk_tab) static int cs4271_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct cs4271_private *cs4271 = snd_soc_codec_get_drvdata(codec); int i, ret; unsigned int ratio, val; cs4271->rate = params_rate(params); /* Configure DAC */ if (cs4271->rate < 50000) val = CS4271_MODE1_MODE_1X; else if (cs4271->rate < 100000) val = CS4271_MODE1_MODE_2X; else val = CS4271_MODE1_MODE_4X; ratio = cs4271->mclk / cs4271->rate; for (i = 0; i < CS4171_NR_RATIOS; i++) if ((cs4271_clk_tab[i].master == cs4271->master) && (cs4271_clk_tab[i].speed_mode == val) && (cs4271_clk_tab[i].ratio == ratio)) break; if (i == CS4171_NR_RATIOS) { dev_err(codec->dev, "Invalid sample rate\n"); return -EINVAL; } val |= cs4271_clk_tab[i].ratio_mask; ret = snd_soc_update_bits(codec, CS4271_MODE1, CS4271_MODE1_MODE_MASK | CS4271_MODE1_DIV_MASK, val); if (ret < 0) return ret; return cs4271_set_deemph(codec); } static int cs4271_digital_mute(struct snd_soc_dai *dai, int mute) { struct snd_soc_codec *codec = dai->codec; int ret; int val_a = 0; int val_b = 0; if (mute) { val_a = CS4271_VOLA_MUTE; val_b = CS4271_VOLB_MUTE; } ret = snd_soc_update_bits(codec, CS4271_VOLA, CS4271_VOLA_MUTE, val_a); if (ret < 0) return ret; ret = snd_soc_update_bits(codec, CS4271_VOLB, CS4271_VOLB_MUTE, val_b); if (ret < 0) return ret; return 0; } /* CS4271 controls */ static DECLARE_TLV_DB_SCALE(cs4271_dac_tlv, -12700, 100, 0); static const struct snd_kcontrol_new cs4271_snd_controls[] = { SOC_DOUBLE_R_TLV("Master Playback Volume", CS4271_VOLA, CS4271_VOLB, 0, 0x7F, 1, cs4271_dac_tlv), SOC_SINGLE("Digital Loopback Switch", CS4271_MODE2, 4, 1, 0), SOC_SINGLE("Soft Ramp Switch", CS4271_DACVOL, 5, 1, 0), SOC_SINGLE("Zero Cross Switch", CS4271_DACVOL, 4, 1, 0), SOC_SINGLE_BOOL_EXT("De-emphasis Switch", 0, cs4271_get_deemph, cs4271_put_deemph), SOC_SINGLE("Auto-Mute Switch", CS4271_DACCTL, 7, 1, 0), SOC_SINGLE("Slow Roll Off Filter Switch", CS4271_DACCTL, 6, 1, 0), SOC_SINGLE("Soft Volume Ramp-Up Switch", CS4271_DACCTL, 3, 1, 0), SOC_SINGLE("Soft Ramp-Down Switch", CS4271_DACCTL, 2, 1, 0), SOC_SINGLE("Left Channel Inversion Switch", CS4271_DACCTL, 1, 1, 0), SOC_SINGLE("Right Channel Inversion Switch", CS4271_DACCTL, 0, 1, 0), SOC_DOUBLE("Master Capture Switch", CS4271_ADCCTL, 3, 2, 1, 1), SOC_SINGLE("Dither 16-Bit Data Switch", CS4271_ADCCTL, 5, 1, 0), SOC_DOUBLE("High Pass Filter Switch", CS4271_ADCCTL, 1, 0, 1, 1), SOC_DOUBLE_R("Master Playback Switch", CS4271_VOLA, CS4271_VOLB, 7, 1, 1), }; static const struct snd_soc_dai_ops cs4271_dai_ops = { .hw_params = cs4271_hw_params, .set_sysclk = cs4271_set_dai_sysclk, .set_fmt = cs4271_set_dai_fmt, .digital_mute = cs4271_digital_mute, }; static struct snd_soc_dai_driver cs4271_dai = { .name = "cs4271-hifi", .playback = { .stream_name = "Playback", .channels_min = 2, .channels_max = 2, .rates = CS4271_PCM_RATES, .formats = CS4271_PCM_FORMATS, }, .capture = { .stream_name = "Capture", .channels_min = 2, .channels_max = 2, .rates = CS4271_PCM_RATES, .formats = CS4271_PCM_FORMATS, }, .ops = &cs4271_dai_ops, .symmetric_rates = 1, }; #ifdef CONFIG_PM static int cs4271_soc_suspend(struct snd_soc_codec *codec) { int ret; /* Set power-down bit */ ret = snd_soc_update_bits(codec, CS4271_MODE2, CS4271_MODE2_PDN, CS4271_MODE2_PDN); if (ret < 0) return ret; return 0; } static int cs4271_soc_resume(struct snd_soc_codec *codec) { int ret; /* Restore codec state */ ret = snd_soc_cache_sync(codec); if (ret < 0) return ret; /* then disable the power-down bit */ ret = snd_soc_update_bits(codec, CS4271_MODE2, CS4271_MODE2_PDN, 0); if (ret < 0) return ret; return 0; } #else #define cs4271_soc_suspend NULL #define cs4271_soc_resume NULL #endif /* CONFIG_PM */ static int cs4271_probe(struct snd_soc_codec *codec) { struct cs4271_private *cs4271 = snd_soc_codec_get_drvdata(codec); struct cs4271_platform_data *cs4271plat = codec->dev->platform_data; int ret; int gpio_nreset = -EINVAL; if (cs4271plat && gpio_is_valid(cs4271plat->gpio_nreset)) gpio_nreset = cs4271plat->gpio_nreset; if (gpio_nreset >= 0) if (gpio_request(gpio_nreset, "CS4271 Reset")) gpio_nreset = -EINVAL; if (gpio_nreset >= 0) { /* Reset codec */ gpio_direction_output(gpio_nreset, 0); udelay(1); gpio_set_value(gpio_nreset, 1); /* Give the codec time to wake up */ udelay(1); } cs4271->gpio_nreset = gpio_nreset; /* * In case of I2C, chip address specified in board data. * So cache IO operations use 8 bit codec register address. * In case of SPI, chip address and register address * passed together as 16 bit value. * Anyway, register address is masked with 0xFF inside * soc-cache code. */ if (cs4271->bus_type == SND_SOC_SPI) ret = snd_soc_codec_set_cache_io(codec, 16, 8, cs4271->bus_type); else ret = snd_soc_codec_set_cache_io(codec, 8, 8, cs4271->bus_type); if (ret) { dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret); return ret; } ret = snd_soc_update_bits(codec, CS4271_MODE2, CS4271_MODE2_PDN | CS4271_MODE2_CPEN, CS4271_MODE2_PDN | CS4271_MODE2_CPEN); if (ret < 0) return ret; ret = snd_soc_update_bits(codec, CS4271_MODE2, CS4271_MODE2_PDN, 0); if (ret < 0) return ret; /* Power-up sequence requires 85 uS */ udelay(85); return snd_soc_add_codec_controls(codec, cs4271_snd_controls, ARRAY_SIZE(cs4271_snd_controls)); } static int cs4271_remove(struct snd_soc_codec *codec) { struct cs4271_private *cs4271 = snd_soc_codec_get_drvdata(codec); int gpio_nreset; gpio_nreset = cs4271->gpio_nreset; if (gpio_is_valid(gpio_nreset)) { /* Set codec to the reset state */ gpio_set_value(gpio_nreset, 0); gpio_free(gpio_nreset); } return 0; }; static struct snd_soc_codec_driver soc_codec_dev_cs4271 = { .probe = cs4271_probe, .remove = cs4271_remove, .suspend = cs4271_soc_suspend, .resume = cs4271_soc_resume, .reg_cache_default = cs4271_dflt_reg, .reg_cache_size = ARRAY_SIZE(cs4271_dflt_reg), .reg_word_size = sizeof(cs4271_dflt_reg[0]), .compress_type = SND_SOC_FLAT_COMPRESSION, }; #if defined(CONFIG_SPI_MASTER) static int __devinit cs4271_spi_probe(struct spi_device *spi) { struct cs4271_private *cs4271; cs4271 = devm_kzalloc(&spi->dev, sizeof(*cs4271), GFP_KERNEL); if (!cs4271) return -ENOMEM; spi_set_drvdata(spi, cs4271); cs4271->bus_type = SND_SOC_SPI; return snd_soc_register_codec(&spi->dev, &soc_codec_dev_cs4271, &cs4271_dai, 1); } static int __devexit cs4271_spi_remove(struct spi_device *spi) { snd_soc_unregister_codec(&spi->dev); return 0; } static struct spi_driver cs4271_spi_driver = { .driver = { .name = "cs4271", .owner = THIS_MODULE, }, .probe = cs4271_spi_probe, .remove = __devexit_p(cs4271_spi_remove), }; #endif /* defined(CONFIG_SPI_MASTER) */ #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) static const struct i2c_device_id cs4271_i2c_id[] = { {"cs4271", 0}, {} }; MODULE_DEVICE_TABLE(i2c, cs4271_i2c_id); static int __devinit cs4271_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct cs4271_private *cs4271; cs4271 = devm_kzalloc(&client->dev, sizeof(*cs4271), GFP_KERNEL); if (!cs4271) return -ENOMEM; i2c_set_clientdata(client, cs4271); cs4271->bus_type = SND_SOC_I2C; return snd_soc_register_codec(&client->dev, &soc_codec_dev_cs4271, &cs4271_dai, 1); } static int __devexit cs4271_i2c_remove(struct i2c_client *client) { snd_soc_unregister_codec(&client->dev); return 0; } static struct i2c_driver cs4271_i2c_driver = { .driver = { .name = "cs4271", .owner = THIS_MODULE, }, .id_table = cs4271_i2c_id, .probe = cs4271_i2c_probe, .remove = __devexit_p(cs4271_i2c_remove), }; #endif /* defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) */ /* * We only register our serial bus driver here without * assignment to particular chip. So if any of the below * fails, there is some problem with I2C or SPI subsystem. * In most cases this module will be compiled with support * of only one serial bus. */ static int __init cs4271_modinit(void) { int ret; #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) ret = i2c_add_driver(&cs4271_i2c_driver); if (ret) { pr_err("Failed to register CS4271 I2C driver: %d\n", ret); return ret; } #endif #if defined(CONFIG_SPI_MASTER) ret = spi_register_driver(&cs4271_spi_driver); if (ret) { pr_err("Failed to register CS4271 SPI driver: %d\n", ret); return ret; } #endif return 0; } module_init(cs4271_modinit); static void __exit cs4271_modexit(void) { #if defined(CONFIG_SPI_MASTER) spi_unregister_driver(&cs4271_spi_driver); #endif #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) i2c_del_driver(&cs4271_i2c_driver); #endif } module_exit(cs4271_modexit); MODULE_AUTHOR("Alexander Sverdlin <subaparts@yandex.ru>"); MODULE_DESCRIPTION("Cirrus Logic CS4271 ALSA SoC Codec Driver"); MODULE_LICENSE("GPL");
santod/NuK3rn3l_m7_sense_lollipop
sound/soc/codecs/cs4271.c
C
gpl-2.0
18,903
/* * Copyright (c) 2009-2011 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * Copyright 2008 Openmoko, Inc. * Copyright 2008 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * http://armlinux.simtec.co.uk/ * * SAMSUNG - GPIOlib support * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/irq.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/device.h> #include <linux/ioport.h> #include <linux/of.h> #include <linux/slab.h> #include <linux/of_address.h> #include <asm/irq.h> #include <mach/hardware.h> #include <mach/map.h> #include <mach/regs-clock.h> #include <mach/regs-gpio.h> #include <plat/cpu.h> #include <plat/gpio-core.h> #include <plat/gpio-cfg.h> #include <plat/gpio-cfg-helpers.h> #include <plat/gpio-fns.h> #include <plat/pm.h> #ifndef DEBUG_GPIO #define gpio_dbg(x...) do { } while (0) #else #define gpio_dbg(x...) printk(KERN_DEBUG x) #endif int samsung_gpio_setpull_updown(struct samsung_gpio_chip *chip, unsigned int off, samsung_gpio_pull_t pull) { void __iomem *reg = chip->base + 0x08; int shift = off * 2; u32 pup; pup = __raw_readl(reg); pup &= ~(3 << shift); pup |= pull << shift; __raw_writel(pup, reg); return 0; } samsung_gpio_pull_t samsung_gpio_getpull_updown(struct samsung_gpio_chip *chip, unsigned int off) { void __iomem *reg = chip->base + 0x08; int shift = off * 2; u32 pup = __raw_readl(reg); pup >>= shift; pup &= 0x3; return (__force samsung_gpio_pull_t)pup; } int s3c2443_gpio_setpull(struct samsung_gpio_chip *chip, unsigned int off, samsung_gpio_pull_t pull) { switch (pull) { case S3C_GPIO_PULL_NONE: pull = 0x01; break; case S3C_GPIO_PULL_UP: pull = 0x00; break; case S3C_GPIO_PULL_DOWN: pull = 0x02; break; } return samsung_gpio_setpull_updown(chip, off, pull); } samsung_gpio_pull_t s3c2443_gpio_getpull(struct samsung_gpio_chip *chip, unsigned int off) { samsung_gpio_pull_t pull; pull = samsung_gpio_getpull_updown(chip, off); switch (pull) { case 0x00: pull = S3C_GPIO_PULL_UP; break; case 0x01: case 0x03: pull = S3C_GPIO_PULL_NONE; break; case 0x02: pull = S3C_GPIO_PULL_DOWN; break; } return pull; } static int s3c24xx_gpio_setpull_1(struct samsung_gpio_chip *chip, unsigned int off, samsung_gpio_pull_t pull, samsung_gpio_pull_t updown) { void __iomem *reg = chip->base + 0x08; u32 pup = __raw_readl(reg); if (pull == updown) pup &= ~(1 << off); else if (pull == S3C_GPIO_PULL_NONE) pup |= (1 << off); else return -EINVAL; __raw_writel(pup, reg); return 0; } static samsung_gpio_pull_t s3c24xx_gpio_getpull_1(struct samsung_gpio_chip *chip, unsigned int off, samsung_gpio_pull_t updown) { void __iomem *reg = chip->base + 0x08; u32 pup = __raw_readl(reg); pup &= (1 << off); return pup ? S3C_GPIO_PULL_NONE : updown; } samsung_gpio_pull_t s3c24xx_gpio_getpull_1up(struct samsung_gpio_chip *chip, unsigned int off) { return s3c24xx_gpio_getpull_1(chip, off, S3C_GPIO_PULL_UP); } int s3c24xx_gpio_setpull_1up(struct samsung_gpio_chip *chip, unsigned int off, samsung_gpio_pull_t pull) { return s3c24xx_gpio_setpull_1(chip, off, pull, S3C_GPIO_PULL_UP); } samsung_gpio_pull_t s3c24xx_gpio_getpull_1down(struct samsung_gpio_chip *chip, unsigned int off) { return s3c24xx_gpio_getpull_1(chip, off, S3C_GPIO_PULL_DOWN); } int s3c24xx_gpio_setpull_1down(struct samsung_gpio_chip *chip, unsigned int off, samsung_gpio_pull_t pull) { return s3c24xx_gpio_setpull_1(chip, off, pull, S3C_GPIO_PULL_DOWN); } static int exynos_gpio_setpull(struct samsung_gpio_chip *chip, unsigned int off, samsung_gpio_pull_t pull) { if (pull == S3C_GPIO_PULL_UP) pull = 3; return samsung_gpio_setpull_updown(chip, off, pull); } static samsung_gpio_pull_t exynos_gpio_getpull(struct samsung_gpio_chip *chip, unsigned int off) { samsung_gpio_pull_t pull; pull = samsung_gpio_getpull_updown(chip, off); if (pull == 3) pull = S3C_GPIO_PULL_UP; return pull; } /* * samsung_gpio_setcfg_2bit - Samsung 2bit style GPIO configuration. * @chip: The gpio chip that is being configured. * @off: The offset for the GPIO being configured. * @cfg: The configuration value to set. * * This helper deal with the GPIO cases where the control register * has two bits of configuration per gpio, which have the following * functions: * 00 = input * 01 = output * 1x = special function */ static int samsung_gpio_setcfg_2bit(struct samsung_gpio_chip *chip, unsigned int off, unsigned int cfg) { void __iomem *reg = chip->base; unsigned int shift = off * 2; u32 con; if (samsung_gpio_is_cfg_special(cfg)) { cfg &= 0xf; if (cfg > 3) return -EINVAL; cfg <<= shift; } con = __raw_readl(reg); con &= ~(0x3 << shift); con |= cfg; __raw_writel(con, reg); return 0; } /* * samsung_gpio_getcfg_2bit - Samsung 2bit style GPIO configuration read. * @chip: The gpio chip that is being configured. * @off: The offset for the GPIO being configured. * * The reverse of samsung_gpio_setcfg_2bit(). Will return a value which * could be directly passed back to samsung_gpio_setcfg_2bit(), from the * S3C_GPIO_SPECIAL() macro. */ static unsigned int samsung_gpio_getcfg_2bit(struct samsung_gpio_chip *chip, unsigned int off) { u32 con; con = __raw_readl(chip->base); con >>= off * 2; con &= 3; /* this conversion works for IN and OUT as well as special mode */ return S3C_GPIO_SPECIAL(con); } /* * samsung_gpio_setcfg_4bit - Samsung 4bit single register GPIO config. * @chip: The gpio chip that is being configured. * @off: The offset for the GPIO being configured. * @cfg: The configuration value to set. * * This helper deal with the GPIO cases where the control register has 4 bits * of control per GPIO, generally in the form of: * 0000 = Input * 0001 = Output * others = Special functions (dependent on bank) * * Note, since the code to deal with the case where there are two control * registers instead of one, we do not have a separate set of functions for * each case. */ static int samsung_gpio_setcfg_4bit(struct samsung_gpio_chip *chip, unsigned int off, unsigned int cfg) { void __iomem *reg = chip->base; unsigned int shift = (off & 7) * 4; u32 con; if (off < 8 && chip->chip.ngpio > 8) reg -= 4; if (samsung_gpio_is_cfg_special(cfg)) { cfg &= 0xf; cfg <<= shift; } con = __raw_readl(reg); con &= ~(0xf << shift); con |= cfg; __raw_writel(con, reg); return 0; } /* * samsung_gpio_getcfg_4bit - Samsung 4bit single register GPIO config read. * @chip: The gpio chip that is being configured. * @off: The offset for the GPIO being configured. * * The reverse of samsung_gpio_setcfg_4bit(), turning a gpio configuration * register setting into a value the software can use, such as could be passed * to samsung_gpio_setcfg_4bit(). * * @sa samsung_gpio_getcfg_2bit */ static unsigned samsung_gpio_getcfg_4bit(struct samsung_gpio_chip *chip, unsigned int off) { void __iomem *reg = chip->base; unsigned int shift = (off & 7) * 4; u32 con; if (off < 8 && chip->chip.ngpio > 8) reg -= 4; con = __raw_readl(reg); con >>= shift; con &= 0xf; /* this conversion works for IN and OUT as well as special mode */ return S3C_GPIO_SPECIAL(con); } #ifdef CONFIG_PLAT_S3C24XX /* * s3c24xx_gpio_setcfg_abank - S3C24XX style GPIO configuration (Bank A) * @chip: The gpio chip that is being configured. * @off: The offset for the GPIO being configured. * @cfg: The configuration value to set. * * This helper deal with the GPIO cases where the control register * has one bit of configuration for the gpio, where setting the bit * means the pin is in special function mode and unset means output. */ static int s3c24xx_gpio_setcfg_abank(struct samsung_gpio_chip *chip, unsigned int off, unsigned int cfg) { void __iomem *reg = chip->base; unsigned int shift = off; u32 con; if (samsung_gpio_is_cfg_special(cfg)) { cfg &= 0xf; /* Map output to 0, and SFN2 to 1 */ cfg -= 1; if (cfg > 1) return -EINVAL; cfg <<= shift; } con = __raw_readl(reg); con &= ~(0x1 << shift); con |= cfg; __raw_writel(con, reg); return 0; } /* * s3c24xx_gpio_getcfg_abank - S3C24XX style GPIO configuration read (Bank A) * @chip: The gpio chip that is being configured. * @off: The offset for the GPIO being configured. * * The reverse of s3c24xx_gpio_setcfg_abank() turning an GPIO into a usable * GPIO configuration value. * * @sa samsung_gpio_getcfg_2bit * @sa samsung_gpio_getcfg_4bit */ static unsigned s3c24xx_gpio_getcfg_abank(struct samsung_gpio_chip *chip, unsigned int off) { u32 con; con = __raw_readl(chip->base); con >>= off; con &= 1; con++; return S3C_GPIO_SFN(con); } #endif #if defined(CONFIG_CPU_S5P6440) || defined(CONFIG_CPU_S5P6450) static int s5p64x0_gpio_setcfg_rbank(struct samsung_gpio_chip *chip, unsigned int off, unsigned int cfg) { void __iomem *reg = chip->base; unsigned int shift; u32 con; switch (off) { case 0: case 1: case 2: case 3: case 4: case 5: shift = (off & 7) * 4; reg -= 4; break; case 6: shift = ((off + 1) & 7) * 4; reg -= 4; default: shift = ((off + 1) & 7) * 4; break; } if (samsung_gpio_is_cfg_special(cfg)) { cfg &= 0xf; cfg <<= shift; } con = __raw_readl(reg); con &= ~(0xf << shift); con |= cfg; __raw_writel(con, reg); return 0; } #endif static void __init samsung_gpiolib_set_cfg(struct samsung_gpio_cfg *chipcfg, int nr_chips) { for (; nr_chips > 0; nr_chips--, chipcfg++) { if (!chipcfg->set_config) chipcfg->set_config = samsung_gpio_setcfg_4bit; if (!chipcfg->get_config) chipcfg->get_config = samsung_gpio_getcfg_4bit; if (!chipcfg->set_pull) chipcfg->set_pull = samsung_gpio_setpull_updown; if (!chipcfg->get_pull) chipcfg->get_pull = samsung_gpio_getpull_updown; } } struct samsung_gpio_cfg s3c24xx_gpiocfg_default = { .set_config = samsung_gpio_setcfg_2bit, .get_config = samsung_gpio_getcfg_2bit, }; #ifdef CONFIG_PLAT_S3C24XX static struct samsung_gpio_cfg s3c24xx_gpiocfg_banka = { .set_config = s3c24xx_gpio_setcfg_abank, .get_config = s3c24xx_gpio_getcfg_abank, }; #endif #if defined(CONFIG_ARCH_EXYNOS4) || defined(CONFIG_ARCH_EXYNOS5) static struct samsung_gpio_cfg exynos_gpio_cfg = { .set_pull = exynos_gpio_setpull, .get_pull = exynos_gpio_getpull, .set_config = samsung_gpio_setcfg_4bit, .get_config = samsung_gpio_getcfg_4bit, }; #endif #if defined(CONFIG_CPU_S5P6440) || defined(CONFIG_CPU_S5P6450) static struct samsung_gpio_cfg s5p64x0_gpio_cfg_rbank = { .cfg_eint = 0x3, .set_config = s5p64x0_gpio_setcfg_rbank, .get_config = samsung_gpio_getcfg_4bit, .set_pull = samsung_gpio_setpull_updown, .get_pull = samsung_gpio_getpull_updown, }; #endif static struct samsung_gpio_cfg samsung_gpio_cfgs[] = { [0] = { .cfg_eint = 0x0, }, [1] = { .cfg_eint = 0x3, }, [2] = { .cfg_eint = 0x7, }, [3] = { .cfg_eint = 0xF, }, [4] = { .cfg_eint = 0x0, .set_config = samsung_gpio_setcfg_2bit, .get_config = samsung_gpio_getcfg_2bit, }, [5] = { .cfg_eint = 0x2, .set_config = samsung_gpio_setcfg_2bit, .get_config = samsung_gpio_getcfg_2bit, }, [6] = { .cfg_eint = 0x3, .set_config = samsung_gpio_setcfg_2bit, .get_config = samsung_gpio_getcfg_2bit, }, [7] = { .set_config = samsung_gpio_setcfg_2bit, .get_config = samsung_gpio_getcfg_2bit, }, [8] = { .set_pull = exynos_gpio_setpull, .get_pull = exynos_gpio_getpull, }, [9] = { .cfg_eint = 0x3, .set_pull = exynos_gpio_setpull, .get_pull = exynos_gpio_getpull, } }; /* * Default routines for controlling GPIO, based on the original S3C24XX * GPIO functions which deal with the case where each gpio bank of the * chip is as following: * * base + 0x00: Control register, 2 bits per gpio * gpio n: 2 bits starting at (2*n) * 00 = input, 01 = output, others mean special-function * base + 0x04: Data register, 1 bit per gpio * bit n: data bit n */ static int samsung_gpiolib_2bit_input(struct gpio_chip *chip, unsigned offset) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; unsigned long flags; unsigned long con; samsung_gpio_lock(ourchip, flags); con = __raw_readl(base + 0x00); con &= ~(3 << (offset * 2)); __raw_writel(con, base + 0x00); samsung_gpio_unlock(ourchip, flags); return 0; } static int samsung_gpiolib_2bit_output(struct gpio_chip *chip, unsigned offset, int value) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; unsigned long flags; unsigned long dat; unsigned long con; samsung_gpio_lock(ourchip, flags); dat = __raw_readl(base + 0x04); dat &= ~(1 << offset); if (value) dat |= 1 << offset; __raw_writel(dat, base + 0x04); con = __raw_readl(base + 0x00); con &= ~(3 << (offset * 2)); con |= 1 << (offset * 2); __raw_writel(con, base + 0x00); __raw_writel(dat, base + 0x04); samsung_gpio_unlock(ourchip, flags); return 0; } /* * The samsung_gpiolib_4bit routines are to control the gpio banks where * the gpio configuration register (GPxCON) has 4 bits per GPIO, as the * following example: * * base + 0x00: Control register, 4 bits per gpio * gpio n: 4 bits starting at (4*n) * 0000 = input, 0001 = output, others mean special-function * base + 0x04: Data register, 1 bit per gpio * bit n: data bit n * * Note, since the data register is one bit per gpio and is at base + 0x4 * we can use samsung_gpiolib_get and samsung_gpiolib_set to change the * state of the output. */ static int samsung_gpiolib_4bit_input(struct gpio_chip *chip, unsigned int offset) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; unsigned long con; con = __raw_readl(base + GPIOCON_OFF); con &= ~(0xf << con_4bit_shift(offset)); __raw_writel(con, base + GPIOCON_OFF); gpio_dbg("%s: %p: CON now %08lx\n", __func__, base, con); return 0; } static int samsung_gpiolib_4bit_output(struct gpio_chip *chip, unsigned int offset, int value) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; unsigned long con; unsigned long dat; con = __raw_readl(base + GPIOCON_OFF); con &= ~(0xf << con_4bit_shift(offset)); con |= 0x1 << con_4bit_shift(offset); dat = __raw_readl(base + GPIODAT_OFF); if (value) dat |= 1 << offset; else dat &= ~(1 << offset); __raw_writel(dat, base + GPIODAT_OFF); __raw_writel(con, base + GPIOCON_OFF); __raw_writel(dat, base + GPIODAT_OFF); gpio_dbg("%s: %p: CON %08lx, DAT %08lx\n", __func__, base, con, dat); return 0; } /* * The next set of routines are for the case where the GPIO configuration * registers are 4 bits per GPIO but there is more than one register (the * bank has more than 8 GPIOs. * * This case is the similar to the 4 bit case, but the registers are as * follows: * * base + 0x00: Control register, 4 bits per gpio (lower 8 GPIOs) * gpio n: 4 bits starting at (4*n) * 0000 = input, 0001 = output, others mean special-function * base + 0x04: Control register, 4 bits per gpio (up to 8 additions GPIOs) * gpio n: 4 bits starting at (4*n) * 0000 = input, 0001 = output, others mean special-function * base + 0x08: Data register, 1 bit per gpio * bit n: data bit n * * To allow us to use the samsung_gpiolib_get and samsung_gpiolib_set * routines we store the 'base + 0x4' address so that these routines see * the data register at ourchip->base + 0x04. */ static int samsung_gpiolib_4bit2_input(struct gpio_chip *chip, unsigned int offset) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; void __iomem *regcon = base; unsigned long con; if (offset > 7) offset -= 8; else regcon -= 4; con = __raw_readl(regcon); con &= ~(0xf << con_4bit_shift(offset)); __raw_writel(con, regcon); gpio_dbg("%s: %p: CON %08lx\n", __func__, base, con); return 0; } static int samsung_gpiolib_4bit2_output(struct gpio_chip *chip, unsigned int offset, int value) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; void __iomem *regcon = base; unsigned long con; unsigned long dat; unsigned con_offset = offset; if (con_offset > 7) con_offset -= 8; else regcon -= 4; con = __raw_readl(regcon); con &= ~(0xf << con_4bit_shift(con_offset)); con |= 0x1 << con_4bit_shift(con_offset); dat = __raw_readl(base + GPIODAT_OFF); if (value) dat |= 1 << offset; else dat &= ~(1 << offset); __raw_writel(dat, base + GPIODAT_OFF); __raw_writel(con, regcon); __raw_writel(dat, base + GPIODAT_OFF); gpio_dbg("%s: %p: CON %08lx, DAT %08lx\n", __func__, base, con, dat); return 0; } #ifdef CONFIG_PLAT_S3C24XX /* The next set of routines are for the case of s3c24xx bank a */ static int s3c24xx_gpiolib_banka_input(struct gpio_chip *chip, unsigned offset) { return -EINVAL; } static int s3c24xx_gpiolib_banka_output(struct gpio_chip *chip, unsigned offset, int value) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; unsigned long flags; unsigned long dat; unsigned long con; local_irq_save(flags); con = __raw_readl(base + 0x00); dat = __raw_readl(base + 0x04); dat &= ~(1 << offset); if (value) dat |= 1 << offset; __raw_writel(dat, base + 0x04); con &= ~(1 << offset); __raw_writel(con, base + 0x00); __raw_writel(dat, base + 0x04); local_irq_restore(flags); return 0; } #endif /* The next set of routines are for the case of s5p64x0 bank r */ static int s5p64x0_gpiolib_rbank_input(struct gpio_chip *chip, unsigned int offset) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; void __iomem *regcon = base; unsigned long con; unsigned long flags; switch (offset) { case 6: offset += 1; case 0: case 1: case 2: case 3: case 4: case 5: regcon -= 4; break; default: offset -= 7; break; } samsung_gpio_lock(ourchip, flags); con = __raw_readl(regcon); con &= ~(0xf << con_4bit_shift(offset)); __raw_writel(con, regcon); samsung_gpio_unlock(ourchip, flags); return 0; } static int s5p64x0_gpiolib_rbank_output(struct gpio_chip *chip, unsigned int offset, int value) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; void __iomem *regcon = base; unsigned long con; unsigned long dat; unsigned long flags; unsigned con_offset = offset; switch (con_offset) { case 6: con_offset += 1; case 0: case 1: case 2: case 3: case 4: case 5: regcon -= 4; break; default: con_offset -= 7; break; } samsung_gpio_lock(ourchip, flags); con = __raw_readl(regcon); con &= ~(0xf << con_4bit_shift(con_offset)); con |= 0x1 << con_4bit_shift(con_offset); dat = __raw_readl(base + GPIODAT_OFF); if (value) dat |= 1 << offset; else dat &= ~(1 << offset); __raw_writel(con, regcon); __raw_writel(dat, base + GPIODAT_OFF); samsung_gpio_unlock(ourchip, flags); return 0; } static void samsung_gpiolib_set(struct gpio_chip *chip, unsigned offset, int value) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); void __iomem *base = ourchip->base; unsigned long flags; unsigned long dat; samsung_gpio_lock(ourchip, flags); dat = __raw_readl(base + 0x04); dat &= ~(1 << offset); if (value) dat |= 1 << offset; __raw_writel(dat, base + 0x04); samsung_gpio_unlock(ourchip, flags); } static int samsung_gpiolib_get(struct gpio_chip *chip, unsigned offset) { struct samsung_gpio_chip *ourchip = to_samsung_gpio(chip); unsigned long val; val = __raw_readl(ourchip->base + 0x04); val >>= offset; val &= 1; return val; } /* * CONFIG_S3C_GPIO_TRACK enables the tracking of the s3c specific gpios * for use with the configuration calls, and other parts of the s3c gpiolib * support code. * * Not all s3c support code will need this, as some configurations of cpu * may only support one or two different configuration options and have an * easy gpio to samsung_gpio_chip mapping function. If this is the case, then * the machine support file should provide its own samsung_gpiolib_getchip() * and any other necessary functions. */ #ifdef CONFIG_S3C_GPIO_TRACK struct samsung_gpio_chip *s3c_gpios[S3C_GPIO_END]; static __init void s3c_gpiolib_track(struct samsung_gpio_chip *chip) { unsigned int gpn; int i; gpn = chip->chip.base; for (i = 0; i < chip->chip.ngpio; i++, gpn++) { BUG_ON(gpn >= ARRAY_SIZE(s3c_gpios)); s3c_gpios[gpn] = chip; } } #endif /* CONFIG_S3C_GPIO_TRACK */ /* * samsung_gpiolib_add() - add the Samsung gpio_chip. * @chip: The chip to register * * This is a wrapper to gpiochip_add() that takes our specific gpio chip * information and makes the necessary alterations for the platform and * notes the information for use with the configuration systems and any * other parts of the system. */ static void __init samsung_gpiolib_add(struct samsung_gpio_chip *chip) { struct gpio_chip *gc = &chip->chip; int ret; BUG_ON(!chip->base); BUG_ON(!gc->label); BUG_ON(!gc->ngpio); spin_lock_init(&chip->lock); if (!gc->direction_input) gc->direction_input = samsung_gpiolib_2bit_input; if (!gc->direction_output) gc->direction_output = samsung_gpiolib_2bit_output; if (!gc->set) gc->set = samsung_gpiolib_set; if (!gc->get) gc->get = samsung_gpiolib_get; #ifdef CONFIG_PM if (chip->pm != NULL) { if (!chip->pm->save || !chip->pm->resume) printk(KERN_ERR "gpio: %s has missing PM functions\n", gc->label); } else printk(KERN_ERR "gpio: %s has no PM function\n", gc->label); #endif /* gpiochip_add() prints own failure message on error. */ ret = gpiochip_add(gc); if (ret >= 0) s3c_gpiolib_track(chip); } static void __init s3c24xx_gpiolib_add_chips(struct samsung_gpio_chip *chip, int nr_chips, void __iomem *base) { int i; struct gpio_chip *gc = &chip->chip; for (i = 0 ; i < nr_chips; i++, chip++) { /* skip banks not present on SoC */ if (chip->chip.base >= S3C_GPIO_END) continue; if (!chip->config) chip->config = &s3c24xx_gpiocfg_default; if (!chip->pm) chip->pm = __gpio_pm(&samsung_gpio_pm_2bit); if ((base != NULL) && (chip->base == NULL)) chip->base = base + ((i) * 0x10); if (!gc->direction_input) gc->direction_input = samsung_gpiolib_2bit_input; if (!gc->direction_output) gc->direction_output = samsung_gpiolib_2bit_output; samsung_gpiolib_add(chip); } } static void __init samsung_gpiolib_add_2bit_chips(struct samsung_gpio_chip *chip, int nr_chips, void __iomem *base, unsigned int offset) { int i; for (i = 0 ; i < nr_chips; i++, chip++) { chip->chip.direction_input = samsung_gpiolib_2bit_input; chip->chip.direction_output = samsung_gpiolib_2bit_output; if (!chip->config) chip->config = &samsung_gpio_cfgs[7]; if (!chip->pm) chip->pm = __gpio_pm(&samsung_gpio_pm_2bit); if ((base != NULL) && (chip->base == NULL)) chip->base = base + ((i) * offset); samsung_gpiolib_add(chip); } } /* * samsung_gpiolib_add_4bit_chips - 4bit single register GPIO config. * @chip: The gpio chip that is being configured. * @nr_chips: The no of chips (gpio ports) for the GPIO being configured. * * This helper deal with the GPIO cases where the control register has 4 bits * of control per GPIO, generally in the form of: * 0000 = Input * 0001 = Output * others = Special functions (dependent on bank) * * Note, since the code to deal with the case where there are two control * registers instead of one, we do not have a separate set of function * (samsung_gpiolib_add_4bit2_chips)for each case. */ static void __init samsung_gpiolib_add_4bit_chips(struct samsung_gpio_chip *chip, int nr_chips, void __iomem *base) { int i; for (i = 0 ; i < nr_chips; i++, chip++) { chip->chip.direction_input = samsung_gpiolib_4bit_input; chip->chip.direction_output = samsung_gpiolib_4bit_output; if (!chip->config) chip->config = &samsung_gpio_cfgs[2]; if (!chip->pm) chip->pm = __gpio_pm(&samsung_gpio_pm_4bit); if ((base != NULL) && (chip->base == NULL)) chip->base = base + ((i) * 0x20); samsung_gpiolib_add(chip); } } static void __init samsung_gpiolib_add_4bit2_chips(struct samsung_gpio_chip *chip, int nr_chips) { for (; nr_chips > 0; nr_chips--, chip++) { chip->chip.direction_input = samsung_gpiolib_4bit2_input; chip->chip.direction_output = samsung_gpiolib_4bit2_output; if (!chip->config) chip->config = &samsung_gpio_cfgs[2]; if (!chip->pm) chip->pm = __gpio_pm(&samsung_gpio_pm_4bit); samsung_gpiolib_add(chip); } } static void __init s5p64x0_gpiolib_add_rbank(struct samsung_gpio_chip *chip, int nr_chips) { for (; nr_chips > 0; nr_chips--, chip++) { chip->chip.direction_input = s5p64x0_gpiolib_rbank_input; chip->chip.direction_output = s5p64x0_gpiolib_rbank_output; if (!chip->pm) chip->pm = __gpio_pm(&samsung_gpio_pm_4bit); samsung_gpiolib_add(chip); } } int samsung_gpiolib_to_irq(struct gpio_chip *chip, unsigned int offset) { struct samsung_gpio_chip *samsung_chip = container_of(chip, struct samsung_gpio_chip, chip); return samsung_chip->irq_base + offset; } #ifdef CONFIG_PLAT_S3C24XX static int s3c24xx_gpiolib_fbank_to_irq(struct gpio_chip *chip, unsigned offset) { if (offset < 4) return IRQ_EINT0 + offset; if (offset < 8) return IRQ_EINT4 + offset - 4; return -EINVAL; } #endif #ifdef CONFIG_PLAT_S3C64XX static int s3c64xx_gpiolib_mbank_to_irq(struct gpio_chip *chip, unsigned pin) { return pin < 5 ? IRQ_EINT(23) + pin : -ENXIO; } static int s3c64xx_gpiolib_lbank_to_irq(struct gpio_chip *chip, unsigned pin) { return pin >= 8 ? IRQ_EINT(16) + pin - 8 : -ENXIO; } #endif struct samsung_gpio_chip s3c24xx_gpios[] = { #ifdef CONFIG_PLAT_S3C24XX { .config = &s3c24xx_gpiocfg_banka, .chip = { .base = S3C2410_GPA(0), .owner = THIS_MODULE, .label = "GPIOA", .ngpio = 24, .direction_input = s3c24xx_gpiolib_banka_input, .direction_output = s3c24xx_gpiolib_banka_output, }, }, { .chip = { .base = S3C2410_GPB(0), .owner = THIS_MODULE, .label = "GPIOB", .ngpio = 16, }, }, { .chip = { .base = S3C2410_GPC(0), .owner = THIS_MODULE, .label = "GPIOC", .ngpio = 16, }, }, { .chip = { .base = S3C2410_GPD(0), .owner = THIS_MODULE, .label = "GPIOD", .ngpio = 16, }, }, { .chip = { .base = S3C2410_GPE(0), .label = "GPIOE", .owner = THIS_MODULE, .ngpio = 16, }, }, { .chip = { .base = S3C2410_GPF(0), .owner = THIS_MODULE, .label = "GPIOF", .ngpio = 8, .to_irq = s3c24xx_gpiolib_fbank_to_irq, }, }, { .irq_base = IRQ_EINT8, .chip = { .base = S3C2410_GPG(0), .owner = THIS_MODULE, .label = "GPIOG", .ngpio = 16, .to_irq = samsung_gpiolib_to_irq, }, }, { .chip = { .base = S3C2410_GPH(0), .owner = THIS_MODULE, .label = "GPIOH", .ngpio = 11, }, }, /* GPIOS for the S3C2443 and later devices. */ { .base = S3C2440_GPJCON, .chip = { .base = S3C2410_GPJ(0), .owner = THIS_MODULE, .label = "GPIOJ", .ngpio = 16, }, }, { .base = S3C2443_GPKCON, .chip = { .base = S3C2410_GPK(0), .owner = THIS_MODULE, .label = "GPIOK", .ngpio = 16, }, }, { .base = S3C2443_GPLCON, .chip = { .base = S3C2410_GPL(0), .owner = THIS_MODULE, .label = "GPIOL", .ngpio = 15, }, }, { .base = S3C2443_GPMCON, .chip = { .base = S3C2410_GPM(0), .owner = THIS_MODULE, .label = "GPIOM", .ngpio = 2, }, }, #endif }; /* * GPIO bank summary: * * Bank GPIOs Style SlpCon ExtInt Group * A 8 4Bit Yes 1 * B 7 4Bit Yes 1 * C 8 4Bit Yes 2 * D 5 4Bit Yes 3 * E 5 4Bit Yes None * F 16 2Bit Yes 4 [1] * G 7 4Bit Yes 5 * H 10 4Bit[2] Yes 6 * I 16 2Bit Yes None * J 12 2Bit Yes None * K 16 4Bit[2] No None * L 15 4Bit[2] No None * M 6 4Bit No IRQ_EINT * N 16 2Bit No IRQ_EINT * O 16 2Bit Yes 7 * P 15 2Bit Yes 8 * Q 9 2Bit Yes 9 * * [1] BANKF pins 14,15 do not form part of the external interrupt sources * [2] BANK has two control registers, GPxCON0 and GPxCON1 */ static struct samsung_gpio_chip s3c64xx_gpios_4bit[] = { #ifdef CONFIG_PLAT_S3C64XX { .chip = { .base = S3C64XX_GPA(0), .ngpio = S3C64XX_GPIO_A_NR, .label = "GPA", }, }, { .chip = { .base = S3C64XX_GPB(0), .ngpio = S3C64XX_GPIO_B_NR, .label = "GPB", }, }, { .chip = { .base = S3C64XX_GPC(0), .ngpio = S3C64XX_GPIO_C_NR, .label = "GPC", }, }, { .chip = { .base = S3C64XX_GPD(0), .ngpio = S3C64XX_GPIO_D_NR, .label = "GPD", }, }, { .config = &samsung_gpio_cfgs[0], .chip = { .base = S3C64XX_GPE(0), .ngpio = S3C64XX_GPIO_E_NR, .label = "GPE", }, }, { .base = S3C64XX_GPG_BASE, .chip = { .base = S3C64XX_GPG(0), .ngpio = S3C64XX_GPIO_G_NR, .label = "GPG", }, }, { .base = S3C64XX_GPM_BASE, .config = &samsung_gpio_cfgs[1], .chip = { .base = S3C64XX_GPM(0), .ngpio = S3C64XX_GPIO_M_NR, .label = "GPM", .to_irq = s3c64xx_gpiolib_mbank_to_irq, }, }, #endif }; static struct samsung_gpio_chip s3c64xx_gpios_4bit2[] = { #ifdef CONFIG_PLAT_S3C64XX { .base = S3C64XX_GPH_BASE + 0x4, .chip = { .base = S3C64XX_GPH(0), .ngpio = S3C64XX_GPIO_H_NR, .label = "GPH", }, }, { .base = S3C64XX_GPK_BASE + 0x4, .config = &samsung_gpio_cfgs[0], .chip = { .base = S3C64XX_GPK(0), .ngpio = S3C64XX_GPIO_K_NR, .label = "GPK", }, }, { .base = S3C64XX_GPL_BASE + 0x4, .config = &samsung_gpio_cfgs[1], .chip = { .base = S3C64XX_GPL(0), .ngpio = S3C64XX_GPIO_L_NR, .label = "GPL", .to_irq = s3c64xx_gpiolib_lbank_to_irq, }, }, #endif }; static struct samsung_gpio_chip s3c64xx_gpios_2bit[] = { #ifdef CONFIG_PLAT_S3C64XX { .base = S3C64XX_GPF_BASE, .config = &samsung_gpio_cfgs[6], .chip = { .base = S3C64XX_GPF(0), .ngpio = S3C64XX_GPIO_F_NR, .label = "GPF", }, }, { .config = &samsung_gpio_cfgs[7], .chip = { .base = S3C64XX_GPI(0), .ngpio = S3C64XX_GPIO_I_NR, .label = "GPI", }, }, { .config = &samsung_gpio_cfgs[7], .chip = { .base = S3C64XX_GPJ(0), .ngpio = S3C64XX_GPIO_J_NR, .label = "GPJ", }, }, { .config = &samsung_gpio_cfgs[6], .chip = { .base = S3C64XX_GPO(0), .ngpio = S3C64XX_GPIO_O_NR, .label = "GPO", }, }, { .config = &samsung_gpio_cfgs[6], .chip = { .base = S3C64XX_GPP(0), .ngpio = S3C64XX_GPIO_P_NR, .label = "GPP", }, }, { .config = &samsung_gpio_cfgs[6], .chip = { .base = S3C64XX_GPQ(0), .ngpio = S3C64XX_GPIO_Q_NR, .label = "GPQ", }, }, { .base = S3C64XX_GPN_BASE, .irq_base = IRQ_EINT(0), .config = &samsung_gpio_cfgs[5], .chip = { .base = S3C64XX_GPN(0), .ngpio = S3C64XX_GPIO_N_NR, .label = "GPN", .to_irq = samsung_gpiolib_to_irq, }, }, #endif }; /* * S5P6440 GPIO bank summary: * * Bank GPIOs Style SlpCon ExtInt Group * A 6 4Bit Yes 1 * B 7 4Bit Yes 1 * C 8 4Bit Yes 2 * F 2 2Bit Yes 4 [1] * G 7 4Bit Yes 5 * H 10 4Bit[2] Yes 6 * I 16 2Bit Yes None * J 12 2Bit Yes None * N 16 2Bit No IRQ_EINT * P 8 2Bit Yes 8 * R 15 4Bit[2] Yes 8 */ static struct samsung_gpio_chip s5p6440_gpios_4bit[] = { #ifdef CONFIG_CPU_S5P6440 { .chip = { .base = S5P6440_GPA(0), .ngpio = S5P6440_GPIO_A_NR, .label = "GPA", }, }, { .chip = { .base = S5P6440_GPB(0), .ngpio = S5P6440_GPIO_B_NR, .label = "GPB", }, }, { .chip = { .base = S5P6440_GPC(0), .ngpio = S5P6440_GPIO_C_NR, .label = "GPC", }, }, { .base = S5P64X0_GPG_BASE, .chip = { .base = S5P6440_GPG(0), .ngpio = S5P6440_GPIO_G_NR, .label = "GPG", }, }, #endif }; static struct samsung_gpio_chip s5p6440_gpios_4bit2[] = { #ifdef CONFIG_CPU_S5P6440 { .base = S5P64X0_GPH_BASE + 0x4, .chip = { .base = S5P6440_GPH(0), .ngpio = S5P6440_GPIO_H_NR, .label = "GPH", }, }, #endif }; static struct samsung_gpio_chip s5p6440_gpios_rbank[] = { #ifdef CONFIG_CPU_S5P6440 { .base = S5P64X0_GPR_BASE + 0x4, .config = &s5p64x0_gpio_cfg_rbank, .chip = { .base = S5P6440_GPR(0), .ngpio = S5P6440_GPIO_R_NR, .label = "GPR", }, }, #endif }; static struct samsung_gpio_chip s5p6440_gpios_2bit[] = { #ifdef CONFIG_CPU_S5P6440 { .base = S5P64X0_GPF_BASE, .config = &samsung_gpio_cfgs[6], .chip = { .base = S5P6440_GPF(0), .ngpio = S5P6440_GPIO_F_NR, .label = "GPF", }, }, { .base = S5P64X0_GPI_BASE, .config = &samsung_gpio_cfgs[4], .chip = { .base = S5P6440_GPI(0), .ngpio = S5P6440_GPIO_I_NR, .label = "GPI", }, }, { .base = S5P64X0_GPJ_BASE, .config = &samsung_gpio_cfgs[4], .chip = { .base = S5P6440_GPJ(0), .ngpio = S5P6440_GPIO_J_NR, .label = "GPJ", }, }, { .base = S5P64X0_GPN_BASE, .config = &samsung_gpio_cfgs[5], .chip = { .base = S5P6440_GPN(0), .ngpio = S5P6440_GPIO_N_NR, .label = "GPN", }, }, { .base = S5P64X0_GPP_BASE, .config = &samsung_gpio_cfgs[6], .chip = { .base = S5P6440_GPP(0), .ngpio = S5P6440_GPIO_P_NR, .label = "GPP", }, }, #endif }; /* * S5P6450 GPIO bank summary: * * Bank GPIOs Style SlpCon ExtInt Group * A 6 4Bit Yes 1 * B 7 4Bit Yes 1 * C 8 4Bit Yes 2 * D 8 4Bit Yes None * F 2 2Bit Yes None * G 14 4Bit[2] Yes 5 * H 10 4Bit[2] Yes 6 * I 16 2Bit Yes None * J 12 2Bit Yes None * K 5 4Bit Yes None * N 16 2Bit No IRQ_EINT * P 11 2Bit Yes 8 * Q 14 2Bit Yes None * R 15 4Bit[2] Yes None * S 8 2Bit Yes None * * [1] BANKF pins 14,15 do not form part of the external interrupt sources * [2] BANK has two control registers, GPxCON0 and GPxCON1 */ static struct samsung_gpio_chip s5p6450_gpios_4bit[] = { #ifdef CONFIG_CPU_S5P6450 { .chip = { .base = S5P6450_GPA(0), .ngpio = S5P6450_GPIO_A_NR, .label = "GPA", }, }, { .chip = { .base = S5P6450_GPB(0), .ngpio = S5P6450_GPIO_B_NR, .label = "GPB", }, }, { .chip = { .base = S5P6450_GPC(0), .ngpio = S5P6450_GPIO_C_NR, .label = "GPC", }, }, { .chip = { .base = S5P6450_GPD(0), .ngpio = S5P6450_GPIO_D_NR, .label = "GPD", }, }, { .base = S5P6450_GPK_BASE, .chip = { .base = S5P6450_GPK(0), .ngpio = S5P6450_GPIO_K_NR, .label = "GPK", }, }, #endif }; static struct samsung_gpio_chip s5p6450_gpios_4bit2[] = { #ifdef CONFIG_CPU_S5P6450 { .base = S5P64X0_GPG_BASE + 0x4, .chip = { .base = S5P6450_GPG(0), .ngpio = S5P6450_GPIO_G_NR, .label = "GPG", }, }, { .base = S5P64X0_GPH_BASE + 0x4, .chip = { .base = S5P6450_GPH(0), .ngpio = S5P6450_GPIO_H_NR, .label = "GPH", }, }, #endif }; static struct samsung_gpio_chip s5p6450_gpios_rbank[] = { #ifdef CONFIG_CPU_S5P6450 { .base = S5P64X0_GPR_BASE + 0x4, .config = &s5p64x0_gpio_cfg_rbank, .chip = { .base = S5P6450_GPR(0), .ngpio = S5P6450_GPIO_R_NR, .label = "GPR", }, }, #endif }; static struct samsung_gpio_chip s5p6450_gpios_2bit[] = { #ifdef CONFIG_CPU_S5P6450 { .base = S5P64X0_GPF_BASE, .config = &samsung_gpio_cfgs[6], .chip = { .base = S5P6450_GPF(0), .ngpio = S5P6450_GPIO_F_NR, .label = "GPF", }, }, { .base = S5P64X0_GPI_BASE, .config = &samsung_gpio_cfgs[4], .chip = { .base = S5P6450_GPI(0), .ngpio = S5P6450_GPIO_I_NR, .label = "GPI", }, }, { .base = S5P64X0_GPJ_BASE, .config = &samsung_gpio_cfgs[4], .chip = { .base = S5P6450_GPJ(0), .ngpio = S5P6450_GPIO_J_NR, .label = "GPJ", }, }, { .base = S5P64X0_GPN_BASE, .config = &samsung_gpio_cfgs[5], .chip = { .base = S5P6450_GPN(0), .ngpio = S5P6450_GPIO_N_NR, .label = "GPN", }, }, { .base = S5P64X0_GPP_BASE, .config = &samsung_gpio_cfgs[6], .chip = { .base = S5P6450_GPP(0), .ngpio = S5P6450_GPIO_P_NR, .label = "GPP", }, }, { .base = S5P6450_GPQ_BASE, .config = &samsung_gpio_cfgs[5], .chip = { .base = S5P6450_GPQ(0), .ngpio = S5P6450_GPIO_Q_NR, .label = "GPQ", }, }, { .base = S5P6450_GPS_BASE, .config = &samsung_gpio_cfgs[6], .chip = { .base = S5P6450_GPS(0), .ngpio = S5P6450_GPIO_S_NR, .label = "GPS", }, }, #endif }; /* * S5PC100 GPIO bank summary: * * Bank GPIOs Style INT Type * A0 8 4Bit GPIO_INT0 * A1 5 4Bit GPIO_INT1 * B 8 4Bit GPIO_INT2 * C 5 4Bit GPIO_INT3 * D 7 4Bit GPIO_INT4 * E0 8 4Bit GPIO_INT5 * E1 6 4Bit GPIO_INT6 * F0 8 4Bit GPIO_INT7 * F1 8 4Bit GPIO_INT8 * F2 8 4Bit GPIO_INT9 * F3 4 4Bit GPIO_INT10 * G0 8 4Bit GPIO_INT11 * G1 3 4Bit GPIO_INT12 * G2 7 4Bit GPIO_INT13 * G3 7 4Bit GPIO_INT14 * H0 8 4Bit WKUP_INT * H1 8 4Bit WKUP_INT * H2 8 4Bit WKUP_INT * H3 8 4Bit WKUP_INT * I 8 4Bit GPIO_INT15 * J0 8 4Bit GPIO_INT16 * J1 5 4Bit GPIO_INT17 * J2 8 4Bit GPIO_INT18 * J3 8 4Bit GPIO_INT19 * J4 4 4Bit GPIO_INT20 * K0 8 4Bit None * K1 6 4Bit None * K2 8 4Bit None * K3 8 4Bit None * L0 8 4Bit None * L1 8 4Bit None * L2 8 4Bit None * L3 8 4Bit None */ static struct samsung_gpio_chip s5pc100_gpios_4bit[] = { #ifdef CONFIG_CPU_S5PC100 { .chip = { .base = S5PC100_GPA0(0), .ngpio = S5PC100_GPIO_A0_NR, .label = "GPA0", }, }, { .chip = { .base = S5PC100_GPA1(0), .ngpio = S5PC100_GPIO_A1_NR, .label = "GPA1", }, }, { .chip = { .base = S5PC100_GPB(0), .ngpio = S5PC100_GPIO_B_NR, .label = "GPB", }, }, { .chip = { .base = S5PC100_GPC(0), .ngpio = S5PC100_GPIO_C_NR, .label = "GPC", }, }, { .chip = { .base = S5PC100_GPD(0), .ngpio = S5PC100_GPIO_D_NR, .label = "GPD", }, }, { .chip = { .base = S5PC100_GPE0(0), .ngpio = S5PC100_GPIO_E0_NR, .label = "GPE0", }, }, { .chip = { .base = S5PC100_GPE1(0), .ngpio = S5PC100_GPIO_E1_NR, .label = "GPE1", }, }, { .chip = { .base = S5PC100_GPF0(0), .ngpio = S5PC100_GPIO_F0_NR, .label = "GPF0", }, }, { .chip = { .base = S5PC100_GPF1(0), .ngpio = S5PC100_GPIO_F1_NR, .label = "GPF1", }, }, { .chip = { .base = S5PC100_GPF2(0), .ngpio = S5PC100_GPIO_F2_NR, .label = "GPF2", }, }, { .chip = { .base = S5PC100_GPF3(0), .ngpio = S5PC100_GPIO_F3_NR, .label = "GPF3", }, }, { .chip = { .base = S5PC100_GPG0(0), .ngpio = S5PC100_GPIO_G0_NR, .label = "GPG0", }, }, { .chip = { .base = S5PC100_GPG1(0), .ngpio = S5PC100_GPIO_G1_NR, .label = "GPG1", }, }, { .chip = { .base = S5PC100_GPG2(0), .ngpio = S5PC100_GPIO_G2_NR, .label = "GPG2", }, }, { .chip = { .base = S5PC100_GPG3(0), .ngpio = S5PC100_GPIO_G3_NR, .label = "GPG3", }, }, { .chip = { .base = S5PC100_GPI(0), .ngpio = S5PC100_GPIO_I_NR, .label = "GPI", }, }, { .chip = { .base = S5PC100_GPJ0(0), .ngpio = S5PC100_GPIO_J0_NR, .label = "GPJ0", }, }, { .chip = { .base = S5PC100_GPJ1(0), .ngpio = S5PC100_GPIO_J1_NR, .label = "GPJ1", }, }, { .chip = { .base = S5PC100_GPJ2(0), .ngpio = S5PC100_GPIO_J2_NR, .label = "GPJ2", }, }, { .chip = { .base = S5PC100_GPJ3(0), .ngpio = S5PC100_GPIO_J3_NR, .label = "GPJ3", }, }, { .chip = { .base = S5PC100_GPJ4(0), .ngpio = S5PC100_GPIO_J4_NR, .label = "GPJ4", }, }, { .chip = { .base = S5PC100_GPK0(0), .ngpio = S5PC100_GPIO_K0_NR, .label = "GPK0", }, }, { .chip = { .base = S5PC100_GPK1(0), .ngpio = S5PC100_GPIO_K1_NR, .label = "GPK1", }, }, { .chip = { .base = S5PC100_GPK2(0), .ngpio = S5PC100_GPIO_K2_NR, .label = "GPK2", }, }, { .chip = { .base = S5PC100_GPK3(0), .ngpio = S5PC100_GPIO_K3_NR, .label = "GPK3", }, }, { .chip = { .base = S5PC100_GPL0(0), .ngpio = S5PC100_GPIO_L0_NR, .label = "GPL0", }, }, { .chip = { .base = S5PC100_GPL1(0), .ngpio = S5PC100_GPIO_L1_NR, .label = "GPL1", }, }, { .chip = { .base = S5PC100_GPL2(0), .ngpio = S5PC100_GPIO_L2_NR, .label = "GPL2", }, }, { .chip = { .base = S5PC100_GPL3(0), .ngpio = S5PC100_GPIO_L3_NR, .label = "GPL3", }, }, { .chip = { .base = S5PC100_GPL4(0), .ngpio = S5PC100_GPIO_L4_NR, .label = "GPL4", }, }, { .base = (S5P_VA_GPIO + 0xC00), .irq_base = IRQ_EINT(0), .chip = { .base = S5PC100_GPH0(0), .ngpio = S5PC100_GPIO_H0_NR, .label = "GPH0", .to_irq = samsung_gpiolib_to_irq, }, }, { .base = (S5P_VA_GPIO + 0xC20), .irq_base = IRQ_EINT(8), .chip = { .base = S5PC100_GPH1(0), .ngpio = S5PC100_GPIO_H1_NR, .label = "GPH1", .to_irq = samsung_gpiolib_to_irq, }, }, { .base = (S5P_VA_GPIO + 0xC40), .irq_base = IRQ_EINT(16), .chip = { .base = S5PC100_GPH2(0), .ngpio = S5PC100_GPIO_H2_NR, .label = "GPH2", .to_irq = samsung_gpiolib_to_irq, }, }, { .base = (S5P_VA_GPIO + 0xC60), .irq_base = IRQ_EINT(24), .chip = { .base = S5PC100_GPH3(0), .ngpio = S5PC100_GPIO_H3_NR, .label = "GPH3", .to_irq = samsung_gpiolib_to_irq, }, }, #endif }; /* * Followings are the gpio banks in S5PV210/S5PC110 * * The 'config' member when left to NULL, is initialized to the default * structure samsung_gpio_cfgs[3] in the init function below. * * The 'base' member is also initialized in the init function below. * Note: The initialization of 'base' member of samsung_gpio_chip structure * uses the above macro and depends on the banks being listed in order here. */ static struct samsung_gpio_chip s5pv210_gpios_4bit[] = { #ifdef CONFIG_CPU_S5PV210 { .chip = { .base = S5PV210_GPA0(0), .ngpio = S5PV210_GPIO_A0_NR, .label = "GPA0", }, }, { .chip = { .base = S5PV210_GPA1(0), .ngpio = S5PV210_GPIO_A1_NR, .label = "GPA1", }, }, { .chip = { .base = S5PV210_GPB(0), .ngpio = S5PV210_GPIO_B_NR, .label = "GPB", }, }, { .chip = { .base = S5PV210_GPC0(0), .ngpio = S5PV210_GPIO_C0_NR, .label = "GPC0", }, }, { .chip = { .base = S5PV210_GPC1(0), .ngpio = S5PV210_GPIO_C1_NR, .label = "GPC1", }, }, { .chip = { .base = S5PV210_GPD0(0), .ngpio = S5PV210_GPIO_D0_NR, .label = "GPD0", }, }, { .chip = { .base = S5PV210_GPD1(0), .ngpio = S5PV210_GPIO_D1_NR, .label = "GPD1", }, }, { .chip = { .base = S5PV210_GPE0(0), .ngpio = S5PV210_GPIO_E0_NR, .label = "GPE0", }, }, { .chip = { .base = S5PV210_GPE1(0), .ngpio = S5PV210_GPIO_E1_NR, .label = "GPE1", }, }, { .chip = { .base = S5PV210_GPF0(0), .ngpio = S5PV210_GPIO_F0_NR, .label = "GPF0", }, }, { .chip = { .base = S5PV210_GPF1(0), .ngpio = S5PV210_GPIO_F1_NR, .label = "GPF1", }, }, { .chip = { .base = S5PV210_GPF2(0), .ngpio = S5PV210_GPIO_F2_NR, .label = "GPF2", }, }, { .chip = { .base = S5PV210_GPF3(0), .ngpio = S5PV210_GPIO_F3_NR, .label = "GPF3", }, }, { .chip = { .base = S5PV210_GPG0(0), .ngpio = S5PV210_GPIO_G0_NR, .label = "GPG0", }, }, { .chip = { .base = S5PV210_GPG1(0), .ngpio = S5PV210_GPIO_G1_NR, .label = "GPG1", }, }, { .chip = { .base = S5PV210_GPG2(0), .ngpio = S5PV210_GPIO_G2_NR, .label = "GPG2", }, }, { .chip = { .base = S5PV210_GPG3(0), .ngpio = S5PV210_GPIO_G3_NR, .label = "GPG3", }, }, { .chip = { .base = S5PV210_GPI(0), .ngpio = S5PV210_GPIO_I_NR, .label = "GPI", }, }, { .chip = { .base = S5PV210_GPJ0(0), .ngpio = S5PV210_GPIO_J0_NR, .label = "GPJ0", }, }, { .chip = { .base = S5PV210_GPJ1(0), .ngpio = S5PV210_GPIO_J1_NR, .label = "GPJ1", }, }, { .chip = { .base = S5PV210_GPJ2(0), .ngpio = S5PV210_GPIO_J2_NR, .label = "GPJ2", }, }, { .chip = { .base = S5PV210_GPJ3(0), .ngpio = S5PV210_GPIO_J3_NR, .label = "GPJ3", }, }, { .chip = { .base = S5PV210_GPJ4(0), .ngpio = S5PV210_GPIO_J4_NR, .label = "GPJ4", }, }, { .chip = { .base = S5PV210_MP01(0), .ngpio = S5PV210_GPIO_MP01_NR, .label = "MP01", }, }, { .chip = { .base = S5PV210_MP02(0), .ngpio = S5PV210_GPIO_MP02_NR, .label = "MP02", }, }, { .chip = { .base = S5PV210_MP03(0), .ngpio = S5PV210_GPIO_MP03_NR, .label = "MP03", }, }, { .chip = { .base = S5PV210_MP04(0), .ngpio = S5PV210_GPIO_MP04_NR, .label = "MP04", }, }, { .chip = { .base = S5PV210_MP05(0), .ngpio = S5PV210_GPIO_MP05_NR, .label = "MP05", }, }, { .base = (S5P_VA_GPIO + 0xC00), .irq_base = IRQ_EINT(0), .chip = { .base = S5PV210_GPH0(0), .ngpio = S5PV210_GPIO_H0_NR, .label = "GPH0", .to_irq = samsung_gpiolib_to_irq, }, }, { .base = (S5P_VA_GPIO + 0xC20), .irq_base = IRQ_EINT(8), .chip = { .base = S5PV210_GPH1(0), .ngpio = S5PV210_GPIO_H1_NR, .label = "GPH1", .to_irq = samsung_gpiolib_to_irq, }, }, { .base = (S5P_VA_GPIO + 0xC40), .irq_base = IRQ_EINT(16), .chip = { .base = S5PV210_GPH2(0), .ngpio = S5PV210_GPIO_H2_NR, .label = "GPH2", .to_irq = samsung_gpiolib_to_irq, }, }, { .base = (S5P_VA_GPIO + 0xC60), .irq_base = IRQ_EINT(24), .chip = { .base = S5PV210_GPH3(0), .ngpio = S5PV210_GPIO_H3_NR, .label = "GPH3", .to_irq = samsung_gpiolib_to_irq, }, }, #endif }; /* * Followings are the gpio banks in EXYNOS SoCs * * The 'config' member when left to NULL, is initialized to the default * structure exynos_gpio_cfg in the init function below. * * The 'base' member is also initialized in the init function below. * Note: The initialization of 'base' member of samsung_gpio_chip structure * uses the above macro and depends on the banks being listed in order here. */ #ifdef CONFIG_ARCH_EXYNOS4 static struct samsung_gpio_chip exynos4_gpios_1[] = { { .chip = { .base = EXYNOS4_GPA0(0), .ngpio = EXYNOS4_GPIO_A0_NR, .label = "GPA0", }, }, { .chip = { .base = EXYNOS4_GPA1(0), .ngpio = EXYNOS4_GPIO_A1_NR, .label = "GPA1", }, }, { .chip = { .base = EXYNOS4_GPB(0), .ngpio = EXYNOS4_GPIO_B_NR, .label = "GPB", }, }, { .chip = { .base = EXYNOS4_GPC0(0), .ngpio = EXYNOS4_GPIO_C0_NR, .label = "GPC0", }, }, { .chip = { .base = EXYNOS4_GPC1(0), .ngpio = EXYNOS4_GPIO_C1_NR, .label = "GPC1", }, }, { .chip = { .base = EXYNOS4_GPD0(0), .ngpio = EXYNOS4_GPIO_D0_NR, .label = "GPD0", }, }, { .chip = { .base = EXYNOS4_GPD1(0), .ngpio = EXYNOS4_GPIO_D1_NR, .label = "GPD1", }, }, { .chip = { .base = EXYNOS4_GPE0(0), .ngpio = EXYNOS4_GPIO_E0_NR, .label = "GPE0", }, }, { .chip = { .base = EXYNOS4_GPE1(0), .ngpio = EXYNOS4_GPIO_E1_NR, .label = "GPE1", }, }, { .chip = { .base = EXYNOS4_GPE2(0), .ngpio = EXYNOS4_GPIO_E2_NR, .label = "GPE2", }, }, { .chip = { .base = EXYNOS4_GPE3(0), .ngpio = EXYNOS4_GPIO_E3_NR, .label = "GPE3", }, }, { .chip = { .base = EXYNOS4_GPE4(0), .ngpio = EXYNOS4_GPIO_E4_NR, .label = "GPE4", }, }, { .chip = { .base = EXYNOS4_GPF0(0), .ngpio = EXYNOS4_GPIO_F0_NR, .label = "GPF0", }, }, { .chip = { .base = EXYNOS4_GPF1(0), .ngpio = EXYNOS4_GPIO_F1_NR, .label = "GPF1", }, }, { .chip = { .base = EXYNOS4_GPF2(0), .ngpio = EXYNOS4_GPIO_F2_NR, .label = "GPF2", }, }, { .chip = { .base = EXYNOS4_GPF3(0), .ngpio = EXYNOS4_GPIO_F3_NR, .label = "GPF3", }, }, }; #endif #ifdef CONFIG_ARCH_EXYNOS4 static struct samsung_gpio_chip exynos4_gpios_2[] = { { .chip = { .base = EXYNOS4_GPJ0(0), .ngpio = EXYNOS4_GPIO_J0_NR, .label = "GPJ0", }, }, { .chip = { .base = EXYNOS4_GPJ1(0), .ngpio = EXYNOS4_GPIO_J1_NR, .label = "GPJ1", }, }, { .chip = { .base = EXYNOS4_GPK0(0), .ngpio = EXYNOS4_GPIO_K0_NR, .label = "GPK0", }, }, { .chip = { .base = EXYNOS4_GPK1(0), .ngpio = EXYNOS4_GPIO_K1_NR, .label = "GPK1", }, }, { .chip = { .base = EXYNOS4_GPK2(0), .ngpio = EXYNOS4_GPIO_K2_NR, .label = "GPK2", }, }, { .chip = { .base = EXYNOS4_GPK3(0), .ngpio = EXYNOS4_GPIO_K3_NR, .label = "GPK3", }, }, { .chip = { .base = EXYNOS4_GPL0(0), .ngpio = EXYNOS4_GPIO_L0_NR, .label = "GPL0", }, }, { .chip = { .base = EXYNOS4_GPL1(0), .ngpio = EXYNOS4_GPIO_L1_NR, .label = "GPL1", }, }, { .chip = { .base = EXYNOS4_GPL2(0), .ngpio = EXYNOS4_GPIO_L2_NR, .label = "GPL2", }, }, { .config = &samsung_gpio_cfgs[8], .chip = { .base = EXYNOS4_GPY0(0), .ngpio = EXYNOS4_GPIO_Y0_NR, .label = "GPY0", }, }, { .config = &samsung_gpio_cfgs[8], .chip = { .base = EXYNOS4_GPY1(0), .ngpio = EXYNOS4_GPIO_Y1_NR, .label = "GPY1", }, }, { .config = &samsung_gpio_cfgs[8], .chip = { .base = EXYNOS4_GPY2(0), .ngpio = EXYNOS4_GPIO_Y2_NR, .label = "GPY2", }, }, { .config = &samsung_gpio_cfgs[8], .chip = { .base = EXYNOS4_GPY3(0), .ngpio = EXYNOS4_GPIO_Y3_NR, .label = "GPY3", }, }, { .config = &samsung_gpio_cfgs[8], .chip = { .base = EXYNOS4_GPY4(0), .ngpio = EXYNOS4_GPIO_Y4_NR, .label = "GPY4", }, }, { .config = &samsung_gpio_cfgs[8], .chip = { .base = EXYNOS4_GPY5(0), .ngpio = EXYNOS4_GPIO_Y5_NR, .label = "GPY5", }, }, { .config = &samsung_gpio_cfgs[8], .chip = { .base = EXYNOS4_GPY6(0), .ngpio = EXYNOS4_GPIO_Y6_NR, .label = "GPY6", }, }, { .config = &samsung_gpio_cfgs[9], .irq_base = IRQ_EINT(0), .chip = { .base = EXYNOS4_GPX0(0), .ngpio = EXYNOS4_GPIO_X0_NR, .label = "GPX0", .to_irq = samsung_gpiolib_to_irq, }, }, { .config = &samsung_gpio_cfgs[9], .irq_base = IRQ_EINT(8), .chip = { .base = EXYNOS4_GPX1(0), .ngpio = EXYNOS4_GPIO_X1_NR, .label = "GPX1", .to_irq = samsung_gpiolib_to_irq, }, }, { .config = &samsung_gpio_cfgs[9], .irq_base = IRQ_EINT(16), .chip = { .base = EXYNOS4_GPX2(0), .ngpio = EXYNOS4_GPIO_X2_NR, .label = "GPX2", .to_irq = samsung_gpiolib_to_irq, }, }, { .config = &samsung_gpio_cfgs[9], .irq_base = IRQ_EINT(24), .chip = { .base = EXYNOS4_GPX3(0), .ngpio = EXYNOS4_GPIO_X3_NR, .label = "GPX3", .to_irq = samsung_gpiolib_to_irq, }, }, }; #endif #ifdef CONFIG_ARCH_EXYNOS4 static struct samsung_gpio_chip exynos4_gpios_3[] = { { .chip = { .base = EXYNOS4_GPZ(0), .ngpio = EXYNOS4_GPIO_Z_NR, .label = "GPZ", }, }, }; #endif #ifdef CONFIG_ARCH_EXYNOS5 static struct samsung_gpio_chip exynos5_gpios_1[] = { { .chip = { .base = EXYNOS5_GPA0(0), .ngpio = EXYNOS5_GPIO_A0_NR, .label = "GPA0", }, }, { .chip = { .base = EXYNOS5_GPA1(0), .ngpio = EXYNOS5_GPIO_A1_NR, .label = "GPA1", }, }, { .chip = { .base = EXYNOS5_GPA2(0), .ngpio = EXYNOS5_GPIO_A2_NR, .label = "GPA2", }, }, { .chip = { .base = EXYNOS5_GPB0(0), .ngpio = EXYNOS5_GPIO_B0_NR, .label = "GPB0", }, }, { .chip = { .base = EXYNOS5_GPB1(0), .ngpio = EXYNOS5_GPIO_B1_NR, .label = "GPB1", }, }, { .chip = { .base = EXYNOS5_GPB2(0), .ngpio = EXYNOS5_GPIO_B2_NR, .label = "GPB2", }, }, { .chip = { .base = EXYNOS5_GPB3(0), .ngpio = EXYNOS5_GPIO_B3_NR, .label = "GPB3", }, }, { .chip = { .base = EXYNOS5_GPC0(0), .ngpio = EXYNOS5_GPIO_C0_NR, .label = "GPC0", }, }, { .chip = { .base = EXYNOS5_GPC1(0), .ngpio = EXYNOS5_GPIO_C1_NR, .label = "GPC1", }, }, { .chip = { .base = EXYNOS5_GPC2(0), .ngpio = EXYNOS5_GPIO_C2_NR, .label = "GPC2", }, }, { .chip = { .base = EXYNOS5_GPC3(0), .ngpio = EXYNOS5_GPIO_C3_NR, .label = "GPC3", }, }, { .chip = { .base = EXYNOS5_GPD0(0), .ngpio = EXYNOS5_GPIO_D0_NR, .label = "GPD0", }, }, { .chip = { .base = EXYNOS5_GPD1(0), .ngpio = EXYNOS5_GPIO_D1_NR, .label = "GPD1", }, }, { .chip = { .base = EXYNOS5_GPY0(0), .ngpio = EXYNOS5_GPIO_Y0_NR, .label = "GPY0", }, }, { .chip = { .base = EXYNOS5_GPY1(0), .ngpio = EXYNOS5_GPIO_Y1_NR, .label = "GPY1", }, }, { .chip = { .base = EXYNOS5_GPY2(0), .ngpio = EXYNOS5_GPIO_Y2_NR, .label = "GPY2", }, }, { .chip = { .base = EXYNOS5_GPY3(0), .ngpio = EXYNOS5_GPIO_Y3_NR, .label = "GPY3", }, }, { .chip = { .base = EXYNOS5_GPY4(0), .ngpio = EXYNOS5_GPIO_Y4_NR, .label = "GPY4", }, }, { .chip = { .base = EXYNOS5_GPY5(0), .ngpio = EXYNOS5_GPIO_Y5_NR, .label = "GPY5", }, }, { .chip = { .base = EXYNOS5_GPY6(0), .ngpio = EXYNOS5_GPIO_Y6_NR, .label = "GPY6", }, }, { .config = &samsung_gpio_cfgs[9], .irq_base = IRQ_EINT(0), .chip = { .base = EXYNOS5_GPX0(0), .ngpio = EXYNOS5_GPIO_X0_NR, .label = "GPX0", .to_irq = samsung_gpiolib_to_irq, }, }, { .config = &samsung_gpio_cfgs[9], .irq_base = IRQ_EINT(8), .chip = { .base = EXYNOS5_GPX1(0), .ngpio = EXYNOS5_GPIO_X1_NR, .label = "GPX1", .to_irq = samsung_gpiolib_to_irq, }, }, { .config = &samsung_gpio_cfgs[9], .irq_base = IRQ_EINT(16), .chip = { .base = EXYNOS5_GPX2(0), .ngpio = EXYNOS5_GPIO_X2_NR, .label = "GPX2", .to_irq = samsung_gpiolib_to_irq, }, }, { .config = &samsung_gpio_cfgs[9], .irq_base = IRQ_EINT(24), .chip = { .base = EXYNOS5_GPX3(0), .ngpio = EXYNOS5_GPIO_X3_NR, .label = "GPX3", .to_irq = samsung_gpiolib_to_irq, }, }, }; #endif #ifdef CONFIG_ARCH_EXYNOS5 static struct samsung_gpio_chip exynos5_gpios_2[] = { { .chip = { .base = EXYNOS5_GPE0(0), .ngpio = EXYNOS5_GPIO_E0_NR, .label = "GPE0", }, }, { .chip = { .base = EXYNOS5_GPE1(0), .ngpio = EXYNOS5_GPIO_E1_NR, .label = "GPE1", }, }, { .chip = { .base = EXYNOS5_GPF0(0), .ngpio = EXYNOS5_GPIO_F0_NR, .label = "GPF0", }, }, { .chip = { .base = EXYNOS5_GPF1(0), .ngpio = EXYNOS5_GPIO_F1_NR, .label = "GPF1", }, }, { .chip = { .base = EXYNOS5_GPG0(0), .ngpio = EXYNOS5_GPIO_G0_NR, .label = "GPG0", }, }, { .chip = { .base = EXYNOS5_GPG1(0), .ngpio = EXYNOS5_GPIO_G1_NR, .label = "GPG1", }, }, { .chip = { .base = EXYNOS5_GPG2(0), .ngpio = EXYNOS5_GPIO_G2_NR, .label = "GPG2", }, }, { .chip = { .base = EXYNOS5_GPH0(0), .ngpio = EXYNOS5_GPIO_H0_NR, .label = "GPH0", }, }, { .chip = { .base = EXYNOS5_GPH1(0), .ngpio = EXYNOS5_GPIO_H1_NR, .label = "GPH1", }, }, }; #endif #ifdef CONFIG_ARCH_EXYNOS5 static struct samsung_gpio_chip exynos5_gpios_3[] = { { .chip = { .base = EXYNOS5_GPV0(0), .ngpio = EXYNOS5_GPIO_V0_NR, .label = "GPV0", }, }, { .chip = { .base = EXYNOS5_GPV1(0), .ngpio = EXYNOS5_GPIO_V1_NR, .label = "GPV1", }, }, { .chip = { .base = EXYNOS5_GPV2(0), .ngpio = EXYNOS5_GPIO_V2_NR, .label = "GPV2", }, }, { .chip = { .base = EXYNOS5_GPV3(0), .ngpio = EXYNOS5_GPIO_V3_NR, .label = "GPV3", }, }, { .chip = { .base = EXYNOS5_GPV4(0), .ngpio = EXYNOS5_GPIO_V4_NR, .label = "GPV4", }, }, }; #endif #ifdef CONFIG_ARCH_EXYNOS5 static struct samsung_gpio_chip exynos5_gpios_4[] = { { .chip = { .base = EXYNOS5_GPZ(0), .ngpio = EXYNOS5_GPIO_Z_NR, .label = "GPZ", }, }, }; #endif #if defined(CONFIG_ARCH_EXYNOS) && defined(CONFIG_OF) static int exynos_gpio_xlate(struct gpio_chip *gc, const struct of_phandle_args *gpiospec, u32 *flags) { unsigned int pin; if (WARN_ON(gc->of_gpio_n_cells < 4)) return -EINVAL; if (WARN_ON(gpiospec->args_count < gc->of_gpio_n_cells)) return -EINVAL; if (gpiospec->args[0] > gc->ngpio) return -EINVAL; pin = gc->base + gpiospec->args[0]; if (s3c_gpio_cfgpin(pin, S3C_GPIO_SFN(gpiospec->args[1]))) pr_warn("gpio_xlate: failed to set pin function\n"); if (s3c_gpio_setpull(pin, gpiospec->args[2])) pr_warn("gpio_xlate: failed to set pin pull up/down\n"); if (s5p_gpio_set_drvstr(pin, gpiospec->args[3])) pr_warn("gpio_xlate: failed to set pin drive strength\n"); return gpiospec->args[0]; } static const struct of_device_id exynos_gpio_dt_match[] __initdata = { { .compatible = "samsung,exynos4-gpio", }, {} }; static __init void exynos_gpiolib_attach_ofnode(struct samsung_gpio_chip *chip, u64 base, u64 offset) { struct gpio_chip *gc = &chip->chip; u64 address; if (!of_have_populated_dt()) return; address = chip->base ? base + ((u32)chip->base & 0xfff) : base + offset; gc->of_node = of_find_matching_node_by_address(NULL, exynos_gpio_dt_match, address); if (!gc->of_node) { pr_info("gpio: device tree node not found for gpio controller" " with base address %08llx\n", address); return; } gc->of_gpio_n_cells = 4; gc->of_xlate = exynos_gpio_xlate; } #elif defined(CONFIG_ARCH_EXYNOS) static __init void exynos_gpiolib_attach_ofnode(struct samsung_gpio_chip *chip, u64 base, u64 offset) { return; } #endif /* defined(CONFIG_ARCH_EXYNOS) && defined(CONFIG_OF) */ /* TODO: cleanup soc_is_* */ static __init int samsung_gpiolib_init(void) { struct samsung_gpio_chip *chip; int i, nr_chips; #if defined(CONFIG_CPU_EXYNOS4210) || defined(CONFIG_SOC_EXYNOS5250) void __iomem *gpio_base1, *gpio_base2, *gpio_base3, *gpio_base4; #endif int group = 0; samsung_gpiolib_set_cfg(samsung_gpio_cfgs, ARRAY_SIZE(samsung_gpio_cfgs)); if (soc_is_s3c24xx()) { s3c24xx_gpiolib_add_chips(s3c24xx_gpios, ARRAY_SIZE(s3c24xx_gpios), S3C24XX_VA_GPIO); } else if (soc_is_s3c64xx()) { samsung_gpiolib_add_2bit_chips(s3c64xx_gpios_2bit, ARRAY_SIZE(s3c64xx_gpios_2bit), S3C64XX_VA_GPIO + 0xE0, 0x20); samsung_gpiolib_add_4bit_chips(s3c64xx_gpios_4bit, ARRAY_SIZE(s3c64xx_gpios_4bit), S3C64XX_VA_GPIO); samsung_gpiolib_add_4bit2_chips(s3c64xx_gpios_4bit2, ARRAY_SIZE(s3c64xx_gpios_4bit2)); } else if (soc_is_s5p6440()) { samsung_gpiolib_add_2bit_chips(s5p6440_gpios_2bit, ARRAY_SIZE(s5p6440_gpios_2bit), NULL, 0x0); samsung_gpiolib_add_4bit_chips(s5p6440_gpios_4bit, ARRAY_SIZE(s5p6440_gpios_4bit), S5P_VA_GPIO); samsung_gpiolib_add_4bit2_chips(s5p6440_gpios_4bit2, ARRAY_SIZE(s5p6440_gpios_4bit2)); s5p64x0_gpiolib_add_rbank(s5p6440_gpios_rbank, ARRAY_SIZE(s5p6440_gpios_rbank)); } else if (soc_is_s5p6450()) { samsung_gpiolib_add_2bit_chips(s5p6450_gpios_2bit, ARRAY_SIZE(s5p6450_gpios_2bit), NULL, 0x0); samsung_gpiolib_add_4bit_chips(s5p6450_gpios_4bit, ARRAY_SIZE(s5p6450_gpios_4bit), S5P_VA_GPIO); samsung_gpiolib_add_4bit2_chips(s5p6450_gpios_4bit2, ARRAY_SIZE(s5p6450_gpios_4bit2)); s5p64x0_gpiolib_add_rbank(s5p6450_gpios_rbank, ARRAY_SIZE(s5p6450_gpios_rbank)); } else if (soc_is_s5pc100()) { group = 0; chip = s5pc100_gpios_4bit; nr_chips = ARRAY_SIZE(s5pc100_gpios_4bit); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &samsung_gpio_cfgs[3]; chip->group = group++; } } samsung_gpiolib_add_4bit_chips(s5pc100_gpios_4bit, nr_chips, S5P_VA_GPIO); #if defined(CONFIG_CPU_S5PC100) && defined(CONFIG_S5P_GPIO_INT) s5p_register_gpioint_bank(IRQ_GPIOINT, 0, S5P_GPIOINT_GROUP_MAXNR); #endif } else if (soc_is_s5pv210()) { group = 0; chip = s5pv210_gpios_4bit; nr_chips = ARRAY_SIZE(s5pv210_gpios_4bit); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &samsung_gpio_cfgs[3]; chip->group = group++; } } samsung_gpiolib_add_4bit_chips(s5pv210_gpios_4bit, nr_chips, S5P_VA_GPIO); #if defined(CONFIG_CPU_S5PV210) && defined(CONFIG_S5P_GPIO_INT) s5p_register_gpioint_bank(IRQ_GPIOINT, 0, S5P_GPIOINT_GROUP_MAXNR); #endif } else if (soc_is_exynos4210()) { #ifdef CONFIG_CPU_EXYNOS4210 void __iomem *gpx_base; /* gpio part1 */ gpio_base1 = ioremap(EXYNOS4_PA_GPIO1, SZ_4K); if (gpio_base1 == NULL) { pr_err("unable to ioremap for gpio_base1\n"); goto err_ioremap1; } chip = exynos4_gpios_1; nr_chips = ARRAY_SIZE(exynos4_gpios_1); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &exynos_gpio_cfg; chip->group = group++; } exynos_gpiolib_attach_ofnode(chip, EXYNOS4_PA_GPIO1, i * 0x20); } samsung_gpiolib_add_4bit_chips(exynos4_gpios_1, nr_chips, gpio_base1); /* gpio part2 */ gpio_base2 = ioremap(EXYNOS4_PA_GPIO2, SZ_4K); if (gpio_base2 == NULL) { pr_err("unable to ioremap for gpio_base2\n"); goto err_ioremap2; } /* need to set base address for gpx */ chip = &exynos4_gpios_2[16]; gpx_base = gpio_base2 + 0xC00; for (i = 0; i < 4; i++, chip++, gpx_base += 0x20) chip->base = gpx_base; chip = exynos4_gpios_2; nr_chips = ARRAY_SIZE(exynos4_gpios_2); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &exynos_gpio_cfg; chip->group = group++; } exynos_gpiolib_attach_ofnode(chip, EXYNOS4_PA_GPIO2, i * 0x20); } samsung_gpiolib_add_4bit_chips(exynos4_gpios_2, nr_chips, gpio_base2); /* gpio part3 */ gpio_base3 = ioremap(EXYNOS4_PA_GPIO3, SZ_256); if (gpio_base3 == NULL) { pr_err("unable to ioremap for gpio_base3\n"); goto err_ioremap3; } chip = exynos4_gpios_3; nr_chips = ARRAY_SIZE(exynos4_gpios_3); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &exynos_gpio_cfg; chip->group = group++; } exynos_gpiolib_attach_ofnode(chip, EXYNOS4_PA_GPIO3, i * 0x20); } samsung_gpiolib_add_4bit_chips(exynos4_gpios_3, nr_chips, gpio_base3); #if defined(CONFIG_CPU_EXYNOS4210) && defined(CONFIG_S5P_GPIO_INT) s5p_register_gpioint_bank(IRQ_GPIO_XA, 0, IRQ_GPIO1_NR_GROUPS); s5p_register_gpioint_bank(IRQ_GPIO_XB, IRQ_GPIO1_NR_GROUPS, IRQ_GPIO2_NR_GROUPS); #endif #endif /* CONFIG_CPU_EXYNOS4210 */ } else if (soc_is_exynos5250()) { #ifdef CONFIG_SOC_EXYNOS5250 void __iomem *gpx_base; /* gpio part1 */ gpio_base1 = ioremap(EXYNOS5_PA_GPIO1, SZ_4K); if (gpio_base1 == NULL) { pr_err("unable to ioremap for gpio_base1\n"); goto err_ioremap1; } /* need to set base address for gpx */ chip = &exynos5_gpios_1[20]; gpx_base = gpio_base1 + 0xC00; for (i = 0; i < 4; i++, chip++, gpx_base += 0x20) chip->base = gpx_base; chip = exynos5_gpios_1; nr_chips = ARRAY_SIZE(exynos5_gpios_1); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &exynos_gpio_cfg; chip->group = group++; } exynos_gpiolib_attach_ofnode(chip, EXYNOS5_PA_GPIO1, i * 0x20); } samsung_gpiolib_add_4bit_chips(exynos5_gpios_1, nr_chips, gpio_base1); /* gpio part2 */ gpio_base2 = ioremap(EXYNOS5_PA_GPIO2, SZ_4K); if (gpio_base2 == NULL) { pr_err("unable to ioremap for gpio_base2\n"); goto err_ioremap2; } chip = exynos5_gpios_2; nr_chips = ARRAY_SIZE(exynos5_gpios_2); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &exynos_gpio_cfg; chip->group = group++; } exynos_gpiolib_attach_ofnode(chip, EXYNOS5_PA_GPIO2, i * 0x20); } samsung_gpiolib_add_4bit_chips(exynos5_gpios_2, nr_chips, gpio_base2); /* gpio part3 */ gpio_base3 = ioremap(EXYNOS5_PA_GPIO3, SZ_4K); if (gpio_base3 == NULL) { pr_err("unable to ioremap for gpio_base3\n"); goto err_ioremap3; } /* need to set base address for gpv */ exynos5_gpios_3[0].base = gpio_base3; exynos5_gpios_3[1].base = gpio_base3 + 0x20; exynos5_gpios_3[2].base = gpio_base3 + 0x60; exynos5_gpios_3[3].base = gpio_base3 + 0x80; exynos5_gpios_3[4].base = gpio_base3 + 0xC0; chip = exynos5_gpios_3; nr_chips = ARRAY_SIZE(exynos5_gpios_3); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &exynos_gpio_cfg; chip->group = group++; } exynos_gpiolib_attach_ofnode(chip, EXYNOS5_PA_GPIO3, i * 0x20); } samsung_gpiolib_add_4bit_chips(exynos5_gpios_3, nr_chips, gpio_base3); /* gpio part4 */ gpio_base4 = ioremap(EXYNOS5_PA_GPIO4, SZ_4K); if (gpio_base4 == NULL) { pr_err("unable to ioremap for gpio_base4\n"); goto err_ioremap4; } chip = exynos5_gpios_4; nr_chips = ARRAY_SIZE(exynos5_gpios_4); for (i = 0; i < nr_chips; i++, chip++) { if (!chip->config) { chip->config = &exynos_gpio_cfg; chip->group = group++; } exynos_gpiolib_attach_ofnode(chip, EXYNOS5_PA_GPIO4, i * 0x20); } samsung_gpiolib_add_4bit_chips(exynos5_gpios_4, nr_chips, gpio_base4); #endif /* CONFIG_SOC_EXYNOS5250 */ } else { WARN(1, "Unknown SoC in gpio-samsung, no GPIOs added\n"); return -ENODEV; } return 0; #if defined(CONFIG_CPU_EXYNOS4210) || defined(CONFIG_SOC_EXYNOS5250) err_ioremap4: iounmap(gpio_base3); err_ioremap3: iounmap(gpio_base2); err_ioremap2: iounmap(gpio_base1); err_ioremap1: return -ENOMEM; #endif } core_initcall(samsung_gpiolib_init); int s3c_gpio_cfgpin(unsigned int pin, unsigned int config) { struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin); unsigned long flags; int offset; int ret; if (!chip) return -EINVAL; offset = pin - chip->chip.base; samsung_gpio_lock(chip, flags); ret = samsung_gpio_do_setcfg(chip, offset, config); samsung_gpio_unlock(chip, flags); return ret; } EXPORT_SYMBOL(s3c_gpio_cfgpin); int s3c_gpio_cfgpin_range(unsigned int start, unsigned int nr, unsigned int cfg) { int ret; for (; nr > 0; nr--, start++) { ret = s3c_gpio_cfgpin(start, cfg); if (ret != 0) return ret; } return 0; } EXPORT_SYMBOL_GPL(s3c_gpio_cfgpin_range); int s3c_gpio_cfgall_range(unsigned int start, unsigned int nr, unsigned int cfg, samsung_gpio_pull_t pull) { int ret; for (; nr > 0; nr--, start++) { s3c_gpio_setpull(start, pull); ret = s3c_gpio_cfgpin(start, cfg); if (ret != 0) return ret; } return 0; } EXPORT_SYMBOL_GPL(s3c_gpio_cfgall_range); unsigned s3c_gpio_getcfg(unsigned int pin) { struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin); unsigned long flags; unsigned ret = 0; int offset; if (chip) { offset = pin - chip->chip.base; samsung_gpio_lock(chip, flags); ret = samsung_gpio_do_getcfg(chip, offset); samsung_gpio_unlock(chip, flags); } return ret; } EXPORT_SYMBOL(s3c_gpio_getcfg); int s3c_gpio_setpull(unsigned int pin, samsung_gpio_pull_t pull) { struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin); unsigned long flags; int offset, ret; if (!chip) return -EINVAL; offset = pin - chip->chip.base; samsung_gpio_lock(chip, flags); ret = samsung_gpio_do_setpull(chip, offset, pull); samsung_gpio_unlock(chip, flags); return ret; } EXPORT_SYMBOL(s3c_gpio_setpull); samsung_gpio_pull_t s3c_gpio_getpull(unsigned int pin) { struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin); unsigned long flags; int offset; u32 pup = 0; if (chip) { offset = pin - chip->chip.base; samsung_gpio_lock(chip, flags); pup = samsung_gpio_do_getpull(chip, offset); samsung_gpio_unlock(chip, flags); } return (__force samsung_gpio_pull_t)pup; } EXPORT_SYMBOL(s3c_gpio_getpull); /* gpiolib wrappers until these are totally eliminated */ void s3c2410_gpio_pullup(unsigned int pin, unsigned int to) { int ret; WARN_ON(to); /* should be none of these left */ if (!to) { /* if pull is enabled, try first with up, and if that * fails, try using down */ ret = s3c_gpio_setpull(pin, S3C_GPIO_PULL_UP); if (ret) s3c_gpio_setpull(pin, S3C_GPIO_PULL_DOWN); } else { s3c_gpio_setpull(pin, S3C_GPIO_PULL_NONE); } } EXPORT_SYMBOL(s3c2410_gpio_pullup); void s3c2410_gpio_setpin(unsigned int pin, unsigned int to) { /* do this via gpiolib until all users removed */ gpio_request(pin, "temporary"); gpio_set_value(pin, to); gpio_free(pin); } EXPORT_SYMBOL(s3c2410_gpio_setpin); unsigned int s3c2410_gpio_getpin(unsigned int pin) { struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin); unsigned long offs = pin - chip->chip.base; return __raw_readl(chip->base + 0x04) & (1 << offs); } EXPORT_SYMBOL(s3c2410_gpio_getpin); #ifdef CONFIG_S5P_GPIO_DRVSTR s5p_gpio_drvstr_t s5p_gpio_get_drvstr(unsigned int pin) { struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin); unsigned int off; void __iomem *reg; int shift; u32 drvstr; if (!chip) return -EINVAL; off = pin - chip->chip.base; shift = off * 2; reg = chip->base + 0x0C; drvstr = __raw_readl(reg); drvstr = drvstr >> shift; drvstr &= 0x3; return (__force s5p_gpio_drvstr_t)drvstr; } EXPORT_SYMBOL(s5p_gpio_get_drvstr); int s5p_gpio_set_drvstr(unsigned int pin, s5p_gpio_drvstr_t drvstr) { struct samsung_gpio_chip *chip = samsung_gpiolib_getchip(pin); unsigned int off; void __iomem *reg; int shift; u32 tmp; if (!chip) return -EINVAL; off = pin - chip->chip.base; shift = off * 2; reg = chip->base + 0x0C; tmp = __raw_readl(reg); tmp &= ~(0x3 << shift); tmp |= drvstr << shift; __raw_writel(tmp, reg); return 0; } EXPORT_SYMBOL(s5p_gpio_set_drvstr); #endif /* CONFIG_S5P_GPIO_DRVSTR */ #ifdef CONFIG_PLAT_S3C24XX unsigned int s3c2410_modify_misccr(unsigned int clear, unsigned int change) { unsigned long flags; unsigned long misccr; local_irq_save(flags); misccr = __raw_readl(S3C24XX_MISCCR); misccr &= ~clear; misccr ^= change; __raw_writel(misccr, S3C24XX_MISCCR); local_irq_restore(flags); return misccr; } EXPORT_SYMBOL(s3c2410_modify_misccr); #endif
c8813q-dev/android_kernel_huawei_c8813q
drivers/gpio/gpio-samsung.c
C
gpl-2.0
69,663
/* * Freescale PowerQUICC Ethernet Driver -- MIIM bus implementation * Provides Bus interface for MIIM regs * * Author: Andy Fleming <afleming@freescale.com> * Modifier: Sandeep Gopalpet <sandeep.kumar@freescale.com> * * Copyright 2002-2004, 2008-2009 Freescale Semiconductor, Inc. * * Based on gianfar_mii.c and ucc_geth_mii.c (Li Yang, Kim Phillips) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * */ #include <linux/kernel.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/unistd.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/crc32.h> #include <linux/mii.h> #include <linux/phy.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_mdio.h> #include <linux/of_platform.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/uaccess.h> #include <asm/ucc.h> #include "gianfar.h" #include "fsl_pq_mdio.h" struct fsl_pq_mdio_priv { void __iomem *map; struct fsl_pq_mdio __iomem *regs; }; /* * Write value to the PHY at mii_id at register regnum, * on the bus attached to the local interface, which may be different from the * generic mdio bus (tied to a single interface), waiting until the write is * done before returning. This is helpful in programming interfaces like * the TBI which control interfaces like onchip SERDES and are always tied to * the local mdio pins, which may not be the same as system mdio bus, used for * controlling the external PHYs, for example. */ int fsl_pq_local_mdio_write(struct fsl_pq_mdio __iomem *regs, int mii_id, int regnum, u16 value) { /* Set the PHY address and the register address we want to write */ out_be32(&regs->miimadd, (mii_id << 8) | regnum); /* Write out the value we want */ out_be32(&regs->miimcon, value); /* Wait for the transaction to finish */ while (in_be32(&regs->miimind) & MIIMIND_BUSY) cpu_relax(); return 0; } /* * Read the bus for PHY at addr mii_id, register regnum, and * return the value. Clears miimcom first. All PHY operation * done on the bus attached to the local interface, * which may be different from the generic mdio bus * This is helpful in programming interfaces like * the TBI which, in turn, control interfaces like onchip SERDES * and are always tied to the local mdio pins, which may not be the * same as system mdio bus, used for controlling the external PHYs, for eg. */ int fsl_pq_local_mdio_read(struct fsl_pq_mdio __iomem *regs, int mii_id, int regnum) { u16 value; /* Set the PHY address and the register address we want to read */ out_be32(&regs->miimadd, (mii_id << 8) | regnum); /* Clear miimcom, and then initiate a read */ out_be32(&regs->miimcom, 0); out_be32(&regs->miimcom, MII_READ_COMMAND); /* Wait for the transaction to finish */ while (in_be32(&regs->miimind) & (MIIMIND_NOTVALID | MIIMIND_BUSY)) cpu_relax(); /* Grab the value of the register from miimstat */ value = in_be32(&regs->miimstat); return value; } static struct fsl_pq_mdio __iomem *fsl_pq_mdio_get_regs(struct mii_bus *bus) { struct fsl_pq_mdio_priv *priv = bus->priv; return priv->regs; } /* * Write value to the PHY at mii_id at register regnum, * on the bus, waiting until the write is done before returning. */ int fsl_pq_mdio_write(struct mii_bus *bus, int mii_id, int regnum, u16 value) { struct fsl_pq_mdio __iomem *regs = fsl_pq_mdio_get_regs(bus); /* Write to the local MII regs */ return fsl_pq_local_mdio_write(regs, mii_id, regnum, value); } /* * Read the bus for PHY at addr mii_id, register regnum, and * return the value. Clears miimcom first. */ int fsl_pq_mdio_read(struct mii_bus *bus, int mii_id, int regnum) { struct fsl_pq_mdio __iomem *regs = fsl_pq_mdio_get_regs(bus); /* Read the local MII regs */ return fsl_pq_local_mdio_read(regs, mii_id, regnum); } /* Reset the MIIM registers, and wait for the bus to free */ static int fsl_pq_mdio_reset(struct mii_bus *bus) { struct fsl_pq_mdio __iomem *regs = fsl_pq_mdio_get_regs(bus); int timeout = PHY_INIT_TIMEOUT; mutex_lock(&bus->mdio_lock); /* Reset the management interface */ out_be32(&regs->miimcfg, MIIMCFG_RESET); /* Setup the MII Mgmt clock speed */ out_be32(&regs->miimcfg, MIIMCFG_INIT_VALUE); /* Wait until the bus is free */ while ((in_be32(&regs->miimind) & MIIMIND_BUSY) && timeout--) cpu_relax(); mutex_unlock(&bus->mdio_lock); if (timeout < 0) { printk(KERN_ERR "%s: The MII Bus is stuck!\n", bus->name); return -EBUSY; } return 0; } void fsl_pq_mdio_bus_name(char *name, struct device_node *np) { const u32 *addr; u64 taddr = OF_BAD_ADDR; addr = of_get_address(np, 0, NULL, NULL); if (addr) taddr = of_translate_address(np, addr); snprintf(name, MII_BUS_ID_SIZE, "%s@%llx", np->name, (unsigned long long)taddr); } EXPORT_SYMBOL_GPL(fsl_pq_mdio_bus_name); static u32 __iomem *get_gfar_tbipa(struct fsl_pq_mdio __iomem *regs, struct device_node *np) { #if defined(CONFIG_GIANFAR) || defined(CONFIG_GIANFAR_MODULE) struct gfar __iomem *enet_regs; /* * This is mildly evil, but so is our hardware for doing this. * Also, we have to cast back to struct gfar because of * definition weirdness done in gianfar.h. */ if(of_device_is_compatible(np, "fsl,gianfar-mdio") || of_device_is_compatible(np, "fsl,gianfar-tbi") || of_device_is_compatible(np, "gianfar")) { enet_regs = (struct gfar __iomem *)regs; return &enet_regs->tbipa; } else if (of_device_is_compatible(np, "fsl,etsec2-mdio") || of_device_is_compatible(np, "fsl,etsec2-tbi")) { return of_iomap(np, 1); } #endif return NULL; } static int get_ucc_id_for_range(u64 start, u64 end, u32 *ucc_id) { #if defined(CONFIG_UCC_GETH) || defined(CONFIG_UCC_GETH_MODULE) struct device_node *np = NULL; int err = 0; for_each_compatible_node(np, NULL, "ucc_geth") { struct resource tempres; err = of_address_to_resource(np, 0, &tempres); if (err) continue; /* if our mdio regs fall within this UCC regs range */ if ((start >= tempres.start) && (end <= tempres.end)) { /* Find the id of the UCC */ const u32 *id; id = of_get_property(np, "cell-index", NULL); if (!id) { id = of_get_property(np, "device-id", NULL); if (!id) continue; } *ucc_id = *id; return 0; } } if (err) return err; else return -EINVAL; #else return -ENODEV; #endif } static int fsl_pq_mdio_probe(struct platform_device *ofdev) { struct device_node *np = ofdev->dev.of_node; struct device_node *tbi; struct fsl_pq_mdio_priv *priv; struct fsl_pq_mdio __iomem *regs = NULL; void __iomem *map; u32 __iomem *tbipa; struct mii_bus *new_bus; int tbiaddr = -1; const u32 *addrp; u64 addr = 0, size = 0; int err; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; new_bus = mdiobus_alloc(); if (!new_bus) { err = -ENOMEM; goto err_free_priv; } new_bus->name = "Freescale PowerQUICC MII Bus", new_bus->read = &fsl_pq_mdio_read, new_bus->write = &fsl_pq_mdio_write, new_bus->reset = &fsl_pq_mdio_reset, new_bus->priv = priv; fsl_pq_mdio_bus_name(new_bus->id, np); addrp = of_get_address(np, 0, &size, NULL); if (!addrp) { err = -EINVAL; goto err_free_bus; } /* Set the PHY base address */ addr = of_translate_address(np, addrp); if (addr == OF_BAD_ADDR) { err = -EINVAL; goto err_free_bus; } map = ioremap(addr, size); if (!map) { err = -ENOMEM; goto err_free_bus; } priv->map = map; if (of_device_is_compatible(np, "fsl,gianfar-mdio") || of_device_is_compatible(np, "fsl,gianfar-tbi") || of_device_is_compatible(np, "fsl,ucc-mdio") || of_device_is_compatible(np, "ucc_geth_phy")) map -= offsetof(struct fsl_pq_mdio, miimcfg); regs = map; priv->regs = regs; new_bus->irq = kcalloc(PHY_MAX_ADDR, sizeof(int), GFP_KERNEL); if (NULL == new_bus->irq) { err = -ENOMEM; goto err_unmap_regs; } new_bus->parent = &ofdev->dev; dev_set_drvdata(&ofdev->dev, new_bus); if (of_device_is_compatible(np, "fsl,gianfar-mdio") || of_device_is_compatible(np, "fsl,gianfar-tbi") || of_device_is_compatible(np, "fsl,etsec2-mdio") || of_device_is_compatible(np, "fsl,etsec2-tbi") || of_device_is_compatible(np, "gianfar")) { tbipa = get_gfar_tbipa(regs, np); if (!tbipa) { err = -EINVAL; goto err_free_irqs; } } else if (of_device_is_compatible(np, "fsl,ucc-mdio") || of_device_is_compatible(np, "ucc_geth_phy")) { u32 id; static u32 mii_mng_master; tbipa = &regs->utbipar; if ((err = get_ucc_id_for_range(addr, addr + size, &id))) goto err_free_irqs; if (!mii_mng_master) { mii_mng_master = id; ucc_set_qe_mux_mii_mng(id - 1); } } else { err = -ENODEV; goto err_free_irqs; } for_each_child_of_node(np, tbi) { if (!strncmp(tbi->type, "tbi-phy", 8)) break; } if (tbi) { const u32 *prop = of_get_property(tbi, "reg", NULL); if (prop) tbiaddr = *prop; if (tbiaddr == -1) { err = -EBUSY; goto err_free_irqs; } else { out_be32(tbipa, tbiaddr); } } err = of_mdiobus_register(new_bus, np); if (err) { printk (KERN_ERR "%s: Cannot register as MDIO bus\n", new_bus->name); goto err_free_irqs; } return 0; err_free_irqs: kfree(new_bus->irq); err_unmap_regs: iounmap(priv->map); err_free_bus: kfree(new_bus); err_free_priv: kfree(priv); return err; } static int fsl_pq_mdio_remove(struct platform_device *ofdev) { struct device *device = &ofdev->dev; struct mii_bus *bus = dev_get_drvdata(device); struct fsl_pq_mdio_priv *priv = bus->priv; mdiobus_unregister(bus); dev_set_drvdata(device, NULL); iounmap(priv->map); bus->priv = NULL; mdiobus_free(bus); kfree(priv); return 0; } static struct of_device_id fsl_pq_mdio_match[] = { { .type = "mdio", .compatible = "ucc_geth_phy", }, { .type = "mdio", .compatible = "gianfar", }, { .compatible = "fsl,ucc-mdio", }, { .compatible = "fsl,gianfar-tbi", }, { .compatible = "fsl,gianfar-mdio", }, { .compatible = "fsl,etsec2-tbi", }, { .compatible = "fsl,etsec2-mdio", }, {}, }; MODULE_DEVICE_TABLE(of, fsl_pq_mdio_match); static struct platform_driver fsl_pq_mdio_driver = { .driver = { .name = "fsl-pq_mdio", .owner = THIS_MODULE, .of_match_table = fsl_pq_mdio_match, }, .probe = fsl_pq_mdio_probe, .remove = fsl_pq_mdio_remove, }; module_platform_driver(fsl_pq_mdio_driver); MODULE_LICENSE("GPL");
imoseyon/leanKernel-d2vzw
drivers/net/ethernet/freescale/fsl_pq_mdio.c
C
gpl-2.0
10,805
/* linux/arch/arm/mach-s5p64x0/clock-s5p6450.c * * Copyright (c) 2010 Samsung Electronics Co., Ltd. * http://www.samsung.com * * S5P6450 - Clock support * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/err.h> #include <linux/clk.h> #include <linux/device.h> #include <linux/io.h> #include <mach/hardware.h> #include <mach/map.h> #include <mach/regs-clock.h> #include <mach/s5p64x0-clock.h> #include <plat/cpu-freq.h> #include <plat/clock.h> #include <plat/cpu.h> #include <plat/pll.h> #include <plat/s5p-clock.h> #include <plat/clock-clksrc.h> #include "common.h" static struct clksrc_clk clk_mout_dpll = { .clk = { .name = "mout_dpll", }, .sources = &clk_src_dpll, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 5, .size = 1 }, }; static u32 epll_div[][5] = { { 133000000, 27307, 55, 2, 2 }, { 100000000, 43691, 41, 2, 2 }, { 480000000, 0, 80, 2, 0 }, }; static int s5p6450_epll_set_rate(struct clk *clk, unsigned long rate) { unsigned int epll_con, epll_con_k; unsigned int i; if (clk->rate == rate) /* Return if nothing changed */ return 0; epll_con = __raw_readl(S5P64X0_EPLL_CON); epll_con_k = __raw_readl(S5P64X0_EPLL_CON_K); epll_con_k &= ~(PLL90XX_KDIV_MASK); epll_con &= ~(PLL90XX_MDIV_MASK | PLL90XX_PDIV_MASK | PLL90XX_SDIV_MASK); for (i = 0; i < ARRAY_SIZE(epll_div); i++) { if (epll_div[i][0] == rate) { epll_con_k |= (epll_div[i][1] << PLL90XX_KDIV_SHIFT); epll_con |= (epll_div[i][2] << PLL90XX_MDIV_SHIFT) | (epll_div[i][3] << PLL90XX_PDIV_SHIFT) | (epll_div[i][4] << PLL90XX_SDIV_SHIFT); break; } } if (i == ARRAY_SIZE(epll_div)) { printk(KERN_ERR "%s: Invalid Clock EPLL Frequency\n", __func__); return -EINVAL; } __raw_writel(epll_con, S5P64X0_EPLL_CON); __raw_writel(epll_con_k, S5P64X0_EPLL_CON_K); printk(KERN_WARNING "EPLL Rate changes from %lu to %lu\n", clk->rate, rate); clk->rate = rate; return 0; } static struct clk_ops s5p6450_epll_ops = { .get_rate = s5p_epll_get_rate, .set_rate = s5p6450_epll_set_rate, }; static struct clksrc_clk clk_dout_epll = { .clk = { .name = "dout_epll", .parent = &clk_mout_epll.clk, }, .reg_div = { .reg = S5P64X0_CLK_DIV1, .shift = 24, .size = 4 }, }; static struct clksrc_clk clk_mout_hclk_sel = { .clk = { .name = "mout_hclk_sel", }, .sources = &clkset_hclk_low, .reg_src = { .reg = S5P64X0_OTHERS, .shift = 15, .size = 1 }, }; static struct clk *clkset_hclk_list[] = { &clk_mout_hclk_sel.clk, &clk_armclk.clk, }; static struct clksrc_sources clkset_hclk = { .sources = clkset_hclk_list, .nr_sources = ARRAY_SIZE(clkset_hclk_list), }; static struct clksrc_clk clk_hclk = { .clk = { .name = "clk_hclk", }, .sources = &clkset_hclk, .reg_src = { .reg = S5P64X0_OTHERS, .shift = 14, .size = 1 }, .reg_div = { .reg = S5P64X0_CLK_DIV0, .shift = 8, .size = 4 }, }; static struct clksrc_clk clk_pclk = { .clk = { .name = "clk_pclk", .parent = &clk_hclk.clk, }, .reg_div = { .reg = S5P64X0_CLK_DIV0, .shift = 12, .size = 4 }, }; static struct clksrc_clk clk_dout_pwm_ratio0 = { .clk = { .name = "clk_dout_pwm_ratio0", .parent = &clk_mout_hclk_sel.clk, }, .reg_div = { .reg = S5P64X0_CLK_DIV3, .shift = 16, .size = 4 }, }; static struct clksrc_clk clk_pclk_to_wdt_pwm = { .clk = { .name = "clk_pclk_to_wdt_pwm", .parent = &clk_dout_pwm_ratio0.clk, }, .reg_div = { .reg = S5P64X0_CLK_DIV3, .shift = 20, .size = 4 }, }; static struct clksrc_clk clk_hclk_low = { .clk = { .name = "clk_hclk_low", }, .sources = &clkset_hclk_low, .reg_src = { .reg = S5P64X0_OTHERS, .shift = 6, .size = 1 }, .reg_div = { .reg = S5P64X0_CLK_DIV3, .shift = 8, .size = 4 }, }; static struct clksrc_clk clk_pclk_low = { .clk = { .name = "clk_pclk_low", .parent = &clk_hclk_low.clk, }, .reg_div = { .reg = S5P64X0_CLK_DIV3, .shift = 12, .size = 4 }, }; /* * The following clocks will be disabled during clock initialization. It is * recommended to keep the following clocks disabled until the driver requests * for enabling the clock. */ static struct clk init_clocks_off[] = { { .name = "usbhost", .parent = &clk_hclk_low.clk, .enable = s5p64x0_hclk0_ctrl, .ctrlbit = (1 << 3), }, { .name = "dma", .devname = "dma-pl330", .parent = &clk_hclk_low.clk, .enable = s5p64x0_hclk0_ctrl, .ctrlbit = (1 << 12), }, { .name = "hsmmc", .devname = "s3c-sdhci.0", .parent = &clk_hclk_low.clk, .enable = s5p64x0_hclk0_ctrl, .ctrlbit = (1 << 17), }, { .name = "hsmmc", .devname = "s3c-sdhci.1", .parent = &clk_hclk_low.clk, .enable = s5p64x0_hclk0_ctrl, .ctrlbit = (1 << 18), }, { .name = "hsmmc", .devname = "s3c-sdhci.2", .parent = &clk_hclk_low.clk, .enable = s5p64x0_hclk0_ctrl, .ctrlbit = (1 << 19), }, { .name = "usbotg", .parent = &clk_hclk_low.clk, .enable = s5p64x0_hclk0_ctrl, .ctrlbit = (1 << 20), }, { .name = "lcd", .parent = &clk_h, .enable = s5p64x0_hclk1_ctrl, .ctrlbit = (1 << 1), }, { .name = "watchdog", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 5), }, { .name = "rtc", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 6), }, { .name = "adc", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 12), }, { .name = "i2c", .devname = "s3c2440-i2c.0", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 17), }, { .name = "spi", .devname = "s3c64xx-spi.0", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 21), }, { .name = "spi", .devname = "s3c64xx-spi.1", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 22), }, { .name = "iis", .devname = "samsung-i2s.0", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 26), }, { .name = "iis", .devname = "samsung-i2s.1", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 15), }, { .name = "iis", .devname = "samsung-i2s.2", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 16), }, { .name = "i2c", .devname = "s3c2440-i2c.1", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 27), }, { .name = "dmc0", .parent = &clk_pclk.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 30), } }; /* * The following clocks will be enabled during clock initialization. */ static struct clk init_clocks[] = { { .name = "intc", .parent = &clk_hclk.clk, .enable = s5p64x0_hclk0_ctrl, .ctrlbit = (1 << 1), }, { .name = "mem", .parent = &clk_hclk.clk, .enable = s5p64x0_hclk0_ctrl, .ctrlbit = (1 << 21), }, { .name = "uart", .devname = "s3c6400-uart.0", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 1), }, { .name = "uart", .devname = "s3c6400-uart.1", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 2), }, { .name = "uart", .devname = "s3c6400-uart.2", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 3), }, { .name = "uart", .devname = "s3c6400-uart.3", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 4), }, { .name = "timers", .parent = &clk_pclk_to_wdt_pwm.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 7), }, { .name = "gpio", .parent = &clk_pclk_low.clk, .enable = s5p64x0_pclk_ctrl, .ctrlbit = (1 << 18), }, }; static struct clk *clkset_uart_list[] = { &clk_dout_epll.clk, &clk_dout_mpll.clk, }; static struct clksrc_sources clkset_uart = { .sources = clkset_uart_list, .nr_sources = ARRAY_SIZE(clkset_uart_list), }; static struct clk *clkset_mali_list[] = { &clk_mout_epll.clk, &clk_mout_apll.clk, &clk_mout_mpll.clk, }; static struct clksrc_sources clkset_mali = { .sources = clkset_mali_list, .nr_sources = ARRAY_SIZE(clkset_mali_list), }; static struct clk *clkset_group2_list[] = { &clk_dout_epll.clk, &clk_dout_mpll.clk, &clk_ext_xtal_mux, }; static struct clksrc_sources clkset_group2 = { .sources = clkset_group2_list, .nr_sources = ARRAY_SIZE(clkset_group2_list), }; static struct clk *clkset_dispcon_list[] = { &clk_dout_epll.clk, &clk_dout_mpll.clk, &clk_ext_xtal_mux, &clk_mout_dpll.clk, }; static struct clksrc_sources clkset_dispcon = { .sources = clkset_dispcon_list, .nr_sources = ARRAY_SIZE(clkset_dispcon_list), }; static struct clk *clkset_hsmmc44_list[] = { &clk_dout_epll.clk, &clk_dout_mpll.clk, &clk_ext_xtal_mux, &s5p_clk_27m, &clk_48m, }; static struct clksrc_sources clkset_hsmmc44 = { .sources = clkset_hsmmc44_list, .nr_sources = ARRAY_SIZE(clkset_hsmmc44_list), }; static struct clk *clkset_sclk_audio0_list[] = { [0] = &clk_dout_epll.clk, [1] = &clk_dout_mpll.clk, [2] = &clk_ext_xtal_mux, [3] = NULL, [4] = NULL, }; static struct clksrc_sources clkset_sclk_audio0 = { .sources = clkset_sclk_audio0_list, .nr_sources = ARRAY_SIZE(clkset_sclk_audio0_list), }; static struct clksrc_clk clk_sclk_audio0 = { .clk = { .name = "audio-bus", .enable = s5p64x0_sclk_ctrl, .ctrlbit = (1 << 8), .parent = &clk_dout_epll.clk, }, .sources = &clkset_sclk_audio0, .reg_src = { .reg = S5P64X0_CLK_SRC1, .shift = 10, .size = 3 }, .reg_div = { .reg = S5P64X0_CLK_DIV2, .shift = 8, .size = 4 }, }; static struct clksrc_clk clksrcs[] = { { .clk = { .name = "sclk_fimc", .ctrlbit = (1 << 10), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_group2, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 26, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV1, .shift = 12, .size = 4 }, }, { .clk = { .name = "aclk_mali", .ctrlbit = (1 << 2), .enable = s5p64x0_sclk1_ctrl, }, .sources = &clkset_mali, .reg_src = { .reg = S5P64X0_CLK_SRC1, .shift = 8, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV3, .shift = 4, .size = 4 }, }, { .clk = { .name = "sclk_2d", .ctrlbit = (1 << 12), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_mali, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 30, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV2, .shift = 20, .size = 4 }, }, { .clk = { .name = "sclk_usi", .ctrlbit = (1 << 7), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_group2, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 10, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV1, .shift = 16, .size = 4 }, }, { .clk = { .name = "sclk_camif", .ctrlbit = (1 << 6), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_group2, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 28, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV1, .shift = 20, .size = 4 }, }, { .clk = { .name = "sclk_dispcon", .ctrlbit = (1 << 1), .enable = s5p64x0_sclk1_ctrl, }, .sources = &clkset_dispcon, .reg_src = { .reg = S5P64X0_CLK_SRC1, .shift = 4, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV3, .shift = 0, .size = 4 }, }, { .clk = { .name = "sclk_hsmmc44", .ctrlbit = (1 << 30), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_hsmmc44, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 6, .size = 3 }, .reg_div = { .reg = S5P64X0_CLK_DIV1, .shift = 28, .size = 4 }, }, }; static struct clksrc_clk clk_sclk_mmc0 = { .clk = { .name = "sclk_mmc", .devname = "s3c-sdhci.0", .ctrlbit = (1 << 24), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_group2, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 18, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV1, .shift = 0, .size = 4 }, }; static struct clksrc_clk clk_sclk_mmc1 = { .clk = { .name = "sclk_mmc", .devname = "s3c-sdhci.1", .ctrlbit = (1 << 25), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_group2, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 20, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV1, .shift = 4, .size = 4 }, }; static struct clksrc_clk clk_sclk_mmc2 = { .clk = { .name = "sclk_mmc", .devname = "s3c-sdhci.2", .ctrlbit = (1 << 26), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_group2, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 22, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV1, .shift = 8, .size = 4 }, }; static struct clksrc_clk clk_sclk_uclk = { .clk = { .name = "uclk1", .ctrlbit = (1 << 5), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_uart, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 13, .size = 1 }, .reg_div = { .reg = S5P64X0_CLK_DIV2, .shift = 16, .size = 4 }, }; static struct clksrc_clk clk_sclk_spi0 = { .clk = { .name = "sclk_spi", .devname = "s3c64xx-spi.0", .ctrlbit = (1 << 20), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_group2, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 14, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV2, .shift = 0, .size = 4 }, }; static struct clksrc_clk clk_sclk_spi1 = { .clk = { .name = "sclk_spi", .devname = "s3c64xx-spi.1", .ctrlbit = (1 << 21), .enable = s5p64x0_sclk_ctrl, }, .sources = &clkset_group2, .reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 16, .size = 2 }, .reg_div = { .reg = S5P64X0_CLK_DIV2, .shift = 4, .size = 4 }, }; static struct clksrc_clk *clksrc_cdev[] = { &clk_sclk_uclk, &clk_sclk_spi0, &clk_sclk_spi1, &clk_sclk_mmc0, &clk_sclk_mmc1, &clk_sclk_mmc2, }; static struct clk_lookup s5p6450_clk_lookup[] = { CLKDEV_INIT(NULL, "clk_uart_baud2", &clk_pclk_low.clk), CLKDEV_INIT(NULL, "clk_uart_baud3", &clk_sclk_uclk.clk), CLKDEV_INIT(NULL, "spi_busclk0", &clk_p), CLKDEV_INIT("s3c64xx-spi.0", "spi_busclk1", &clk_sclk_spi0.clk), CLKDEV_INIT("s3c64xx-spi.1", "spi_busclk1", &clk_sclk_spi1.clk), CLKDEV_INIT("s3c-sdhci.0", "mmc_busclk.2", &clk_sclk_mmc0.clk), CLKDEV_INIT("s3c-sdhci.1", "mmc_busclk.2", &clk_sclk_mmc1.clk), CLKDEV_INIT("s3c-sdhci.2", "mmc_busclk.2", &clk_sclk_mmc2.clk), }; /* Clock initialization code */ static struct clksrc_clk *sysclks[] = { &clk_mout_apll, &clk_mout_epll, &clk_dout_epll, &clk_mout_mpll, &clk_dout_mpll, &clk_armclk, &clk_mout_hclk_sel, &clk_dout_pwm_ratio0, &clk_pclk_to_wdt_pwm, &clk_hclk, &clk_pclk, &clk_hclk_low, &clk_pclk_low, &clk_sclk_audio0, }; static struct clk dummy_apb_pclk = { .name = "apb_pclk", .id = -1, }; void __init_or_cpufreq s5p6450_setup_clocks(void) { struct clk *xtal_clk; unsigned long xtal; unsigned long fclk; unsigned long hclk; unsigned long hclk_low; unsigned long pclk; unsigned long pclk_low; unsigned long apll; unsigned long mpll; unsigned long epll; unsigned long dpll; unsigned int ptr; /* Set S5P6450 functions for clk_fout_epll */ clk_fout_epll.enable = s5p_epll_enable; clk_fout_epll.ops = &s5p6450_epll_ops; clk_48m.enable = s5p64x0_clk48m_ctrl; xtal_clk = clk_get(NULL, "ext_xtal"); BUG_ON(IS_ERR(xtal_clk)); xtal = clk_get_rate(xtal_clk); clk_put(xtal_clk); apll = s5p_get_pll45xx(xtal, __raw_readl(S5P64X0_APLL_CON), pll_4502); mpll = s5p_get_pll45xx(xtal, __raw_readl(S5P64X0_MPLL_CON), pll_4502); epll = s5p_get_pll90xx(xtal, __raw_readl(S5P64X0_EPLL_CON), __raw_readl(S5P64X0_EPLL_CON_K)); dpll = s5p_get_pll46xx(xtal, __raw_readl(S5P6450_DPLL_CON), __raw_readl(S5P6450_DPLL_CON_K), pll_4650c); clk_fout_apll.rate = apll; clk_fout_mpll.rate = mpll; clk_fout_epll.rate = epll; clk_fout_dpll.rate = dpll; printk(KERN_INFO "S5P6450: PLL settings, A=%ld.%ldMHz, M=%ld.%ldMHz," \ " E=%ld.%ldMHz, D=%ld.%ldMHz\n", print_mhz(apll), print_mhz(mpll), print_mhz(epll), print_mhz(dpll)); fclk = clk_get_rate(&clk_armclk.clk); hclk = clk_get_rate(&clk_hclk.clk); pclk = clk_get_rate(&clk_pclk.clk); hclk_low = clk_get_rate(&clk_hclk_low.clk); pclk_low = clk_get_rate(&clk_pclk_low.clk); printk(KERN_INFO "S5P6450: HCLK=%ld.%ldMHz, HCLK_LOW=%ld.%ldMHz," \ " PCLK=%ld.%ldMHz, PCLK_LOW=%ld.%ldMHz\n", print_mhz(hclk), print_mhz(hclk_low), print_mhz(pclk), print_mhz(pclk_low)); clk_f.rate = fclk; clk_h.rate = hclk; clk_p.rate = pclk; for (ptr = 0; ptr < ARRAY_SIZE(clksrcs); ptr++) s3c_set_clksrc(&clksrcs[ptr], true); } void __init s5p6450_register_clocks(void) { int ptr; for (ptr = 0; ptr < ARRAY_SIZE(sysclks); ptr++) s3c_register_clksrc(sysclks[ptr], 1); s3c_register_clksrc(clksrcs, ARRAY_SIZE(clksrcs)); s3c_register_clocks(init_clocks, ARRAY_SIZE(init_clocks)); for (ptr = 0; ptr < ARRAY_SIZE(clksrc_cdev); ptr++) s3c_register_clksrc(clksrc_cdev[ptr], 1); s3c_register_clocks(init_clocks_off, ARRAY_SIZE(init_clocks_off)); s3c_disable_clocks(init_clocks_off, ARRAY_SIZE(init_clocks_off)); clkdev_add_table(s5p6450_clk_lookup, ARRAY_SIZE(s5p6450_clk_lookup)); s3c24xx_register_clock(&dummy_apb_pclk); s3c_pwmclk_init(); }
WildfireDEV/android_kernel_htc_m7
arch/arm/mach-s5p64x0/clock-s5p6450.c
C
gpl-2.0
17,056
/*! * jQuery UI Dialog 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/dialog/ */ !function(a){"function"==typeof define&&define.amd?define(["jquery","./core","./widget","./button","./draggable","./mouse","./position","./resizable"],a):a(jQuery)}(function(a){return a.widget("ui.dialog",{version:"1.11.4",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"Close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(b){var c=a(this).css(b).offset().top;0>c&&a(this).css("top",b.top-c)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&a.fn.draggable&&this._makeDraggable(),this.options.resizable&&a.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var b=this.options.appendTo;return b&&(b.jquery||b.nodeType)?a(b):this.document.find(b||"body").eq(0)},_destroy:function(){var a,b=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),a=b.parent.children().eq(b.index),a.length&&a[0]!==this.element[0]?a.before(this.element):b.parent.append(this.element)},widget:function(){return this.uiDialog},disable:a.noop,enable:a.noop,close:function(b){var c,d=this;if(this._isOpen&&this._trigger("beforeClose",b)!==!1){if(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),!this.opener.filter(":focusable").focus().length)try{c=this.document[0].activeElement,c&&"body"!==c.nodeName.toLowerCase()&&a(c).blur()}catch(e){}this._hide(this.uiDialog,this.options.hide,function(){d._trigger("close",b)})}},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(b,c){var d=!1,e=this.uiDialog.siblings(".ui-front:visible").map(function(){return+a(this).css("z-index")}).get(),f=Math.max.apply(null,e);return f>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",f+1),d=!0),d&&!c&&this._trigger("focus",b),d},open:function(){var b=this;return this._isOpen?void(this._moveToTop()&&this._focusTabbable()):(this._isOpen=!0,this.opener=a(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){b._focusTabbable(),b._trigger("focus")}),this._makeFocusTarget(),void this._trigger("open"))},_focusTabbable:function(){var a=this._focusedElement;a||(a=this.element.find("[autofocus]")),a.length||(a=this.element.find(":tabbable")),a.length||(a=this.uiDialogButtonPane.find(":tabbable")),a.length||(a=this.uiDialogTitlebarClose.filter(":tabbable")),a.length||(a=this.uiDialog),a.eq(0).focus()},_keepFocus:function(b){function c(){var b=this.document[0].activeElement,c=this.uiDialog[0]===b||a.contains(this.uiDialog[0],b);c||this._focusTabbable()}b.preventDefault(),c.call(this),this._delay(c)},_createWrapper:function(){this.uiDialog=a("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(b){if(this.options.closeOnEscape&&!b.isDefaultPrevented()&&b.keyCode&&b.keyCode===a.ui.keyCode.ESCAPE)return b.preventDefault(),void this.close(b);if(b.keyCode===a.ui.keyCode.TAB&&!b.isDefaultPrevented()){var c=this.uiDialog.find(":tabbable"),d=c.filter(":first"),e=c.filter(":last");b.target!==e[0]&&b.target!==this.uiDialog[0]||b.shiftKey?b.target!==d[0]&&b.target!==this.uiDialog[0]||!b.shiftKey||(this._delay(function(){e.focus()}),b.preventDefault()):(this._delay(function(){d.focus()}),b.preventDefault())}},mousedown:function(a){this._moveToTop(a)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var b;this.uiDialogTitlebar=a("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(b){a(b.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=a("<button type='button'></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(a){a.preventDefault(),this.close(a)}}),b=a("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(b),this.uiDialog.attr({"aria-labelledby":b.attr("id")})},_title:function(a){this.options.title||a.html("&#160;"),a.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=a("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=a("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var b=this,c=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),a.isEmptyObject(c)||a.isArray(c)&&!c.length?void this.uiDialog.removeClass("ui-dialog-buttons"):(a.each(c,function(c,d){var e,f;d=a.isFunction(d)?{click:d,text:c}:d,d=a.extend({type:"button"},d),e=d.click,d.click=function(){e.apply(b.element[0],arguments)},f={icons:d.icons,text:d.showText},delete d.icons,delete d.showText,a("<button></button>",d).button(f).appendTo(b.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),void this.uiDialogButtonPane.appendTo(this.uiDialog))},_makeDraggable:function(){function b(a){return{position:a.position,offset:a.offset}}var c=this,d=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(d,e){a(this).addClass("ui-dialog-dragging"),c._blockFrames(),c._trigger("dragStart",d,b(e))},drag:function(a,d){c._trigger("drag",a,b(d))},stop:function(e,f){var g=f.offset.left-c.document.scrollLeft(),h=f.offset.top-c.document.scrollTop();d.position={my:"left top",at:"left"+(g>=0?"+":"")+g+" top"+(h>=0?"+":"")+h,of:c.window},a(this).removeClass("ui-dialog-dragging"),c._unblockFrames(),c._trigger("dragStop",e,b(f))}})},_makeResizable:function(){function b(a){return{originalPosition:a.originalPosition,originalSize:a.originalSize,position:a.position,size:a.size}}var c=this,d=this.options,e=d.resizable,f=this.uiDialog.css("position"),g="string"==typeof e?e:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:d.maxWidth,maxHeight:d.maxHeight,minWidth:d.minWidth,minHeight:this._minHeight(),handles:g,start:function(d,e){a(this).addClass("ui-dialog-resizing"),c._blockFrames(),c._trigger("resizeStart",d,b(e))},resize:function(a,d){c._trigger("resize",a,b(d))},stop:function(e,f){var g=c.uiDialog.offset(),h=g.left-c.document.scrollLeft(),i=g.top-c.document.scrollTop();d.height=c.uiDialog.height(),d.width=c.uiDialog.width(),d.position={my:"left top",at:"left"+(h>=0?"+":"")+h+" top"+(i>=0?"+":"")+i,of:c.window},a(this).removeClass("ui-dialog-resizing"),c._unblockFrames(),c._trigger("resizeStop",e,b(f))}}).css("position",f)},_trackFocus:function(){this._on(this.widget(),{focusin:function(b){this._makeFocusTarget(),this._focusedElement=a(b.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var b=this._trackingInstances(),c=a.inArray(this,b);-1!==c&&b.splice(c,1)},_trackingInstances:function(){var a=this.document.data("ui-dialog-instances");return a||(a=[],this.document.data("ui-dialog-instances",a)),a},_minHeight:function(){var a=this.options;return"auto"===a.height?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(){var a=this.uiDialog.is(":visible");a||this.uiDialog.show(),this.uiDialog.position(this.options.position),a||this.uiDialog.hide()},_setOptions:function(b){var c=this,d=!1,e={};a.each(b,function(a,b){c._setOption(a,b),a in c.sizeRelatedOptions&&(d=!0),a in c.resizableRelatedOptions&&(e[a]=b)}),d&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",e)},_setOption:function(a,b){var c,d,e=this.uiDialog;"dialogClass"===a&&e.removeClass(this.options.dialogClass).addClass(b),"disabled"!==a&&(this._super(a,b),"appendTo"===a&&this.uiDialog.appendTo(this._appendTo()),"buttons"===a&&this._createButtons(),"closeText"===a&&this.uiDialogTitlebarClose.button({label:""+b}),"draggable"===a&&(c=e.is(":data(ui-draggable)"),c&&!b&&e.draggable("destroy"),!c&&b&&this._makeDraggable()),"position"===a&&this._position(),"resizable"===a&&(d=e.is(":data(ui-resizable)"),d&&!b&&e.resizable("destroy"),d&&"string"==typeof b&&e.resizable("option","handles",b),d||b===!1||this._makeResizable()),"title"===a&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var a,b,c,d=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),d.minWidth>d.width&&(d.width=d.minWidth),a=this.uiDialog.css({height:"auto",width:d.width}).outerHeight(),b=Math.max(0,d.minHeight-a),c="number"==typeof d.maxHeight?Math.max(0,d.maxHeight-a):"none","auto"===d.height?this.element.css({minHeight:b,maxHeight:c,height:"auto"}):this.element.height(Math.max(0,d.height-a)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var b=a(this);return a("<div>").css({position:"absolute",width:b.outerWidth(),height:b.outerHeight()}).appendTo(b.parent()).offset(b.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(b){return a(b.target).closest(".ui-dialog").length?!0:!!a(b.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var b=!0;this._delay(function(){b=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(a){b||this._allowInteraction(a)||(a.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=a("<div>").addClass("ui-widget-overlay ui-front").appendTo(this._appendTo()),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)}},_destroyOverlay:function(){if(this.options.modal&&this.overlay){var a=this.document.data("ui-dialog-overlays")-1;a?this.document.data("ui-dialog-overlays",a):this.document.unbind("focusin").removeData("ui-dialog-overlays"),this.overlay.remove(),this.overlay=null}}})});
yuuyama/vccw-wp-orange
wp-includes/js/jquery/ui/dialog.min.js
JavaScript
gpl-2.0
12,140
/*! * jQuery UI Resizable 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/resizable/ */ !function(a){"function"==typeof define&&define.amd?define(["jquery","./core","./mouse","./widget"],a):a(jQuery)}(function(a){return a.widget("ui.resizable",a.ui.mouse,{version:"1.11.4",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(a){return parseInt(a,10)||0},_isNumber:function(a){return!isNaN(parseInt(a,10))},_hasScroll:function(b,c){if("hidden"===a(b).css("overflow"))return!1;var d=c&&"left"===c?"scrollLeft":"scrollTop",e=!1;return b[d]>0?!0:(b[d]=1,e=b[d]>0,b[d]=0,e)},_create:function(){var b,c,d,e,f,g=this,h=this.options;if(this.element.addClass("ui-resizable"),a.extend(this,{_aspectRatio:!!h.aspectRatio,aspectRatio:h.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:h.helper||h.ghost||h.animate?h.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(a("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=h.handles||(a(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=a(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),b=this.handles.split(","),this.handles={},c=0;c<b.length;c++)d=a.trim(b[c]),f="ui-resizable-"+d,e=a("<div class='ui-resizable-handle "+f+"'></div>"),e.css({zIndex:h.zIndex}),"se"===d&&e.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[d]=".ui-resizable-"+d,this.element.append(e);this._renderAxis=function(b){var c,d,e,f;b=b||this.element;for(c in this.handles)this.handles[c].constructor===String?this.handles[c]=this.element.children(this.handles[c]).first().show():(this.handles[c].jquery||this.handles[c].nodeType)&&(this.handles[c]=a(this.handles[c]),this._on(this.handles[c],{mousedown:g._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(d=a(this.handles[c],this.element),f=/sw|ne|nw|se|n|s/.test(c)?d.outerHeight():d.outerWidth(),e=["padding",/ne|nw|n/.test(c)?"Top":/se|sw|s/.test(c)?"Bottom":/^e$/.test(c)?"Right":"Left"].join(""),b.css(e,f),this._proportionallyResize()),this._handles=this._handles.add(this.handles[c])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.mouseover(function(){g.resizing||(this.className&&(e=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),g.axis=e&&e[1]?e[1]:"se")}),h.autoHide&&(this._handles.hide(),a(this.element).addClass("ui-resizable-autohide").mouseenter(function(){h.disabled||(a(this).removeClass("ui-resizable-autohide"),g._handles.show())}).mouseleave(function(){h.disabled||g.resizing||(a(this).addClass("ui-resizable-autohide"),g._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var b,c=function(b){a(b).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(c(this.element),b=this.element,this.originalElement.css({position:b.css("position"),width:b.outerWidth(),height:b.outerHeight(),top:b.css("top"),left:b.css("left")}).insertAfter(b),b.remove()),this.originalElement.css("resize",this.originalResizeStyle),c(this.originalElement),this},_mouseCapture:function(b){var c,d,e=!1;for(c in this.handles)d=a(this.handles[c])[0],(d===b.target||a.contains(d,b.target))&&(e=!0);return!this.options.disabled&&e},_mouseStart:function(b){var c,d,e,f=this.options,g=this.element;return this.resizing=!0,this._renderProxy(),c=this._num(this.helper.css("left")),d=this._num(this.helper.css("top")),f.containment&&(c+=a(f.containment).scrollLeft()||0,d+=a(f.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:c,top:d},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:g.width(),height:g.height()},this.originalSize=this._helper?{width:g.outerWidth(),height:g.outerHeight()}:{width:g.width(),height:g.height()},this.sizeDiff={width:g.outerWidth()-g.width(),height:g.outerHeight()-g.height()},this.originalPosition={left:c,top:d},this.originalMousePosition={left:b.pageX,top:b.pageY},this.aspectRatio="number"==typeof f.aspectRatio?f.aspectRatio:this.originalSize.width/this.originalSize.height||1,e=a(".ui-resizable-"+this.axis).css("cursor"),a("body").css("cursor","auto"===e?this.axis+"-resize":e),g.addClass("ui-resizable-resizing"),this._propagate("start",b),!0},_mouseDrag:function(b){var c,d,e=this.originalMousePosition,f=this.axis,g=b.pageX-e.left||0,h=b.pageY-e.top||0,i=this._change[f];return this._updatePrevProperties(),i?(c=i.apply(this,[b,g,h]),this._updateVirtualBoundaries(b.shiftKey),(this._aspectRatio||b.shiftKey)&&(c=this._updateRatio(c,b)),c=this._respectSize(c,b),this._updateCache(c),this._propagate("resize",b),d=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),a.isEmptyObject(d)||(this._updatePrevProperties(),this._trigger("resize",b,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(b){this.resizing=!1;var c,d,e,f,g,h,i,j=this.options,k=this;return this._helper&&(c=this._proportionallyResizeElements,d=c.length&&/textarea/i.test(c[0].nodeName),e=d&&this._hasScroll(c[0],"left")?0:k.sizeDiff.height,f=d?0:k.sizeDiff.width,g={width:k.helper.width()-f,height:k.helper.height()-e},h=parseInt(k.element.css("left"),10)+(k.position.left-k.originalPosition.left)||null,i=parseInt(k.element.css("top"),10)+(k.position.top-k.originalPosition.top)||null,j.animate||this.element.css(a.extend(g,{top:i,left:h})),k.helper.height(k.size.height),k.helper.width(k.size.width),this._helper&&!j.animate&&this._proportionallyResize()),a("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",b),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var a={};return this.position.top!==this.prevPosition.top&&(a.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(a.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(a.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(a.height=this.size.height+"px"),this.helper.css(a),a},_updateVirtualBoundaries:function(a){var b,c,d,e,f,g=this.options;f={minWidth:this._isNumber(g.minWidth)?g.minWidth:0,maxWidth:this._isNumber(g.maxWidth)?g.maxWidth:1/0,minHeight:this._isNumber(g.minHeight)?g.minHeight:0,maxHeight:this._isNumber(g.maxHeight)?g.maxHeight:1/0},(this._aspectRatio||a)&&(b=f.minHeight*this.aspectRatio,d=f.minWidth/this.aspectRatio,c=f.maxHeight*this.aspectRatio,e=f.maxWidth/this.aspectRatio,b>f.minWidth&&(f.minWidth=b),d>f.minHeight&&(f.minHeight=d),c<f.maxWidth&&(f.maxWidth=c),e<f.maxHeight&&(f.maxHeight=e)),this._vBoundaries=f},_updateCache:function(a){this.offset=this.helper.offset(),this._isNumber(a.left)&&(this.position.left=a.left),this._isNumber(a.top)&&(this.position.top=a.top),this._isNumber(a.height)&&(this.size.height=a.height),this._isNumber(a.width)&&(this.size.width=a.width)},_updateRatio:function(a){var b=this.position,c=this.size,d=this.axis;return this._isNumber(a.height)?a.width=a.height*this.aspectRatio:this._isNumber(a.width)&&(a.height=a.width/this.aspectRatio),"sw"===d&&(a.left=b.left+(c.width-a.width),a.top=null),"nw"===d&&(a.top=b.top+(c.height-a.height),a.left=b.left+(c.width-a.width)),a},_respectSize:function(a){var b=this._vBoundaries,c=this.axis,d=this._isNumber(a.width)&&b.maxWidth&&b.maxWidth<a.width,e=this._isNumber(a.height)&&b.maxHeight&&b.maxHeight<a.height,f=this._isNumber(a.width)&&b.minWidth&&b.minWidth>a.width,g=this._isNumber(a.height)&&b.minHeight&&b.minHeight>a.height,h=this.originalPosition.left+this.originalSize.width,i=this.position.top+this.size.height,j=/sw|nw|w/.test(c),k=/nw|ne|n/.test(c);return f&&(a.width=b.minWidth),g&&(a.height=b.minHeight),d&&(a.width=b.maxWidth),e&&(a.height=b.maxHeight),f&&j&&(a.left=h-b.minWidth),d&&j&&(a.left=h-b.maxWidth),g&&k&&(a.top=i-b.minHeight),e&&k&&(a.top=i-b.maxHeight),a.width||a.height||a.left||!a.top?a.width||a.height||a.top||!a.left||(a.left=null):a.top=null,a},_getPaddingPlusBorderDimensions:function(a){for(var b=0,c=[],d=[a.css("borderTopWidth"),a.css("borderRightWidth"),a.css("borderBottomWidth"),a.css("borderLeftWidth")],e=[a.css("paddingTop"),a.css("paddingRight"),a.css("paddingBottom"),a.css("paddingLeft")];4>b;b++)c[b]=parseInt(d[b],10)||0,c[b]+=parseInt(e[b],10)||0;return{height:c[0]+c[2],width:c[1]+c[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var a,b=0,c=this.helper||this.element;b<this._proportionallyResizeElements.length;b++)a=this._proportionallyResizeElements[b],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(a)),a.css({height:c.height()-this.outerDimensions.height||0,width:c.width()-this.outerDimensions.width||0})},_renderProxy:function(){var b=this.element,c=this.options;this.elementOffset=b.offset(),this._helper?(this.helper=this.helper||a("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++c.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(a,b){return{width:this.originalSize.width+b}},w:function(a,b){var c=this.originalSize,d=this.originalPosition;return{left:d.left+b,width:c.width-b}},n:function(a,b,c){var d=this.originalSize,e=this.originalPosition;return{top:e.top+c,height:d.height-c}},s:function(a,b,c){return{height:this.originalSize.height+c}},se:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},sw:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,c,d]))},ne:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},nw:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,c,d]))}},_propagate:function(b,c){a.ui.plugin.call(this,b,[c,this.ui()]),"resize"!==b&&this._trigger(b,c,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),a.ui.plugin.add("resizable","animate",{stop:function(b){var c=a(this).resizable("instance"),d=c.options,e=c._proportionallyResizeElements,f=e.length&&/textarea/i.test(e[0].nodeName),g=f&&c._hasScroll(e[0],"left")?0:c.sizeDiff.height,h=f?0:c.sizeDiff.width,i={width:c.size.width-h,height:c.size.height-g},j=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null,k=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null;c.element.animate(a.extend(i,k&&j?{top:k,left:j}:{}),{duration:d.animateDuration,easing:d.animateEasing,step:function(){var d={width:parseInt(c.element.css("width"),10),height:parseInt(c.element.css("height"),10),top:parseInt(c.element.css("top"),10),left:parseInt(c.element.css("left"),10)};e&&e.length&&a(e[0]).css({width:d.width,height:d.height}),c._updateCache(d),c._propagate("resize",b)}})}}),a.ui.plugin.add("resizable","containment",{start:function(){var b,c,d,e,f,g,h,i=a(this).resizable("instance"),j=i.options,k=i.element,l=j.containment,m=l instanceof a?l.get(0):/parent/.test(l)?k.parent().get(0):l;m&&(i.containerElement=a(m),/document/.test(l)||l===document?(i.containerOffset={left:0,top:0},i.containerPosition={left:0,top:0},i.parentData={element:a(document),left:0,top:0,width:a(document).width(),height:a(document).height()||document.body.parentNode.scrollHeight}):(b=a(m),c=[],a(["Top","Right","Left","Bottom"]).each(function(a,d){c[a]=i._num(b.css("padding"+d))}),i.containerOffset=b.offset(),i.containerPosition=b.position(),i.containerSize={height:b.innerHeight()-c[3],width:b.innerWidth()-c[1]},d=i.containerOffset,e=i.containerSize.height,f=i.containerSize.width,g=i._hasScroll(m,"left")?m.scrollWidth:f,h=i._hasScroll(m)?m.scrollHeight:e,i.parentData={element:m,left:d.left,top:d.top,width:g,height:h}))},resize:function(b){var c,d,e,f,g=a(this).resizable("instance"),h=g.options,i=g.containerOffset,j=g.position,k=g._aspectRatio||b.shiftKey,l={top:0,left:0},m=g.containerElement,n=!0;m[0]!==document&&/static/.test(m.css("position"))&&(l=i),j.left<(g._helper?i.left:0)&&(g.size.width=g.size.width+(g._helper?g.position.left-i.left:g.position.left-l.left),k&&(g.size.height=g.size.width/g.aspectRatio,n=!1),g.position.left=h.helper?i.left:0),j.top<(g._helper?i.top:0)&&(g.size.height=g.size.height+(g._helper?g.position.top-i.top:g.position.top),k&&(g.size.width=g.size.height*g.aspectRatio,n=!1),g.position.top=g._helper?i.top:0),e=g.containerElement.get(0)===g.element.parent().get(0),f=/relative|absolute/.test(g.containerElement.css("position")),e&&f?(g.offset.left=g.parentData.left+g.position.left,g.offset.top=g.parentData.top+g.position.top):(g.offset.left=g.element.offset().left,g.offset.top=g.element.offset().top),c=Math.abs(g.sizeDiff.width+(g._helper?g.offset.left-l.left:g.offset.left-i.left)),d=Math.abs(g.sizeDiff.height+(g._helper?g.offset.top-l.top:g.offset.top-i.top)),c+g.size.width>=g.parentData.width&&(g.size.width=g.parentData.width-c,k&&(g.size.height=g.size.width/g.aspectRatio,n=!1)),d+g.size.height>=g.parentData.height&&(g.size.height=g.parentData.height-d,k&&(g.size.width=g.size.height*g.aspectRatio,n=!1)),n||(g.position.left=g.prevPosition.left,g.position.top=g.prevPosition.top,g.size.width=g.prevSize.width,g.size.height=g.prevSize.height)},stop:function(){var b=a(this).resizable("instance"),c=b.options,d=b.containerOffset,e=b.containerPosition,f=b.containerElement,g=a(b.helper),h=g.offset(),i=g.outerWidth()-b.sizeDiff.width,j=g.outerHeight()-b.sizeDiff.height;b._helper&&!c.animate&&/relative/.test(f.css("position"))&&a(this).css({left:h.left-e.left-d.left,width:i,height:j}),b._helper&&!c.animate&&/static/.test(f.css("position"))&&a(this).css({left:h.left-e.left-d.left,width:i,height:j})}}),a.ui.plugin.add("resizable","alsoResize",{start:function(){var b=a(this).resizable("instance"),c=b.options;a(c.alsoResize).each(function(){var b=a(this);b.data("ui-resizable-alsoresize",{width:parseInt(b.width(),10),height:parseInt(b.height(),10),left:parseInt(b.css("left"),10),top:parseInt(b.css("top"),10)})})},resize:function(b,c){var d=a(this).resizable("instance"),e=d.options,f=d.originalSize,g=d.originalPosition,h={height:d.size.height-f.height||0,width:d.size.width-f.width||0,top:d.position.top-g.top||0,left:d.position.left-g.left||0};a(e.alsoResize).each(function(){var b=a(this),d=a(this).data("ui-resizable-alsoresize"),e={},f=b.parents(c.originalElement[0]).length?["width","height"]:["width","height","top","left"];a.each(f,function(a,b){var c=(d[b]||0)+(h[b]||0);c&&c>=0&&(e[b]=c||null)}),b.css(e)})},stop:function(){a(this).removeData("resizable-alsoresize")}}),a.ui.plugin.add("resizable","ghost",{start:function(){var b=a(this).resizable("instance"),c=b.options,d=b.size;b.ghost=b.originalElement.clone(),b.ghost.css({opacity:.25,display:"block",position:"relative",height:d.height,width:d.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof c.ghost?c.ghost:""),b.ghost.appendTo(b.helper)},resize:function(){var b=a(this).resizable("instance");b.ghost&&b.ghost.css({position:"relative",height:b.size.height,width:b.size.width})},stop:function(){var b=a(this).resizable("instance");b.ghost&&b.helper&&b.helper.get(0).removeChild(b.ghost.get(0))}}),a.ui.plugin.add("resizable","grid",{resize:function(){var b,c=a(this).resizable("instance"),d=c.options,e=c.size,f=c.originalSize,g=c.originalPosition,h=c.axis,i="number"==typeof d.grid?[d.grid,d.grid]:d.grid,j=i[0]||1,k=i[1]||1,l=Math.round((e.width-f.width)/j)*j,m=Math.round((e.height-f.height)/k)*k,n=f.width+l,o=f.height+m,p=d.maxWidth&&d.maxWidth<n,q=d.maxHeight&&d.maxHeight<o,r=d.minWidth&&d.minWidth>n,s=d.minHeight&&d.minHeight>o;d.grid=i,r&&(n+=j),s&&(o+=k),p&&(n-=j),q&&(o-=k),/^(se|s|e)$/.test(h)?(c.size.width=n,c.size.height=o):/^(ne)$/.test(h)?(c.size.width=n,c.size.height=o,c.position.top=g.top-m):/^(sw)$/.test(h)?(c.size.width=n,c.size.height=o,c.position.left=g.left-l):((0>=o-k||0>=n-j)&&(b=c._getPaddingPlusBorderDimensions(this)),o-k>0?(c.size.height=o,c.position.top=g.top-m):(o=k-b.height,c.size.height=o,c.position.top=g.top+f.height-o),n-j>0?(c.size.width=n,c.position.left=g.left-l):(n=j-b.width,c.size.width=n,c.position.left=g.left+f.width-n))}}),a.ui.resizable});
swamyg/wordpress
wp-includes/js/jquery/ui/resizable.min.js
JavaScript
gpl-2.0
18,428
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * 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., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Adrian Hunter * Artem Bityutskiy (Битюцкий Артём) */ /* * This file implements commit-related functionality of the LEB properties * subsystem. */ #include <linux/crc16.h> #include <linux/slab.h> #include <linux/random.h> #include "ubifs.h" #ifdef CONFIG_UBIFS_FS_DEBUG static int dbg_populate_lsave(struct ubifs_info *c); #else #define dbg_populate_lsave(c) 0 #endif /** * first_dirty_cnode - find first dirty cnode. * @c: UBIFS file-system description object * @nnode: nnode at which to start * * This function returns the first dirty cnode or %NULL if there is not one. */ static struct ubifs_cnode *first_dirty_cnode(struct ubifs_nnode *nnode) { ubifs_assert(nnode); while (1) { int i, cont = 0; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { struct ubifs_cnode *cnode; cnode = nnode->nbranch[i].cnode; if (cnode && test_bit(DIRTY_CNODE, &cnode->flags)) { if (cnode->level == 0) return cnode; nnode = (struct ubifs_nnode *)cnode; cont = 1; break; } } if (!cont) return (struct ubifs_cnode *)nnode; } } /** * next_dirty_cnode - find next dirty cnode. * @cnode: cnode from which to begin searching * * This function returns the next dirty cnode or %NULL if there is not one. */ static struct ubifs_cnode *next_dirty_cnode(struct ubifs_cnode *cnode) { struct ubifs_nnode *nnode; int i; ubifs_assert(cnode); nnode = cnode->parent; if (!nnode) return NULL; for (i = cnode->iip + 1; i < UBIFS_LPT_FANOUT; i++) { cnode = nnode->nbranch[i].cnode; if (cnode && test_bit(DIRTY_CNODE, &cnode->flags)) { if (cnode->level == 0) return cnode; /* cnode is a pnode */ /* cnode is a nnode */ return first_dirty_cnode((struct ubifs_nnode *)cnode); } } return (struct ubifs_cnode *)nnode; } /** * get_cnodes_to_commit - create list of dirty cnodes to commit. * @c: UBIFS file-system description object * * This function returns the number of cnodes to commit. */ static int get_cnodes_to_commit(struct ubifs_info *c) { struct ubifs_cnode *cnode, *cnext; int cnt = 0; if (!c->nroot) return 0; if (!test_bit(DIRTY_CNODE, &c->nroot->flags)) return 0; c->lpt_cnext = first_dirty_cnode(c->nroot); cnode = c->lpt_cnext; if (!cnode) return 0; cnt += 1; while (1) { ubifs_assert(!test_bit(COW_CNODE, &cnode->flags)); __set_bit(COW_CNODE, &cnode->flags); cnext = next_dirty_cnode(cnode); if (!cnext) { cnode->cnext = c->lpt_cnext; break; } cnode->cnext = cnext; cnode = cnext; cnt += 1; } dbg_cmt("committing %d cnodes", cnt); dbg_lp("committing %d cnodes", cnt); ubifs_assert(cnt == c->dirty_nn_cnt + c->dirty_pn_cnt); return cnt; } /** * upd_ltab - update LPT LEB properties. * @c: UBIFS file-system description object * @lnum: LEB number * @free: amount of free space * @dirty: amount of dirty space to add */ static void upd_ltab(struct ubifs_info *c, int lnum, int free, int dirty) { dbg_lp("LEB %d free %d dirty %d to %d +%d", lnum, c->ltab[lnum - c->lpt_first].free, c->ltab[lnum - c->lpt_first].dirty, free, dirty); ubifs_assert(lnum >= c->lpt_first && lnum <= c->lpt_last); c->ltab[lnum - c->lpt_first].free = free; c->ltab[lnum - c->lpt_first].dirty += dirty; } /** * alloc_lpt_leb - allocate an LPT LEB that is empty. * @c: UBIFS file-system description object * @lnum: LEB number is passed and returned here * * This function finds the next empty LEB in the ltab starting from @lnum. If a * an empty LEB is found it is returned in @lnum and the function returns %0. * Otherwise the function returns -ENOSPC. Note however, that LPT is designed * never to run out of space. */ static int alloc_lpt_leb(struct ubifs_info *c, int *lnum) { int i, n; n = *lnum - c->lpt_first + 1; for (i = n; i < c->lpt_lebs; i++) { if (c->ltab[i].tgc || c->ltab[i].cmt) continue; if (c->ltab[i].free == c->leb_size) { c->ltab[i].cmt = 1; *lnum = i + c->lpt_first; return 0; } } for (i = 0; i < n; i++) { if (c->ltab[i].tgc || c->ltab[i].cmt) continue; if (c->ltab[i].free == c->leb_size) { c->ltab[i].cmt = 1; *lnum = i + c->lpt_first; return 0; } } return -ENOSPC; } /** * layout_cnodes - layout cnodes for commit. * @c: UBIFS file-system description object * * This function returns %0 on success and a negative error code on failure. */ static int layout_cnodes(struct ubifs_info *c) { int lnum, offs, len, alen, done_lsave, done_ltab, err; struct ubifs_cnode *cnode; err = dbg_chk_lpt_sz(c, 0, 0); if (err) return err; cnode = c->lpt_cnext; if (!cnode) return 0; lnum = c->nhead_lnum; offs = c->nhead_offs; /* Try to place lsave and ltab nicely */ done_lsave = !c->big_lpt; done_ltab = 0; if (!done_lsave && offs + c->lsave_sz <= c->leb_size) { done_lsave = 1; c->lsave_lnum = lnum; c->lsave_offs = offs; offs += c->lsave_sz; dbg_chk_lpt_sz(c, 1, c->lsave_sz); } if (offs + c->ltab_sz <= c->leb_size) { done_ltab = 1; c->ltab_lnum = lnum; c->ltab_offs = offs; offs += c->ltab_sz; dbg_chk_lpt_sz(c, 1, c->ltab_sz); } do { if (cnode->level) { len = c->nnode_sz; c->dirty_nn_cnt -= 1; } else { len = c->pnode_sz; c->dirty_pn_cnt -= 1; } while (offs + len > c->leb_size) { alen = ALIGN(offs, c->min_io_size); upd_ltab(c, lnum, c->leb_size - alen, alen - offs); dbg_chk_lpt_sz(c, 2, c->leb_size - offs); err = alloc_lpt_leb(c, &lnum); if (err) goto no_space; offs = 0; ubifs_assert(lnum >= c->lpt_first && lnum <= c->lpt_last); /* Try to place lsave and ltab nicely */ if (!done_lsave) { done_lsave = 1; c->lsave_lnum = lnum; c->lsave_offs = offs; offs += c->lsave_sz; dbg_chk_lpt_sz(c, 1, c->lsave_sz); continue; } if (!done_ltab) { done_ltab = 1; c->ltab_lnum = lnum; c->ltab_offs = offs; offs += c->ltab_sz; dbg_chk_lpt_sz(c, 1, c->ltab_sz); continue; } break; } if (cnode->parent) { cnode->parent->nbranch[cnode->iip].lnum = lnum; cnode->parent->nbranch[cnode->iip].offs = offs; } else { c->lpt_lnum = lnum; c->lpt_offs = offs; } offs += len; dbg_chk_lpt_sz(c, 1, len); cnode = cnode->cnext; } while (cnode && cnode != c->lpt_cnext); /* Make sure to place LPT's save table */ if (!done_lsave) { if (offs + c->lsave_sz > c->leb_size) { alen = ALIGN(offs, c->min_io_size); upd_ltab(c, lnum, c->leb_size - alen, alen - offs); dbg_chk_lpt_sz(c, 2, c->leb_size - offs); err = alloc_lpt_leb(c, &lnum); if (err) goto no_space; offs = 0; ubifs_assert(lnum >= c->lpt_first && lnum <= c->lpt_last); } done_lsave = 1; c->lsave_lnum = lnum; c->lsave_offs = offs; offs += c->lsave_sz; dbg_chk_lpt_sz(c, 1, c->lsave_sz); } /* Make sure to place LPT's own lprops table */ if (!done_ltab) { if (offs + c->ltab_sz > c->leb_size) { alen = ALIGN(offs, c->min_io_size); upd_ltab(c, lnum, c->leb_size - alen, alen - offs); dbg_chk_lpt_sz(c, 2, c->leb_size - offs); err = alloc_lpt_leb(c, &lnum); if (err) goto no_space; offs = 0; ubifs_assert(lnum >= c->lpt_first && lnum <= c->lpt_last); } done_ltab = 1; c->ltab_lnum = lnum; c->ltab_offs = offs; offs += c->ltab_sz; dbg_chk_lpt_sz(c, 1, c->ltab_sz); } alen = ALIGN(offs, c->min_io_size); upd_ltab(c, lnum, c->leb_size - alen, alen - offs); dbg_chk_lpt_sz(c, 4, alen - offs); err = dbg_chk_lpt_sz(c, 3, alen); if (err) return err; return 0; no_space: ubifs_err("LPT out of space"); dbg_err("LPT out of space at LEB %d:%d needing %d, done_ltab %d, " "done_lsave %d", lnum, offs, len, done_ltab, done_lsave); dbg_dump_lpt_info(c); dbg_dump_lpt_lebs(c); dump_stack(); return err; } /** * realloc_lpt_leb - allocate an LPT LEB that is empty. * @c: UBIFS file-system description object * @lnum: LEB number is passed and returned here * * This function duplicates exactly the results of the function alloc_lpt_leb. * It is used during end commit to reallocate the same LEB numbers that were * allocated by alloc_lpt_leb during start commit. * * This function finds the next LEB that was allocated by the alloc_lpt_leb * function starting from @lnum. If a LEB is found it is returned in @lnum and * the function returns %0. Otherwise the function returns -ENOSPC. * Note however, that LPT is designed never to run out of space. */ static int realloc_lpt_leb(struct ubifs_info *c, int *lnum) { int i, n; n = *lnum - c->lpt_first + 1; for (i = n; i < c->lpt_lebs; i++) if (c->ltab[i].cmt) { c->ltab[i].cmt = 0; *lnum = i + c->lpt_first; return 0; } for (i = 0; i < n; i++) if (c->ltab[i].cmt) { c->ltab[i].cmt = 0; *lnum = i + c->lpt_first; return 0; } return -ENOSPC; } /** * write_cnodes - write cnodes for commit. * @c: UBIFS file-system description object * * This function returns %0 on success and a negative error code on failure. */ static int write_cnodes(struct ubifs_info *c) { int lnum, offs, len, from, err, wlen, alen, done_ltab, done_lsave; struct ubifs_cnode *cnode; void *buf = c->lpt_buf; cnode = c->lpt_cnext; if (!cnode) return 0; lnum = c->nhead_lnum; offs = c->nhead_offs; from = offs; /* Ensure empty LEB is unmapped */ if (offs == 0) { err = ubifs_leb_unmap(c, lnum); if (err) return err; } /* Try to place lsave and ltab nicely */ done_lsave = !c->big_lpt; done_ltab = 0; if (!done_lsave && offs + c->lsave_sz <= c->leb_size) { done_lsave = 1; ubifs_pack_lsave(c, buf + offs, c->lsave); offs += c->lsave_sz; dbg_chk_lpt_sz(c, 1, c->lsave_sz); } if (offs + c->ltab_sz <= c->leb_size) { done_ltab = 1; ubifs_pack_ltab(c, buf + offs, c->ltab_cmt); offs += c->ltab_sz; dbg_chk_lpt_sz(c, 1, c->ltab_sz); } /* Loop for each cnode */ do { if (cnode->level) len = c->nnode_sz; else len = c->pnode_sz; while (offs + len > c->leb_size) { wlen = offs - from; if (wlen) { alen = ALIGN(wlen, c->min_io_size); memset(buf + offs, 0xff, alen - wlen); err = ubifs_leb_write(c, lnum, buf + from, from, alen, UBI_SHORTTERM); if (err) return err; } dbg_chk_lpt_sz(c, 2, c->leb_size - offs); err = realloc_lpt_leb(c, &lnum); if (err) goto no_space; offs = from = 0; ubifs_assert(lnum >= c->lpt_first && lnum <= c->lpt_last); err = ubifs_leb_unmap(c, lnum); if (err) return err; /* Try to place lsave and ltab nicely */ if (!done_lsave) { done_lsave = 1; ubifs_pack_lsave(c, buf + offs, c->lsave); offs += c->lsave_sz; dbg_chk_lpt_sz(c, 1, c->lsave_sz); continue; } if (!done_ltab) { done_ltab = 1; ubifs_pack_ltab(c, buf + offs, c->ltab_cmt); offs += c->ltab_sz; dbg_chk_lpt_sz(c, 1, c->ltab_sz); continue; } break; } if (cnode->level) ubifs_pack_nnode(c, buf + offs, (struct ubifs_nnode *)cnode); else ubifs_pack_pnode(c, buf + offs, (struct ubifs_pnode *)cnode); /* * The reason for the barriers is the same as in case of TNC. * See comment in 'write_index()'. 'dirty_cow_nnode()' and * 'dirty_cow_pnode()' are the functions for which this is * important. */ clear_bit(DIRTY_CNODE, &cnode->flags); smp_mb__before_clear_bit(); clear_bit(COW_CNODE, &cnode->flags); smp_mb__after_clear_bit(); offs += len; dbg_chk_lpt_sz(c, 1, len); cnode = cnode->cnext; } while (cnode && cnode != c->lpt_cnext); /* Make sure to place LPT's save table */ if (!done_lsave) { if (offs + c->lsave_sz > c->leb_size) { wlen = offs - from; alen = ALIGN(wlen, c->min_io_size); memset(buf + offs, 0xff, alen - wlen); err = ubifs_leb_write(c, lnum, buf + from, from, alen, UBI_SHORTTERM); if (err) return err; dbg_chk_lpt_sz(c, 2, c->leb_size - offs); err = realloc_lpt_leb(c, &lnum); if (err) goto no_space; offs = from = 0; ubifs_assert(lnum >= c->lpt_first && lnum <= c->lpt_last); err = ubifs_leb_unmap(c, lnum); if (err) return err; } done_lsave = 1; ubifs_pack_lsave(c, buf + offs, c->lsave); offs += c->lsave_sz; dbg_chk_lpt_sz(c, 1, c->lsave_sz); } /* Make sure to place LPT's own lprops table */ if (!done_ltab) { if (offs + c->ltab_sz > c->leb_size) { wlen = offs - from; alen = ALIGN(wlen, c->min_io_size); memset(buf + offs, 0xff, alen - wlen); err = ubifs_leb_write(c, lnum, buf + from, from, alen, UBI_SHORTTERM); if (err) return err; dbg_chk_lpt_sz(c, 2, c->leb_size - offs); err = realloc_lpt_leb(c, &lnum); if (err) goto no_space; offs = from = 0; ubifs_assert(lnum >= c->lpt_first && lnum <= c->lpt_last); err = ubifs_leb_unmap(c, lnum); if (err) return err; } done_ltab = 1; ubifs_pack_ltab(c, buf + offs, c->ltab_cmt); offs += c->ltab_sz; dbg_chk_lpt_sz(c, 1, c->ltab_sz); } /* Write remaining data in buffer */ wlen = offs - from; alen = ALIGN(wlen, c->min_io_size); memset(buf + offs, 0xff, alen - wlen); err = ubifs_leb_write(c, lnum, buf + from, from, alen, UBI_SHORTTERM); if (err) return err; dbg_chk_lpt_sz(c, 4, alen - wlen); err = dbg_chk_lpt_sz(c, 3, ALIGN(offs, c->min_io_size)); if (err) return err; c->nhead_lnum = lnum; c->nhead_offs = ALIGN(offs, c->min_io_size); dbg_lp("LPT root is at %d:%d", c->lpt_lnum, c->lpt_offs); dbg_lp("LPT head is at %d:%d", c->nhead_lnum, c->nhead_offs); dbg_lp("LPT ltab is at %d:%d", c->ltab_lnum, c->ltab_offs); if (c->big_lpt) dbg_lp("LPT lsave is at %d:%d", c->lsave_lnum, c->lsave_offs); return 0; no_space: ubifs_err("LPT out of space mismatch"); dbg_err("LPT out of space mismatch at LEB %d:%d needing %d, done_ltab " "%d, done_lsave %d", lnum, offs, len, done_ltab, done_lsave); dbg_dump_lpt_info(c); dbg_dump_lpt_lebs(c); dump_stack(); return err; } /** * next_pnode_to_dirty - find next pnode to dirty. * @c: UBIFS file-system description object * @pnode: pnode * * This function returns the next pnode to dirty or %NULL if there are no more * pnodes. Note that pnodes that have never been written (lnum == 0) are * skipped. */ static struct ubifs_pnode *next_pnode_to_dirty(struct ubifs_info *c, struct ubifs_pnode *pnode) { struct ubifs_nnode *nnode; int iip; /* Try to go right */ nnode = pnode->parent; for (iip = pnode->iip + 1; iip < UBIFS_LPT_FANOUT; iip++) { if (nnode->nbranch[iip].lnum) return ubifs_get_pnode(c, nnode, iip); } /* Go up while can't go right */ do { iip = nnode->iip + 1; nnode = nnode->parent; if (!nnode) return NULL; for (; iip < UBIFS_LPT_FANOUT; iip++) { if (nnode->nbranch[iip].lnum) break; } } while (iip >= UBIFS_LPT_FANOUT); /* Go right */ nnode = ubifs_get_nnode(c, nnode, iip); if (IS_ERR(nnode)) return (void *)nnode; /* Go down to level 1 */ while (nnode->level > 1) { for (iip = 0; iip < UBIFS_LPT_FANOUT; iip++) { if (nnode->nbranch[iip].lnum) break; } if (iip >= UBIFS_LPT_FANOUT) { /* * Should not happen, but we need to keep going * if it does. */ iip = 0; } nnode = ubifs_get_nnode(c, nnode, iip); if (IS_ERR(nnode)) return (void *)nnode; } for (iip = 0; iip < UBIFS_LPT_FANOUT; iip++) if (nnode->nbranch[iip].lnum) break; if (iip >= UBIFS_LPT_FANOUT) /* Should not happen, but we need to keep going if it does */ iip = 0; return ubifs_get_pnode(c, nnode, iip); } /** * pnode_lookup - lookup a pnode in the LPT. * @c: UBIFS file-system description object * @i: pnode number (0 to main_lebs - 1) * * This function returns a pointer to the pnode on success or a negative * error code on failure. */ static struct ubifs_pnode *pnode_lookup(struct ubifs_info *c, int i) { int err, h, iip, shft; struct ubifs_nnode *nnode; if (!c->nroot) { err = ubifs_read_nnode(c, NULL, 0); if (err) return ERR_PTR(err); } i <<= UBIFS_LPT_FANOUT_SHIFT; nnode = c->nroot; shft = c->lpt_hght * UBIFS_LPT_FANOUT_SHIFT; for (h = 1; h < c->lpt_hght; h++) { iip = ((i >> shft) & (UBIFS_LPT_FANOUT - 1)); shft -= UBIFS_LPT_FANOUT_SHIFT; nnode = ubifs_get_nnode(c, nnode, iip); if (IS_ERR(nnode)) return ERR_CAST(nnode); } iip = ((i >> shft) & (UBIFS_LPT_FANOUT - 1)); return ubifs_get_pnode(c, nnode, iip); } /** * add_pnode_dirt - add dirty space to LPT LEB properties. * @c: UBIFS file-system description object * @pnode: pnode for which to add dirt */ static void add_pnode_dirt(struct ubifs_info *c, struct ubifs_pnode *pnode) { ubifs_add_lpt_dirt(c, pnode->parent->nbranch[pnode->iip].lnum, c->pnode_sz); } /** * do_make_pnode_dirty - mark a pnode dirty. * @c: UBIFS file-system description object * @pnode: pnode to mark dirty */ static void do_make_pnode_dirty(struct ubifs_info *c, struct ubifs_pnode *pnode) { /* Assumes cnext list is empty i.e. not called during commit */ if (!test_and_set_bit(DIRTY_CNODE, &pnode->flags)) { struct ubifs_nnode *nnode; c->dirty_pn_cnt += 1; add_pnode_dirt(c, pnode); /* Mark parent and ancestors dirty too */ nnode = pnode->parent; while (nnode) { if (!test_and_set_bit(DIRTY_CNODE, &nnode->flags)) { c->dirty_nn_cnt += 1; ubifs_add_nnode_dirt(c, nnode); nnode = nnode->parent; } else break; } } } /** * make_tree_dirty - mark the entire LEB properties tree dirty. * @c: UBIFS file-system description object * * This function is used by the "small" LPT model to cause the entire LEB * properties tree to be written. The "small" LPT model does not use LPT * garbage collection because it is more efficient to write the entire tree * (because it is small). * * This function returns %0 on success and a negative error code on failure. */ static int make_tree_dirty(struct ubifs_info *c) { struct ubifs_pnode *pnode; pnode = pnode_lookup(c, 0); if (IS_ERR(pnode)) return PTR_ERR(pnode); while (pnode) { do_make_pnode_dirty(c, pnode); pnode = next_pnode_to_dirty(c, pnode); if (IS_ERR(pnode)) return PTR_ERR(pnode); } return 0; } /** * need_write_all - determine if the LPT area is running out of free space. * @c: UBIFS file-system description object * * This function returns %1 if the LPT area is running out of free space and %0 * if it is not. */ static int need_write_all(struct ubifs_info *c) { long long free = 0; int i; for (i = 0; i < c->lpt_lebs; i++) { if (i + c->lpt_first == c->nhead_lnum) free += c->leb_size - c->nhead_offs; else if (c->ltab[i].free == c->leb_size) free += c->leb_size; else if (c->ltab[i].free + c->ltab[i].dirty == c->leb_size) free += c->leb_size; } /* Less than twice the size left */ if (free <= c->lpt_sz * 2) return 1; return 0; } /** * lpt_tgc_start - start trivial garbage collection of LPT LEBs. * @c: UBIFS file-system description object * * LPT trivial garbage collection is where a LPT LEB contains only dirty and * free space and so may be reused as soon as the next commit is completed. * This function is called during start commit to mark LPT LEBs for trivial GC. */ static void lpt_tgc_start(struct ubifs_info *c) { int i; for (i = 0; i < c->lpt_lebs; i++) { if (i + c->lpt_first == c->nhead_lnum) continue; if (c->ltab[i].dirty > 0 && c->ltab[i].free + c->ltab[i].dirty == c->leb_size) { c->ltab[i].tgc = 1; c->ltab[i].free = c->leb_size; c->ltab[i].dirty = 0; dbg_lp("LEB %d", i + c->lpt_first); } } } /** * lpt_tgc_end - end trivial garbage collection of LPT LEBs. * @c: UBIFS file-system description object * * LPT trivial garbage collection is where a LPT LEB contains only dirty and * free space and so may be reused as soon as the next commit is completed. * This function is called after the commit is completed (master node has been * written) and un-maps LPT LEBs that were marked for trivial GC. */ static int lpt_tgc_end(struct ubifs_info *c) { int i, err; for (i = 0; i < c->lpt_lebs; i++) if (c->ltab[i].tgc) { err = ubifs_leb_unmap(c, i + c->lpt_first); if (err) return err; c->ltab[i].tgc = 0; dbg_lp("LEB %d", i + c->lpt_first); } return 0; } /** * populate_lsave - fill the lsave array with important LEB numbers. * @c: the UBIFS file-system description object * * This function is only called for the "big" model. It records a small number * of LEB numbers of important LEBs. Important LEBs are ones that are (from * most important to least important): empty, freeable, freeable index, dirty * index, dirty or free. Upon mount, we read this list of LEB numbers and bring * their pnodes into memory. That will stop us from having to scan the LPT * straight away. For the "small" model we assume that scanning the LPT is no * big deal. */ static void populate_lsave(struct ubifs_info *c) { struct ubifs_lprops *lprops; struct ubifs_lpt_heap *heap; int i, cnt = 0; ubifs_assert(c->big_lpt); if (!(c->lpt_drty_flgs & LSAVE_DIRTY)) { c->lpt_drty_flgs |= LSAVE_DIRTY; ubifs_add_lpt_dirt(c, c->lsave_lnum, c->lsave_sz); } if (dbg_populate_lsave(c)) return; list_for_each_entry(lprops, &c->empty_list, list) { c->lsave[cnt++] = lprops->lnum; if (cnt >= c->lsave_cnt) return; } list_for_each_entry(lprops, &c->freeable_list, list) { c->lsave[cnt++] = lprops->lnum; if (cnt >= c->lsave_cnt) return; } list_for_each_entry(lprops, &c->frdi_idx_list, list) { c->lsave[cnt++] = lprops->lnum; if (cnt >= c->lsave_cnt) return; } heap = &c->lpt_heap[LPROPS_DIRTY_IDX - 1]; for (i = 0; i < heap->cnt; i++) { c->lsave[cnt++] = heap->arr[i]->lnum; if (cnt >= c->lsave_cnt) return; } heap = &c->lpt_heap[LPROPS_DIRTY - 1]; for (i = 0; i < heap->cnt; i++) { c->lsave[cnt++] = heap->arr[i]->lnum; if (cnt >= c->lsave_cnt) return; } heap = &c->lpt_heap[LPROPS_FREE - 1]; for (i = 0; i < heap->cnt; i++) { c->lsave[cnt++] = heap->arr[i]->lnum; if (cnt >= c->lsave_cnt) return; } /* Fill it up completely */ while (cnt < c->lsave_cnt) c->lsave[cnt++] = c->main_first; } /** * nnode_lookup - lookup a nnode in the LPT. * @c: UBIFS file-system description object * @i: nnode number * * This function returns a pointer to the nnode on success or a negative * error code on failure. */ static struct ubifs_nnode *nnode_lookup(struct ubifs_info *c, int i) { int err, iip; struct ubifs_nnode *nnode; if (!c->nroot) { err = ubifs_read_nnode(c, NULL, 0); if (err) return ERR_PTR(err); } nnode = c->nroot; while (1) { iip = i & (UBIFS_LPT_FANOUT - 1); i >>= UBIFS_LPT_FANOUT_SHIFT; if (!i) break; nnode = ubifs_get_nnode(c, nnode, iip); if (IS_ERR(nnode)) return nnode; } return nnode; } /** * make_nnode_dirty - find a nnode and, if found, make it dirty. * @c: UBIFS file-system description object * @node_num: nnode number of nnode to make dirty * @lnum: LEB number where nnode was written * @offs: offset where nnode was written * * This function is used by LPT garbage collection. LPT garbage collection is * used only for the "big" LPT model (c->big_lpt == 1). Garbage collection * simply involves marking all the nodes in the LEB being garbage-collected as * dirty. The dirty nodes are written next commit, after which the LEB is free * to be reused. * * This function returns %0 on success and a negative error code on failure. */ static int make_nnode_dirty(struct ubifs_info *c, int node_num, int lnum, int offs) { struct ubifs_nnode *nnode; nnode = nnode_lookup(c, node_num); if (IS_ERR(nnode)) return PTR_ERR(nnode); if (nnode->parent) { struct ubifs_nbranch *branch; branch = &nnode->parent->nbranch[nnode->iip]; if (branch->lnum != lnum || branch->offs != offs) return 0; /* nnode is obsolete */ } else if (c->lpt_lnum != lnum || c->lpt_offs != offs) return 0; /* nnode is obsolete */ /* Assumes cnext list is empty i.e. not called during commit */ if (!test_and_set_bit(DIRTY_CNODE, &nnode->flags)) { c->dirty_nn_cnt += 1; ubifs_add_nnode_dirt(c, nnode); /* Mark parent and ancestors dirty too */ nnode = nnode->parent; while (nnode) { if (!test_and_set_bit(DIRTY_CNODE, &nnode->flags)) { c->dirty_nn_cnt += 1; ubifs_add_nnode_dirt(c, nnode); nnode = nnode->parent; } else break; } } return 0; } /** * make_pnode_dirty - find a pnode and, if found, make it dirty. * @c: UBIFS file-system description object * @node_num: pnode number of pnode to make dirty * @lnum: LEB number where pnode was written * @offs: offset where pnode was written * * This function is used by LPT garbage collection. LPT garbage collection is * used only for the "big" LPT model (c->big_lpt == 1). Garbage collection * simply involves marking all the nodes in the LEB being garbage-collected as * dirty. The dirty nodes are written next commit, after which the LEB is free * to be reused. * * This function returns %0 on success and a negative error code on failure. */ static int make_pnode_dirty(struct ubifs_info *c, int node_num, int lnum, int offs) { struct ubifs_pnode *pnode; struct ubifs_nbranch *branch; pnode = pnode_lookup(c, node_num); if (IS_ERR(pnode)) return PTR_ERR(pnode); branch = &pnode->parent->nbranch[pnode->iip]; if (branch->lnum != lnum || branch->offs != offs) return 0; do_make_pnode_dirty(c, pnode); return 0; } /** * make_ltab_dirty - make ltab node dirty. * @c: UBIFS file-system description object * @lnum: LEB number where ltab was written * @offs: offset where ltab was written * * This function is used by LPT garbage collection. LPT garbage collection is * used only for the "big" LPT model (c->big_lpt == 1). Garbage collection * simply involves marking all the nodes in the LEB being garbage-collected as * dirty. The dirty nodes are written next commit, after which the LEB is free * to be reused. * * This function returns %0 on success and a negative error code on failure. */ static int make_ltab_dirty(struct ubifs_info *c, int lnum, int offs) { if (lnum != c->ltab_lnum || offs != c->ltab_offs) return 0; /* This ltab node is obsolete */ if (!(c->lpt_drty_flgs & LTAB_DIRTY)) { c->lpt_drty_flgs |= LTAB_DIRTY; ubifs_add_lpt_dirt(c, c->ltab_lnum, c->ltab_sz); } return 0; } /** * make_lsave_dirty - make lsave node dirty. * @c: UBIFS file-system description object * @lnum: LEB number where lsave was written * @offs: offset where lsave was written * * This function is used by LPT garbage collection. LPT garbage collection is * used only for the "big" LPT model (c->big_lpt == 1). Garbage collection * simply involves marking all the nodes in the LEB being garbage-collected as * dirty. The dirty nodes are written next commit, after which the LEB is free * to be reused. * * This function returns %0 on success and a negative error code on failure. */ static int make_lsave_dirty(struct ubifs_info *c, int lnum, int offs) { if (lnum != c->lsave_lnum || offs != c->lsave_offs) return 0; /* This lsave node is obsolete */ if (!(c->lpt_drty_flgs & LSAVE_DIRTY)) { c->lpt_drty_flgs |= LSAVE_DIRTY; ubifs_add_lpt_dirt(c, c->lsave_lnum, c->lsave_sz); } return 0; } /** * make_node_dirty - make node dirty. * @c: UBIFS file-system description object * @node_type: LPT node type * @node_num: node number * @lnum: LEB number where node was written * @offs: offset where node was written * * This function is used by LPT garbage collection. LPT garbage collection is * used only for the "big" LPT model (c->big_lpt == 1). Garbage collection * simply involves marking all the nodes in the LEB being garbage-collected as * dirty. The dirty nodes are written next commit, after which the LEB is free * to be reused. * * This function returns %0 on success and a negative error code on failure. */ static int make_node_dirty(struct ubifs_info *c, int node_type, int node_num, int lnum, int offs) { switch (node_type) { case UBIFS_LPT_NNODE: return make_nnode_dirty(c, node_num, lnum, offs); case UBIFS_LPT_PNODE: return make_pnode_dirty(c, node_num, lnum, offs); case UBIFS_LPT_LTAB: return make_ltab_dirty(c, lnum, offs); case UBIFS_LPT_LSAVE: return make_lsave_dirty(c, lnum, offs); } return -EINVAL; } /** * get_lpt_node_len - return the length of a node based on its type. * @c: UBIFS file-system description object * @node_type: LPT node type */ static int get_lpt_node_len(const struct ubifs_info *c, int node_type) { switch (node_type) { case UBIFS_LPT_NNODE: return c->nnode_sz; case UBIFS_LPT_PNODE: return c->pnode_sz; case UBIFS_LPT_LTAB: return c->ltab_sz; case UBIFS_LPT_LSAVE: return c->lsave_sz; } return 0; } /** * get_pad_len - return the length of padding in a buffer. * @c: UBIFS file-system description object * @buf: buffer * @len: length of buffer */ static int get_pad_len(const struct ubifs_info *c, uint8_t *buf, int len) { int offs, pad_len; if (c->min_io_size == 1) return 0; offs = c->leb_size - len; pad_len = ALIGN(offs, c->min_io_size) - offs; return pad_len; } /** * get_lpt_node_type - return type (and node number) of a node in a buffer. * @c: UBIFS file-system description object * @buf: buffer * @node_num: node number is returned here */ static int get_lpt_node_type(const struct ubifs_info *c, uint8_t *buf, int *node_num) { uint8_t *addr = buf + UBIFS_LPT_CRC_BYTES; int pos = 0, node_type; node_type = ubifs_unpack_bits(&addr, &pos, UBIFS_LPT_TYPE_BITS); *node_num = ubifs_unpack_bits(&addr, &pos, c->pcnt_bits); return node_type; } /** * is_a_node - determine if a buffer contains a node. * @c: UBIFS file-system description object * @buf: buffer * @len: length of buffer * * This function returns %1 if the buffer contains a node or %0 if it does not. */ static int is_a_node(const struct ubifs_info *c, uint8_t *buf, int len) { uint8_t *addr = buf + UBIFS_LPT_CRC_BYTES; int pos = 0, node_type, node_len; uint16_t crc, calc_crc; if (len < UBIFS_LPT_CRC_BYTES + (UBIFS_LPT_TYPE_BITS + 7) / 8) return 0; node_type = ubifs_unpack_bits(&addr, &pos, UBIFS_LPT_TYPE_BITS); if (node_type == UBIFS_LPT_NOT_A_NODE) return 0; node_len = get_lpt_node_len(c, node_type); if (!node_len || node_len > len) return 0; pos = 0; addr = buf; crc = ubifs_unpack_bits(&addr, &pos, UBIFS_LPT_CRC_BITS); calc_crc = crc16(-1, buf + UBIFS_LPT_CRC_BYTES, node_len - UBIFS_LPT_CRC_BYTES); if (crc != calc_crc) return 0; return 1; } /** * lpt_gc_lnum - garbage collect a LPT LEB. * @c: UBIFS file-system description object * @lnum: LEB number to garbage collect * * LPT garbage collection is used only for the "big" LPT model * (c->big_lpt == 1). Garbage collection simply involves marking all the nodes * in the LEB being garbage-collected as dirty. The dirty nodes are written * next commit, after which the LEB is free to be reused. * * This function returns %0 on success and a negative error code on failure. */ static int lpt_gc_lnum(struct ubifs_info *c, int lnum) { int err, len = c->leb_size, node_type, node_num, node_len, offs; void *buf = c->lpt_buf; dbg_lp("LEB %d", lnum); err = ubifs_leb_read(c, lnum, buf, 0, c->leb_size, 1); if (err) return err; while (1) { if (!is_a_node(c, buf, len)) { int pad_len; pad_len = get_pad_len(c, buf, len); if (pad_len) { buf += pad_len; len -= pad_len; continue; } return 0; } node_type = get_lpt_node_type(c, buf, &node_num); node_len = get_lpt_node_len(c, node_type); offs = c->leb_size - len; ubifs_assert(node_len != 0); mutex_lock(&c->lp_mutex); err = make_node_dirty(c, node_type, node_num, lnum, offs); mutex_unlock(&c->lp_mutex); if (err) return err; buf += node_len; len -= node_len; } return 0; } /** * lpt_gc - LPT garbage collection. * @c: UBIFS file-system description object * * Select a LPT LEB for LPT garbage collection and call 'lpt_gc_lnum()'. * Returns %0 on success and a negative error code on failure. */ static int lpt_gc(struct ubifs_info *c) { int i, lnum = -1, dirty = 0; mutex_lock(&c->lp_mutex); for (i = 0; i < c->lpt_lebs; i++) { ubifs_assert(!c->ltab[i].tgc); if (i + c->lpt_first == c->nhead_lnum || c->ltab[i].free + c->ltab[i].dirty == c->leb_size) continue; if (c->ltab[i].dirty > dirty) { dirty = c->ltab[i].dirty; lnum = i + c->lpt_first; } } mutex_unlock(&c->lp_mutex); if (lnum == -1) return -ENOSPC; return lpt_gc_lnum(c, lnum); } /** * ubifs_lpt_start_commit - UBIFS commit starts. * @c: the UBIFS file-system description object * * This function has to be called when UBIFS starts the commit operation. * This function "freezes" all currently dirty LEB properties and does not * change them anymore. Further changes are saved and tracked separately * because they are not part of this commit. This function returns zero in case * of success and a negative error code in case of failure. */ int ubifs_lpt_start_commit(struct ubifs_info *c) { int err, cnt; dbg_lp(""); mutex_lock(&c->lp_mutex); err = dbg_chk_lpt_free_spc(c); if (err) goto out; err = dbg_check_ltab(c); if (err) goto out; if (c->check_lpt_free) { /* * We ensure there is enough free space in * ubifs_lpt_post_commit() by marking nodes dirty. That * information is lost when we unmount, so we also need * to check free space once after mounting also. */ c->check_lpt_free = 0; while (need_write_all(c)) { mutex_unlock(&c->lp_mutex); err = lpt_gc(c); if (err) return err; mutex_lock(&c->lp_mutex); } } lpt_tgc_start(c); if (!c->dirty_pn_cnt) { dbg_cmt("no cnodes to commit"); err = 0; goto out; } if (!c->big_lpt && need_write_all(c)) { /* If needed, write everything */ err = make_tree_dirty(c); if (err) goto out; lpt_tgc_start(c); } if (c->big_lpt) populate_lsave(c); cnt = get_cnodes_to_commit(c); ubifs_assert(cnt != 0); err = layout_cnodes(c); if (err) goto out; /* Copy the LPT's own lprops for end commit to write */ memcpy(c->ltab_cmt, c->ltab, sizeof(struct ubifs_lpt_lprops) * c->lpt_lebs); c->lpt_drty_flgs &= ~(LTAB_DIRTY | LSAVE_DIRTY); out: mutex_unlock(&c->lp_mutex); return err; } /** * free_obsolete_cnodes - free obsolete cnodes for commit end. * @c: UBIFS file-system description object */ static void free_obsolete_cnodes(struct ubifs_info *c) { struct ubifs_cnode *cnode, *cnext; cnext = c->lpt_cnext; if (!cnext) return; do { cnode = cnext; cnext = cnode->cnext; if (test_bit(OBSOLETE_CNODE, &cnode->flags)) kfree(cnode); else cnode->cnext = NULL; } while (cnext != c->lpt_cnext); c->lpt_cnext = NULL; } /** * ubifs_lpt_end_commit - finish the commit operation. * @c: the UBIFS file-system description object * * This function has to be called when the commit operation finishes. It * flushes the changes which were "frozen" by 'ubifs_lprops_start_commit()' to * the media. Returns zero in case of success and a negative error code in case * of failure. */ int ubifs_lpt_end_commit(struct ubifs_info *c) { int err; dbg_lp(""); if (!c->lpt_cnext) return 0; err = write_cnodes(c); if (err) return err; mutex_lock(&c->lp_mutex); free_obsolete_cnodes(c); mutex_unlock(&c->lp_mutex); return 0; } /** * ubifs_lpt_post_commit - post commit LPT trivial GC and LPT GC. * @c: UBIFS file-system description object * * LPT trivial GC is completed after a commit. Also LPT GC is done after a * commit for the "big" LPT model. */ int ubifs_lpt_post_commit(struct ubifs_info *c) { int err; mutex_lock(&c->lp_mutex); err = lpt_tgc_end(c); if (err) goto out; if (c->big_lpt) while (need_write_all(c)) { mutex_unlock(&c->lp_mutex); err = lpt_gc(c); if (err) return err; mutex_lock(&c->lp_mutex); } out: mutex_unlock(&c->lp_mutex); return err; } /** * first_nnode - find the first nnode in memory. * @c: UBIFS file-system description object * @hght: height of tree where nnode found is returned here * * This function returns a pointer to the nnode found or %NULL if no nnode is * found. This function is a helper to 'ubifs_lpt_free()'. */ static struct ubifs_nnode *first_nnode(struct ubifs_info *c, int *hght) { struct ubifs_nnode *nnode; int h, i, found; nnode = c->nroot; *hght = 0; if (!nnode) return NULL; for (h = 1; h < c->lpt_hght; h++) { found = 0; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { if (nnode->nbranch[i].nnode) { found = 1; nnode = nnode->nbranch[i].nnode; *hght = h; break; } } if (!found) break; } return nnode; } /** * next_nnode - find the next nnode in memory. * @c: UBIFS file-system description object * @nnode: nnode from which to start. * @hght: height of tree where nnode is, is passed and returned here * * This function returns a pointer to the nnode found or %NULL if no nnode is * found. This function is a helper to 'ubifs_lpt_free()'. */ static struct ubifs_nnode *next_nnode(struct ubifs_info *c, struct ubifs_nnode *nnode, int *hght) { struct ubifs_nnode *parent; int iip, h, i, found; parent = nnode->parent; if (!parent) return NULL; if (nnode->iip == UBIFS_LPT_FANOUT - 1) { *hght -= 1; return parent; } for (iip = nnode->iip + 1; iip < UBIFS_LPT_FANOUT; iip++) { nnode = parent->nbranch[iip].nnode; if (nnode) break; } if (!nnode) { *hght -= 1; return parent; } for (h = *hght + 1; h < c->lpt_hght; h++) { found = 0; for (i = 0; i < UBIFS_LPT_FANOUT; i++) { if (nnode->nbranch[i].nnode) { found = 1; nnode = nnode->nbranch[i].nnode; *hght = h; break; } } if (!found) break; } return nnode; } /** * ubifs_lpt_free - free resources owned by the LPT. * @c: UBIFS file-system description object * @wr_only: free only resources used for writing */ void ubifs_lpt_free(struct ubifs_info *c, int wr_only) { struct ubifs_nnode *nnode; int i, hght; /* Free write-only things first */ free_obsolete_cnodes(c); /* Leftover from a failed commit */ vfree(c->ltab_cmt); c->ltab_cmt = NULL; vfree(c->lpt_buf); c->lpt_buf = NULL; kfree(c->lsave); c->lsave = NULL; if (wr_only) return; /* Now free the rest */ nnode = first_nnode(c, &hght); while (nnode) { for (i = 0; i < UBIFS_LPT_FANOUT; i++) kfree(nnode->nbranch[i].nnode); nnode = next_nnode(c, nnode, &hght); } for (i = 0; i < LPROPS_HEAP_CNT; i++) kfree(c->lpt_heap[i].arr); kfree(c->dirty_idx.arr); kfree(c->nroot); vfree(c->ltab); kfree(c->lpt_nod_buf); } #ifdef CONFIG_UBIFS_FS_DEBUG /** * dbg_is_all_ff - determine if a buffer contains only 0xFF bytes. * @buf: buffer * @len: buffer length */ static int dbg_is_all_ff(uint8_t *buf, int len) { int i; for (i = 0; i < len; i++) if (buf[i] != 0xff) return 0; return 1; } /** * dbg_is_nnode_dirty - determine if a nnode is dirty. * @c: the UBIFS file-system description object * @lnum: LEB number where nnode was written * @offs: offset where nnode was written */ static int dbg_is_nnode_dirty(struct ubifs_info *c, int lnum, int offs) { struct ubifs_nnode *nnode; int hght; /* Entire tree is in memory so first_nnode / next_nnode are OK */ nnode = first_nnode(c, &hght); for (; nnode; nnode = next_nnode(c, nnode, &hght)) { struct ubifs_nbranch *branch; cond_resched(); if (nnode->parent) { branch = &nnode->parent->nbranch[nnode->iip]; if (branch->lnum != lnum || branch->offs != offs) continue; if (test_bit(DIRTY_CNODE, &nnode->flags)) return 1; return 0; } else { if (c->lpt_lnum != lnum || c->lpt_offs != offs) continue; if (test_bit(DIRTY_CNODE, &nnode->flags)) return 1; return 0; } } return 1; } /** * dbg_is_pnode_dirty - determine if a pnode is dirty. * @c: the UBIFS file-system description object * @lnum: LEB number where pnode was written * @offs: offset where pnode was written */ static int dbg_is_pnode_dirty(struct ubifs_info *c, int lnum, int offs) { int i, cnt; cnt = DIV_ROUND_UP(c->main_lebs, UBIFS_LPT_FANOUT); for (i = 0; i < cnt; i++) { struct ubifs_pnode *pnode; struct ubifs_nbranch *branch; cond_resched(); pnode = pnode_lookup(c, i); if (IS_ERR(pnode)) return PTR_ERR(pnode); branch = &pnode->parent->nbranch[pnode->iip]; if (branch->lnum != lnum || branch->offs != offs) continue; if (test_bit(DIRTY_CNODE, &pnode->flags)) return 1; return 0; } return 1; } /** * dbg_is_ltab_dirty - determine if a ltab node is dirty. * @c: the UBIFS file-system description object * @lnum: LEB number where ltab node was written * @offs: offset where ltab node was written */ static int dbg_is_ltab_dirty(struct ubifs_info *c, int lnum, int offs) { if (lnum != c->ltab_lnum || offs != c->ltab_offs) return 1; return (c->lpt_drty_flgs & LTAB_DIRTY) != 0; } /** * dbg_is_lsave_dirty - determine if a lsave node is dirty. * @c: the UBIFS file-system description object * @lnum: LEB number where lsave node was written * @offs: offset where lsave node was written */ static int dbg_is_lsave_dirty(struct ubifs_info *c, int lnum, int offs) { if (lnum != c->lsave_lnum || offs != c->lsave_offs) return 1; return (c->lpt_drty_flgs & LSAVE_DIRTY) != 0; } /** * dbg_is_node_dirty - determine if a node is dirty. * @c: the UBIFS file-system description object * @node_type: node type * @lnum: LEB number where node was written * @offs: offset where node was written */ static int dbg_is_node_dirty(struct ubifs_info *c, int node_type, int lnum, int offs) { switch (node_type) { case UBIFS_LPT_NNODE: return dbg_is_nnode_dirty(c, lnum, offs); case UBIFS_LPT_PNODE: return dbg_is_pnode_dirty(c, lnum, offs); case UBIFS_LPT_LTAB: return dbg_is_ltab_dirty(c, lnum, offs); case UBIFS_LPT_LSAVE: return dbg_is_lsave_dirty(c, lnum, offs); } return 1; } /** * dbg_check_ltab_lnum - check the ltab for a LPT LEB number. * @c: the UBIFS file-system description object * @lnum: LEB number where node was written * @offs: offset where node was written * * This function returns %0 on success and a negative error code on failure. */ static int dbg_check_ltab_lnum(struct ubifs_info *c, int lnum) { int err, len = c->leb_size, dirty = 0, node_type, node_num, node_len; int ret; void *buf, *p; if (!dbg_is_chk_lprops(c)) return 0; buf = p = __vmalloc(c->leb_size, GFP_NOFS, PAGE_KERNEL); if (!buf) { ubifs_err("cannot allocate memory for ltab checking"); return 0; } dbg_lp("LEB %d", lnum); err = ubifs_leb_read(c, lnum, buf, 0, c->leb_size, 1); if (err) goto out; while (1) { if (!is_a_node(c, p, len)) { int i, pad_len; pad_len = get_pad_len(c, p, len); if (pad_len) { p += pad_len; len -= pad_len; dirty += pad_len; continue; } if (!dbg_is_all_ff(p, len)) { dbg_msg("invalid empty space in LEB %d at %d", lnum, c->leb_size - len); err = -EINVAL; } i = lnum - c->lpt_first; if (len != c->ltab[i].free) { dbg_msg("invalid free space in LEB %d " "(free %d, expected %d)", lnum, len, c->ltab[i].free); err = -EINVAL; } if (dirty != c->ltab[i].dirty) { dbg_msg("invalid dirty space in LEB %d " "(dirty %d, expected %d)", lnum, dirty, c->ltab[i].dirty); err = -EINVAL; } goto out; } node_type = get_lpt_node_type(c, p, &node_num); node_len = get_lpt_node_len(c, node_type); ret = dbg_is_node_dirty(c, node_type, lnum, c->leb_size - len); if (ret == 1) dirty += node_len; p += node_len; len -= node_len; } err = 0; out: vfree(buf); return err; } /** * dbg_check_ltab - check the free and dirty space in the ltab. * @c: the UBIFS file-system description object * * This function returns %0 on success and a negative error code on failure. */ int dbg_check_ltab(struct ubifs_info *c) { int lnum, err, i, cnt; if (!dbg_is_chk_lprops(c)) return 0; /* Bring the entire tree into memory */ cnt = DIV_ROUND_UP(c->main_lebs, UBIFS_LPT_FANOUT); for (i = 0; i < cnt; i++) { struct ubifs_pnode *pnode; pnode = pnode_lookup(c, i); if (IS_ERR(pnode)) return PTR_ERR(pnode); cond_resched(); } /* Check nodes */ err = dbg_check_lpt_nodes(c, (struct ubifs_cnode *)c->nroot, 0, 0); if (err) return err; /* Check each LEB */ for (lnum = c->lpt_first; lnum <= c->lpt_last; lnum++) { err = dbg_check_ltab_lnum(c, lnum); if (err) { dbg_err("failed at LEB %d", lnum); return err; } } dbg_lp("succeeded"); return 0; } /** * dbg_chk_lpt_free_spc - check LPT free space is enough to write entire LPT. * @c: the UBIFS file-system description object * * This function returns %0 on success and a negative error code on failure. */ int dbg_chk_lpt_free_spc(struct ubifs_info *c) { long long free = 0; int i; if (!dbg_is_chk_lprops(c)) return 0; for (i = 0; i < c->lpt_lebs; i++) { if (c->ltab[i].tgc || c->ltab[i].cmt) continue; if (i + c->lpt_first == c->nhead_lnum) free += c->leb_size - c->nhead_offs; else if (c->ltab[i].free == c->leb_size) free += c->leb_size; } if (free < c->lpt_sz) { dbg_err("LPT space error: free %lld lpt_sz %lld", free, c->lpt_sz); dbg_dump_lpt_info(c); dbg_dump_lpt_lebs(c); dump_stack(); return -EINVAL; } return 0; } /** * dbg_chk_lpt_sz - check LPT does not write more than LPT size. * @c: the UBIFS file-system description object * @action: what to do * @len: length written * * This function returns %0 on success and a negative error code on failure. * The @action argument may be one of: * o %0 - LPT debugging checking starts, initialize debugging variables; * o %1 - wrote an LPT node, increase LPT size by @len bytes; * o %2 - switched to a different LEB and wasted @len bytes; * o %3 - check that we've written the right number of bytes. * o %4 - wasted @len bytes; */ int dbg_chk_lpt_sz(struct ubifs_info *c, int action, int len) { struct ubifs_debug_info *d = c->dbg; long long chk_lpt_sz, lpt_sz; int err = 0; if (!dbg_is_chk_lprops(c)) return 0; switch (action) { case 0: d->chk_lpt_sz = 0; d->chk_lpt_sz2 = 0; d->chk_lpt_lebs = 0; d->chk_lpt_wastage = 0; if (c->dirty_pn_cnt > c->pnode_cnt) { dbg_err("dirty pnodes %d exceed max %d", c->dirty_pn_cnt, c->pnode_cnt); err = -EINVAL; } if (c->dirty_nn_cnt > c->nnode_cnt) { dbg_err("dirty nnodes %d exceed max %d", c->dirty_nn_cnt, c->nnode_cnt); err = -EINVAL; } return err; case 1: d->chk_lpt_sz += len; return 0; case 2: d->chk_lpt_sz += len; d->chk_lpt_wastage += len; d->chk_lpt_lebs += 1; return 0; case 3: chk_lpt_sz = c->leb_size; chk_lpt_sz *= d->chk_lpt_lebs; chk_lpt_sz += len - c->nhead_offs; if (d->chk_lpt_sz != chk_lpt_sz) { dbg_err("LPT wrote %lld but space used was %lld", d->chk_lpt_sz, chk_lpt_sz); err = -EINVAL; } if (d->chk_lpt_sz > c->lpt_sz) { dbg_err("LPT wrote %lld but lpt_sz is %lld", d->chk_lpt_sz, c->lpt_sz); err = -EINVAL; } if (d->chk_lpt_sz2 && d->chk_lpt_sz != d->chk_lpt_sz2) { dbg_err("LPT layout size %lld but wrote %lld", d->chk_lpt_sz, d->chk_lpt_sz2); err = -EINVAL; } if (d->chk_lpt_sz2 && d->new_nhead_offs != len) { dbg_err("LPT new nhead offs: expected %d was %d", d->new_nhead_offs, len); err = -EINVAL; } lpt_sz = (long long)c->pnode_cnt * c->pnode_sz; lpt_sz += (long long)c->nnode_cnt * c->nnode_sz; lpt_sz += c->ltab_sz; if (c->big_lpt) lpt_sz += c->lsave_sz; if (d->chk_lpt_sz - d->chk_lpt_wastage > lpt_sz) { dbg_err("LPT chk_lpt_sz %lld + waste %lld exceeds %lld", d->chk_lpt_sz, d->chk_lpt_wastage, lpt_sz); err = -EINVAL; } if (err) { dbg_dump_lpt_info(c); dbg_dump_lpt_lebs(c); dump_stack(); } d->chk_lpt_sz2 = d->chk_lpt_sz; d->chk_lpt_sz = 0; d->chk_lpt_wastage = 0; d->chk_lpt_lebs = 0; d->new_nhead_offs = len; return err; case 4: d->chk_lpt_sz += len; d->chk_lpt_wastage += len; return 0; default: return -EINVAL; } } /** * dbg_dump_lpt_leb - dump an LPT LEB. * @c: UBIFS file-system description object * @lnum: LEB number to dump * * This function dumps an LEB from LPT area. Nodes in this area are very * different to nodes in the main area (e.g., they do not have common headers, * they do not have 8-byte alignments, etc), so we have a separate function to * dump LPT area LEBs. Note, LPT has to be locked by the caller. */ static void dump_lpt_leb(const struct ubifs_info *c, int lnum) { int err, len = c->leb_size, node_type, node_num, node_len, offs; void *buf, *p; printk(KERN_DEBUG "(pid %d) start dumping LEB %d\n", current->pid, lnum); buf = p = __vmalloc(c->leb_size, GFP_NOFS, PAGE_KERNEL); if (!buf) { ubifs_err("cannot allocate memory to dump LPT"); return; } err = ubifs_leb_read(c, lnum, buf, 0, c->leb_size, 1); if (err) goto out; while (1) { offs = c->leb_size - len; if (!is_a_node(c, p, len)) { int pad_len; pad_len = get_pad_len(c, p, len); if (pad_len) { printk(KERN_DEBUG "LEB %d:%d, pad %d bytes\n", lnum, offs, pad_len); p += pad_len; len -= pad_len; continue; } if (len) printk(KERN_DEBUG "LEB %d:%d, free %d bytes\n", lnum, offs, len); break; } node_type = get_lpt_node_type(c, p, &node_num); switch (node_type) { case UBIFS_LPT_PNODE: { node_len = c->pnode_sz; if (c->big_lpt) printk(KERN_DEBUG "LEB %d:%d, pnode num %d\n", lnum, offs, node_num); else printk(KERN_DEBUG "LEB %d:%d, pnode\n", lnum, offs); break; } case UBIFS_LPT_NNODE: { int i; struct ubifs_nnode nnode; node_len = c->nnode_sz; if (c->big_lpt) printk(KERN_DEBUG "LEB %d:%d, nnode num %d, ", lnum, offs, node_num); else printk(KERN_DEBUG "LEB %d:%d, nnode, ", lnum, offs); err = ubifs_unpack_nnode(c, p, &nnode); for (i = 0; i < UBIFS_LPT_FANOUT; i++) { printk(KERN_CONT "%d:%d", nnode.nbranch[i].lnum, nnode.nbranch[i].offs); if (i != UBIFS_LPT_FANOUT - 1) printk(KERN_CONT ", "); } printk(KERN_CONT "\n"); break; } case UBIFS_LPT_LTAB: node_len = c->ltab_sz; printk(KERN_DEBUG "LEB %d:%d, ltab\n", lnum, offs); break; case UBIFS_LPT_LSAVE: node_len = c->lsave_sz; printk(KERN_DEBUG "LEB %d:%d, lsave len\n", lnum, offs); break; default: ubifs_err("LPT node type %d not recognized", node_type); goto out; } p += node_len; len -= node_len; } printk(KERN_DEBUG "(pid %d) finish dumping LEB %d\n", current->pid, lnum); out: vfree(buf); return; } /** * dbg_dump_lpt_lebs - dump LPT lebs. * @c: UBIFS file-system description object * * This function dumps all LPT LEBs. The caller has to make sure the LPT is * locked. */ void dbg_dump_lpt_lebs(const struct ubifs_info *c) { int i; printk(KERN_DEBUG "(pid %d) start dumping all LPT LEBs\n", current->pid); for (i = 0; i < c->lpt_lebs; i++) dump_lpt_leb(c, i + c->lpt_first); printk(KERN_DEBUG "(pid %d) finish dumping all LPT LEBs\n", current->pid); } /** * dbg_populate_lsave - debugging version of 'populate_lsave()' * @c: UBIFS file-system description object * * This is a debugging version for 'populate_lsave()' which populates lsave * with random LEBs instead of useful LEBs, which is good for test coverage. * Returns zero if lsave has not been populated (this debugging feature is * disabled) an non-zero if lsave has been populated. */ static int dbg_populate_lsave(struct ubifs_info *c) { struct ubifs_lprops *lprops; struct ubifs_lpt_heap *heap; int i; if (!dbg_is_chk_gen(c)) return 0; if (random32() & 3) return 0; for (i = 0; i < c->lsave_cnt; i++) c->lsave[i] = c->main_first; list_for_each_entry(lprops, &c->empty_list, list) c->lsave[random32() % c->lsave_cnt] = lprops->lnum; list_for_each_entry(lprops, &c->freeable_list, list) c->lsave[random32() % c->lsave_cnt] = lprops->lnum; list_for_each_entry(lprops, &c->frdi_idx_list, list) c->lsave[random32() % c->lsave_cnt] = lprops->lnum; heap = &c->lpt_heap[LPROPS_DIRTY_IDX - 1]; for (i = 0; i < heap->cnt; i++) c->lsave[random32() % c->lsave_cnt] = heap->arr[i]->lnum; heap = &c->lpt_heap[LPROPS_DIRTY - 1]; for (i = 0; i < heap->cnt; i++) c->lsave[random32() % c->lsave_cnt] = heap->arr[i]->lnum; heap = &c->lpt_heap[LPROPS_FREE - 1]; for (i = 0; i < heap->cnt; i++) c->lsave[random32() % c->lsave_cnt] = heap->arr[i]->lnum; return 1; } #endif /* CONFIG_UBIFS_FS_DEBUG */
thanhphat11/Android_kernel_xiaomi_ALL
fs/ubifs/lpt_commit.c
C
gpl-2.0
53,304
/* * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. * * Copyright (C) 2002-2010 Aleph One Ltd. * for Toby Churchill Ltd and Brightstar Engineering * * Created by Charles Manning <charles@aleph1.co.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include "yaffs_packedtags2.h" #include "yportenv.h" #include "yaffs_trace.h" #include "yaffs_tagsvalidity.h" /* This code packs a set of extended tags into a binary structure for * NAND storage */ /* Some of the information is "extra" struff which can be packed in to * speed scanning * This is defined by having the EXTRA_HEADER_INFO_FLAG set. */ /* Extra flags applied to chunk_id */ #define EXTRA_HEADER_INFO_FLAG 0x80000000 #define EXTRA_SHRINK_FLAG 0x40000000 #define EXTRA_SHADOWS_FLAG 0x20000000 #define EXTRA_SPARE_FLAGS 0x10000000 #define ALL_EXTRA_FLAGS 0xF0000000 /* Also, the top 4 bits of the object Id are set to the object type. */ #define EXTRA_OBJECT_TYPE_SHIFT (28) #define EXTRA_OBJECT_TYPE_MASK ((0x0F) << EXTRA_OBJECT_TYPE_SHIFT) static void yaffs_dump_packed_tags2_tags_only(const struct yaffs_packed_tags2_tags_only *ptt) { yaffs_trace(YAFFS_TRACE_MTD, "packed tags obj %d chunk %d byte %d seq %d", ptt->obj_id, ptt->chunk_id, ptt->n_bytes, ptt->seq_number); } static void yaffs_dump_packed_tags2(const struct yaffs_packed_tags2 *pt) { yaffs_dump_packed_tags2_tags_only(&pt->t); } static void yaffs_dump_tags2(const struct yaffs_ext_tags *t) { yaffs_trace(YAFFS_TRACE_MTD, "ext.tags eccres %d blkbad %d chused %d obj %d chunk%d byte %d del %d ser %d seq %d", t->ecc_result, t->block_bad, t->chunk_used, t->obj_id, t->chunk_id, t->n_bytes, t->is_deleted, t->serial_number, t->seq_number); } void yaffs_pack_tags2_tags_only(struct yaffs_packed_tags2_tags_only *ptt, const struct yaffs_ext_tags *t) { ptt->chunk_id = t->chunk_id; ptt->seq_number = t->seq_number; ptt->n_bytes = t->n_bytes; ptt->obj_id = t->obj_id; if (t->chunk_id == 0 && t->extra_available) { /* Store the extra header info instead */ /* We save the parent object in the chunk_id */ ptt->chunk_id = EXTRA_HEADER_INFO_FLAG | t->extra_parent_id; if (t->extra_is_shrink) ptt->chunk_id |= EXTRA_SHRINK_FLAG; if (t->extra_shadows) ptt->chunk_id |= EXTRA_SHADOWS_FLAG; ptt->obj_id &= ~EXTRA_OBJECT_TYPE_MASK; ptt->obj_id |= (t->extra_obj_type << EXTRA_OBJECT_TYPE_SHIFT); if (t->extra_obj_type == YAFFS_OBJECT_TYPE_HARDLINK) ptt->n_bytes = t->extra_equiv_id; else if (t->extra_obj_type == YAFFS_OBJECT_TYPE_FILE) ptt->n_bytes = t->extra_length; else ptt->n_bytes = 0; } yaffs_dump_packed_tags2_tags_only(ptt); yaffs_dump_tags2(t); } void yaffs_pack_tags2(struct yaffs_packed_tags2 *pt, const struct yaffs_ext_tags *t, int tags_ecc) { yaffs_pack_tags2_tags_only(&pt->t, t); if (tags_ecc) yaffs_ecc_calc_other((unsigned char *)&pt->t, sizeof(struct yaffs_packed_tags2_tags_only), &pt->ecc); } void yaffs_unpack_tags2_tags_only(struct yaffs_ext_tags *t, struct yaffs_packed_tags2_tags_only *ptt) { memset(t, 0, sizeof(struct yaffs_ext_tags)); yaffs_init_tags(t); if (ptt->seq_number != 0xFFFFFFFF) { t->block_bad = 0; t->chunk_used = 1; t->obj_id = ptt->obj_id; t->chunk_id = ptt->chunk_id; t->n_bytes = ptt->n_bytes; t->is_deleted = 0; t->serial_number = 0; t->seq_number = ptt->seq_number; /* Do extra header info stuff */ if (ptt->chunk_id & EXTRA_HEADER_INFO_FLAG) { t->chunk_id = 0; t->n_bytes = 0; t->extra_available = 1; t->extra_parent_id = ptt->chunk_id & (~(ALL_EXTRA_FLAGS)); t->extra_is_shrink = (ptt->chunk_id & EXTRA_SHRINK_FLAG) ? 1 : 0; t->extra_shadows = (ptt->chunk_id & EXTRA_SHADOWS_FLAG) ? 1 : 0; t->extra_obj_type = ptt->obj_id >> EXTRA_OBJECT_TYPE_SHIFT; t->obj_id &= ~EXTRA_OBJECT_TYPE_MASK; if (t->extra_obj_type == YAFFS_OBJECT_TYPE_HARDLINK) t->extra_equiv_id = ptt->n_bytes; else t->extra_length = ptt->n_bytes; } } yaffs_dump_packed_tags2_tags_only(ptt); yaffs_dump_tags2(t); } void yaffs_unpack_tags2(struct yaffs_ext_tags *t, struct yaffs_packed_tags2 *pt, int tags_ecc) { enum yaffs_ecc_result ecc_result = YAFFS_ECC_RESULT_NO_ERROR; if (pt->t.seq_number != 0xFFFFFFFF && tags_ecc) { /* Chunk is in use and we need to do ECC */ struct yaffs_ecc_other ecc; int result; yaffs_ecc_calc_other((unsigned char *)&pt->t, sizeof(struct yaffs_packed_tags2_tags_only), &ecc); result = yaffs_ecc_correct_other((unsigned char *)&pt->t, sizeof(struct yaffs_packed_tags2_tags_only), &pt->ecc, &ecc); switch (result) { case 0: ecc_result = YAFFS_ECC_RESULT_NO_ERROR; break; case 1: ecc_result = YAFFS_ECC_RESULT_FIXED; break; case -1: ecc_result = YAFFS_ECC_RESULT_UNFIXED; break; default: ecc_result = YAFFS_ECC_RESULT_UNKNOWN; } } yaffs_unpack_tags2_tags_only(t, &pt->t); t->ecc_result = ecc_result; yaffs_dump_packed_tags2(pt); yaffs_dump_tags2(t); }
mtx512/linux-mixtile
fs/yaffs2/yaffs_packedtags2.c
C
gpl-2.0
5,247
/* * Copyright (C) 1996 SpellCaster Telecommunications Inc. * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include "includes.h" #include "hardware.h" #include "message.h" #include "card.h" #include "scioc.h" static int GetStatus(int card, boardInfo *); /* * Process private IOCTL messages (typically from scctrl) */ int sc_ioctl(int card, scs_ioctl *data) { int status; RspMessage *rcvmsg; char *spid; char *dn; char switchtype; char speed; rcvmsg = kmalloc(sizeof(RspMessage), GFP_KERNEL); if (!rcvmsg) return -ENOMEM; switch (data->command) { case SCIOCRESET: /* Perform a hard reset of the adapter */ { pr_debug("%s: SCIOCRESET: ioctl received\n", sc_adapter[card]->devicename); sc_adapter[card]->StartOnReset = 0; kfree(rcvmsg); return reset(card); } case SCIOCLOAD: { char *srec; srec = kmalloc(SCIOC_SRECSIZE, GFP_KERNEL); if (!srec) { kfree(rcvmsg); return -ENOMEM; } pr_debug("%s: SCIOLOAD: ioctl received\n", sc_adapter[card]->devicename); if (sc_adapter[card]->EngineUp) { pr_debug("%s: SCIOCLOAD: command failed, LoadProc while engine running.\n", sc_adapter[card]->devicename); kfree(rcvmsg); kfree(srec); return -1; } /* * Get the SRec from user space */ if (copy_from_user(srec, data->dataptr, SCIOC_SRECSIZE)) { kfree(rcvmsg); kfree(srec); return -EFAULT; } status = send_and_receive(card, CMPID, cmReqType2, cmReqClass0, cmReqLoadProc, 0, SCIOC_SRECSIZE, srec, rcvmsg, SAR_TIMEOUT); kfree(rcvmsg); kfree(srec); if (status) { pr_debug("%s: SCIOCLOAD: command failed, status = %d\n", sc_adapter[card]->devicename, status); return -1; } else { pr_debug("%s: SCIOCLOAD: command successful\n", sc_adapter[card]->devicename); return 0; } } case SCIOCSTART: { kfree(rcvmsg); pr_debug("%s: SCIOSTART: ioctl received\n", sc_adapter[card]->devicename); if (sc_adapter[card]->EngineUp) { pr_debug("%s: SCIOCSTART: command failed, engine already running.\n", sc_adapter[card]->devicename); return -1; } sc_adapter[card]->StartOnReset = 1; startproc(card); return 0; } case SCIOCSETSWITCH: { pr_debug("%s: SCIOSETSWITCH: ioctl received\n", sc_adapter[card]->devicename); /* * Get the switch type from user space */ if (copy_from_user(&switchtype, data->dataptr, sizeof(char))) { kfree(rcvmsg); return -EFAULT; } pr_debug("%s: SCIOCSETSWITCH: setting switch type to %d\n", sc_adapter[card]->devicename, switchtype); status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallSetSwitchType, 0, sizeof(char), &switchtype, rcvmsg, SAR_TIMEOUT); if (!status && !(rcvmsg->rsp_status)) { pr_debug("%s: SCIOCSETSWITCH: command successful\n", sc_adapter[card]->devicename); kfree(rcvmsg); return 0; } else { pr_debug("%s: SCIOCSETSWITCH: command failed (status = %d)\n", sc_adapter[card]->devicename, status); kfree(rcvmsg); return status; } } case SCIOCGETSWITCH: { pr_debug("%s: SCIOGETSWITCH: ioctl received\n", sc_adapter[card]->devicename); /* * Get the switch type from the board */ status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallGetSwitchType, 0, 0, NULL, rcvmsg, SAR_TIMEOUT); if (!status && !(rcvmsg->rsp_status)) { pr_debug("%s: SCIOCGETSWITCH: command successful\n", sc_adapter[card]->devicename); } else { pr_debug("%s: SCIOCGETSWITCH: command failed (status = %d)\n", sc_adapter[card]->devicename, status); kfree(rcvmsg); return status; } switchtype = rcvmsg->msg_data.byte_array[0]; /* * Package the switch type and send to user space */ if (copy_to_user(data->dataptr, &switchtype, sizeof(char))) { kfree(rcvmsg); return -EFAULT; } kfree(rcvmsg); return 0; } case SCIOCGETSPID: { pr_debug("%s: SCIOGETSPID: ioctl received\n", sc_adapter[card]->devicename); spid = kzalloc(SCIOC_SPIDSIZE, GFP_KERNEL); if (!spid) { kfree(rcvmsg); return -ENOMEM; } /* * Get the spid from the board */ status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallGetSPID, data->channel, 0, NULL, rcvmsg, SAR_TIMEOUT); if (!status) { pr_debug("%s: SCIOCGETSPID: command successful\n", sc_adapter[card]->devicename); } else { pr_debug("%s: SCIOCGETSPID: command failed (status = %d)\n", sc_adapter[card]->devicename, status); kfree(spid); kfree(rcvmsg); return status; } strlcpy(spid, rcvmsg->msg_data.byte_array, SCIOC_SPIDSIZE); /* * Package the switch type and send to user space */ if (copy_to_user(data->dataptr, spid, SCIOC_SPIDSIZE)) { kfree(spid); kfree(rcvmsg); return -EFAULT; } kfree(spid); kfree(rcvmsg); return 0; } case SCIOCSETSPID: { pr_debug("%s: DCBIOSETSPID: ioctl received\n", sc_adapter[card]->devicename); /* * Get the spid from user space */ spid = memdup_user(data->dataptr, SCIOC_SPIDSIZE); if (IS_ERR(spid)) { kfree(rcvmsg); return PTR_ERR(spid); } pr_debug("%s: SCIOCSETSPID: setting channel %d spid to %s\n", sc_adapter[card]->devicename, data->channel, spid); status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallSetSPID, data->channel, strlen(spid), spid, rcvmsg, SAR_TIMEOUT); if (!status && !(rcvmsg->rsp_status)) { pr_debug("%s: SCIOCSETSPID: command successful\n", sc_adapter[card]->devicename); kfree(rcvmsg); kfree(spid); return 0; } else { pr_debug("%s: SCIOCSETSPID: command failed (status = %d)\n", sc_adapter[card]->devicename, status); kfree(rcvmsg); kfree(spid); return status; } } case SCIOCGETDN: { pr_debug("%s: SCIOGETDN: ioctl received\n", sc_adapter[card]->devicename); /* * Get the dn from the board */ status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallGetMyNumber, data->channel, 0, NULL, rcvmsg, SAR_TIMEOUT); if (!status) { pr_debug("%s: SCIOCGETDN: command successful\n", sc_adapter[card]->devicename); } else { pr_debug("%s: SCIOCGETDN: command failed (status = %d)\n", sc_adapter[card]->devicename, status); kfree(rcvmsg); return status; } dn = kzalloc(SCIOC_DNSIZE, GFP_KERNEL); if (!dn) { kfree(rcvmsg); return -ENOMEM; } strlcpy(dn, rcvmsg->msg_data.byte_array, SCIOC_DNSIZE); kfree(rcvmsg); /* * Package the dn and send to user space */ if (copy_to_user(data->dataptr, dn, SCIOC_DNSIZE)) { kfree(dn); return -EFAULT; } kfree(dn); return 0; } case SCIOCSETDN: { pr_debug("%s: SCIOSETDN: ioctl received\n", sc_adapter[card]->devicename); /* * Get the spid from user space */ dn = memdup_user(data->dataptr, SCIOC_DNSIZE); if (IS_ERR(dn)) { kfree(rcvmsg); return PTR_ERR(dn); } pr_debug("%s: SCIOCSETDN: setting channel %d dn to %s\n", sc_adapter[card]->devicename, data->channel, dn); status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallSetMyNumber, data->channel, strlen(dn), dn, rcvmsg, SAR_TIMEOUT); if (!status && !(rcvmsg->rsp_status)) { pr_debug("%s: SCIOCSETDN: command successful\n", sc_adapter[card]->devicename); kfree(rcvmsg); kfree(dn); return 0; } else { pr_debug("%s: SCIOCSETDN: command failed (status = %d)\n", sc_adapter[card]->devicename, status); kfree(rcvmsg); kfree(dn); return status; } } case SCIOCTRACE: pr_debug("%s: SCIOTRACE: ioctl received\n", sc_adapter[card]->devicename); /* sc_adapter[card]->trace = !sc_adapter[card]->trace; pr_debug("%s: SCIOCTRACE: tracing turned %s\n", sc_adapter[card]->devicename, sc_adapter[card]->trace ? "ON" : "OFF"); */ break; case SCIOCSTAT: { boardInfo *bi; pr_debug("%s: SCIOSTAT: ioctl received\n", sc_adapter[card]->devicename); bi = kzalloc(sizeof(boardInfo), GFP_KERNEL); if (!bi) { kfree(rcvmsg); return -ENOMEM; } kfree(rcvmsg); GetStatus(card, bi); if (copy_to_user(data->dataptr, bi, sizeof(boardInfo))) { kfree(bi); return -EFAULT; } kfree(bi); return 0; } case SCIOCGETSPEED: { pr_debug("%s: SCIOGETSPEED: ioctl received\n", sc_adapter[card]->devicename); /* * Get the speed from the board */ status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallGetCallType, data->channel, 0, NULL, rcvmsg, SAR_TIMEOUT); if (!status && !(rcvmsg->rsp_status)) { pr_debug("%s: SCIOCGETSPEED: command successful\n", sc_adapter[card]->devicename); } else { pr_debug("%s: SCIOCGETSPEED: command failed (status = %d)\n", sc_adapter[card]->devicename, status); kfree(rcvmsg); return status; } speed = rcvmsg->msg_data.byte_array[0]; kfree(rcvmsg); /* * Package the switch type and send to user space */ if (copy_to_user(data->dataptr, &speed, sizeof(char))) return -EFAULT; return 0; } case SCIOCSETSPEED: pr_debug("%s: SCIOCSETSPEED: ioctl received\n", sc_adapter[card]->devicename); break; case SCIOCLOOPTST: pr_debug("%s: SCIOCLOOPTST: ioctl received\n", sc_adapter[card]->devicename); break; default: kfree(rcvmsg); return -1; } kfree(rcvmsg); return 0; } static int GetStatus(int card, boardInfo *bi) { RspMessage rcvmsg; int i, status; /* * Fill in some of the basic info about the board */ bi->modelid = sc_adapter[card]->model; strcpy(bi->serial_no, sc_adapter[card]->hwconfig.serial_no); strcpy(bi->part_no, sc_adapter[card]->hwconfig.part_no); bi->iobase = sc_adapter[card]->iobase; bi->rambase = sc_adapter[card]->rambase; bi->irq = sc_adapter[card]->interrupt; bi->ramsize = sc_adapter[card]->hwconfig.ram_size; bi->interface = sc_adapter[card]->hwconfig.st_u_sense; strcpy(bi->load_ver, sc_adapter[card]->load_ver); strcpy(bi->proc_ver, sc_adapter[card]->proc_ver); /* * Get the current PhyStats and LnkStats */ status = send_and_receive(card, CEPID, ceReqTypePhy, ceReqClass2, ceReqPhyStatus, 0, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) { if (sc_adapter[card]->model < PRI_BOARD) { bi->l1_status = rcvmsg.msg_data.byte_array[2]; for (i = 0; i < BRI_CHANNELS; i++) bi->status.bristats[i].phy_stat = rcvmsg.msg_data.byte_array[i]; } else { bi->l1_status = rcvmsg.msg_data.byte_array[0]; bi->l2_status = rcvmsg.msg_data.byte_array[1]; for (i = 0; i < PRI_CHANNELS; i++) bi->status.pristats[i].phy_stat = rcvmsg.msg_data.byte_array[i + 2]; } } /* * Get the call types for each channel */ for (i = 0; i < sc_adapter[card]->nChannels; i++) { status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallGetCallType, 0, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) { if (sc_adapter[card]->model == PRI_BOARD) { bi->status.pristats[i].call_type = rcvmsg.msg_data.byte_array[0]; } else { bi->status.bristats[i].call_type = rcvmsg.msg_data.byte_array[0]; } } } /* * If PRI, get the call states and service states for each channel */ if (sc_adapter[card]->model == PRI_BOARD) { /* * Get the call states */ status = send_and_receive(card, CEPID, ceReqTypeStat, ceReqClass2, ceReqPhyChCallState, 0, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) { for (i = 0; i < PRI_CHANNELS; i++) bi->status.pristats[i].call_state = rcvmsg.msg_data.byte_array[i]; } /* * Get the service states */ status = send_and_receive(card, CEPID, ceReqTypeStat, ceReqClass2, ceReqPhyChServState, 0, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) { for (i = 0; i < PRI_CHANNELS; i++) bi->status.pristats[i].serv_state = rcvmsg.msg_data.byte_array[i]; } /* * Get the link stats for the channels */ for (i = 1; i <= PRI_CHANNELS; i++) { status = send_and_receive(card, CEPID, ceReqTypeLnk, ceReqClass0, ceReqLnkGetStats, i, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) { bi->status.pristats[i - 1].link_stats.tx_good = (unsigned long)rcvmsg.msg_data.byte_array[0]; bi->status.pristats[i - 1].link_stats.tx_bad = (unsigned long)rcvmsg.msg_data.byte_array[4]; bi->status.pristats[i - 1].link_stats.rx_good = (unsigned long)rcvmsg.msg_data.byte_array[8]; bi->status.pristats[i - 1].link_stats.rx_bad = (unsigned long)rcvmsg.msg_data.byte_array[12]; } } /* * Link stats for the D channel */ status = send_and_receive(card, CEPID, ceReqTypeLnk, ceReqClass0, ceReqLnkGetStats, 0, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) { bi->dch_stats.tx_good = (unsigned long)rcvmsg.msg_data.byte_array[0]; bi->dch_stats.tx_bad = (unsigned long)rcvmsg.msg_data.byte_array[4]; bi->dch_stats.rx_good = (unsigned long)rcvmsg.msg_data.byte_array[8]; bi->dch_stats.rx_bad = (unsigned long)rcvmsg.msg_data.byte_array[12]; } return 0; } /* * If BRI or POTS, Get SPID, DN and call types for each channel */ /* * Get the link stats for the channels */ status = send_and_receive(card, CEPID, ceReqTypeLnk, ceReqClass0, ceReqLnkGetStats, 0, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) { bi->dch_stats.tx_good = (unsigned long)rcvmsg.msg_data.byte_array[0]; bi->dch_stats.tx_bad = (unsigned long)rcvmsg.msg_data.byte_array[4]; bi->dch_stats.rx_good = (unsigned long)rcvmsg.msg_data.byte_array[8]; bi->dch_stats.rx_bad = (unsigned long)rcvmsg.msg_data.byte_array[12]; bi->status.bristats[0].link_stats.tx_good = (unsigned long)rcvmsg.msg_data.byte_array[16]; bi->status.bristats[0].link_stats.tx_bad = (unsigned long)rcvmsg.msg_data.byte_array[20]; bi->status.bristats[0].link_stats.rx_good = (unsigned long)rcvmsg.msg_data.byte_array[24]; bi->status.bristats[0].link_stats.rx_bad = (unsigned long)rcvmsg.msg_data.byte_array[28]; bi->status.bristats[1].link_stats.tx_good = (unsigned long)rcvmsg.msg_data.byte_array[32]; bi->status.bristats[1].link_stats.tx_bad = (unsigned long)rcvmsg.msg_data.byte_array[36]; bi->status.bristats[1].link_stats.rx_good = (unsigned long)rcvmsg.msg_data.byte_array[40]; bi->status.bristats[1].link_stats.rx_bad = (unsigned long)rcvmsg.msg_data.byte_array[44]; } /* * Get the SPIDs */ for (i = 0; i < BRI_CHANNELS; i++) { status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallGetSPID, i + 1, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) strcpy(bi->status.bristats[i].spid, rcvmsg.msg_data.byte_array); } /* * Get the DNs */ for (i = 0; i < BRI_CHANNELS; i++) { status = send_and_receive(card, CEPID, ceReqTypeCall, ceReqClass0, ceReqCallGetMyNumber, i + 1, 0, NULL, &rcvmsg, SAR_TIMEOUT); if (!status) strcpy(bi->status.bristats[i].dn, rcvmsg.msg_data.byte_array); } return 0; }
jpjust/android_kernel_lge_v4xx
drivers/isdn/sc/ioctl.c
C
gpl-2.0
14,998
/* * Process version 3 NFSACL requests. * * Copyright (C) 2002-2003 Andreas Gruenbacher <agruen@suse.de> */ #include "nfsd.h" /* FIXME: nfsacl.h is a broken header */ #include <linux/nfsacl.h> #include <linux/gfp.h> #include "cache.h" #include "xdr3.h" #include "vfs.h" #define RETURN_STATUS(st) { resp->status = (st); return (st); } /* * NULL call. */ static __be32 nfsd3_proc_null(struct svc_rqst *rqstp, void *argp, void *resp) { return nfs_ok; } /* * Get the Access and/or Default ACL of a file. */ static __be32 nfsd3_proc_getacl(struct svc_rqst * rqstp, struct nfsd3_getaclargs *argp, struct nfsd3_getaclres *resp) { svc_fh *fh; struct posix_acl *acl; __be32 nfserr = 0; fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP); if (nfserr) RETURN_STATUS(nfserr); if (argp->mask & ~(NFS_ACL|NFS_ACLCNT|NFS_DFACL|NFS_DFACLCNT)) RETURN_STATUS(nfserr_inval); resp->mask = argp->mask; if (resp->mask & (NFS_ACL|NFS_ACLCNT)) { acl = nfsd_get_posix_acl(fh, ACL_TYPE_ACCESS); if (IS_ERR(acl)) { int err = PTR_ERR(acl); if (err == -ENODATA || err == -EOPNOTSUPP) acl = NULL; else { nfserr = nfserrno(err); goto fail; } } if (acl == NULL) { /* Solaris returns the inode's minimum ACL. */ struct inode *inode = fh->fh_dentry->d_inode; acl = posix_acl_from_mode(inode->i_mode, GFP_KERNEL); } resp->acl_access = acl; } if (resp->mask & (NFS_DFACL|NFS_DFACLCNT)) { /* Check how Solaris handles requests for the Default ACL of a non-directory! */ acl = nfsd_get_posix_acl(fh, ACL_TYPE_DEFAULT); if (IS_ERR(acl)) { int err = PTR_ERR(acl); if (err == -ENODATA || err == -EOPNOTSUPP) acl = NULL; else { nfserr = nfserrno(err); goto fail; } } resp->acl_default = acl; } /* resp->acl_{access,default} are released in nfs3svc_release_getacl. */ RETURN_STATUS(0); fail: posix_acl_release(resp->acl_access); posix_acl_release(resp->acl_default); RETURN_STATUS(nfserr); } /* * Set the Access and/or Default ACL of a file. */ static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd3_attrstat *resp) { svc_fh *fh; __be32 nfserr = 0; fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (!nfserr) { nfserr = nfserrno( nfsd_set_posix_acl( fh, ACL_TYPE_ACCESS, argp->acl_access) ); } if (!nfserr) { nfserr = nfserrno( nfsd_set_posix_acl( fh, ACL_TYPE_DEFAULT, argp->acl_default) ); } /* argp->acl_{access,default} may have been allocated in nfs3svc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); RETURN_STATUS(nfserr); } /* * XDR decode functions */ static int nfs3svc_decode_getaclargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_getaclargs *args) { if (!(p = nfs3svc_decode_fh(p, &args->fh))) return 0; args->mask = ntohl(*p); p++; return xdr_argsize_check(rqstp, p); } static int nfs3svc_decode_setaclargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_setaclargs *args) { struct kvec *head = rqstp->rq_arg.head; unsigned int base; int n; if (!(p = nfs3svc_decode_fh(p, &args->fh))) return 0; args->mask = ntohl(*p++); if (args->mask & ~(NFS_ACL|NFS_ACLCNT|NFS_DFACL|NFS_DFACLCNT) || !xdr_argsize_check(rqstp, p)) return 0; base = (char *)p - (char *)head->iov_base; n = nfsacl_decode(&rqstp->rq_arg, base, NULL, (args->mask & NFS_ACL) ? &args->acl_access : NULL); if (n > 0) n = nfsacl_decode(&rqstp->rq_arg, base + n, NULL, (args->mask & NFS_DFACL) ? &args->acl_default : NULL); return (n > 0); } /* * XDR encode functions */ /* GETACL */ static int nfs3svc_encode_getaclres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_getaclres *resp) { struct dentry *dentry = resp->fh.fh_dentry; p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh); if (resp->status == 0 && dentry && dentry->d_inode) { struct inode *inode = dentry->d_inode; struct kvec *head = rqstp->rq_res.head; unsigned int base; int n; int w; *p++ = htonl(resp->mask); if (!xdr_ressize_check(rqstp, p)) return 0; base = (char *)p - (char *)head->iov_base; rqstp->rq_res.page_len = w = nfsacl_size( (resp->mask & NFS_ACL) ? resp->acl_access : NULL, (resp->mask & NFS_DFACL) ? resp->acl_default : NULL); while (w > 0) { if (!rqstp->rq_respages[rqstp->rq_resused++]) return 0; w -= PAGE_SIZE; } n = nfsacl_encode(&rqstp->rq_res, base, inode, resp->acl_access, resp->mask & NFS_ACL, 0); if (n > 0) n = nfsacl_encode(&rqstp->rq_res, base + n, inode, resp->acl_default, resp->mask & NFS_DFACL, NFS_ACL_DEFAULT); if (n <= 0) return 0; } else if (!xdr_ressize_check(rqstp, p)) return 0; return 1; } /* SETACL */ static int nfs3svc_encode_setaclres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_attrstat *resp) { p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh); return xdr_ressize_check(rqstp, p); } /* * XDR release functions */ static int nfs3svc_release_getacl(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_getaclres *resp) { fh_put(&resp->fh); posix_acl_release(resp->acl_access); posix_acl_release(resp->acl_default); return 1; } #define nfs3svc_decode_voidargs NULL #define nfs3svc_release_void NULL #define nfsd3_setaclres nfsd3_attrstat #define nfsd3_voidres nfsd3_voidargs struct nfsd3_voidargs { int dummy; }; #define PROC(name, argt, rest, relt, cache, respsize) \ { (svc_procfunc) nfsd3_proc_##name, \ (kxdrproc_t) nfs3svc_decode_##argt##args, \ (kxdrproc_t) nfs3svc_encode_##rest##res, \ (kxdrproc_t) nfs3svc_release_##relt, \ sizeof(struct nfsd3_##argt##args), \ sizeof(struct nfsd3_##rest##res), \ 0, \ cache, \ respsize, \ } #define ST 1 /* status*/ #define AT 21 /* attributes */ #define pAT (1+AT) /* post attributes - conditional */ #define ACL (1+NFS_ACL_MAX_ENTRIES*3) /* Access Control List */ static struct svc_procedure nfsd_acl_procedures3[] = { PROC(null, void, void, void, RC_NOCACHE, ST), PROC(getacl, getacl, getacl, getacl, RC_NOCACHE, ST+1+2*(1+ACL)), PROC(setacl, setacl, setacl, fhandle, RC_NOCACHE, ST+pAT), }; struct svc_version nfsd_acl_version3 = { .vs_vers = 3, .vs_nproc = 3, .vs_proc = nfsd_acl_procedures3, .vs_dispatch = nfsd_dispatch, .vs_xdrsize = NFS3_SVC_XDRSIZE, .vs_hidden = 0, };
NoelMacwan/android_kernel_sony_u8500
fs/nfsd/nfs3acl.c
C
gpl-2.0
6,488
/* * RapidIO Tsi500 switch support * * Copyright 2009-2010 Integrated Device Technology, Inc. * Alexandre Bounine <alexandre.bounine@idt.com> * - Modified switch operations initialization. * * Copyright 2005 MontaVista Software, Inc. * Matt Porter <mporter@kernel.crashing.org> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/rio.h> #include <linux/rio_drv.h> #include <linux/rio_ids.h> #include "../rio.h" static int tsi500_route_add_entry(struct rio_mport *mport, u16 destid, u8 hopcount, u16 table, u16 route_destid, u8 route_port) { int i; u32 offset = 0x10000 + 0xa00 + ((route_destid / 2)&~0x3); u32 result; if (table == 0xff) { rio_mport_read_config_32(mport, destid, hopcount, offset, &result); result &= ~(0xf << (4*(route_destid & 0x7))); for (i=0;i<4;i++) rio_mport_write_config_32(mport, destid, hopcount, offset + (0x20000*i), result | (route_port << (4*(route_destid & 0x7)))); } else { rio_mport_read_config_32(mport, destid, hopcount, offset + (0x20000*table), &result); result &= ~(0xf << (4*(route_destid & 0x7))); rio_mport_write_config_32(mport, destid, hopcount, offset + (0x20000*table), result | (route_port << (4*(route_destid & 0x7)))); } return 0; } static int tsi500_route_get_entry(struct rio_mport *mport, u16 destid, u8 hopcount, u16 table, u16 route_destid, u8 *route_port) { int ret = 0; u32 offset = 0x10000 + 0xa00 + ((route_destid / 2)&~0x3); u32 result; if (table == 0xff) rio_mport_read_config_32(mport, destid, hopcount, offset, &result); else rio_mport_read_config_32(mport, destid, hopcount, offset + (0x20000*table), &result); result &= 0xf << (4*(route_destid & 0x7)); *route_port = result >> (4*(route_destid & 0x7)); if (*route_port > 3) ret = -1; return ret; } static int tsi500_switch_init(struct rio_dev *rdev, int do_enum) { pr_debug("RIO: %s for %s\n", __func__, rio_name(rdev)); rdev->rswitch->add_entry = tsi500_route_add_entry; rdev->rswitch->get_entry = tsi500_route_get_entry; rdev->rswitch->clr_table = NULL; rdev->rswitch->set_domain = NULL; rdev->rswitch->get_domain = NULL; rdev->rswitch->em_init = NULL; rdev->rswitch->em_handle = NULL; return 0; } DECLARE_RIO_SWITCH_INIT(RIO_VID_TUNDRA, RIO_DID_TSI500, tsi500_switch_init);
casinobrawl/dt2w_native_Z
drivers/rapidio/switches/tsi500.c
C
gpl-2.0
2,485
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * Copyright (C) 2007 Imendio AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include "giggle-description-editor.h" #include <libgiggle-git/giggle-git.h> #include <glib/gi18n.h> typedef struct GiggleDescriptionEditorPriv GiggleDescriptionEditorPriv; struct GiggleDescriptionEditorPriv { GtkWidget *textview; GtkWidget *save; GtkWidget *restore; GiggleGit *git; }; static void description_editor_finalize (GObject *object); G_DEFINE_TYPE (GiggleDescriptionEditor, giggle_description_editor, GTK_TYPE_VBOX) #define GET_PRIV(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GIGGLE_TYPE_DESCRIPTION_EDITOR, GiggleDescriptionEditorPriv)) static void giggle_description_editor_class_init (GiggleDescriptionEditorClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); object_class->finalize = description_editor_finalize; g_type_class_add_private (object_class, sizeof (GiggleDescriptionEditorPriv)); } static void description_editor_update (GiggleDescriptionEditor *editor) { GiggleDescriptionEditorPriv *priv; GtkTextBuffer *buffer; const gchar *description; priv = GET_PRIV (editor); description = giggle_git_get_description (priv->git); if (!description) { description = ""; } buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (priv->textview)); gtk_text_buffer_set_text (buffer, description, -1); gtk_text_buffer_set_modified (buffer, FALSE); } static void description_editor_save (GiggleDescriptionEditor *editor) { GiggleDescriptionEditorPriv *priv; GtkTextBuffer *buffer; GtkTextIter start, end; gchar *text; priv = GET_PRIV (editor); buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (priv->textview)); gtk_text_buffer_get_bounds (buffer, &start, &end); text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE); giggle_git_write_description (priv->git, text); g_free (text); gtk_text_buffer_set_modified (buffer, FALSE); } static void description_editor_modified_changed_cb (GiggleDescriptionEditor *editor) { /* called when the description within the GtkTextView changes */ GiggleDescriptionEditorPriv *priv; GtkTextBuffer *buffer; gboolean modified; priv = GET_PRIV (editor); buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (priv->textview)); modified = gtk_text_buffer_get_modified (buffer); gtk_widget_set_sensitive (priv->save, modified); gtk_widget_set_sensitive (priv->restore, modified); } static void giggle_description_editor_init (GiggleDescriptionEditor *editor) { GiggleDescriptionEditorPriv *priv; GtkWidget *buttonbox, *scrolled_window; GtkTextBuffer *buffer; priv = GET_PRIV (editor); gtk_box_set_spacing (GTK_BOX (editor), 6); priv->git = giggle_git_get (); g_signal_connect_swapped (priv->git, "notify::git-dir", G_CALLBACK (description_editor_update), editor); g_signal_connect_swapped (priv->git, "notify::description", G_CALLBACK (description_editor_update), editor); scrolled_window = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_window), GTK_SHADOW_IN); gtk_widget_show (scrolled_window); gtk_box_pack_start (GTK_BOX (editor), scrolled_window, TRUE, TRUE, 0); priv->textview = gtk_text_view_new (); gtk_widget_show (priv->textview); gtk_container_add (GTK_CONTAINER (scrolled_window), priv->textview); buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (priv->textview)); g_signal_connect_swapped (buffer, "modified-changed", G_CALLBACK (description_editor_modified_changed_cb), editor); buttonbox = gtk_hbutton_box_new (); gtk_widget_show (buttonbox); gtk_button_box_set_layout (GTK_BUTTON_BOX (buttonbox), GTK_BUTTONBOX_START); gtk_box_pack_start (GTK_BOX (editor), buttonbox, FALSE, FALSE, 0); priv->save = gtk_button_new_from_stock (GTK_STOCK_SAVE); gtk_widget_show (priv->save); gtk_widget_set_sensitive (priv->save, FALSE); gtk_box_pack_start (GTK_BOX (buttonbox), priv->save, FALSE, FALSE, 0); g_signal_connect_swapped (priv->save, "clicked", G_CALLBACK (description_editor_save), editor); priv->restore = gtk_button_new_from_stock (GTK_STOCK_REVERT_TO_SAVED); gtk_widget_show (priv->restore); gtk_widget_set_sensitive (priv->restore, FALSE); gtk_box_pack_start (GTK_BOX (buttonbox), priv->restore, FALSE, FALSE, 0); g_signal_connect_swapped (priv->restore, "clicked", G_CALLBACK (description_editor_update), editor); description_editor_update (editor); } static void description_editor_finalize (GObject *object) { GiggleDescriptionEditorPriv *priv; priv = GET_PRIV (object); g_object_unref (priv->git); G_OBJECT_CLASS (giggle_description_editor_parent_class)->finalize (object); } GtkWidget * giggle_description_editor_new (void) { return g_object_new (GIGGLE_TYPE_DESCRIPTION_EDITOR, NULL); }
guyou/giggle
src/giggle-description-editor.c
C
gpl-2.0
5,814
/* * Public key-based simple decryption program * * Copyright (C) 2006-2013, Brainspark B.V. * * This file is part of PolarSSL (http://www.polarssl.org) * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org> * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "polarssl/config.h" #include <string.h> #include <stdio.h> #include "polarssl/error.h" #include "polarssl/pk.h" #include "polarssl/entropy.h" #include "polarssl/ctr_drbg.h" #if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_PK_PARSE_C) || \ !defined(POLARSSL_FS_IO) || !defined(POLARSSL_ENTROPY_C) || \ !defined(POLARSSL_CTR_DRBG_C) int main( int argc, char *argv[] ) { ((void) argc); ((void) argv); printf("POLARSSL_BIGNUM_C and/or POLARSSL_PK_PARSE_C and/or " "POLARSSL_FS_IO and/or POLARSSL_ENTROPY_C and/or " "POLARSSL_CTR_DRBG_C not defined.\n"); return( 0 ); } #else int main( int argc, char *argv[] ) { FILE *f; int ret, c; size_t i, olen = 0; pk_context pk; entropy_context entropy; ctr_drbg_context ctr_drbg; unsigned char result[1024]; unsigned char buf[512]; const char *pers = "pk_decrypt"; ((void) argv); memset(result, 0, sizeof( result ) ); ret = 1; if( argc != 2 ) { printf( "usage: pk_decrypt <key_file>\n" ); #if defined(_WIN32) printf( "\n" ); #endif goto exit; } printf( "\n . Seeding the random number generator..." ); fflush( stdout ); entropy_init( &entropy ); if( ( ret = ctr_drbg_init( &ctr_drbg, entropy_func, &entropy, (const unsigned char *) pers, strlen( pers ) ) ) != 0 ) { printf( " failed\n ! ctr_drbg_init returned %d\n", ret ); goto exit; } printf( "\n . Reading private key from '%s'", argv[1] ); fflush( stdout ); pk_init( &pk ); if( ( ret = pk_parse_keyfile( &pk, argv[1], "" ) ) != 0 ) { printf( " failed\n ! pk_parse_keyfile returned -0x%04x\n", -ret ); goto exit; } /* * Extract the RSA encrypted value from the text file */ ret = 1; if( ( f = fopen( "result-enc.txt", "rb" ) ) == NULL ) { printf( "\n ! Could not open %s\n\n", "result-enc.txt" ); goto exit; } i = 0; while( fscanf( f, "%02X", &c ) > 0 && i < (int) sizeof( buf ) ) buf[i++] = (unsigned char) c; fclose( f ); /* * Decrypt the encrypted RSA data and print the result. */ printf( "\n . Decrypting the encrypted data" ); fflush( stdout ); if( ( ret = pk_decrypt( &pk, buf, i, result, &olen, sizeof(result), ctr_drbg_random, &ctr_drbg ) ) != 0 ) { printf( " failed\n ! pk_decrypt returned -0x%04x\n", -ret ); goto exit; } printf( "\n . OK\n\n" ); printf( "The decrypted result is: '%s'\n\n", result ); ret = 0; exit: entropy_free( &entropy ); #if defined(POLARSSL_ERROR_C) polarssl_strerror( ret, (char *) buf, sizeof(buf) ); printf( " ! Last error was: %s\n", buf ); #endif #if defined(_WIN32) printf( " + Press Enter to exit this program.\n" ); fflush( stdout ); getchar(); #endif return( ret ); } #endif /* POLARSSL_BIGNUM_C && POLARSSL_PK_PARSE_C && POLARSSL_FS_IO && POLARSSL_ENTROPY_C && POLARSSL_CTR_DRBG_C */
techstormteam/12-vision-connect-ios-linphone
submodules/externals/polarssl/programs/pkey/pk_decrypt.c
C
gpl-2.0
4,138
/* * FCKeditor - The text editor for internet * Copyright (C) 2003-2005 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * "Support Open Source software. What about a donation today?" * * File Name: de.js * German language file. * * File Authors: * Maik Unruh (m.unruh@mm-concept.de) * Hendrik Kramer (HK@lwd.de) */ var FCKLang = { // Language direction : "ltr" (left to right) or "rtl" (right to left). Dir : "ltr", ToolbarCollapse : "Toolbar einklappen", ToolbarExpand : "Toolbar ausklappen", // Toolbar Items and Context Menu Save : "Speichern", NewPage : "Neue Seite", Preview : "Vorschau", Cut : "Ausschneiden", Copy : "Kopieren", Paste : "Einfügen", PasteText : "aus Textdatei einfügen", PasteWord : "aus Word einfügen", Print : "Drucken", SelectAll : "Alles auswählen", RemoveFormat : "Formatierungen entfernen", InsertLinkLbl : "Link", InsertLink : "Link einfügen/editieren", RemoveLink : "Link entfernen", Anchor : "Anker einfügen/editieren", InsertImageLbl : "Bild", InsertImage : "Bild einfügen/editieren", InsertFlashLbl : "Flash", InsertFlash : "Flash einfügen/editieren", InsertTableLbl : "Tabelle", InsertTable : "Tabelle einfügen/editieren", InsertLineLbl : "Linie", InsertLine : "Horizontale Linie einfügen", InsertSpecialCharLbl: "Sonderzeichen", InsertSpecialChar : "Sonderzeichen einfügen/editieren", InsertSmileyLbl : "Smiley", InsertSmiley : "Smiley einfügen", About : "Über FCKeditor", Bold : "Fett", Italic : "Kursiv", Underline : "Unterstrichen", StrikeThrough : "Durchgestrichen", Subscript : "Tiefgestellt", Superscript : "Hochgestellt", LeftJustify : "Linksbündig", CenterJustify : "Zentriert", RightJustify : "Rechtsbündig", BlockJustify : "Blocksatz", DecreaseIndent : "Einzug verringern", IncreaseIndent : "Einzug erhöhen", Undo : "Rückgängig", Redo : "Wiederherstellen", NumberedListLbl : "Nummerierte Liste", NumberedList : "Nummerierte Liste einfügen/entfernen", BulletedListLbl : "Liste", BulletedList : "Liste einfügen/entfernen", ShowTableBorders : "Zeige Tabellenrahmen", ShowDetails : "Zeige Details", Style : "Style", FontFormat : "Format", Font : "Font", FontSize : "Size", TextColor : "Textfarbe", BGColor : "Hintergrundfarbe", Source : "Quellcode", Find : "Finden", Replace : "Ersetzen", SpellCheck : "Rechtschreibprüfung", UniversalKeyboard : "Universal-Tastatur", PageBreakLbl : "Seitenumbruch", PageBreak : "Seitenumbruch einfügen", Form : "Formular", Checkbox : "Checkbox", RadioButton : "Radiobutton", TextField : "Textfeld einzeilig", Textarea : "Textfeld mehrzeilig", HiddenField : "verstecktes Feld", Button : "Klickbutton", SelectionField : "Auswahlfeld", ImageButton : "Bildbutton", // Context Menu EditLink : "Link editieren", InsertRow : "Zeile einfügen", DeleteRows : "Zeile entfernen", InsertColumn : "Spalte einfügen", DeleteColumns : "Spalte löschen", InsertCell : "Zelle einfügen", DeleteCells : "Zelle löschen", MergeCells : "Zellen vereinen", SplitCell : "Zelle teilen", TableDelete : "Tabelle löschen", CellProperties : "Zellen Eigenschaften", TableProperties : "Tabellen Eigenschaften", ImageProperties : "Bild Eigenschaften", FlashProperties : "Flash Eigenschaften", AnchorProp : "Anker Eigenschaften", ButtonProp : "Button Eigenschaften", CheckboxProp : "Checkbox Eigenschaften", HiddenFieldProp : "Verstecktes Feld Eigenschaften", RadioButtonProp : "Radiobutton Eigenschaften", ImageButtonProp : "Bildbutton Eigenschaften", TextFieldProp : "Textfeld einzeilig Eigenschaften", SelectionFieldProp : "Auswahlfeld Eigenschaften", TextareaProp : "Textfeld mehrzeilig Eigenschaften", FormProp : "Formular Eigenschaften", FontFormats : "Normal;Formatiert;Addresse;Überschrift 1;Überschrift 2;Überschrift 3;Überschrift 4;Überschrift 5;Überschrift 6", // Alerts and Messages ProcessingXHTML : "Bearbeite XHTML. Bitte warten...", Done : "Fertig", PasteWordConfirm : "Der Text, den Sie einfügen Möchten, scheint aus Word kopiert zu sein. Möchten Sie ihn zuvor bereinigen lassen?", NotCompatiblePaste : "Diese Funktion steht nur im Internet Explorer ab Version 5.5 zur Verfügung. Möchten Sie den Text unbereinigt einfügen?", UnknownToolbarItem : "Unbekanntes Menüleisten-Objekt \"%1\"", UnknownCommand : "Unbekannter Befehl \"%1\"", NotImplemented : "Befehl nicht implementiert", UnknownToolbarSet : "Menüleiste \"%1\" existiert nicht", NoActiveX : "Die Sicherheitseinstellungen Ihres Browsers beschränken evtl. einige Funktionen des Editors. Aktivieren Sie \"ActiveX-Steuerelemente und Plugins ausführen\" in den Sicherheitseinstellungen, um diese Funktionen nutzen zu können", BrowseServerBlocked : "Ein Auswahlfenster konnte nicht geöffnet werden. Stellen Sie sicher, das alle Popup-Blocker ausgeschaltet sind.", DialogBlocked : "Das Dialog-Fenster konnte nicht geöffnet werden. Stellen Sie sicher, das alle Popup-Blocker ausgeschaltet sind.", // Dialogs DlgBtnOK : "OK", DlgBtnCancel : "Abbrechen", DlgBtnClose : "Schließen", DlgBtnBrowseServer : "Server durchsuchen", DlgAdvancedTag : "Erweitert", DlgOpOther : "&lt;andere&gt;", DlgInfoTab : "Info", DlgAlertUrl : "Bitte tragen Sie die URL ein", // General Dialogs Labels DlgGenNotSet : "&lt; nichts &gt;", DlgGenId : "ID", DlgGenLangDir : "Schreibrichtung", DlgGenLangDirLtr : "Links nach Rechts (LTR)", DlgGenLangDirRtl : "Rechts nach Links (RTL)", DlgGenLangCode : "Sprachenkürzel", DlgGenAccessKey : "Schlüssel", DlgGenName : "Name", DlgGenTabIndex : "Tab Index", DlgGenLongDescr : "Langform URL", DlgGenClass : "Stylesheet Klasse", DlgGenTitle : "Titel Beschreibung", DlgGenContType : "Content Beschreibung", DlgGenLinkCharset : "Ziel-Zeichensatz", DlgGenStyle : "Style", // Image Dialog DlgImgTitle : "Bild Eigenschaften", DlgImgInfoTab : "Bild-Info", DlgImgBtnUpload : "Zum Server senden", DlgImgURL : "Bildauswahl", DlgImgUpload : "Upload", DlgImgAlt : "Alternativer Text", DlgImgWidth : "Breite", DlgImgHeight : "Höhe", DlgImgLockRatio : "Größenverhältniss beibehalten", DlgBtnResetSize : "Größe zurücksetzen", DlgImgBorder : "Rahmen", DlgImgHSpace : "H-Freiraum", DlgImgVSpace : "V-Freiraum", DlgImgAlign : "Ausrichtung", DlgImgAlignLeft : "Links", DlgImgAlignAbsBottom: "Abs Unten", DlgImgAlignAbsMiddle: "Abs Mitte", DlgImgAlignBaseline : "Baseline", DlgImgAlignBottom : "Unten", DlgImgAlignMiddle : "Mitte", DlgImgAlignRight : "Rechts", DlgImgAlignTextTop : "Text Oben", DlgImgAlignTop : "Oben", DlgImgPreview : "Vorschau", DlgImgAlertUrl : "Bitte geben Sie die Bild-URL an", DlgImgLinkTab : "Link", // Flash Dialog DlgFlashTitle : "Flash Eigenschaften", DlgFlashChkPlay : "autom. Abspielen", DlgFlashChkLoop : "Endlosschleife", DlgFlashChkMenu : "Aktiviere Flash Menü", DlgFlashScale : "Skalierung", DlgFlashScaleAll : "Alles anzeigen", DlgFlashScaleNoBorder : "ohne Rand", DlgFlashScaleFit : "Passgenau", // Link Dialog DlgLnkWindowTitle : "Link", DlgLnkInfoTab : "Link Info", DlgLnkTargetTab : "Zielseite", DlgLnkType : "Link-Typ", DlgLnkTypeURL : "URL", DlgLnkTypeAnchor : "Anker in dieser Seite", DlgLnkTypeEMail : "E-Mail", DlgLnkProto : "Protokoll", DlgLnkProtoOther : "&lt;anderes&gt;", DlgLnkURL : "URL", DlgLnkAnchorSel : "Anker auswählen", DlgLnkAnchorByName : "nach Anker Name", DlgLnkAnchorById : "nach Element Id", DlgLnkNoAnchors : "&lt;keine Anker im Dokument vorhanden&gt;", DlgLnkEMail : "E-Mail Addresse", DlgLnkEMailSubject : "Betreffzeile", DlgLnkEMailBody : "Nachrichtentext", DlgLnkUpload : "Upload", DlgLnkBtnUpload : "Zum Server senden", DlgLnkTarget : "Zielseite", DlgLnkTargetFrame : "&lt;Frame&gt;", DlgLnkTargetPopup : "&lt;Pop-up Fenster&gt;", DlgLnkTargetBlank : "Neues Fenster (_blank)", DlgLnkTargetParent : "Oberes Fenster (_parent)", DlgLnkTargetSelf : "Gleiches Fenster (_self)", DlgLnkTargetTop : "Oberstes Fenster (_top)", DlgLnkTargetFrameName : "Ziel-Frame Name", DlgLnkPopWinName : "Pop-up Fenster Name", DlgLnkPopWinFeat : "Pop-up Fenster Eigenschaften", DlgLnkPopResize : "Vergrößerbar", DlgLnkPopLocation : "Adress-Leiste", DlgLnkPopMenu : "Menü-Leiste", DlgLnkPopScroll : "Scroll-Leisten", DlgLnkPopStatus : "Status-Leiste", DlgLnkPopToolbar : "Werkzeugleiste", DlgLnkPopFullScrn : "Vollbild (IE)", DlgLnkPopDependent : "Abhängig (Netscape)", DlgLnkPopWidth : "Breite", DlgLnkPopHeight : "Höhe", DlgLnkPopLeft : "Linke Position", DlgLnkPopTop : "Obere Position", DlnLnkMsgNoUrl : "Bitte geben Sie die Link-URL an", DlnLnkMsgNoEMail : "Bitte geben Sie e-Mail Adresse an", DlnLnkMsgNoAnchor : "Bitte wählen Sie einen Anker aus", // Color Dialog DlgColorTitle : "Farbauswahl", DlgColorBtnClear : "Keine Farbe", DlgColorHighlight : "Vorschau", DlgColorSelected : "Ausgewählt", // Smiley Dialog DlgSmileyTitle : "Smiley auswählen", // Special Character Dialog DlgSpecialCharTitle : "Sonderzeichen auswählen", // Table Dialog DlgTableTitle : "Tabellen Eigenschaften", DlgTableRows : "Zeile", DlgTableColumns : "Spalte", DlgTableBorder : "Rahmen", DlgTableAlign : "Ausrichtung", DlgTableAlignNotSet : "<nichts>", DlgTableAlignLeft : "Links", DlgTableAlignCenter : "Zentriert", DlgTableAlignRight : "Rechts", DlgTableWidth : "Breite", DlgTableWidthPx : "Pixel", DlgTableWidthPc : "%", DlgTableHeight : "Höhe", DlgTableCellSpace : "Zellenabstand außen", DlgTableCellPad : "Zellenabstand innen", DlgTableCaption : "Überschrift", DlgTableSummary : "Inhaltsübersicht", // Table Cell Dialog DlgCellTitle : "Zellen-Eigenschaften", DlgCellWidth : "Breite", DlgCellWidthPx : "Pixel", DlgCellWidthPc : "%", DlgCellHeight : "Höhe", DlgCellWordWrap : "Umbruch", DlgCellWordWrapNotSet : "&lt;nichts&gt;", DlgCellWordWrapYes : "Ja", DlgCellWordWrapNo : "Nein", DlgCellHorAlign : "Horizontale Ausrichtung", DlgCellHorAlignNotSet : "&lt;nichts&gt;", DlgCellHorAlignLeft : "Links", DlgCellHorAlignCenter : "Zentriert", DlgCellHorAlignRight: "Rechts", DlgCellVerAlign : "Vertikale Ausrichtung", DlgCellVerAlignNotSet : "&lt;nichts&gt;", DlgCellVerAlignTop : "Oben", DlgCellVerAlignMiddle : "Mitte", DlgCellVerAlignBottom : "Unten", DlgCellVerAlignBaseline : "Baseline", DlgCellRowSpan : "Zeilen zusammenfassen", DlgCellCollSpan : "Spalten zusammenfassen", DlgCellBackColor : "Hintergrundfarbe", DlgCellBorderColor : "Rahmenfarbe", DlgCellBtnSelect : "Auswahl...", // Find Dialog DlgFindTitle : "Finden", DlgFindFindBtn : "Finden", DlgFindNotFoundMsg : "Der Suchtext wurde nicht gefunden.", // Replace Dialog DlgReplaceTitle : "Ersetzen", DlgReplaceFindLbl : "Suche nach:", DlgReplaceReplaceLbl : "Ersetze mit:", DlgReplaceCaseChk : "Groß-Kleinschreibung beachten", DlgReplaceReplaceBtn : "Ersetzen", DlgReplaceReplAllBtn : "Alle Ersetzen", DlgReplaceWordChk : "Nur ganze Worte suchen", // Paste Operations / Dialog PasteErrorPaste : "Die Sicherheitseinstellungen Ihres Browsers lassen es nicht zu, den Text automatisch einzufügen. Bitte benutzen Sie die System-Zwischenablage über STRG-C (kopieren) und STRG-V (einfügen).", PasteErrorCut : "Die Sicherheitseinstellungen Ihres Browsers lassen es nicht zu, den Text automatisch auszuschneiden. Bitte benutzen Sie die System-Zwischenablage über STRG-X (ausschneiden) und STRG-V (einfügen).", PasteErrorCopy : "Die Sicherheitseinstellungen Ihres Browsers lassen es nicht zu, den Text automatisch kopieren. Bitte benutzen Sie die System-Zwischenablage über STRG-C (kopieren).", PasteAsText : "Als Text einfügen", PasteFromWord : "Aus Word einfügen", DlgPasteMsg2 : "Bitte fügen Sie den Text in der folgenden Box über die Tastatur (mit <STRONG>Ctrl+V</STRONG>) ein und bestätigen Sie mit <STRONG>OK</STRONG>.", DlgPasteIgnoreFont : "Ignoriere Schriftart-Definitionen", DlgPasteRemoveStyles : "Entferne Style-Definitionen", DlgPasteCleanBox : "Inhalt aufräumen", // Color Picker ColorAutomatic : "Automatisch", ColorMoreColors : "Weitere Farben...", // Document Properties DocProps : "Dokument Eigenschaften", // Anchor Dialog DlgAnchorTitle : "Anker Eigenschaften", DlgAnchorName : "Anker Name", DlgAnchorErrorName : "Bitte geben Sie den Namen des Ankers ein", // Speller Pages Dialog DlgSpellNotInDic : "Nicht im Wörterbuch", DlgSpellChangeTo : "Ändern in", DlgSpellBtnIgnore : "Ignorieren", DlgSpellBtnIgnoreAll : "Alle Ignorieren", DlgSpellBtnReplace : "Ersetzen", DlgSpellBtnReplaceAll : "Alle Ersetzen", DlgSpellBtnUndo : "Rückgängig", DlgSpellNoSuggestions : " - keine Vorschläge - ", DlgSpellProgress : "Rechtschreibprüfung läuft...", DlgSpellNoMispell : "Rechtschreibprüfung abgeschlossen - keine Fehler gefunden", DlgSpellNoChanges : "Rechtschreibprüfung abgeschlossen - keine Worte geändert", DlgSpellOneChange : "Rechtschreibprüfung abgeschlossen - ein Wort geändert", DlgSpellManyChanges : "Rechtschreibprüfung abgeschlossen - %1 Wörter geändert", IeSpellDownload : "Rechtschreibprüfung nicht installiert. Möchten Sie sie jetzt herunterladen?", // Button Dialog DlgButtonText : "Text (Wert)", DlgButtonType : "Typ", // Checkbox and Radio Button Dialogs DlgCheckboxName : "Name", DlgCheckboxValue : "Wert", DlgCheckboxSelected : "ausgewählt", // Form Dialog DlgFormName : "Name", DlgFormAction : "Action", DlgFormMethod : "Method", // Select Field Dialog DlgSelectName : "Name", DlgSelectValue : "Wert", DlgSelectSize : "Größe", DlgSelectLines : "Linien", DlgSelectChkMulti : "Erlaube Mehrfachauswahl", DlgSelectOpAvail : "Mögliche Optionen", DlgSelectOpText : "Text", DlgSelectOpValue : "Wert", DlgSelectBtnAdd : "Hinzufügen", DlgSelectBtnModify : "Ändern", DlgSelectBtnUp : "Hoch", DlgSelectBtnDown : "Runter", DlgSelectBtnSetValue : "Setze als Standardwert", DlgSelectBtnDelete : "Entfernen", // Textarea Dialog DlgTextareaName : "Name", DlgTextareaCols : "Spalten", DlgTextareaRows : "Reihen", // Text Field Dialog DlgTextName : "Name", DlgTextValue : "Wert", DlgTextCharWidth : "Zeichenbreite", DlgTextMaxChars : "Max. Zeichen", DlgTextType : "Typ", DlgTextTypeText : "Text", DlgTextTypePass : "Passwort", // Hidden Field Dialog DlgHiddenName : "Name", DlgHiddenValue : "Wert", // Bulleted List Dialog BulletedListProp : "Listen-Eigenschaften", NumberedListProp : "Nummerierte Listen-Eigenschaften", DlgLstType : "Typ", DlgLstTypeCircle : "Kreis", DlgLstTypeDisc : "Disc", //MISSING DlgLstTypeSquare : "Quadrat", DlgLstTypeNumbers : "Nummern (1, 2, 3)", DlgLstTypeLCase : "Kleinbuchstaben (a, b, c)", DlgLstTypeUCase : "Großbuchstaben (A, B, C)", DlgLstTypeSRoman : "Kleine römische Zahlen (i, ii, iii)", DlgLstTypeLRoman : "Große römische Zahlen (I, II, III)", // Document Properties Dialog DlgDocGeneralTab : "Allgemein", DlgDocBackTab : "Hintergrund", DlgDocColorsTab : "Farben und Abstände", DlgDocMetaTab : "Metadaten", DlgDocPageTitle : "Seitentitel", DlgDocLangDir : "Schriftrichtung", DlgDocLangDirLTR : "Links nach Rechts", DlgDocLangDirRTL : "rechts nach Links", DlgDocLangCode : "Sprachkürzel", DlgDocCharSet : "Zeichenkodierung", DlgDocCharSetOther : "Andere Zeichenkodierung", DlgDocDocType : "Dokumententyp", DlgDocDocTypeOther : "Anderer Dokumententyp", DlgDocIncXHTML : "Beziehe XHTML Deklarationen ein", DlgDocBgColor : "Hintergrundfarbe", DlgDocBgImage : "Hintergrundbild URL", DlgDocBgNoScroll : "Nicht-Scrollender Hintergrund", DlgDocCText : "Text", DlgDocCLink : "Link", DlgDocCVisited : "Besuchter Link", DlgDocCActive : "Aktiver Link", DlgDocMargins : "Seitenränder", DlgDocMaTop : "Oben", DlgDocMaLeft : "Links", DlgDocMaRight : "Rechts", DlgDocMaBottom : "Unten", DlgDocMeIndex : "Schlüsselwörter (Komma-getrennt)", DlgDocMeDescr : "Dokument-Beschreibung", DlgDocMeAuthor : "Autor", DlgDocMeCopy : "Copyright", DlgDocPreview : "Vorschau", // Templates Dialog Templates : "Vorlagen", DlgTemplatesTitle : "Vorlagen", DlgTemplatesSelMsg : "Klicken Sie auf eine Vorlage, um sie im Editor zu öffnen (der aktuelle Inhalt wird dabei gelöscht!):", DlgTemplatesLoading : "Liste der Vorlagen wird geladen. Bitte warten...", DlgTemplatesNoTpl : "(keine Vorlagen definiert)", // About Dialog DlgAboutAboutTab : "Über", DlgAboutBrowserInfoTab : "Browser-Info", DlgAboutVersion : "Version", DlgAboutLicense : "Lizensiert unter den Richtlinien der GNU Lesser General Public License", DlgAboutInfo : "Für weitere Informationen siehe" }
dapfru/gladiators
parsek/cls/editor/editor/lang/de.js
JavaScript
gpl-2.0
17,165
/* * aes.c * * An implemnetation of the AES block cipher. * * David A. McGrew * Cisco Systems, Inc. */ /* * * Copyright (c) 2001-2005, Cisco Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Cisco Systems, Inc. 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "aes.h" #include "err.h" /* * we use the tables T0, T1, T2, T3, and T4 to compute AES, and * the tables U0, U1, U2, and U4 to compute its inverse * * different tables are used on little-endian (Intel, VMS) and * big-endian processors (everything else) * * these tables are computed using the program tables/aes_tables; use * this program to generate different tables for porting or * optimization on a different platform */ #ifndef WORDS_BIGENDIAN static uint32_t T0[256] = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0xdf2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x3010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0xbf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x2f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x8f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0xc040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0xf05050a, 0xb59a9a2f, 0x907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x0, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x6020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x4f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0xef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0xa06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x7f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x5030306, 0x1f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c, }; static uint32_t T1[256] = { 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x1010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x5050a0f, 0x9a9a2fb5, 0x7070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x2020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0xc0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0xb0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0xa0a141e, 0x494992db, 0x6060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x8081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x3030605, 0xf6f6f701, 0xe0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0xd0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0xf0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a, }; static uint32_t T2[256] = { 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x1020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x4080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x50a0f05, 0x9a2fb59a, 0x70e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x9121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x0, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x2040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0xc18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0xb161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0xa141e0a, 0x4992db49, 0x60c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x8101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x3060503, 0xf6f701f6, 0xe1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0xd1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0xf1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16, }; static uint32_t T3[256] = { 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x2030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x80c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0xa0f0505, 0x2fb59a9a, 0xe090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x0, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x4060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x58a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0xb838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0xc0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x18c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0xd868b8b, 0xf858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x6050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x7898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x38f8c8c, 0x59f8a1a1, 0x9808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616, }; static uint32_t U0[256] = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x2752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x728ebb2, 0x3c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x69f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x55dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x0, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0xfe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0xaba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0xb0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0xd927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x97826cd, 0xf418596e, 0x1b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x8cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0xe50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x4ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0xc25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0, }; static uint32_t U1[256] = { 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x3e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0xeea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x24b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x6dd963d, 0x53eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0xa7ca147, 0xf427ce9, 0x1e84f8c9, 0x0, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0xd090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0xbd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x99fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0xca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x1a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042, }; static uint32_t U2[256] = { 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x2f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x8f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x7f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x6046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x0, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0xefdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0xf0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0xa0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x90e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x1f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x4f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0xbfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0xdff4195, 0xa8397101, 0xc08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257, }; static uint32_t U3[256] = { 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x3e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x2ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x6d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x532e18a, 0xa475ebf6, 0xb39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x46fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x7888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x0, 0x9838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0xf563885, 0x3d1ed5ae, 0x3627392d, 0xa64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0xcb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0xe0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0xdec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x15d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x8deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8, }; #else /* assume big endian */ static uint32_t T0[256] = { 0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x2010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0xa05050f, 0x2f9a9ab5, 0xe070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x0, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x4020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x58f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0xb888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0xc06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x18d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0xd8b8b86, 0xf8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x6030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x78e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x38c8c8f, 0x59a1a1f8, 0x9898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a, }; static uint32_t T1[256] = { 0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0xdfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x3020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0xbfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x2f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x8f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0xc080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0xf0a0505, 0xb52f9a9a, 0x90e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x0, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x6040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x4f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0xefdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0xa0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x7f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x5060303, 0x1f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616, }; static uint32_t T2[256] = { 0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x1030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x40c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x50f0a05, 0x9ab52f9a, 0x7090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x91b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x0, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x2060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0xc14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0xb1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0xa1e140a, 0x49db9249, 0x60a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x8181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x3050603, 0xf601f7f6, 0xe121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0xd171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0xf111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16, }; static uint32_t T3[256] = { 0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x1010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x4040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x5050f0a, 0x9a9ab52f, 0x707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x9091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x0, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x2020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0xc0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0xb0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0xa0a1e14, 0x4949db92, 0x6060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x8081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x3030506, 0xf6f601f7, 0xe0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0xd0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0xf0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c, }; static uint32_t U0[256] = { 0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x38f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x2036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x58ae132, 0xa4f6eb75, 0xb83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x7898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x0, 0x9808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0xf853856, 0x3daed51e, 0x362d3927, 0xa0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0xc0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0xe090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0xd8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x18c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x80cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742 }; static uint32_t U1[256] = { 0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x2c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x7b2eb28, 0x32fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x65e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x0, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0xf9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0xae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0xb0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0xd507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x9cd2678, 0xf46e5918, 0x1ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0xe7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x49d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0xcbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857 }; static uint32_t U2[256] = { 0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x3934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0xe9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x2e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x8a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x63d96dd, 0x5aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0xa47a17c, 0xfe97c42, 0x1ec9f884, 0x0, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0xd0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x74caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0xb3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x9d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x4dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0xc7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x17139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8 }; static uint32_t U3[256] = { 0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x24c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x82b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x36aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x7f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x5bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x6d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x0, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0xefffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0xfd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0xa67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x90d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x1269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x4984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0xb412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0xd9541ff, 0xa8017139, 0xcb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0 }; #endif /* * the following tables (aes_sbox, aes_inv_sbox, T4, U4) are * endian-neutral */ static uint8_t aes_sbox[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; #ifndef CPU_RISC static uint8_t aes_inv_sbox[256] = { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; #endif /* ! CPU_RISC */ #ifdef CPU_RISC static uint32_t T4[256] = { 0x63636363, 0x7c7c7c7c, 0x77777777, 0x7b7b7b7b, 0xf2f2f2f2, 0x6b6b6b6b, 0x6f6f6f6f, 0xc5c5c5c5, 0x30303030, 0x01010101, 0x67676767, 0x2b2b2b2b, 0xfefefefe, 0xd7d7d7d7, 0xabababab, 0x76767676, 0xcacacaca, 0x82828282, 0xc9c9c9c9, 0x7d7d7d7d, 0xfafafafa, 0x59595959, 0x47474747, 0xf0f0f0f0, 0xadadadad, 0xd4d4d4d4, 0xa2a2a2a2, 0xafafafaf, 0x9c9c9c9c, 0xa4a4a4a4, 0x72727272, 0xc0c0c0c0, 0xb7b7b7b7, 0xfdfdfdfd, 0x93939393, 0x26262626, 0x36363636, 0x3f3f3f3f, 0xf7f7f7f7, 0xcccccccc, 0x34343434, 0xa5a5a5a5, 0xe5e5e5e5, 0xf1f1f1f1, 0x71717171, 0xd8d8d8d8, 0x31313131, 0x15151515, 0x04040404, 0xc7c7c7c7, 0x23232323, 0xc3c3c3c3, 0x18181818, 0x96969696, 0x05050505, 0x9a9a9a9a, 0x07070707, 0x12121212, 0x80808080, 0xe2e2e2e2, 0xebebebeb, 0x27272727, 0xb2b2b2b2, 0x75757575, 0x09090909, 0x83838383, 0x2c2c2c2c, 0x1a1a1a1a, 0x1b1b1b1b, 0x6e6e6e6e, 0x5a5a5a5a, 0xa0a0a0a0, 0x52525252, 0x3b3b3b3b, 0xd6d6d6d6, 0xb3b3b3b3, 0x29292929, 0xe3e3e3e3, 0x2f2f2f2f, 0x84848484, 0x53535353, 0xd1d1d1d1, 0x00000000, 0xedededed, 0x20202020, 0xfcfcfcfc, 0xb1b1b1b1, 0x5b5b5b5b, 0x6a6a6a6a, 0xcbcbcbcb, 0xbebebebe, 0x39393939, 0x4a4a4a4a, 0x4c4c4c4c, 0x58585858, 0xcfcfcfcf, 0xd0d0d0d0, 0xefefefef, 0xaaaaaaaa, 0xfbfbfbfb, 0x43434343, 0x4d4d4d4d, 0x33333333, 0x85858585, 0x45454545, 0xf9f9f9f9, 0x02020202, 0x7f7f7f7f, 0x50505050, 0x3c3c3c3c, 0x9f9f9f9f, 0xa8a8a8a8, 0x51515151, 0xa3a3a3a3, 0x40404040, 0x8f8f8f8f, 0x92929292, 0x9d9d9d9d, 0x38383838, 0xf5f5f5f5, 0xbcbcbcbc, 0xb6b6b6b6, 0xdadadada, 0x21212121, 0x10101010, 0xffffffff, 0xf3f3f3f3, 0xd2d2d2d2, 0xcdcdcdcd, 0x0c0c0c0c, 0x13131313, 0xecececec, 0x5f5f5f5f, 0x97979797, 0x44444444, 0x17171717, 0xc4c4c4c4, 0xa7a7a7a7, 0x7e7e7e7e, 0x3d3d3d3d, 0x64646464, 0x5d5d5d5d, 0x19191919, 0x73737373, 0x60606060, 0x81818181, 0x4f4f4f4f, 0xdcdcdcdc, 0x22222222, 0x2a2a2a2a, 0x90909090, 0x88888888, 0x46464646, 0xeeeeeeee, 0xb8b8b8b8, 0x14141414, 0xdededede, 0x5e5e5e5e, 0x0b0b0b0b, 0xdbdbdbdb, 0xe0e0e0e0, 0x32323232, 0x3a3a3a3a, 0x0a0a0a0a, 0x49494949, 0x06060606, 0x24242424, 0x5c5c5c5c, 0xc2c2c2c2, 0xd3d3d3d3, 0xacacacac, 0x62626262, 0x91919191, 0x95959595, 0xe4e4e4e4, 0x79797979, 0xe7e7e7e7, 0xc8c8c8c8, 0x37373737, 0x6d6d6d6d, 0x8d8d8d8d, 0xd5d5d5d5, 0x4e4e4e4e, 0xa9a9a9a9, 0x6c6c6c6c, 0x56565656, 0xf4f4f4f4, 0xeaeaeaea, 0x65656565, 0x7a7a7a7a, 0xaeaeaeae, 0x08080808, 0xbabababa, 0x78787878, 0x25252525, 0x2e2e2e2e, 0x1c1c1c1c, 0xa6a6a6a6, 0xb4b4b4b4, 0xc6c6c6c6, 0xe8e8e8e8, 0xdddddddd, 0x74747474, 0x1f1f1f1f, 0x4b4b4b4b, 0xbdbdbdbd, 0x8b8b8b8b, 0x8a8a8a8a, 0x70707070, 0x3e3e3e3e, 0xb5b5b5b5, 0x66666666, 0x48484848, 0x03030303, 0xf6f6f6f6, 0x0e0e0e0e, 0x61616161, 0x35353535, 0x57575757, 0xb9b9b9b9, 0x86868686, 0xc1c1c1c1, 0x1d1d1d1d, 0x9e9e9e9e, 0xe1e1e1e1, 0xf8f8f8f8, 0x98989898, 0x11111111, 0x69696969, 0xd9d9d9d9, 0x8e8e8e8e, 0x94949494, 0x9b9b9b9b, 0x1e1e1e1e, 0x87878787, 0xe9e9e9e9, 0xcececece, 0x55555555, 0x28282828, 0xdfdfdfdf, 0x8c8c8c8c, 0xa1a1a1a1, 0x89898989, 0x0d0d0d0d, 0xbfbfbfbf, 0xe6e6e6e6, 0x42424242, 0x68686868, 0x41414141, 0x99999999, 0x2d2d2d2d, 0x0f0f0f0f, 0xb0b0b0b0, 0x54545454, 0xbbbbbbbb, 0x16161616 }; static uint32_t U4[256] = { 0x52525252, 0x9090909, 0x6a6a6a6a, 0xd5d5d5d5, 0x30303030, 0x36363636, 0xa5a5a5a5, 0x38383838, 0xbfbfbfbf, 0x40404040, 0xa3a3a3a3, 0x9e9e9e9e, 0x81818181, 0xf3f3f3f3, 0xd7d7d7d7, 0xfbfbfbfb, 0x7c7c7c7c, 0xe3e3e3e3, 0x39393939, 0x82828282, 0x9b9b9b9b, 0x2f2f2f2f, 0xffffffff, 0x87878787, 0x34343434, 0x8e8e8e8e, 0x43434343, 0x44444444, 0xc4c4c4c4, 0xdededede, 0xe9e9e9e9, 0xcbcbcbcb, 0x54545454, 0x7b7b7b7b, 0x94949494, 0x32323232, 0xa6a6a6a6, 0xc2c2c2c2, 0x23232323, 0x3d3d3d3d, 0xeeeeeeee, 0x4c4c4c4c, 0x95959595, 0xb0b0b0b, 0x42424242, 0xfafafafa, 0xc3c3c3c3, 0x4e4e4e4e, 0x8080808, 0x2e2e2e2e, 0xa1a1a1a1, 0x66666666, 0x28282828, 0xd9d9d9d9, 0x24242424, 0xb2b2b2b2, 0x76767676, 0x5b5b5b5b, 0xa2a2a2a2, 0x49494949, 0x6d6d6d6d, 0x8b8b8b8b, 0xd1d1d1d1, 0x25252525, 0x72727272, 0xf8f8f8f8, 0xf6f6f6f6, 0x64646464, 0x86868686, 0x68686868, 0x98989898, 0x16161616, 0xd4d4d4d4, 0xa4a4a4a4, 0x5c5c5c5c, 0xcccccccc, 0x5d5d5d5d, 0x65656565, 0xb6b6b6b6, 0x92929292, 0x6c6c6c6c, 0x70707070, 0x48484848, 0x50505050, 0xfdfdfdfd, 0xedededed, 0xb9b9b9b9, 0xdadadada, 0x5e5e5e5e, 0x15151515, 0x46464646, 0x57575757, 0xa7a7a7a7, 0x8d8d8d8d, 0x9d9d9d9d, 0x84848484, 0x90909090, 0xd8d8d8d8, 0xabababab, 0x0, 0x8c8c8c8c, 0xbcbcbcbc, 0xd3d3d3d3, 0xa0a0a0a, 0xf7f7f7f7, 0xe4e4e4e4, 0x58585858, 0x5050505, 0xb8b8b8b8, 0xb3b3b3b3, 0x45454545, 0x6060606, 0xd0d0d0d0, 0x2c2c2c2c, 0x1e1e1e1e, 0x8f8f8f8f, 0xcacacaca, 0x3f3f3f3f, 0xf0f0f0f, 0x2020202, 0xc1c1c1c1, 0xafafafaf, 0xbdbdbdbd, 0x3030303, 0x1010101, 0x13131313, 0x8a8a8a8a, 0x6b6b6b6b, 0x3a3a3a3a, 0x91919191, 0x11111111, 0x41414141, 0x4f4f4f4f, 0x67676767, 0xdcdcdcdc, 0xeaeaeaea, 0x97979797, 0xf2f2f2f2, 0xcfcfcfcf, 0xcececece, 0xf0f0f0f0, 0xb4b4b4b4, 0xe6e6e6e6, 0x73737373, 0x96969696, 0xacacacac, 0x74747474, 0x22222222, 0xe7e7e7e7, 0xadadadad, 0x35353535, 0x85858585, 0xe2e2e2e2, 0xf9f9f9f9, 0x37373737, 0xe8e8e8e8, 0x1c1c1c1c, 0x75757575, 0xdfdfdfdf, 0x6e6e6e6e, 0x47474747, 0xf1f1f1f1, 0x1a1a1a1a, 0x71717171, 0x1d1d1d1d, 0x29292929, 0xc5c5c5c5, 0x89898989, 0x6f6f6f6f, 0xb7b7b7b7, 0x62626262, 0xe0e0e0e, 0xaaaaaaaa, 0x18181818, 0xbebebebe, 0x1b1b1b1b, 0xfcfcfcfc, 0x56565656, 0x3e3e3e3e, 0x4b4b4b4b, 0xc6c6c6c6, 0xd2d2d2d2, 0x79797979, 0x20202020, 0x9a9a9a9a, 0xdbdbdbdb, 0xc0c0c0c0, 0xfefefefe, 0x78787878, 0xcdcdcdcd, 0x5a5a5a5a, 0xf4f4f4f4, 0x1f1f1f1f, 0xdddddddd, 0xa8a8a8a8, 0x33333333, 0x88888888, 0x7070707, 0xc7c7c7c7, 0x31313131, 0xb1b1b1b1, 0x12121212, 0x10101010, 0x59595959, 0x27272727, 0x80808080, 0xecececec, 0x5f5f5f5f, 0x60606060, 0x51515151, 0x7f7f7f7f, 0xa9a9a9a9, 0x19191919, 0xb5b5b5b5, 0x4a4a4a4a, 0xd0d0d0d, 0x2d2d2d2d, 0xe5e5e5e5, 0x7a7a7a7a, 0x9f9f9f9f, 0x93939393, 0xc9c9c9c9, 0x9c9c9c9c, 0xefefefef, 0xa0a0a0a0, 0xe0e0e0e0, 0x3b3b3b3b, 0x4d4d4d4d, 0xaeaeaeae, 0x2a2a2a2a, 0xf5f5f5f5, 0xb0b0b0b0, 0xc8c8c8c8, 0xebebebeb, 0xbbbbbbbb, 0x3c3c3c3c, 0x83838383, 0x53535353, 0x99999999, 0x61616161, 0x17171717, 0x2b2b2b2b, 0x4040404, 0x7e7e7e7e, 0xbabababa, 0x77777777, 0xd6d6d6d6, 0x26262626, 0xe1e1e1e1, 0x69696969, 0x14141414, 0x63636363, 0x55555555, 0x21212121, 0xc0c0c0c, 0x7d7d7d7d }; #endif /* CPU_RISC */ /* aes internals */ extern debug_module_t mod_aes_icm; inline void aes_expand_encryption_key(const v128_t *key, aes_expanded_key_t expanded_key) { int i; gf2_8 rc; /* initialize round constant */ rc = 1; expanded_key[0].v32[0] = key->v32[0]; expanded_key[0].v32[1] = key->v32[1]; expanded_key[0].v32[2] = key->v32[2]; expanded_key[0].v32[3] = key->v32[3]; #if 0 debug_print(mod_aes_icm, "expanded key[0]: %s", v128_hex_string(&expanded_key[0])); #endif /* loop over round keys */ for (i=1; i < 11; i++) { /* munge first word of round key */ expanded_key[i].v8[0] = aes_sbox[expanded_key[i-1].v8[13]] ^ rc; expanded_key[i].v8[1] = aes_sbox[expanded_key[i-1].v8[14]]; expanded_key[i].v8[2] = aes_sbox[expanded_key[i-1].v8[15]]; expanded_key[i].v8[3] = aes_sbox[expanded_key[i-1].v8[12]]; expanded_key[i].v32[0] ^= expanded_key[i-1].v32[0]; /* set remaining 32 bit words to the exor of the one previous with * the one four words previous */ expanded_key[i].v32[1] = expanded_key[i].v32[0] ^ expanded_key[i-1].v32[1]; expanded_key[i].v32[2] = expanded_key[i].v32[1] ^ expanded_key[i-1].v32[2]; expanded_key[i].v32[3] = expanded_key[i].v32[2] ^ expanded_key[i-1].v32[3]; #if 0 debug_print2(mod_aes_icm, "expanded key[%d]: %s", i,v128_hex_string(&expanded_key[i])); #endif /* modify round constant */ rc = gf2_8_shift(rc); } } inline void aes_expand_decryption_key(const v128_t *key, aes_expanded_key_t expanded_key) { int i; aes_expand_encryption_key(key, expanded_key); /* invert the order of the round keys */ for (i=0; i < 5; i++) { v128_t tmp; v128_copy(&tmp, &expanded_key[10-i]); v128_copy(&expanded_key[10-i], &expanded_key[i]); v128_copy(&expanded_key[i], &tmp); } /* * apply the inverse mixColumn transform to the round keys (except * for the first and the last) * * mixColumn is implemented by using the tables U0, U1, U2, U3, * followed by the T4 table (which cancels out the use of the sbox * in the U-tables) */ for (i=1; i < 10; i++) { #ifdef CPU_RISC uint32_t tmp; tmp = expanded_key[i].v32[0]; expanded_key[i].v32[0] = U0[T4[(tmp >> 24) ] & 0xff] ^ U1[T4[(tmp >> 16) & 0xff] & 0xff] ^ U2[T4[(tmp >> 8) & 0xff] & 0xff] ^ U3[T4[(tmp) & 0xff] & 0xff]; tmp = expanded_key[i].v32[1]; expanded_key[i].v32[1] = U0[T4[(tmp >> 24) ] & 0xff] ^ U1[T4[(tmp >> 16) & 0xff] & 0xff] ^ U2[T4[(tmp >> 8) & 0xff] & 0xff] ^ U3[T4[(tmp) & 0xff] & 0xff]; tmp = expanded_key[i].v32[2]; expanded_key[i].v32[2] = U0[T4[(tmp >> 24) ] & 0xff] ^ U1[T4[(tmp >> 16) & 0xff] & 0xff] ^ U2[T4[(tmp >> 8) & 0xff] & 0xff] ^ U3[T4[(tmp) & 0xff] & 0xff]; tmp = expanded_key[i].v32[3]; expanded_key[i].v32[3] = U0[T4[(tmp >> 24) ] & 0xff] ^ U1[T4[(tmp >> 16) & 0xff] & 0xff] ^ U2[T4[(tmp >> 8) & 0xff] & 0xff] ^ U3[T4[(tmp) & 0xff] & 0xff]; #else /* assume CPU_CISC */ uint32_t c0, c1, c2, c3; c0 = U0[aes_sbox[expanded_key[i].v8[0]]] ^ U1[aes_sbox[expanded_key[i].v8[1]]] ^ U2[aes_sbox[expanded_key[i].v8[2]]] ^ U3[aes_sbox[expanded_key[i].v8[3]]]; c1 = U0[aes_sbox[expanded_key[i].v8[4]]] ^ U1[aes_sbox[expanded_key[i].v8[5]]] ^ U2[aes_sbox[expanded_key[i].v8[6]]] ^ U3[aes_sbox[expanded_key[i].v8[7]]]; c2 = U0[aes_sbox[expanded_key[i].v8[8]]] ^ U1[aes_sbox[expanded_key[i].v8[9]]] ^ U2[aes_sbox[expanded_key[i].v8[10]]] ^ U3[aes_sbox[expanded_key[i].v8[11]]]; c3 = U0[aes_sbox[expanded_key[i].v8[12]]] ^ U1[aes_sbox[expanded_key[i].v8[13]]] ^ U2[aes_sbox[expanded_key[i].v8[14]]] ^ U3[aes_sbox[expanded_key[i].v8[15]]]; expanded_key[i].v32[0] = c0; expanded_key[i].v32[1] = c1; expanded_key[i].v32[2] = c2; expanded_key[i].v32[3] = c3; #endif } } #ifdef CPU_CISC static inline void aes_round(v128_t *state, const v128_t *round_key) { uint32_t column0, column1, column2, column3; /* compute the columns of the output square in terms of the octets of state, using the tables T0, T1, T2, T3 */ column0 = T0[state->v8[0]] ^ T1[state->v8[5]] ^ T2[state->v8[10]] ^ T3[state->v8[15]]; column1 = T0[state->v8[4]] ^ T1[state->v8[9]] ^ T2[state->v8[14]] ^ T3[state->v8[3]]; column2 = T0[state->v8[8]] ^ T1[state->v8[13]] ^ T2[state->v8[2]] ^ T3[state->v8[7]]; column3 = T0[state->v8[12]] ^ T1[state->v8[1]] ^ T2[state->v8[6]] ^ T3[state->v8[11]]; state->v32[0] = column0 ^ round_key->v32[0]; state->v32[1] = column1 ^ round_key->v32[1]; state->v32[2] = column2 ^ round_key->v32[2]; state->v32[3] = column3 ^ round_key->v32[3]; } static inline void aes_inv_round(v128_t *state, const v128_t *round_key) { uint32_t column0, column1, column2, column3; /* compute the columns of the output square in terms of the octets of state, using the tables U0, U1, U2, U3 */ column0 = U0[state->v8[0]] ^ U1[state->v8[13]] ^ U2[state->v8[10]] ^ U3[state->v8[7]]; column1 = U0[state->v8[4]] ^ U1[state->v8[1]] ^ U2[state->v8[14]] ^ U3[state->v8[11]]; column2 = U0[state->v8[8]] ^ U1[state->v8[5]] ^ U2[state->v8[2]] ^ U3[state->v8[15]]; column3 = U0[state->v8[12]] ^ U1[state->v8[9]] ^ U2[state->v8[6]] ^ U3[state->v8[3]]; state->v32[0] = column0 ^ round_key->v32[0]; state->v32[1] = column1 ^ round_key->v32[1]; state->v32[2] = column2 ^ round_key->v32[2]; state->v32[3] = column3 ^ round_key->v32[3]; } static inline void aes_final_round(v128_t *state, const v128_t *round_key) { uint8_t tmp; /* byte substitutions and row shifts */ /* first row - no shift */ state->v8[0] = aes_sbox[state->v8[0]]; state->v8[4] = aes_sbox[state->v8[4]]; state->v8[8] = aes_sbox[state->v8[8]]; state->v8[12] = aes_sbox[state->v8[12]]; /* second row - shift one left */ tmp = aes_sbox[state->v8[1]]; state->v8[1] = aes_sbox[state->v8[5]]; state->v8[5] = aes_sbox[state->v8[9]]; state->v8[9] = aes_sbox[state->v8[13]]; state->v8[13] = tmp; /* third row - shift two left */ tmp = aes_sbox[state->v8[10]]; state->v8[10] = aes_sbox[state->v8[2]]; state->v8[2] = tmp; tmp = aes_sbox[state->v8[14]]; state->v8[14] = aes_sbox[state->v8[6]]; state->v8[6] = tmp; /* fourth row - shift three left */ tmp = aes_sbox[state->v8[15]]; state->v8[15] = aes_sbox[state->v8[11]]; state->v8[11] = aes_sbox[state->v8[7]]; state->v8[7] = aes_sbox[state->v8[3]]; state->v8[3] = tmp; v128_xor_eq(state, round_key); } static inline void aes_inv_final_round(v128_t *state, const v128_t *round_key) { uint8_t tmp; /* byte substitutions and row shifts */ /* first row - no shift */ state->v8[0] = aes_inv_sbox[state->v8[0]]; state->v8[4] = aes_inv_sbox[state->v8[4]]; state->v8[8] = aes_inv_sbox[state->v8[8]]; state->v8[12] = aes_inv_sbox[state->v8[12]]; /* second row - shift one right */ tmp = aes_inv_sbox[state->v8[13]]; state->v8[13] = aes_inv_sbox[state->v8[9]]; state->v8[9] = aes_inv_sbox[state->v8[5]]; state->v8[5] = aes_inv_sbox[state->v8[1]]; state->v8[1] = tmp; /* third row - shift two right */ tmp = aes_inv_sbox[state->v8[2]]; state->v8[2] = aes_inv_sbox[state->v8[10]]; state->v8[10] = tmp; tmp = aes_inv_sbox[state->v8[6]]; state->v8[6] = aes_inv_sbox[state->v8[14]]; state->v8[14] = tmp; /* fourth row - shift three right */ tmp = aes_inv_sbox[state->v8[3]]; state->v8[3] = aes_inv_sbox[state->v8[7]]; state->v8[7] = aes_inv_sbox[state->v8[11]]; state->v8[11] = aes_inv_sbox[state->v8[15]]; state->v8[15] = tmp; v128_xor_eq(state, round_key); } #elif CPU_RISC static inline void aes_round(v128_t *state, const v128_t *round_key) { uint32_t column0, column1, column2, column3; /* compute the columns of the output square in terms of the octets of state, using the tables T0, T1, T2, T3 */ #ifdef WORDS_BIGENDIAN column0 = T0[state->v32[0] >> 24] ^ T1[(state->v32[1] >> 16) & 0xff] ^ T2[(state->v32[2] >> 8) & 0xff] ^ T3[state->v32[3] & 0xff]; column1 = T0[state->v32[1] >> 24] ^ T1[(state->v32[2] >> 16) & 0xff] ^ T2[(state->v32[3] >> 8) & 0xff] ^ T3[state->v32[0] & 0xff]; column2 = T0[state->v32[2] >> 24] ^ T1[(state->v32[3] >> 16) & 0xff] ^ T2[(state->v32[0] >> 8) & 0xff] ^ T3[state->v32[1] & 0xff]; column3 = T0[state->v32[3] >> 24] ^ T1[(state->v32[0] >> 16) & 0xff] ^ T2[(state->v32[1] >> 8) & 0xff] ^ T3[state->v32[2] & 0xff]; #else column0 = T0[state->v32[0] & 0xff] ^ T1[(state->v32[1] >> 8) & 0xff] ^ T2[(state->v32[2] >> 16) & 0xff] ^ T3[state->v32[3] >> 24]; column1 = T0[state->v32[1] & 0xff] ^ T1[(state->v32[2] >> 8) & 0xff] ^ T2[(state->v32[3] >> 16) & 0xff] ^ T3[state->v32[0] >> 24]; column2 = T0[state->v32[2] & 0xff] ^ T1[(state->v32[3] >> 8) & 0xff] ^ T2[(state->v32[0] >> 16) & 0xff] ^ T3[state->v32[1] >> 24]; column3 = T0[state->v32[3] & 0xff] ^ T1[(state->v32[0] >> 8) & 0xff] ^ T2[(state->v32[1] >> 16) & 0xff] ^ T3[state->v32[2] >> 24]; #endif /* WORDS_BIGENDIAN */ state->v32[0] = column0 ^ round_key->v32[0]; state->v32[1] = column1 ^ round_key->v32[1]; state->v32[2] = column2 ^ round_key->v32[2]; state->v32[3] = column3 ^ round_key->v32[3]; } static inline void aes_inv_round(v128_t *state, const v128_t *round_key) { uint32_t column0, column1, column2, column3; /* compute the columns of the output square in terms of the octets of state, using the tables U0, U1, U2, U3 */ #ifdef WORDS_BIGENDIAN /* FIX! WRong indexes */ column0 = U0[state->v32[0] >> 24] ^ U1[(state->v32[3] >> 16) & 0xff] ^ U2[(state->v32[2] >> 8) & 0xff] ^ U3[state->v32[1] & 0xff]; column1 = U0[state->v32[1] >> 24] ^ U1[(state->v32[0] >> 16) & 0xff] ^ U2[(state->v32[3] >> 8) & 0xff] ^ U3[state->v32[2] & 0xff]; column2 = U0[state->v32[2] >> 24] ^ U1[(state->v32[1] >> 16) & 0xff] ^ U2[(state->v32[0] >> 8) & 0xff] ^ U3[state->v32[3] & 0xff]; column3 = U0[state->v32[3] >> 24] ^ U1[(state->v32[2] >> 16) & 0xff] ^ U2[(state->v32[1] >> 8) & 0xff] ^ U3[state->v32[0] & 0xff]; #else column0 = U0[state->v32[0] & 0xff] ^ U1[(state->v32[1] >> 8) & 0xff] ^ U2[(state->v32[2] >> 16) & 0xff] ^ U3[state->v32[3] >> 24]; column1 = U0[state->v32[1] & 0xff] ^ U1[(state->v32[2] >> 8) & 0xff] ^ U2[(state->v32[3] >> 16) & 0xff] ^ U3[state->v32[0] >> 24]; column2 = U0[state->v32[2] & 0xff] ^ U1[(state->v32[3] >> 8) & 0xff] ^ U2[(state->v32[0] >> 16) & 0xff] ^ U3[state->v32[1] >> 24]; column3 = U0[state->v32[3] & 0xff] ^ U1[(state->v32[0] >> 8) & 0xff] ^ U2[(state->v32[1] >> 16) & 0xff] ^ U3[state->v32[2] >> 24]; #endif /* WORDS_BIGENDIAN */ state->v32[0] = column0 ^ round_key->v32[0]; state->v32[1] = column1 ^ round_key->v32[1]; state->v32[2] = column2 ^ round_key->v32[2]; state->v32[3] = column3 ^ round_key->v32[3]; } static inline void aes_final_round(v128_t *state, const v128_t *round_key) { uint32_t tmp0, tmp1, tmp2, tmp3; tmp0 = (T4[(state->v32[0] >> 24)] & 0xff000000) ^ (T4[(state->v32[1] >> 16) & 0xff] & 0x00ff0000) ^ (T4[(state->v32[2] >> 8) & 0xff] & 0x0000ff00) ^ (T4[(state->v32[3] ) & 0xff] & 0x000000ff) ^ round_key->v32[0]; tmp1 = (T4[(state->v32[1] >> 24)] & 0xff000000) ^ (T4[(state->v32[2] >> 16) & 0xff] & 0x00ff0000) ^ (T4[(state->v32[3] >> 8) & 0xff] & 0x0000ff00) ^ (T4[(state->v32[0] ) & 0xff] & 0x000000ff) ^ round_key->v32[1]; tmp2 = (T4[(state->v32[2] >> 24)] & 0xff000000) ^ (T4[(state->v32[3] >> 16) & 0xff] & 0x00ff0000) ^ (T4[(state->v32[0] >> 8) & 0xff] & 0x0000ff00) ^ (T4[(state->v32[1] ) & 0xff] & 0x000000ff) ^ round_key->v32[2]; tmp3 = (T4[(state->v32[3] >> 24)] & 0xff000000) ^ (T4[(state->v32[0] >> 16) & 0xff] & 0x00ff0000) ^ (T4[(state->v32[1] >> 8) & 0xff] & 0x0000ff00) ^ (T4[(state->v32[2] ) & 0xff] & 0x000000ff) ^ round_key->v32[3]; state->v32[0] = tmp0; state->v32[1] = tmp1; state->v32[2] = tmp2; state->v32[3] = tmp3; } static inline void aes_inv_final_round(v128_t *state, const v128_t *round_key) { uint32_t tmp0, tmp1, tmp2, tmp3; tmp0 = (U4[(state->v32[0] >> 24)] & 0xff000000) ^ (U4[(state->v32[3] >> 16) & 0xff] & 0x00ff0000) ^ (U4[(state->v32[2] >> 8) & 0xff] & 0x0000ff00) ^ (U4[(state->v32[1] ) & 0xff] & 0x000000ff) ^ round_key->v32[0]; tmp1 = (U4[(state->v32[1] >> 24)] & 0xff000000) ^ (U4[(state->v32[0] >> 16) & 0xff] & 0x00ff0000) ^ (U4[(state->v32[3] >> 8) & 0xff] & 0x0000ff00) ^ (U4[(state->v32[2] ) & 0xff] & 0x000000ff) ^ round_key->v32[1]; tmp2 = (U4[(state->v32[2] >> 24)] & 0xff000000) ^ (U4[(state->v32[1] >> 16) & 0xff] & 0x00ff0000) ^ (U4[(state->v32[0] >> 8) & 0xff] & 0x0000ff00) ^ (U4[(state->v32[3] ) & 0xff] & 0x000000ff) ^ round_key->v32[2]; tmp3 = (U4[(state->v32[3] >> 24)] & 0xff000000) ^ (U4[(state->v32[2] >> 16) & 0xff] & 0x00ff0000) ^ (U4[(state->v32[1] >> 8) & 0xff] & 0x0000ff00) ^ (U4[(state->v32[0] ) & 0xff] & 0x000000ff) ^ round_key->v32[3]; state->v32[0] = tmp0; state->v32[1] = tmp1; state->v32[2] = tmp2; state->v32[3] = tmp3; } #elif CPU_16 /* assume 16-bit word size on processor */ static inline void aes_round(v128_t *state, const v128_t *round_key) { uint32_t column0, column1, column2, column3; uint16_t c /* compute the columns of the output square in terms of the octets of state, using the tables T0, T1, T2, T3 */ column0 = T0[state->v8[0]] ^ T1[state->v8[5]] ^ T2[state->v8[10]] ^ T3[state->v8[15]]; column1 = T0[state->v8[4]] ^ T1[state->v8[9]] ^ T2[state->v8[14]] ^ T3[state->v8[3]]; column2 = T0[state->v8[8]] ^ T1[state->v8[13]] ^ T2[state->v8[2]] ^ T3[state->v8[7]]; column3 = T0[state->v8[12]] ^ T1[state->v8[1]] ^ T2[state->v8[6]] ^ T3[state->v8[11]]; state->v32[0] = column0 ^ round_key->v32[0]; state->v32[1] = column1 ^ round_key->v32[1]; state->v32[2] = column2 ^ round_key->v32[2]; state->v32[3] = column3 ^ round_key->v32[3]; } static inline void aes_inv_round(v128_t *state, const v128_t *round_key) { uint32_t column0, column1, column2, column3; /* compute the columns of the output square in terms of the octets of state, using the tables U0, U1, U2, U3 */ column0 = U0[state->v8[0]] ^ U1[state->v8[5]] ^ U2[state->v8[10]] ^ U3[state->v8[15]]; column1 = U0[state->v8[4]] ^ U1[state->v8[9]] ^ U2[state->v8[14]] ^ U3[state->v8[3]]; column2 = U0[state->v8[8]] ^ U1[state->v8[13]] ^ U2[state->v8[2]] ^ U3[state->v8[7]]; column3 = U0[state->v8[12]] ^ U1[state->v8[1]] ^ U2[state->v8[6]] ^ U3[state->v8[11]]; state->v32[0] = column0 ^ round_key->v32[0]; state->v32[1] = column1 ^ round_key->v32[1]; state->v32[2] = column2 ^ round_key->v32[2]; state->v32[3] = column3 ^ round_key->v32[3]; } static inline void aes_final_round(v128_t *state, const v128_t *round_key) { uint8_t tmp; /* byte substitutions and row shifts */ /* first row - no shift */ state->v8[0] = aes_sbox[state->v8[0]]; state->v8[4] = aes_sbox[state->v8[4]]; state->v8[8] = aes_sbox[state->v8[8]]; state->v8[12] = aes_sbox[state->v8[12]]; /* second row - shift one left */ tmp = aes_sbox[state->v8[1]]; state->v8[1] = aes_sbox[state->v8[5]]; state->v8[5] = aes_sbox[state->v8[9]]; state->v8[9] = aes_sbox[state->v8[13]]; state->v8[13] = tmp; /* third row - shift two left */ tmp = aes_sbox[state->v8[10]]; state->v8[10] = aes_sbox[state->v8[2]]; state->v8[2] = tmp; tmp = aes_sbox[state->v8[14]]; state->v8[14] = aes_sbox[state->v8[6]]; state->v8[6] = tmp; /* fourth row - shift three left */ tmp = aes_sbox[state->v8[15]]; state->v8[15] = aes_sbox[state->v8[11]]; state->v8[11] = aes_sbox[state->v8[7]]; state->v8[7] = aes_sbox[state->v8[3]]; state->v8[3] = tmp; v128_xor_eq(state, round_key); } static inline void aes_inv_final_round(v128_t *state, const v128_t *round_key) { uint8_t tmp; /* byte substitutions and row shifts */ /* first row - no shift */ state->v8[0] = aes_inv_sbox[state->v8[0]]; state->v8[4] = aes_inv_sbox[state->v8[4]]; state->v8[8] = aes_inv_sbox[state->v8[8]]; state->v8[12] = aes_inv_sbox[state->v8[12]]; /* second row - shift one left */ tmp = aes_inv_sbox[state->v8[1]]; state->v8[1] = aes_inv_sbox[state->v8[5]]; state->v8[5] = aes_inv_sbox[state->v8[9]]; state->v8[9] = aes_inv_sbox[state->v8[13]]; state->v8[13] = tmp; /* third row - shift two left */ tmp = aes_inv_sbox[state->v8[10]]; state->v8[10] = aes_inv_sbox[state->v8[2]]; state->v8[2] = tmp; tmp = aes_inv_sbox[state->v8[14]]; state->v8[14] = aes_inv_sbox[state->v8[6]]; state->v8[6] = tmp; /* fourth row - shift three left */ tmp = aes_inv_sbox[state->v8[15]]; state->v8[15] = aes_inv_sbox[state->v8[11]]; state->v8[11] = aes_inv_sbox[state->v8[7]]; state->v8[7] = aes_inv_sbox[state->v8[3]]; state->v8[3] = tmp; v128_xor_eq(state, round_key); } #endif /* CPU type */ #ifdef CONFIG_RTK_VOIP_AES_128_HW_8186 #include "rtl8186_crypto_if.h" #include "rtl8186_crypto.h" struct rtl8186_crypto_request reqest; v128_t zero_iv; void aes_encrypt(v128_t *plaintext, const aes_expanded_key_t exp_key) { struct rtl8186_crypto_request *req = &reqest; req->crypt_iv = (unsigned char *)&zero_iv.v8[0]; req->crypt_offset = 0; req->cmds = RTL_CRYPT_AES; req->inbuf = &plaintext->v8[0]; req->outbuf = req->inbuf; req->inlen = 16; req->outlen = 16; req->crypt_len = 16; req->crypt_key = (unsigned char *)&exp_key[0].v8[0]; // HW crypto if ( rtl8186_crypto_execute(req) != RTL_CRYPT_OK) { printf("rtl8186_crypto_execute(req) error!"); } //r3k_flush_dcache_range(0,0); while (rtl8186_crypto_query_request(req) != RTL_CRYPT_DONE) ; //printf(" w ");} } #else void aes_encrypt(v128_t *plaintext, const aes_expanded_key_t exp_key) { /* add in the subkey */ v128_xor_eq(plaintext, exp_key + 0); /* now do nine rounds */ aes_round(plaintext, exp_key + 1); aes_round(plaintext, exp_key + 2); aes_round(plaintext, exp_key + 3); aes_round(plaintext, exp_key + 4); aes_round(plaintext, exp_key + 5); aes_round(plaintext, exp_key + 6); aes_round(plaintext, exp_key + 7); aes_round(plaintext, exp_key + 8); aes_round(plaintext, exp_key + 9); /* the last round is different */ aes_final_round(plaintext, exp_key + 10); } #endif void aes_decrypt(v128_t *plaintext, const aes_expanded_key_t exp_key) { /* add in the subkey */ v128_xor_eq(plaintext, exp_key + 0); /* now do nine rounds */ aes_inv_round(plaintext, exp_key + 1); aes_inv_round(plaintext, exp_key + 2); aes_inv_round(plaintext, exp_key + 3); aes_inv_round(plaintext, exp_key + 4); aes_inv_round(plaintext, exp_key + 5); aes_inv_round(plaintext, exp_key + 6); aes_inv_round(plaintext, exp_key + 7); aes_inv_round(plaintext, exp_key + 8); aes_inv_round(plaintext, exp_key + 9); /* the last round is different */ aes_inv_final_round(plaintext, exp_key + 10); }
ysleu/RTL8685
uClinux-dist/linux-2.6.x/rtk_voip-asmp/srtp/crypto/cipher/aes.c
C
gpl-2.0
84,057
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-x11-free-3.3.8/include/qasyncimageio.h:67 --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>QImageFormat Member List</title> <style type="text/css"><!-- fn { margin-left: 1cm; text-indent: -1cm; } a:link { color: #004faf; text-decoration: none } a:visited { color: #672967; text-decoration: none } body { background: #ffffff; color: black; } --></style> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr bgcolor="#E5E5E5"> <td valign=center> <a href="index.html"> <font color="#004faf">Home</font></a> | <a href="classes.html"> <font color="#004faf">All&nbsp;Classes</font></a> | <a href="mainclasses.html"> <font color="#004faf">Main&nbsp;Classes</font></a> | <a href="annotated.html"> <font color="#004faf">Annotated</font></a> | <a href="groups.html"> <font color="#004faf">Grouped&nbsp;Classes</font></a> | <a href="functions.html"> <font color="#004faf">Functions</font></a> </td> <td align="right" valign="center"><img src="logo32.png" align="right" width="64" height="32" border="0"></td></tr></table><h1 align=center>Complete Member List for QImageFormat</h1> <p>This is the complete list of member functions for <a href="qimageformat.html">QImageFormat</a>, including inherited members. <ul> <li><a href="qimageformat.html#decode">decode</a>() </ul> <!-- eof --> <p><address><hr><div align=center> <table width=100% cellspacing=0 border=0><tr> <td>Copyright &copy; 2007 <a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a> <td align=right><div align=right>Qt 3.3.8</div> </table></div></address></body> </html>
OS2World/LIB-QT3_Toolkit_Vbox
doc/html/qimageformat-members.html
HTML
gpl-2.0
1,758
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>oRTP: /Users/sajidiqbal/linphone-iphone/submodules/linphone/oRTP/src Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">oRTP &#160;<span id="projectnumber">0.22.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_cb9869b27e826b77484549eff4a4ca49.html">linphone</a></li><li class="navelem"><a class="el" href="dir_e16d2a1838f7bfd05e5d9e48ef98bd51.html">oRTP</a></li><li class="navelem"><a class="el" href="dir_280d7e7a0b50d8c818a606c73d366652.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">src Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:avprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>avprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b64_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="b64_8c.html">b64.c</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:dll__entry_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>dll_entry.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:event_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>event.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.h</b> <a href="jitterctl_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:logging_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>logging.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:netsim_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>netsim.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp-config-win32_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp-config-win32.h</b> <a href="ortp-config-win32_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp__srtp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp_srtp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:payloadtype_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>payloadtype.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:port_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>port.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:posixtimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>posixtimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__inet_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_inet.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__priv_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_priv.h</b> <a href="rtpsession__priv_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsignaltable_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsignaltable.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.h</b> <a href="rtptimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.h</b> <a href="scheduler_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:sessionset_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>sessionset.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:str__utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>str_utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:stun_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>stun.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:stun__udp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>stun_udp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:telephonyevents_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>telephonyevents.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.h</b> <a href="utils_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:winrttimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>winrttimer.h</b> <a href="winrttimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:zrtp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>zrtp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jul 15 2013 17:05:21 for oRTP by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
guardianproject/linphone-ios-secure
liblinphone-sdk/armv7-apple-darwin/share/doc/ortp-0.22.0/html/dir_280d7e7a0b50d8c818a606c73d366652.html
HTML
gpl-2.0
11,330
/* * COPYRIGHT * * PCB, interactive printed circuit board design * Copyright (C) 2003 DJ Delorie * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Contact addresses for paper mail and Email: * DJ Delorie, 334 North Road, Deerfield NH 03037-1110, USA * dj@delorie.com * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "global.h" #include <memory.h> #include <limits.h> #include "data.h" #include "create.h" #include "remove.h" #include "move.h" #include "draw.h" #include "undo.h" #include "strflags.h" #include "find.h" #include "pcb-printf.h" #ifdef HAVE_LIBDMALLOC #include <dmalloc.h> #endif #ifndef HAVE_RINT #define rint(x) (ceil((x) - 0.5)) #endif #define dprintf if(0)pcb_printf #define selected(x) TEST_FLAG (SELECTEDFLAG, (x)) #define autorouted(x) TEST_FLAG (AUTOFLAG, (x)) #define SB (PCB->Bloat+1) /* must be 2^N-1 */ #define INC 7 #define O_HORIZ 0x10 #define O_VERT 0x20 #define LEFT 0x11 #define RIGHT 0x12 #define UP 0x24 #define DOWN 0x28 #define DIAGONAL 0xf0 #define ORIENT(x) ((x) & 0xf0) #define DIRECT(x) ((x) & 0x0f) /* Manhattan length of the longest "freckle" */ #define LONGEST_FRECKLE 2 struct line_s; typedef struct corner_s { int layer; struct corner_s *next; int x, y; int net; PinType *via; PadType *pad; PinType *pin; int miter; int n_lines; struct line_s **lines; } corner_s; typedef struct line_s { int layer; struct line_s *next; corner_s *s, *e; LineType *line; char is_pad; } line_s; typedef struct rect_s { int x1, y1, x2, y2; } rect_s; #define DELETE(q) (q)->layer = 0xdeadbeef #define DELETED(q) ((q)->layer == 0xdeadbeef) static corner_s *corners, *next_corner = 0; static line_s *lines; static int layer_groupings[MAX_LAYER]; static char layer_type[MAX_LAYER]; #define LT_COMPONENT 1 #define LT_SOLDER 2 static int autorouted_only = 1; static const char djopt_sao_syntax[] = "OptAutoOnly()"; static const char djopt_sao_help[] = "Toggles the optimize-only-autorouted flag."; /* %start-doc actions OptAutoOnly The original purpose of the trace optimizer was to clean up the traces created by the various autorouters that have been used with PCB. When a board has a mix of autorouted and carefully hand-routed traces, you don't normally want the optimizer to move your hand-routed traces. But, sometimes you do. By default, the optimizer only optimizes autorouted traces. This action toggles that setting, so that you can optimize hand-routed traces also. %end-doc */ int djopt_set_auto_only (int argc, char **argv, Coord x, Coord y) { autorouted_only = autorouted_only ? 0 : 1; return 0; } static int djopt_get_auto_only (int dummy) { return autorouted_only; } HID_Flag djopt_flag_list[] = { {"optautoonly", djopt_get_auto_only, 0} }; REGISTER_FLAGS (djopt_flag_list) static char * element_name_for (corner_s * c) { ELEMENT_LOOP (PCB->Data); { PIN_LOOP (element); { if (pin == c->pin) return element->Name[1].TextString; } END_LOOP; PAD_LOOP (element); { if (pad == c->pad) return element->Name[1].TextString; } END_LOOP; } END_LOOP; return "unknown"; } static char * corner_name (corner_s * c) { static char buf[4][100]; static int bn = 0; char *bp; bn = (bn + 1) % 4; if (c->net == 0xf1eef1ee) { sprintf (buf[bn], "\033[31m[%p freed corner]\033[0m", (void *) c); return buf[bn]; } sprintf (buf[bn], "\033[%dm[%p ", (c->pin || c->pad || c->via) ? 33 : 34, (void *) c); bp = buf[bn] + strlen (buf[bn]); if (c->pin) pcb_sprintf (bp, "pin %s:%s at %#mD", element_name_for (c), c->pin->Number, c->x, c->y); else if (c->via) pcb_sprintf (bp, "via at %#mD", c->x, c->y); else if (c->pad) { pcb_sprintf (bp, "pad %s:%s at %#mD %#mD-%#mD", element_name_for (c), c->pad->Number, c->x, c->y, c->pad->Point1.X, c->pad->Point1.Y, c->pad->Point2.X, c->pad->Point2.Y); } else pcb_sprintf (bp, "at %#mD", c->x, c->y); sprintf (bp + strlen (bp), " n%d l%d]\033[0m", c->n_lines, c->layer); return buf[bn]; } static int solder_layer, component_layer; static void dj_abort (char *msg, ...) { va_list a; va_start (a, msg); vprintf (msg, a); va_end (a); fflush (stdout); abort (); } #if 1 #define check(c,l) #else #define check(c,l) check2(__LINE__,c,l) static void check2 (int srcline, corner_s * c, line_s * l) { int saw_c = 0, saw_l = 0; corner_s *cc; line_s *ll; int i; for (cc = corners; cc; cc = cc->next) { if (DELETED (cc)) continue; if (cc == c) saw_c = 1; for (i = 0; i < cc->n_lines; i++) if (cc->lines[i]->s != cc && cc->lines[i]->e != cc) dj_abort ("check:%d: cc has line without backref\n", srcline); if (cc->via && (cc->x != cc->via->X || cc->y != cc->via->Y)) dj_abort ("check:%d: via not at corner\n", srcline); if (cc->pin && (cc->x != cc->pin->X || cc->y != cc->pin->Y)) dj_abort ("check:%d: pin not at corner\n", srcline); } if (c && !saw_c) dj_abort ("check:%d: corner not in corners list\n", srcline); for (ll = lines; ll; ll = ll->next) { if (DELETED (ll)) continue; if (ll == l) saw_l = 1; for (i = 0; i < ll->s->n_lines; i++) if (ll->s->lines[i] == ll) break; if (i == ll->s->n_lines) dj_abort ("check:%d: ll->s has no backref\n", srcline); for (i = 0; i < ll->e->n_lines; i++) if (ll->e->lines[i] == ll) break; if (i == ll->e->n_lines) dj_abort ("check:%d: ll->e has no backref\n", srcline); if (!ll->is_pad && (ll->s->x != ll->line->Point1.X || ll->s->y != ll->line->Point1.Y || ll->e->x != ll->line->Point2.X || ll->e->y != ll->line->Point2.Y)) { pcb_printf ("line: %#mD to %#mD pcbline: %#mD to %#mD\n", ll->s->x, ll->s->y, ll->e->x, ll->e->y, ll->line->Point1.X, ll->line->Point1.Y, ll->line->Point2.X, ll->line->Point2.Y); dj_abort ("check:%d: line doesn't match pcbline\n", srcline); } } if (l && !saw_l) dj_abort ("check:%d: line not in lines list\n", srcline); } #endif #define SWAP(a,b) { a^=b; b^=a; a^=b; } static int gridsnap (Coord n) { if (n <= 0) return 0; return n - n % (Settings.Grid); } /* Avoid commonly used names. */ static int djabs (int x) { return x > 0 ? x : -x; } static int djmax (int x, int y) { return x > y ? x : y; } static int djmin (int x, int y) { return x < y ? x : y; } /* * Find distance between 2 points. We use floating point math here * because we can fairly easily overflow a 32 bit integer here. In * fact it only takes 0.46" to do so. */ static int dist (int x1, int y1, int x2, int y2) { double dx1, dy1, dx2, dy2, d; dx1 = (double) x1; dy1 = (double) y1; dx2 = (double) x2; dy2 = (double) y2; d = sqrt ((dx1 - dx2) * (dx1 - dx2) + (dy1 - dy2) * (dy1 - dy2)); d = rint (d); return (int) d; } static int line_length (line_s * l) { if (l->s->x == l->e->x) return djabs (l->s->y - l->e->y); if (l->s->y == l->e->y) return djabs (l->s->x - l->e->x); return dist (l->s->x, l->s->y, l->e->x, l->e->y); } static int dist_ltp2 (int dx, int y, int y1, int y2) { if (y1 > y2) SWAP (y1, y2); if (y < y1) return dist (dx, y, 0, y1); if (y > y2) return dist (dx, y, 0, y2); return djabs (dx); } int sqr (int a) { return a * a; } static int intersecting_layers (int l1, int l2) { if (l1 == -1 || l2 == -1) return 1; if (l1 == l2) return 1; if (layer_groupings[l1] == layer_groupings[l2]) return 1; return 0; } static int dist_line_to_point (line_s * l, corner_s * c) { double len, r, d; /* We can do this quickly if l is vertical or horizontal. */ if (l->s->x == l->e->x) return dist_ltp2 (l->s->x - c->x, c->y, l->s->y, l->e->y); if (l->s->y == l->e->y) return dist_ltp2 (l->s->y - c->y, c->x, l->s->x, l->e->x); /* Do it the hard way. See comments for IsPointOnLine() in search.c */ len = sqrt (sqr (l->s->x - l->e->x) + sqr (l->s->y - l->e->y)); if (len == 0) return dist (l->s->x, l->s->y, c->x, c->y); r = (l->s->y - c->y) * (l->s->y - l->e->y) + (l->s->x - c->x) * (l->s->x - l->e->x); r /= len * len; if (r < 0) return dist (l->s->x, l->s->y, c->x, c->y); if (r > 1) return dist (l->e->x, l->e->y, c->x, c->y); d = (l->e->y - l->s->y) * (c->x * l->s->x) + (l->e->x - l->s->x) * (c->y - l->s->y); return (int) (d / len); } static int line_orient (line_s * l, corner_s * c) { int x1, y1, x2, y2; if (c == l->s) { x1 = l->s->x; y1 = l->s->y; x2 = l->e->x; y2 = l->e->y; } else { x1 = l->e->x; y1 = l->e->y; x2 = l->s->x; y2 = l->s->y; } if (x1 == x2) { if (y1 < y2) return DOWN; return UP; } else if (y1 == y2) { if (x1 < x2) return RIGHT; return LEFT; } return DIAGONAL; } #if 0 /* Not used */ static corner_s * common_corner (line_s * l1, line_s * l2) { if (l1->s == l2->s || l1->s == l2->e) return l1->s; if (l1->e == l2->s || l1->e == l2->e) return l1->e; dj_abort ("common_corner: no common corner found\n"); return NULL; } #endif static corner_s * other_corner (line_s * l, corner_s * c) { if (l->s == c) return l->e; if (l->e == c) return l->s; dj_abort ("other_corner: neither corner passed\n"); return NULL; } static corner_s * find_corner_if (int x, int y, int l) { corner_s *c; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (c->x != x || c->y != y) continue; if (!(c->layer == -1 || intersecting_layers (c->layer, l))) continue; return c; } return 0; } static corner_s * find_corner (int x, int y, int l) { corner_s *c; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (c->x != x || c->y != y) continue; if (!(c->layer == -1 || intersecting_layers (c->layer, l))) continue; return c; } c = (corner_s *) malloc (sizeof (corner_s)); c->next = corners; corners = c; c->x = x; c->y = y; c->net = 0; c->via = 0; c->pad = 0; c->pin = 0; c->layer = l; c->n_lines = 0; c->lines = (line_s **) malloc (INC * sizeof (line_s *)); return c; } static void add_line_to_corner (line_s * l, corner_s * c) { int n; n = (c->n_lines + 1 + INC) & ~INC; c->lines = (line_s **) realloc (c->lines, n * sizeof (line_s *)); c->lines[c->n_lines] = l; c->n_lines++; dprintf ("add_line_to_corner %#mD\n", c->x, c->y); } static LineType * create_pcb_line (int layer, int x1, int y1, int x2, int y2, int thick, int clear, FlagType flags) { char *from, *to; LineType *nl; LayerType *lyr = LAYER_PTR (layer); from = (char *) lyr->Line; nl = CreateNewLineOnLayer (PCB->Data->Layer + layer, x1, y1, x2, y2, thick, clear, flags); AddObjectToCreateUndoList (LINE_TYPE, lyr, nl, nl); to = (char *) lyr->Line; if (from != to) { line_s *lp; for (lp = lines; lp; lp = lp->next) { if (DELETED (lp)) continue; if ((char *) (lp->line) >= from && (char *) (lp->line) <= from + lyr->LineN * sizeof (LineType)) lp->line = (LineType *) ((char *) (lp->line) + (to - from)); } } return nl; } static void new_line (corner_s * s, corner_s * e, int layer, LineType * example) { line_s *ls; if (layer >= max_copper_layer) dj_abort ("layer %d\n", layer); if (example == NULL) dj_abort ("NULL example passed to new_line()\n", layer); if (s->x == e->x && s->y == e->y) return; ls = (line_s *) malloc (sizeof (line_s)); ls->next = lines; lines = ls; ls->is_pad = 0; ls->s = s; ls->e = e; ls->layer = layer; #if 0 if ((example->Point1.X == s->x && example->Point1.Y == s->y && example->Point2.X == e->x && example->Point2.Y == e->y) || (example->Point2.X == s->x && example->Point2.Y == s->y && example->Point1.X == e->x && example->Point1.Y == e->y)) { ls->line = example; } else #endif { LineType *nl; dprintf ("New line \033[35m%#mD to %#mD from l%d t%#mS c%#mS f%s\033[0m\n", s->x, s->y, e->x, e->y, layer, example->Thickness, example->Clearance, flags_to_string (example->Flags, LINE_TYPE)); nl = create_pcb_line (layer, s->x, s->y, e->x, e->y, example->Thickness, example->Clearance, example->Flags); if (!nl) dj_abort ("can't create new line!"); ls->line = nl; } add_line_to_corner (ls, s); add_line_to_corner (ls, e); check (s, ls); check (e, ls); } #if 0 /* Not used */ static int c_orth_to (corner_s * c, line_s * l, int o) { int i, o2; int rv = 0; for (i = 0; i < c->n_lines; i++) { if (c->lines[i] == l) continue; o2 = line_orient (c->lines[i], c); if (ORIENT (o) == ORIENT (o2) || o2 == DIAGONAL) return 0; rv++; } return rv; } #endif static line_s * other_line (corner_s * c, line_s * l) { int i; line_s *rv = 0; if (c->pin || c->pad || c->via) return 0; for (i = 0; i < c->n_lines; i++) { if (c->lines[i] == l) continue; if (rv) return 0; rv = c->lines[i]; } return rv; } static void empty_rect (rect_s * rect) { rect->x1 = rect->y1 = INT_MAX; rect->x2 = rect->y2 = INT_MIN; } static void add_point_to_rect (rect_s * rect, int x, int y, int w) { if (rect->x1 > x - w) rect->x1 = x - w; if (rect->x2 < x + w) rect->x2 = x + w; if (rect->y1 > y - w) rect->y1 = y - w; if (rect->y2 < y + w) rect->y2 = y + w; } static void add_line_to_rect (rect_s * rect, line_s * l) { add_point_to_rect (rect, l->s->x, l->s->y, 0); add_point_to_rect (rect, l->e->x, l->e->y, 0); } static int pin_in_rect (rect_s * r, int x, int y, int w) { if (x < r->x1 && x + w < r->x1) return 0; if (x > r->x2 && x - w > r->x2) return 0; if (y < r->y1 && y + w < r->y1) return 0; if (y > r->y2 && y - w > r->y2) return 0; return 1; } static int line_in_rect (rect_s * r, line_s * l) { rect_s lr; empty_rect (&lr); add_point_to_rect (&lr, l->s->x, l->s->y, l->line->Thickness / 2); add_point_to_rect (&lr, l->e->x, l->e->y, l->line->Thickness / 2); dprintf ("line_in_rect %#mD-%#mD vs %#mD-%#mD\n", r->x1, r->y1, r->x2, r->y2, lr.x1, lr.y1, lr.x2, lr.y2); /* simple intersection of rectangles */ if (lr.x1 < r->x1) lr.x1 = r->x1; if (lr.x2 > r->x2) lr.x2 = r->x2; if (lr.y1 < r->y1) lr.y1 = r->y1; if (lr.y2 > r->y2) lr.y2 = r->y2; if (lr.x1 < lr.x2 && lr.y1 < lr.y2) return 1; return 0; } static int corner_radius (corner_s * c) { int diam = 0; int i; if (c->pin) diam = djmax (c->pin->Thickness, diam); if (c->via) diam = djmax (c->via->Thickness, diam); for (i = 0; i < c->n_lines; i++) if (c->lines[i]->line) diam = djmax (c->lines[i]->line->Thickness, diam); diam = (diam + 1) / 2; return diam; } #if 0 /* Not used */ static int corner_layer (corner_s * c) { if (c->pin || c->via) return -1; if (c->n_lines < 1) return -1; return c->lines[0]->layer; } #endif static void add_corner_to_rect_if (rect_s * rect, corner_s * c, rect_s * e) { int diam = corner_radius (c); if (!pin_in_rect (e, c->x, c->y, diam)) return; if (c->x < e->x1 && c->y < e->y1 && dist (c->x, c->y, e->x1, e->y1) > diam) return; if (c->x > e->x2 && c->y < e->y1 && dist (c->x, c->y, e->x2, e->y1) > diam) return; if (c->x < e->x1 && c->y > e->y2 && dist (c->x, c->y, e->x1, e->y2) > diam) return; if (c->x > e->x2 && c->y > e->y2 && dist (c->x, c->y, e->x2, e->y2) > diam) return; /*pcb_printf("add point %#mD diam %#mS\n", c->x, c->y, diam); */ add_point_to_rect (rect, c->x, c->y, diam); } static void remove_line (line_s * l) { int i, j; LayerType *layer = &(PCB->Data->Layer[l->layer]); check (0, 0); if (l->line) RemoveLine (layer, l->line); DELETE (l); for (i = 0, j = 0; i < l->s->n_lines; i++) if (l->s->lines[i] != l) l->s->lines[j++] = l->s->lines[i]; l->s->n_lines = j; for (i = 0, j = 0; i < l->e->n_lines; i++) if (l->e->lines[i] != l) l->e->lines[j++] = l->e->lines[i]; l->e->n_lines = j; check (0, 0); } static void move_line_to_layer (line_s * l, int layer) { LayerType *ls, *ld; ls = LAYER_PTR (l->layer); ld = LAYER_PTR (layer); MoveObjectToLayer (LINE_TYPE, ls, l->line, 0, ld, 0); l->layer = layer; } static void remove_via_at (corner_s * c) { RemoveObject (VIA_TYPE, c->via, 0, 0); c->via = 0; } static void remove_corner (corner_s * c2) { corner_s *c; dprintf ("remove corner %s\n", corner_name (c2)); if (corners == c2) corners = c2->next; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (c->next == c2) c->next = c2->next; } if (next_corner == c2) next_corner = c2->next; free (c2->lines); c2->lines = 0; DELETE (c2); } static void merge_corners (corner_s * c1, corner_s * c2) { int i; if (c1 == c2) abort (); dprintf ("merge corners %s %s\n", corner_name (c1), corner_name (c2)); for (i = 0; i < c2->n_lines; i++) { add_line_to_corner (c2->lines[i], c1); if (c2->lines[i]->s == c2) c2->lines[i]->s = c1; if (c2->lines[i]->e == c2) c2->lines[i]->e = c1; } if (c1->via && c2->via) remove_via_at (c2); else if (c2->via) c1->via = c2->via; if (c2->pad) c1->pad = c2->pad; if (c2->pin) c1->pin = c2->pin; if (c2->layer != c1->layer) c1->layer = -1; remove_corner (c2); } static void move_corner (corner_s * c, int x, int y) { PinType *via; int i; corner_s *pad; check (c, 0); if (c->pad || c->pin) dj_abort ("move_corner: has pin or pad\n"); dprintf ("move_corner %p from %#mD to %#mD\n", (void *) c, c->x, c->y, x, y); pad = find_corner_if (x, y, c->layer); c->x = x; c->y = y; via = c->via; if (via) { MoveObject (VIA_TYPE, via, via, via, x - via->X, y - via->Y); dprintf ("via move %#mD to %#mD\n", via->X, via->Y, x, y); } for (i = 0; i < c->n_lines; i++) { LineType *tl = c->lines[i]->line; if (tl) { if (c->lines[i]->s == c) { MoveObject (LINEPOINT_TYPE, LAYER_PTR (c->lines[i]->layer), tl, &tl->Point1, x - (tl->Point1.X), y - (tl->Point1.Y)); } else { MoveObject (LINEPOINT_TYPE, LAYER_PTR (c->lines[i]->layer), tl, &tl->Point2, x - (tl->Point2.X), y - (tl->Point2.Y)); } dprintf ("Line %p moved to %#mD %#mD\n", (void *) tl, tl->Point1.X, tl->Point1.Y, tl->Point2.X, tl->Point2.Y); } } if (pad && pad != c) merge_corners (c, pad); else for (i = 0; i < c->n_lines; i++) { if (c->lines[i]->s->x == c->lines[i]->e->x && c->lines[i]->s->y == c->lines[i]->e->y) { corner_s *c2 = other_corner (c->lines[i], c); dprintf ("move_corner: removing line %#mD %#mD %p %p\n", c->x, c->y, c2->x, c2->y, (void *) c, (void *) c2); remove_line (c->lines[i]); if (c != c2) merge_corners (c, c2); check (c, 0); i--; break; } } gui->progress (0, 0, 0); check (c, 0); } static int any_line_selected () { line_s *l; for (l = lines; l; l = l->next) { if (DELETED (l)) continue; if (l->line && selected (l->line)) return 1; } return 0; } static int trim_step (int s, int l1, int l2) { dprintf ("trim %d %d %d\n", s, l1, l2); if (s > l1) s = l1; if (s > l2) s = l2; if (s != l1 && s != l2) s = gridsnap (s); return s; } static int canonicalize_line (line_s * l); static int split_line (line_s * l, corner_s * c) { int i; LineType *pcbline; line_s *ls; if (!intersecting_layers (l->layer, c->layer)) return 0; if (l->is_pad) return 0; if (c->pad) { dprintf ("split on pad!\n"); if (l->s->pad == c->pad || l->e->pad == c->pad) return 0; dprintf ("splitting...\n"); } check (c, l); pcbline = create_pcb_line (l->layer, c->x, c->y, l->e->x, l->e->y, l->line->Thickness, l->line->Clearance, l->line->Flags); if (pcbline == 0) return 0; /* already a line there */ check (c, l); dprintf ("split line from %#mD to %#mD at %#mD\n", l->s->x, l->s->y, l->e->x, l->e->y, c->x, c->y); ls = (line_s *) malloc (sizeof (line_s)); ls->next = lines; lines = ls; ls->is_pad = 0; ls->s = c; ls->e = l->e; ls->line = pcbline; ls->layer = l->layer; for (i = 0; i < l->e->n_lines; i++) if (l->e->lines[i] == l) l->e->lines[i] = ls; l->e = c; add_line_to_corner (l, c); add_line_to_corner (ls, c); MoveObject (LINEPOINT_TYPE, LAYER_PTR (l->layer), l->line, &l->line->Point2, c->x - (l->line->Point2.X), c->y - (l->line->Point2.Y)); return 1; } static int canonicalize_line (line_s * l) { /* This could be faster */ corner_s *c; if (l->s->x == l->e->x) { int y1 = l->s->y; int y2 = l->e->y; int x1 = l->s->x - l->line->Thickness / 2; int x2 = l->s->x + l->line->Thickness / 2; if (y1 > y2) { int t = y1; y1 = y2; y2 = t; } for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if ((y1 < c->y && c->y < y2) && intersecting_layers (l->layer, c->layer)) { if (c->x != l->s->x && c->x < x2 && c->x > x1 && !(c->pad || c->pin)) { move_corner (c, l->s->x, c->y); } if (c->x == l->s->x) { /* FIXME: if the line is split, we have to re-canonicalize both segments. */ return split_line (l, c); } } } } else if (l->s->y == l->e->y) { int x1 = l->s->x; int x2 = l->e->x; int y1 = l->s->y - l->line->Thickness / 2; int y2 = l->s->y + l->line->Thickness / 2; if (x1 > x2) { int t = x1; x1 = x2; x2 = t; } for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if ((x1 < c->x && c->x < x2) && intersecting_layers (l->layer, c->layer)) { if (c->y != l->s->y && c->y < y2 && c->y > y1 && !(c->pad || c->pin)) { move_corner (c, c->x, l->s->y); } if (c->y == l->s->y) { /* FIXME: Likewise. */ return split_line (l, c); } } } } else { /* diagonal lines. Let's try to split them at pins/vias anyway. */ int x1 = l->s->x; int x2 = l->e->x; int y1 = l->s->y; int y2 = l->e->y; if (x1 > x2) { int t = x1; x1 = x2; x2 = t; } if (y1 > y2) { int t = y1; y1 = y2; y2 = t; } for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (!c->via && !c->pin) continue; if ((x1 < c->x && c->x < x2) && (y1 < c->y && c->y < y2) && intersecting_layers (l->layer, c->layer)) { int th = c->pin ? c->pin->Thickness : c->via->Thickness; th /= 2; if (dist (l->s->x, l->s->y, c->x, c->y) > th && dist (l->e->x, l->e->y, c->x, c->y) > th && PinLineIntersect (c->pin ? c->pin : c->via, l->line)) { return split_line (l, c); } } } } return 0; } /* Make sure all vias are at line end points */ static int canonicalize_lines () { int changes = 0; int count; line_s *l; while (1) { count = 0; for (l = lines; l; l = l->next) { if (DELETED (l)) continue; count += canonicalize_line (l); } changes += count; if (count == 0) break; } return changes; } static int simple_optimize_corner (corner_s * c) { int i; int rv = 0; check (c, 0); if (c->via) { /* see if no via is needed */ if (selected (c->via)) dprintf ("via check: line[0] layer %d at %#mD nl %d\n", c->lines[0]->layer, c->x, c->y, c->n_lines); /* We can't delete vias that connect to power planes, or vias that aren't tented (assume they're test points). */ if (!TEST_ANY_THERMS (c->via) && c->via->Mask == 0) { for (i = 1; i < c->n_lines; i++) { if (selected (c->via)) dprintf (" line[%d] layer %d %#mD to %#mD\n", i, c->lines[i]->layer, c->lines[i]->s->x, c->lines[i]->s->y, c->lines[i]->e->x, c->lines[i]->e->y); if (c->lines[i]->layer != c->lines[0]->layer) break; } if (i == c->n_lines) { if (selected (c->via)) dprintf (" remove it\n"); remove_via_at (c); rv++; } } } check (c, 0); if (c->n_lines == 2 && !c->via) { /* see if it is an unneeded corner */ int o = line_orient (c->lines[0], c); corner_s *c2 = other_corner (c->lines[1], c); corner_s *c0 = other_corner (c->lines[0], c); if (o == line_orient (c->lines[1], c2) && o != DIAGONAL) { dprintf ("straight %#mD to %#mD to %#mD\n", c0->x, c0->y, c->x, c->y, c2->x, c2->y); if (selected (c->lines[0]->line)) SET_FLAG (SELECTEDFLAG, c->lines[1]->line); if (selected (c->lines[1]->line)) SET_FLAG (SELECTEDFLAG, c->lines[0]->line); move_corner (c, c2->x, c2->y); } } check (c, 0); if (c->n_lines == 1 && !c->via) { corner_s *c0 = other_corner (c->lines[0], c); if (abs(c->x - c0->x) + abs(c->y - c0->y) <= LONGEST_FRECKLE) { /* * Remove this line, as it is a "freckle". A freckle is an extremely * short line (around 0.01 thou) that is unconnected at one end. * Freckles are almost insignificantly small, but are annoying as * they prevent the mitering optimiser from working. * Freckles sometimes arise because of a bug in the autorouter that * causes it to create small overshoots (typically 0.01 thou) at the * intersections of vertical and horizontal lines. These overshoots * are converted to freckles as a side effect of canonicalize_line(). * Note that canonicalize_line() is not at fault, the bug is in the * autorouter creating overshoots. * The autorouter bug arose some time between the 20080202 and 20091103 * releases. * This code is probably worth keeping even when the autorouter bug is * fixed, as "freckles" could conceivably arise in other ways. */ dprintf ("freckle %#mD to %#mD\n", c->x, c->y, c0->x, c0->y); move_corner (c, c0->x, c0->y); } } check (c, 0); return rv; } /* We always run these */ static int simple_optimizations () { corner_s *c; int rv = 0; /* Look for corners that aren't */ for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (c->pad || c->pin) continue; rv += simple_optimize_corner (c); } return rv; } static int is_hole (corner_s * c) { return c->pin || c->pad || c->via; } static int orthopull_1 (corner_s * c, int fdir, int rdir, int any_sel) { static corner_s **cs = 0; static int cm = 0; static line_s **ls = 0; static int lm = 0; int i, li, ln, cn, snap; line_s *l = 0; corner_s *c2, *cb; int adir = 0, sdir = 0, pull; int saw_sel = 0, saw_auto = 0; int max, len = 0, r1 = 0, r2; rect_s rr; int edir = 0, done; if (cs == 0) { cs = (corner_s **) malloc (10 * sizeof (corner_s)); cm = 10; ls = (line_s **) malloc (10 * sizeof (line_s)); lm = 10; } for (i = 0; i < c->n_lines; i++) { int o = line_orient (c->lines[i], c); if (o == rdir) return 0; } switch (fdir) { case RIGHT: adir = DOWN; sdir = UP; break; case DOWN: adir = RIGHT; sdir = LEFT; break; default: dj_abort ("fdir not right or down\n"); } c2 = c; cn = 0; ln = 0; pull = 0; while (c2) { if (c2->pad || c2->pin || c2->n_lines < 2) return 0; if (cn >= cm) { cm = cn + 10; cs = (corner_s **) realloc (cs, cm * sizeof (corner_s *)); } cs[cn++] = c2; r2 = corner_radius (c2); if (r1 < r2) r1 = r2; l = 0; for (i = 0; i < c2->n_lines; i++) { int o = line_orient (c2->lines[i], c2); if (o == DIAGONAL) return 0; if (o == fdir) { if (l) return 0; /* we don't support overlapping lines yet */ l = c2->lines[i]; } if (o == rdir && c2->lines[i] != ls[ln - 1]) return 0; /* likewise */ if (o == adir) pull++; if (o == sdir) pull--; } if (!l) break; if (selected (l->line)) saw_sel = 1; if (autorouted (l->line)) saw_auto = 1; if (ln >= lm) { lm = ln + 10; ls = (line_s **) realloc (ls, lm * sizeof (line_s *)); } ls[ln++] = l; c2 = other_corner (l, c2); } if (cn < 2 || pull == 0) return 0; if (any_sel && !saw_sel) return 0; if (!any_sel && autorouted_only && !saw_auto) return 0; /* Ok, now look for other blockages. */ empty_rect (&rr); add_point_to_rect (&rr, c->x, c->y, corner_radius (c)); add_point_to_rect (&rr, c2->x, c2->y, corner_radius (c2)); if (fdir == RIGHT && pull < 0) edir = UP; else if (fdir == RIGHT && pull > 0) edir = DOWN; else if (fdir == DOWN && pull < 0) edir = LEFT; else if (fdir == DOWN && pull > 0) edir = RIGHT; max = -1; for (i = 0; i < cn; i++) for (li = 0; li < cs[i]->n_lines; li++) { if (line_orient (cs[i]->lines[li], cs[i]) != edir) continue; len = line_length (cs[i]->lines[li]); if (max > len || max == -1) max = len; } dprintf ("c %s %4#mD cn %d pull %3d max %4#mS\n", fdir == RIGHT ? "right" : "down ", c->x, c->y, cn, pull, max); switch (edir) { case UP: rr.y1 = c->y - r1 - max; break; case DOWN: rr.y2 = c->y + r1 + max; break; case LEFT: rr.x1 = c->x - r1 - max; break; case RIGHT: rr.x2 = c->x + r1 + max; break; } rr.x1 -= SB + 1; rr.x2 += SB + 1; rr.y1 -= SB + 1; rr.y2 += SB + 1; snap = 0; for (cb = corners; cb; cb = cb->next) { int sep; if (DELETED (cb)) continue; r1 = corner_radius (cb); if (cb->net == c->net && !cb->pad) continue; if (!pin_in_rect (&rr, cb->x, cb->y, r1)) continue; switch (edir) { #define ECHK(X,Y,LT) \ for (i=0; i<cn; i++) \ { \ if (!intersecting_layers(cs[i]->layer, cb->layer)) \ continue; \ r2 = corner_radius(cs[i]); \ if (cb->X + r1 <= cs[i]->X - r2 - SB - 1) \ continue; \ if (cb->X - r1 >= cs[i]->X + r2 + SB + 1) \ continue; \ if (cb->Y LT cs[i]->Y) \ continue; \ sep = djabs(cb->Y - cs[i]->Y) - r1 - r2 - SB - 1; \ if (max > sep) \ { max = sep; snap = 1; }\ } \ for (i=0; i<ln; i++) \ { \ if (!intersecting_layers(ls[i]->layer, cb->layer)) \ continue; \ if (cb->X <= cs[i]->X || cb->X >= cs[i+1]->X) \ continue; \ sep = (djabs(cb->Y - cs[i]->Y) - ls[i]->line->Thickness/2 \ - r1 - SB - 1); \ if (max > sep) \ { max = sep; snap = 1; }\ } case UP: ECHK (x, y, >=); break; case DOWN: ECHK (x, y, <=); break; case LEFT: ECHK (y, x, >=); break; case RIGHT: ECHK (y, x, <=); break; } } /* We must now check every line segment against our corners. */ for (l = lines; l; l = l->next) { int o, x1, x2, y1, y2; if (DELETED (l)) continue; dprintf ("check line %#mD to %#mD\n", l->s->x, l->s->y, l->e->x, l->e->y); if (l->s->net == c->net) { dprintf (" same net\n"); continue; } o = line_orient (l, 0); /* We don't need to check perpendicular lines, because their corners already take care of it. */ if ((fdir == RIGHT && (o == UP || o == DOWN)) || (fdir == DOWN && (o == RIGHT || o == LEFT))) { dprintf (" perpendicular\n"); continue; } /* Choose so that x1,y1 is closest to corner C */ if ((fdir == RIGHT && l->s->x < l->e->x) || (fdir == DOWN && l->s->y < l->e->y)) { x1 = l->s->x; y1 = l->s->y; x2 = l->e->x; y2 = l->e->y; } else { x1 = l->e->x; y1 = l->e->y; x2 = l->s->x; y2 = l->s->y; } /* Eliminate all lines outside our range */ if ((fdir == RIGHT && (x2 < c->x || x1 > c2->x)) || (fdir == DOWN && (y2 < c->y || y1 > c2->y))) { dprintf (" outside our range\n"); continue; } /* Eliminate all lines on the wrong side of us */ if ((edir == UP && y1 > c->y && y2 > c->y) || (edir == DOWN && y1 < c->y && y2 < c->y) || (edir == LEFT && x1 > c->x && x2 > c->x) || (edir == RIGHT && x1 < c->x && x2 < c->x)) { dprintf (" wrong side\n"); continue; } /* For now, cheat on diagonals */ switch (edir) { case RIGHT: if (x1 > x2) x1 = x2; break; case LEFT: if (x1 < x2) x1 = x2; break; case DOWN: if (y1 > y2) y1 = y2; break; case UP: if (y1 < y2) y1 = y2; break; } /* Ok, now see how far we can get for each of our corners. */ for (i = 0; i < cn; i++) { int r = l->line->Thickness + SB + corner_radius (cs[i]) + 1; int len = 0; if ((fdir == RIGHT && (x2 < cs[i]->x || x1 > cs[i]->x)) || (fdir == DOWN && (y2 < cs[i]->y || y1 > cs[i]->y))) continue; if (!intersecting_layers (cs[i]->layer, l->layer)) continue; switch (edir) { case RIGHT: len = x1 - c->x; break; case LEFT: len = c->x - x1; break; case DOWN: len = y1 - c->y; break; case UP: len = c->y - y1; break; } len -= r; dprintf (" len is %#mS vs corner at %#mD\n", len, cs[i]->x, cs[i]->y); if (len <= 0) return 0; if (max > len) max = len; } } /* We must make sure that if a segment isn't being completely removed, that any vias and/or pads don't overlap. */ done = 0; while (!done) { done = 1; for (i = 0; i < cn; i++) for (li = 0; li < cs[i]->n_lines; li++) { line_s *l = cs[i]->lines[li]; corner_s *oc = other_corner (l, cs[i]); if (line_orient (l, cs[i]) != edir) continue; len = line_length (l); if (!oc->pad || !cs[i]->via) { if (!is_hole (l->s) || !is_hole (l->e)) continue; if (len == max) continue; } len -= corner_radius (l->s); len -= corner_radius (l->e); len -= SB + 1; if (max > len) { max = len; done = 0; } } } if (max <= 0) return 0; switch (edir) { case UP: len = c->y - max; break; case DOWN: len = c->y + max; break; case LEFT: len = c->x - max; break; case RIGHT: len = c->x + max; break; } if (snap && max > Settings.Grid) { if (pull < 0) len += Settings.Grid - 1; len = gridsnap (len); } if ((fdir == RIGHT && len == cs[0]->y) || (fdir == DOWN && len == cs[0]->x)) return 0; for (i = 0; i < cn; i++) { if (fdir == RIGHT) { max = len - cs[i]->y; move_corner (cs[i], cs[i]->x, len); } else { max = len - cs[i]->x; move_corner (cs[i], len, cs[i]->y); } } return max * pull; } static int orthopull () { /* Look for straight runs which could be moved to reduce total trace length. */ int any_sel = any_line_selected (); corner_s *c; int rv = 0; for (c = corners; c;) { if (DELETED (c)) continue; if (c->pin || c->pad) { c = c->next; continue; } next_corner = c; rv += orthopull_1 (c, RIGHT, LEFT, any_sel); if (c != next_corner) { c = next_corner; continue; } rv += orthopull_1 (c, DOWN, UP, any_sel); if (c != next_corner) { c = next_corner; continue; } c = c->next; } if (rv) pcb_printf ("orthopull: %ml mils saved\n", rv); return rv; } static int debumpify () { /* Look for "U" shaped traces we can shorten (or eliminate) */ int rv = 0; int any_selected = any_line_selected (); line_s *l, *l1, *l2; corner_s *c, *c1, *c2; rect_s rr, rp; int o, o1, o2, step, w; for (l = lines; l; l = l->next) { if (DELETED (l)) continue; if (!l->line) continue; if (any_selected && !selected (l->line)) continue; if (!any_selected && autorouted_only && !autorouted (l->line)) continue; if (l->s->pin || l->s->pad || l->e->pin || l->e->pad) continue; o = line_orient (l, 0); if (o == DIAGONAL) continue; l1 = other_line (l->s, l); if (!l1) continue; o1 = line_orient (l1, l->s); l2 = other_line (l->e, l); if (!l2) continue; o2 = line_orient (l2, l->e); if (ORIENT (o) == ORIENT (o1) || o1 != o2 || o1 == DIAGONAL) continue; dprintf ("\nline: %#mD to %#mD\n", l->s->x, l->s->y, l->e->x, l->e->y); w = l->line->Thickness / 2 + SB + 1; empty_rect (&rr); add_line_to_rect (&rr, l1); add_line_to_rect (&rr, l2); if (rr.x1 != l->s->x && rr.x1 != l->e->x) rr.x1 -= w; if (rr.x2 != l->s->x && rr.x2 != l->e->x) rr.x2 += w; if (rr.y1 != l->s->y && rr.y1 != l->e->y) rr.y1 -= w; if (rr.y2 != l->s->y && rr.y2 != l->e->y) rr.y2 += w; dprintf ("range: x %#mS..%#mS y %#mS..%#mS\n", rr.x1, rr.x2, rr.y1, rr.y2); c1 = other_corner (l1, l->s); c2 = other_corner (l2, l->e); empty_rect (&rp); for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (c->net != l->s->net && intersecting_layers (c->layer, l->s->layer)) add_corner_to_rect_if (&rp, c, &rr); } if (rp.x1 == INT_MAX) { rp.x1 = rr.x2; rp.x2 = rr.x1; rp.y1 = rr.y2; rp.y2 = rr.y1; } dprintf ("pin r: x %#mS..%#mS y %#mS..%#mS\n", rp.x1, rp.x2, rp.y1, rp.y2); switch (o1) { case LEFT: step = l->s->x - rp.x2 - w; step = gridsnap (step); if (step > l->s->x - c1->x) step = l->s->x - c1->x; if (step > l->s->x - c2->x) step = l->s->x - c2->x; if (step > 0) { dprintf ("left step %#mS at %#mD\n", step, l->s->x, l->s->y); move_corner (l->s, l->s->x - step, l->s->y); move_corner (l->e, l->e->x - step, l->e->y); rv += step; } break; case RIGHT: step = rp.x1 - l->s->x - w; step = gridsnap (step); if (step > c1->x - l->s->x) step = c1->x - l->s->x; if (step > c2->x - l->s->x) step = c2->x - l->s->x; if (step > 0) { dprintf ("right step %#mS at %#mD\n", step, l->s->x, l->s->y); move_corner (l->s, l->s->x + step, l->s->y); move_corner (l->e, l->e->x + step, l->e->y); rv += step; } break; case UP: if (rp.y2 == INT_MIN) rp.y2 = rr.y1; step = trim_step (l->s->y - rp.y2 - w, l->s->y - c1->y, l->s->y - c2->y); if (step > 0) { dprintf ("up step %#mS at %#mD\n", step, l->s->x, l->s->y); move_corner (l->s, l->s->x, l->s->y - step); move_corner (l->e, l->e->x, l->e->y - step); rv += step; } break; case DOWN: step = rp.y1 - l->s->y - w; step = gridsnap (step); if (step > c1->y - l->s->y) step = c1->y - l->s->y; if (step > c2->y - l->s->y) step = c2->y - l->s->y; if (step > 0) { dprintf ("down step %#mS at %#mD\n", step, l->s->x, l->s->y); move_corner (l->s, l->s->x, l->s->y + step); move_corner (l->e, l->e->x, l->e->y + step); rv += step; } break; } check (0, l); } rv += simple_optimizations (); if (rv) pcb_printf ("debumpify: %ml mils saved\n", rv / 50); return rv; } static int simple_corner (corner_s * c) { int o1, o2; if (c->pad || c->pin || c->via) return 0; if (c->n_lines != 2) return 0; o1 = line_orient (c->lines[0], c); o2 = line_orient (c->lines[1], c); if (ORIENT (o1) == ORIENT (o2)) return 0; if (ORIENT (o1) == DIAGONAL || ORIENT (o2) == DIAGONAL) return 0; return 1; } static int unjaggy_once () { /* Look for sequences of simple corners we can reduce. */ int rv = 0; corner_s *c, *c0, *c1, *cc; int l, w, sel = any_line_selected (); int o0, o1, s0, s1; rect_s rr, rp; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (!simple_corner (c)) continue; if (!c->lines[0]->line || !c->lines[1]->line) continue; if (sel && !(selected (c->lines[0]->line) || selected (c->lines[1]->line))) continue; if (!sel && autorouted_only && !(autorouted (c->lines[0]->line) || autorouted (c->lines[1]->line))) continue; dprintf ("simple at %#mD\n", c->x, c->y); c0 = other_corner (c->lines[0], c); o0 = line_orient (c->lines[0], c); s0 = simple_corner (c0); c1 = other_corner (c->lines[1], c); o1 = line_orient (c->lines[1], c); s1 = simple_corner (c1); if (!s0 && !s1) continue; dprintf ("simples at %#mD\n", c->x, c->y); w = 1; for (l = 0; l < c0->n_lines; l++) if (c0->lines[l] != c->lines[0] && c0->lines[l]->layer == c->lines[0]->layer) { int o = line_orient (c0->lines[l], c0); if (o == o1) w = 0; } for (l = 0; l < c1->n_lines; l++) if (c1->lines[l] != c->lines[0] && c1->lines[l]->layer == c->lines[0]->layer) { int o = line_orient (c1->lines[l], c1); if (o == o0) w = 0; } if (!w) continue; dprintf ("orient ok\n"); w = c->lines[0]->line->Thickness / 2 + SB + 1; empty_rect (&rr); add_line_to_rect (&rr, c->lines[0]); add_line_to_rect (&rr, c->lines[1]); if (c->x != rr.x1) rr.x1 -= w; else rr.x2 += w; if (c->y != rr.y1) rr.y1 -= w; else rr.y2 += w; empty_rect (&rp); for (cc = corners; cc; cc = cc->next) { if (DELETED (cc)) continue; if (cc->net != c->net && intersecting_layers (cc->layer, c->layer)) add_corner_to_rect_if (&rp, cc, &rr); } dprintf ("rp x %#mS..%#mS y %#mS..%#mS\n", rp.x1, rp.x2, rp.y1, rp.y2); if (rp.x1 <= rp.x2) /* something triggered */ continue; dprintf ("unjaggy at %#mD layer %d\n", c->x, c->y, c->layer); if (c->x == c0->x) move_corner (c, c1->x, c0->y); else move_corner (c, c0->x, c1->y); rv++; check (c, 0); } rv += simple_optimizations (); check (c, 0); return rv; } static int unjaggy () { int i, r = 0, j; for (i = 0; i < 100; i++) { j = unjaggy_once (); if (j == 0) break; r += j; } if (r) printf ("%d unjagg%s \n", r, r == 1 ? "y" : "ies"); return r; } static int vianudge () { /* Look for vias with all lines leaving the same way, try to nudge via to eliminate one or more of them. */ int rv = 0; corner_s *c, *c2, *c3; line_s *l; unsigned char directions[MAX_LAYER]; unsigned char counts[MAX_LAYER]; memset (directions, 0, sizeof (directions)); memset (counts, 0, sizeof (counts)); for (c = corners; c; c = c->next) { int o, i, vr, cr, oboth; int len = 0, saved = 0; if (DELETED (c)) continue; if (!c->via) continue; memset (directions, 0, sizeof (directions)); memset (counts, 0, sizeof (counts)); for (i = 0; i < c->n_lines; i++) { o = line_orient (c->lines[i], c); counts[c->lines[i]->layer]++; directions[c->lines[i]->layer] |= o; } for (o = 0, i = 0; i < max_copper_layer; i++) if (counts[i] == 1) { o = directions[i]; break; } switch (o) { case LEFT: case RIGHT: oboth = LEFT | RIGHT; break; case UP: case DOWN: oboth = UP | DOWN; break; default: continue; } for (i = 0; i < max_copper_layer; i++) if (counts[i] && directions[i] != o && directions[i] != oboth) goto vianudge_continue; c2 = 0; for (i = 0; i < c->n_lines; i++) { int ll = line_length (c->lines[i]); if (line_orient (c->lines[i], c) != o) { saved--; continue; } saved++; if (c2 == 0 || len > ll) { len = ll; c2 = other_corner (c->lines[i], c); } } if (c2->pad || c2->pin || c2->via) continue; /* Now look for clearance in the new position */ vr = c->via->Thickness / 2 + SB + 1; for (c3 = corners; c3; c3 = c3->next) { if (DELETED (c3)) continue; if ((c3->net != c->net && (c3->pin || c3->via)) || c3->pad) { cr = corner_radius (c3); if (dist (c2->x, c2->y, c3->x, c3->y) < vr + cr) goto vianudge_continue; } } for (l = lines; l; l = l->next) { if (DELETED (l)) continue; if (l->s->net != c->net) { int ld = dist_line_to_point (l, c2); if (ld < l->line->Thickness / 2 + vr) goto vianudge_continue; } } /* at this point, we know we can move it */ dprintf ("vianudge: nudging via at %#mD by %#mS saving %#mS\n", c->x, c->y, len, saved); rv += len * saved; move_corner (c, c2->x, c2->y); check (c, 0); vianudge_continue: continue; } if (rv) pcb_printf ("vianudge: %ml mils saved\n", rv); return rv; } static int viatrim () { /* Look for traces that can be moved to the other side of the board, to reduce the number of vias needed. For now, we look for simple lines, not multi-segmented lines. */ line_s *l, *l2; int i, rv = 0, vrm = 0; int any_sel = any_line_selected (); for (l = lines; l; l = l->next) { rect_s r; int my_layer, other_layer; if (DELETED (l)) continue; if (!l->s->via) continue; if (!l->e->via) continue; if (any_sel && !selected (l->line)) continue; if (!any_sel && autorouted_only && !autorouted (l->line)) continue; my_layer = l->layer; other_layer = -1; dprintf ("line %p on layer %d from %#mD to %#mD\n", (void *) l, l->layer, l->s->x, l->s->y, l->e->x, l->e->y); for (i = 0; i < l->s->n_lines; i++) if (l->s->lines[i] != l) { if (other_layer == -1) { other_layer = l->s->lines[i]->layer; dprintf ("noting other line %p on layer %d\n", (void *) (l->s->lines[i]), my_layer); } else if (l->s->lines[i]->layer != other_layer) { dprintf ("saw other line %p on layer %d (not %d)\n", (void *) (l->s->lines[i]), l->s->lines[i]->layer, my_layer); other_layer = -1; goto viatrim_other_corner; } } viatrim_other_corner: if (other_layer == -1) for (i = 0; i < l->e->n_lines; i++) if (l->e->lines[i] != l) { if (other_layer == -1) { other_layer = l->s->lines[i]->layer; dprintf ("noting other line %p on layer %d\n", (void *) (l->s->lines[i]), my_layer); } else if (l->e->lines[i]->layer != other_layer) { dprintf ("saw end line on layer %d (not %d)\n", l->e->lines[i]->layer, other_layer); goto viatrim_continue; } } /* Now see if any other line intersects us. We don't need to check corners, because they'd either be pins/vias and already conflict, or pads, which we'll check here anyway. */ empty_rect (&r); add_point_to_rect (&r, l->s->x, l->s->y, l->line->Thickness); add_point_to_rect (&r, l->e->x, l->e->y, l->line->Thickness); for (l2 = lines; l2; l2 = l2->next) { if (DELETED (l2)) continue; if (l2->s->net != l->s->net && l2->layer == other_layer) { dprintf ("checking other line %#mD to %#mD\n", l2->s->x, l2->s->y, l2->e->x, l2->e->y); if (line_in_rect (&r, l2)) { dprintf ("line from %#mD to %#mD in the way\n", l2->s->x, l2->s->y, l2->e->x, l2->e->y); goto viatrim_continue; } } } if (l->layer == other_layer) continue; move_line_to_layer (l, other_layer); rv++; viatrim_continue: continue; } vrm = simple_optimizations (); if (rv > 0) printf ("viatrim: %d traces moved, %d vias removed\n", rv, vrm); return rv + vrm; } static int automagic () { int more = 1, oldmore = 0; int toomany = 100; while (more != oldmore && --toomany) { oldmore = more; more += debumpify (); more += unjaggy (); more += orthopull (); more += vianudge (); more += viatrim (); } return more - 1; } static int miter () { corner_s *c; int done, progress; int sel = any_line_selected (); int saved = 0; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; c->miter = 0; if (c->n_lines == 2 && !c->via && !c->pin && !c->via) { int o1 = line_orient (c->lines[0], c); int o2 = line_orient (c->lines[1], c); if (ORIENT (o1) != ORIENT (o2) && o1 != DIAGONAL && o2 != DIAGONAL && c->lines[0]->line->Thickness == c->lines[1]->line->Thickness) c->miter = -1; } } done = 0; progress = 1; while (!done && progress) { done = 1; progress = 0; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (c->miter == -1) { int max = line_length (c->lines[0]); int len = line_length (c->lines[1]); int bloat; int ref, dist; corner_s *closest_corner = 0, *c2, *oc1, *oc2; int mx = 0, my = 0, x, y; int o1 = line_orient (c->lines[0], c); int o2 = line_orient (c->lines[1], c); if (c->pad || c->pin || c->via) { c->miter = 0; progress = 1; continue; } oc1 = other_corner (c->lines[0], c); oc2 = other_corner (c->lines[1], c); #if 0 if (oc1->pad) oc1 = 0; if (oc2->pad) oc2 = 0; #endif if ((sel && !(selected (c->lines[0]->line) || selected (c->lines[1]->line))) || (!sel && autorouted_only && !(autorouted (c->lines[0]->line) || autorouted (c->lines[1]->line)))) { c->miter = 0; progress = 1; continue; } if (max > len) max = len; switch (o1) { case LEFT: mx = -1; break; case RIGHT: mx = 1; break; case UP: my = -1; break; case DOWN: my = 1; break; } switch (o2) { case LEFT: mx = -1; break; case RIGHT: mx = 1; break; case UP: my = -1; break; case DOWN: my = 1; break; } ref = c->x * mx + c->y * my; dist = max; bloat = (c->lines[0]->line->Thickness / 2 + SB + 1) * 3 / 2; for (c2 = corners; c2; c2 = c2->next) { if (DELETED (c2)) continue; if (c2 != c && c2 != oc1 && c2 != oc2 && c->x * mx <= c2->x * mx && c->y * my <= c2->y * my && c->net != c2->net && intersecting_layers (c->layer, c2->layer)) { int cr = corner_radius (c2); len = c2->x * mx + c2->y * my - ref - cr - bloat; if (c->x != c2->x && c->y != c2->y) len -= cr; if (len < dist || (len == dist && c->miter != -1)) { dist = len; closest_corner = c2; } } } if (closest_corner && closest_corner->miter == -1) { done = 0; continue; } #if 0 if (dist < Settings.Grid) { c->miter = 0; progress = 1; continue; } dist -= dist % Settings.Grid; #endif if (dist <= 0) { c->miter = 0; progress = 1; continue; } x = c->x; y = c->y; switch (o1) { case LEFT: x -= dist; break; case RIGHT: x += dist; break; case UP: y -= dist; break; case DOWN: y += dist; break; } c2 = find_corner (x, y, c->layer); if (c2 != other_corner (c->lines[0], c)) split_line (c->lines[0], c2); x = c->x; y = c->y; switch (o2) { case LEFT: x -= dist; break; case RIGHT: x += dist; break; case UP: y -= dist; break; case DOWN: y += dist; break; } move_corner (c, x, y); c->miter = 0; c2->miter = 0; progress = 1; saved++; } } } return saved; } static void classify_corner (corner_s * c, int this_net) { int i; if (c->net == this_net) return; c->net = this_net; for (i = 0; i < c->n_lines; i++) classify_corner (other_corner (c->lines[i], c), this_net); } static void classify_nets () { static int this_net = 1; corner_s *c; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (c->net) continue; classify_corner (c, this_net); this_net++; } } #if 0 /* Not used */ static void dump_all () { corner_s *c; line_s *l; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; printf ("%p corner %d,%d layer %d net %d\n", (void *) c, c->x, c->y, c->layer, c->net); } for (l = lines; l; l = l->next) { if (DELETED (l)) continue; printf ("%p line %p to %p layer %d\n", (void *) l, (void *) (l->s), (void *) (l->e), l->layer); } } #endif #if 0 static void nudge_corner (corner_s * c, int dx, int dy, corner_s * prev_corner) { int ox = c->x; int oy = c->y; int l; if (prev_corner && (c->pin || c->pad)) return; move_corner (c, ox + dx, oy + dy); for (l = 0; l < c->n_lines; l++) { corner_s *oc = other_corner (c->lines[l], c); if (oc == prev_corner) continue; if (dx && oc->x == ox) nudge_corner (oc, dx, 0, c); if (dy && oc->y == oy) nudge_corner (oc, 0, dy, c); } } #endif static line_s * choose_example_line (corner_s * c1, corner_s * c2) { int ci, li; corner_s *c[2]; c[0] = c1; c[1] = c2; dprintf ("choose_example_line\n"); for (ci = 0; ci < 2; ci++) for (li = 0; li < c[ci]->n_lines; li++) { dprintf (" try[%d,%d] \033[36m<%#mD-%#mD t%#mS c%#mS f%s>\033[0m\n", ci, li, c[ci]->lines[li]->s->x, c[ci]->lines[li]->s->y, c[ci]->lines[li]->e->x, c[ci]->lines[li]->e->y, c[ci]->lines[li]->line->Thickness, c[ci]->lines[li]->line->Clearance, flags_to_string (c[ci]->lines[li]->line->Flags, LINE_TYPE)); /* Pads are disqualified, as we want to mimic a trace line. */ if (c[ci]->lines[li]->line == (LineType *) c[ci]->pad) { dprintf (" bad, pad\n"); continue; } /* Lines on layers that don't connect to the other pad are bad too. */ if (!intersecting_layers (c[ci]->lines[li]->layer, c[1 - ci]->layer)) { dprintf (" bad, layers\n"); continue; } dprintf (" good\n"); return c[ci]->lines[li]; } dprintf ("choose_example_line: none found!\n"); return 0; } static int connect_corners (corner_s * c1, corner_s * c2) { int layer; line_s *ex = choose_example_line (c1, c2); LineType *example = ex->line; dprintf ("connect_corners \033[32m%#mD to %#mD, example line %#mD to %#mD l%d\033[0m\n", c1->x, c1->y, c2->x, c2->y, ex->s->x, ex->s->y, ex->e->x, ex->e->y, ex->layer); layer = ex->layer; /* Assume c1 is the moveable one. */ if (!(c1->pin || c1->pad || c1->via) && c1->n_lines == 1) { int nx, ny; /* Extend the line */ if (c1->lines[0]->s->x == c1->lines[0]->e->x) nx = c1->x, ny = c2->y; else nx = c2->x, ny = c1->y; if (nx != c2->x || ny != c2->y) { move_corner (c1, nx, ny); new_line (c1, c2, layer, example); return 1; } else { move_corner (c1, nx, ny); return 1; } } else { corner_s *nc = find_corner (c1->x, c2->y, layer); new_line (c1, nc, layer, example); new_line (nc, c2, layer, example); return 0; } } static void pinsnap () { corner_s *c; int best_dist[MAX_LAYER + 1]; corner_s *best_c[MAX_LAYER + 1]; int l, got_one; int left = 0, right = 0, top = 0, bottom = 0; PinType *pin; int again = 1; int close = 0; corner_s *c2; /* Look for pins that have no connections. See if there's a corner close by that should be connected to it. This usually happens when the MUCS router needs to route to an off-grid pin. */ while (again) { again = 0; for (c = corners; c; c = c->next) { if (DELETED (c)) continue; if (!(c->pin || c->via || c->pad)) continue; pin = 0; dprintf ("\ncorner %s\n", corner_name (c)); if (c->pin || c->via) { pin = c->pin ? c->pin : c->via; close = pin->Thickness / 2; left = c->x - close; right = c->x + close; bottom = c->y - close; top = c->y + close; } else if (c->pad) { close = c->pad->Thickness / 2 + 1; left = djmin (c->pad->Point1.X, c->pad->Point2.X) - close; right = djmax (c->pad->Point1.X, c->pad->Point2.X) + close; bottom = djmin (c->pad->Point1.Y, c->pad->Point2.Y) - close; top = djmax (c->pad->Point1.Y, c->pad->Point2.Y) + close; if (c->pad->Point1.X == c->pad->Point2.X) { int hy = (c->pad->Point1.Y + c->pad->Point2.Y) / 2; dprintf ("pad y %#mS %#mS hy %#mS c %#mS\n", c->pad->Point1.Y, c->pad->Point2.Y, hy, c->y); if (c->y < hy) top = hy; else bottom = hy + 1; } else { int hx = (c->pad->Point1.X + c->pad->Point2.X) / 2; dprintf ("pad x %#mS %#mS hx %#mS c %#mS\n", c->pad->Point1.X, c->pad->Point2.X, hx, c->x); if (c->x < hx) right = hx; else left = hx + 1; } } dprintf ("%s x %#mS-%#mS y %#mS-%#mS\n", corner_name (c), left, right, bottom, top); for (l = 0; l <= max_copper_layer; l++) { best_dist[l] = close * 2; best_c[l] = 0; } got_one = 0; for (c2 = corners; c2; c2 = c2->next) { int lt; if (DELETED (c2)) continue; lt = corner_radius (c2); if (c2->n_lines && c2 != c && !(c2->pin || c2->pad || c2->via) && intersecting_layers (c->layer, c2->layer) && c2->x >= left - lt && c2->x <= right + lt && c2->y >= bottom - lt && c2->y <= top + lt) { int d = dist (c->x, c->y, c2->x, c2->y); if (pin && d > pin->Thickness / 2 + lt) continue; if (c2->n_lines == 1) { got_one++; dprintf ("found orphan %s vs %s\n", corner_name (c2), corner_name (c)); connect_corners (c, c2); again = 1; continue; } if (best_c[c2->layer] == 0 || c2->n_lines < best_c[c2->layer]->n_lines || (d < best_dist[c2->layer] && c2->n_lines <= best_c[c2->layer]->n_lines)) { best_dist[c2->layer] = d; best_c[c2->layer] = c2; dprintf ("layer %d best now %s\n", c2->layer, corner_name (c2)); } } if (!got_one && c->n_lines == (c->pad ? 1 : 0)) { for (l = 0; l <= max_copper_layer; l++) if (best_c[l]) dprintf ("best[%d] = %s\n", l, corner_name (best_c[l])); for (l = 0; l <= max_copper_layer; l++) if (best_c[l]) { dprintf ("move %s to %s\n", corner_name (best_c[l]), corner_name (c)); connect_corners (best_c[l], c); again = 1; continue; } } } } } /* Now look for line ends that don't connect, see if they need to be extended to intersect another line. */ for (c = corners; c; c = c->next) { line_s *l, *t; int lo; if (DELETED (c)) continue; if (c->pin || c->via || c->pad) continue; if (c->n_lines != 1) continue; l = c->lines[0]; lo = line_orient (l, c); dprintf ("line end %#mD orient %d\n", c->x, c->y, lo); for (t = lines; t; t = t->next) { if (DELETED (t)) continue; if (t->layer != c->lines[0]->layer) continue; switch (lo) /* remember, orient is for the line relative to the corner */ { case LEFT: if (t->s->x == t->e->x && c->x < t->s->x && t->s->x < c->x + (l->line->Thickness + t->line->Thickness) / 2 && ((t->s->y < c->y && c->y < t->e->y) || (t->e->y < c->y && c->y < t->s->y))) { dprintf ("found %#mD - %#mD\n", t->s->x, t->s->y, t->e->x, t->e->y); move_corner (c, t->s->x, c->y); } break; case RIGHT: if (t->s->x == t->e->x && c->x > t->s->x && t->s->x > c->x - (l->line->Thickness + t->line->Thickness) / 2 && ((t->s->y < c->y && c->y < t->e->y) || (t->e->y < c->y && c->y < t->s->y))) { dprintf ("found %#mD - %#mD\n", t->s->x, t->s->y, t->e->x, t->e->y); move_corner (c, t->s->x, c->y); } break; case UP: if (t->s->y == t->e->y && c->y < t->s->y && t->s->y < c->y + (l->line->Thickness + t->line->Thickness) / 2 && ((t->s->x < c->x && c->x < t->e->x) || (t->e->x < c->x && c->x < t->s->x))) { dprintf ("found %#mD - %#mD\n", t->s->x, t->s->y, t->e->x, t->e->y); move_corner (c, c->x, t->s->y); } break; case DOWN: if (t->s->y == t->e->y && c->y > t->s->y && t->s->y > c->y - (l->line->Thickness + t->line->Thickness) / 2 && ((t->s->x < c->x && c->x < t->e->x) || (t->e->x < c->x && c->x < t->s->x))) { dprintf ("found %#mD - %#mD\n", t->s->x, t->s->y, t->e->x, t->e->y); move_corner (c, c->x, t->s->y); } break; } } } } static int pad_orient (PadType * p) { if (p->Point1.X == p->Point2.X) return O_VERT; if (p->Point1.Y == p->Point2.Y) return O_HORIZ; return DIAGONAL; } static void padcleaner () { line_s *l, *nextl; int close; rect_s r; dprintf ("\ndj: padcleaner\n"); for (l = lines; l; l = nextl) { nextl = l->next; if (l->is_pad) continue; if (DELETED (l)) continue; dprintf ("dj: line %p\n", (void *) l); check (0, l); if (l->s->pad && l->s->pad == l->e->pad) continue; ALLPAD_LOOP (PCB->Data); { int layerflag = TEST_FLAG (ONSOLDERFLAG, element) ? LT_SOLDER : LT_COMPONENT; if (layer_type[l->layer] != layerflag) continue; empty_rect (&r); close = pad->Thickness / 2 + 1; add_point_to_rect (&r, pad->Point1.X, pad->Point1.Y, close - SB / 2); add_point_to_rect (&r, pad->Point2.X, pad->Point2.Y, close - SB / 2); if (pin_in_rect (&r, l->s->x, l->s->y, 0) && pin_in_rect (&r, l->e->x, l->e->y, 0) && ORIENT (line_orient (l, 0)) == pad_orient (pad)) { dprintf ("padcleaner %#mD-%#mD %#mS vs line %#mD-%#mD %#mS\n", pad->Point1.X, pad->Point1.Y, pad->Point2.X, pad->Point2.Y, pad->Thickness, l->s->x, l->s->y, l->e->x, l->e->y, l->line->Thickness); remove_line (l); goto next_line; } } ENDALL_LOOP; next_line:; } } static void grok_layer_groups () { int i, j, f; LayerGroupType *l = &(PCB->LayerGroups); solder_layer = component_layer = -1; for (i = 0; i < max_copper_layer; i++) { layer_type[i] = 0; layer_groupings[i] = 0; } for (i = 0; i < max_group; i++) { f = 0; for (j = 0; j < l->Number[i]; j++) { if (l->Entries[i][j] == solder_silk_layer) f |= LT_SOLDER; if (l->Entries[i][j] == component_silk_layer) f |= LT_COMPONENT; } for (j = 0; j < l->Number[i]; j++) { if (l->Entries[i][j] < max_copper_layer) { layer_type[l->Entries[i][j]] |= f; layer_groupings[l->Entries[i][j]] = i; if (solder_layer == -1 && f == LT_SOLDER) solder_layer = l->Entries[i][j]; if (component_layer == -1 && f == LT_COMPONENT) component_layer = l->Entries[i][j]; } } } } static const char djopt_syntax[] = "djopt(debumpify|unjaggy|simple|vianudge|viatrim|orthopull)\n" "djopt(auto) - all of the above\n" "djopt(miter)"; static const char djopt_help[] = "Perform various optimizations on the current board."; /* %start-doc actions djopt The different types of optimizations change your board in order to reduce the total trace length and via count. @table @code @item debumpify Looks for U-shaped traces that can be shortened or eliminated. @item unjaggy Looks for corners which could be flipped to eliminate one or more corners (i.e. jaggy lines become simpler). @item simple Removing uneeded vias, replacing two or more trace segments in a row with a single segment. This is usually performed automatically after other optimizations. @item vianudge Looks for vias where all traces leave in the same direction. Tries to move via in that direction to eliminate one of the traces (and thus a corner). @item viatrim Looks for traces that go from via to via, where moving that trace to a different layer eliminates one or both vias. @item orthopull Looks for chains of traces all going in one direction, with more traces orthogonal on one side than on the other. Moves the chain in that direction, causing a net reduction in trace length, possibly eliminating traces and/or corners. @item splitlines Looks for lines that pass through vias, pins, or pads, and splits them into separate lines so they can be managed separately. @item auto Performs the above options, repeating until no further optimizations can be made. @item miter Replaces 90 degree corners with a pair of 45 degree corners, to reduce RF losses and trace length. @end table %end-doc */ static int ActionDJopt (int argc, char **argv, Coord x, Coord y) { char *arg = argc > 0 ? argv[0] : 0; int layn, saved = 0; corner_s *c; #ifdef ENDIF SwitchDrawingWindow (PCB->Zoom, Output.drawing_area->window, Settings.ShowSolderSide, false); #endif hid_action("Busy"); lines = 0; corners = 0; grok_layer_groups (); ELEMENT_LOOP (PCB->Data); PIN_LOOP (element); { c = find_corner (pin->X, pin->Y, -1); c->pin = pin; } END_LOOP; PAD_LOOP (element); { int layern = TEST_FLAG (ONSOLDERFLAG, pad) ? solder_layer : component_layer; line_s *ls = (line_s *) malloc (sizeof (line_s)); ls->next = lines; lines = ls; ls->is_pad = 1; ls->s = find_corner (pad->Point1.X, pad->Point1.Y, layern); ls->s->pad = pad; ls->e = find_corner (pad->Point2.X, pad->Point2.Y, layern); ls->e->pad = pad; ls->layer = layern; ls->line = (LineType *) pad; add_line_to_corner (ls, ls->s); add_line_to_corner (ls, ls->e); } END_LOOP; END_LOOP; VIA_LOOP (PCB->Data); /* hace don't mess with vias that have thermals */ /* but then again don't bump into them if (!TEST_FLAG(ALLTHERMFLAGS, via)) */ { c = find_corner (via->X, via->Y, -1); c->via = via; } END_LOOP; check (0, 0); if (NSTRCMP (arg, "splitlines") == 0) { if (canonicalize_lines ()) IncrementUndoSerialNumber (); return 0; } for (layn = 0; layn < max_copper_layer; layn++) { LayerType *layer = LAYER_PTR (layn); LINE_LOOP (layer); { line_s *ls; if(autorouted_only && !autorouted (line)) continue; /* don't mess with thermals */ if (TEST_FLAG (USETHERMALFLAG, line)) continue; if (line->Point1.X == line->Point2.X && line->Point1.Y == line->Point2.Y) { RemoveLine (layer, line); continue; } ls = (line_s *) malloc (sizeof (line_s)); ls->next = lines; lines = ls; ls->is_pad = 0; ls->s = find_corner (line->Point1.X, line->Point1.Y, layn); ls->e = find_corner (line->Point2.X, line->Point2.Y, layn); ls->line = line; add_line_to_corner (ls, ls->s); add_line_to_corner (ls, ls->e); ls->layer = layn; } END_LOOP; } check (0, 0); pinsnap (); canonicalize_lines (); check (0, 0); classify_nets (); /*dump_all(); */ check (0, 0); if (NSTRCMP (arg, "debumpify") == 0) saved += debumpify (); else if (NSTRCMP (arg, "unjaggy") == 0) saved += unjaggy (); else if (NSTRCMP (arg, "simple") == 0) saved += simple_optimizations (); else if (NSTRCMP (arg, "vianudge") == 0) saved += vianudge (); else if (NSTRCMP (arg, "viatrim") == 0) saved += viatrim (); else if (NSTRCMP (arg, "orthopull") == 0) saved += orthopull (); else if (NSTRCMP (arg, "auto") == 0) saved += automagic (); else if (NSTRCMP (arg, "miter") == 0) saved += miter (); else { printf ("unknown command: %s\n", arg); return 1; } padcleaner (); check (0, 0); if (saved) IncrementUndoSerialNumber (); return 0; } HID_Action djopt_action_list[] = { {"djopt", 0, ActionDJopt, djopt_help, djopt_syntax} , {"OptAutoOnly", 0, djopt_set_auto_only, djopt_sao_help, djopt_sao_syntax} }; REGISTER_ACTIONS (djopt_action_list)
russdill/pcb
src/djopt.c
C
gpl-2.0
68,831
/* * drivers/media/radio/radio-si476x.c -- V4L2 driver for SI476X chips * * Copyright (C) 2012 Innovative Converged Devices(ICD) * Copyright (C) 2013 Andrey Smirnov * * Author: Andrey Smirnov <andrew.smirnov@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * */ #include <linux/module.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/atomic.h> #include <linux/videodev2.h> #include <linux/mutex.h> #include <linux/debugfs.h> #include <media/v4l2-common.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-event.h> #include <media/v4l2-device.h> #include <media/si476x.h> #include <linux/mfd/si476x-core.h> #define FM_FREQ_RANGE_LOW 64000000 #define FM_FREQ_RANGE_HIGH 108000000 #define AM_FREQ_RANGE_LOW 520000 #define AM_FREQ_RANGE_HIGH 30000000 #define PWRLINEFLTR (1 << 8) #define FREQ_MUL (10000000 / 625) #define SI476X_PHDIV_STATUS_LINK_LOCKED(status) (0x80 & (status)) #define DRIVER_NAME "si476x-radio" #define DRIVER_CARD "SI476x AM/FM Receiver" enum si476x_freq_bands { SI476X_BAND_FM, SI476X_BAND_AM, }; static const struct v4l2_frequency_band si476x_bands[] = { [SI476X_BAND_FM] = { .type = V4L2_TUNER_RADIO, .index = SI476X_BAND_FM, .capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_RDS | V4L2_TUNER_CAP_RDS_BLOCK_IO | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = 64 * FREQ_MUL, .rangehigh = 108 * FREQ_MUL, .modulation = V4L2_BAND_MODULATION_FM, }, [SI476X_BAND_AM] = { .type = V4L2_TUNER_RADIO, .index = SI476X_BAND_AM, .capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = 0.52 * FREQ_MUL, .rangehigh = 30 * FREQ_MUL, .modulation = V4L2_BAND_MODULATION_AM, }, }; static inline bool si476x_radio_freq_is_inside_of_the_band(u32 freq, int band) { return freq >= si476x_bands[band].rangelow && freq <= si476x_bands[band].rangehigh; } static inline bool si476x_radio_range_is_inside_of_the_band(u32 low, u32 high, int band) { return low >= si476x_bands[band].rangelow && high <= si476x_bands[band].rangehigh; } static int si476x_radio_s_ctrl(struct v4l2_ctrl *ctrl); static int si476x_radio_g_volatile_ctrl(struct v4l2_ctrl *ctrl); enum phase_diversity_modes_idx { SI476X_IDX_PHDIV_DISABLED, SI476X_IDX_PHDIV_PRIMARY_COMBINING, SI476X_IDX_PHDIV_PRIMARY_ANTENNA, SI476X_IDX_PHDIV_SECONDARY_ANTENNA, SI476X_IDX_PHDIV_SECONDARY_COMBINING, }; static const char * const phase_diversity_modes[] = { [SI476X_IDX_PHDIV_DISABLED] = "Disabled", [SI476X_IDX_PHDIV_PRIMARY_COMBINING] = "Primary with Secondary", [SI476X_IDX_PHDIV_PRIMARY_ANTENNA] = "Primary Antenna", [SI476X_IDX_PHDIV_SECONDARY_ANTENNA] = "Secondary Antenna", [SI476X_IDX_PHDIV_SECONDARY_COMBINING] = "Secondary with Primary", }; static inline enum phase_diversity_modes_idx si476x_phase_diversity_mode_to_idx(enum si476x_phase_diversity_mode mode) { switch (mode) { default: /* FALLTHROUGH */ case SI476X_PHDIV_DISABLED: return SI476X_IDX_PHDIV_DISABLED; case SI476X_PHDIV_PRIMARY_COMBINING: return SI476X_IDX_PHDIV_PRIMARY_COMBINING; case SI476X_PHDIV_PRIMARY_ANTENNA: return SI476X_IDX_PHDIV_PRIMARY_ANTENNA; case SI476X_PHDIV_SECONDARY_ANTENNA: return SI476X_IDX_PHDIV_SECONDARY_ANTENNA; case SI476X_PHDIV_SECONDARY_COMBINING: return SI476X_IDX_PHDIV_SECONDARY_COMBINING; } } static inline enum si476x_phase_diversity_mode si476x_phase_diversity_idx_to_mode(enum phase_diversity_modes_idx idx) { static const int idx_to_value[] = { [SI476X_IDX_PHDIV_DISABLED] = SI476X_PHDIV_DISABLED, [SI476X_IDX_PHDIV_PRIMARY_COMBINING] = SI476X_PHDIV_PRIMARY_COMBINING, [SI476X_IDX_PHDIV_PRIMARY_ANTENNA] = SI476X_PHDIV_PRIMARY_ANTENNA, [SI476X_IDX_PHDIV_SECONDARY_ANTENNA] = SI476X_PHDIV_SECONDARY_ANTENNA, [SI476X_IDX_PHDIV_SECONDARY_COMBINING] = SI476X_PHDIV_SECONDARY_COMBINING, }; return idx_to_value[idx]; } static const struct v4l2_ctrl_ops si476x_ctrl_ops = { .g_volatile_ctrl = si476x_radio_g_volatile_ctrl, .s_ctrl = si476x_radio_s_ctrl, }; enum si476x_ctrl_idx { SI476X_IDX_RSSI_THRESHOLD, SI476X_IDX_SNR_THRESHOLD, SI476X_IDX_MAX_TUNE_ERROR, SI476X_IDX_HARMONICS_COUNT, SI476X_IDX_DIVERSITY_MODE, SI476X_IDX_INTERCHIP_LINK, }; static struct v4l2_ctrl_config si476x_ctrls[] = { /** * SI476X during its station seeking(or tuning) process uses several * parameters to detrmine if "the station" is valid: * * - Signal's SNR(in dBuV) must be lower than * #V4L2_CID_SI476X_SNR_THRESHOLD * - Signal's RSSI(in dBuV) must be greater than * #V4L2_CID_SI476X_RSSI_THRESHOLD * - Signal's frequency deviation(in units of 2ppm) must not be * more than #V4L2_CID_SI476X_MAX_TUNE_ERROR */ [SI476X_IDX_RSSI_THRESHOLD] = { .ops = &si476x_ctrl_ops, .id = V4L2_CID_SI476X_RSSI_THRESHOLD, .name = "Valid RSSI Threshold", .type = V4L2_CTRL_TYPE_INTEGER, .min = -128, .max = 127, .step = 1, }, [SI476X_IDX_SNR_THRESHOLD] = { .ops = &si476x_ctrl_ops, .id = V4L2_CID_SI476X_SNR_THRESHOLD, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Valid SNR Threshold", .min = -128, .max = 127, .step = 1, }, [SI476X_IDX_MAX_TUNE_ERROR] = { .ops = &si476x_ctrl_ops, .id = V4L2_CID_SI476X_MAX_TUNE_ERROR, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Max Tune Errors", .min = 0, .max = 126 * 2, .step = 2, }, /** * #V4L2_CID_SI476X_HARMONICS_COUNT -- number of harmonics * built-in power-line noise supression filter is to reject * during AM-mode operation. */ [SI476X_IDX_HARMONICS_COUNT] = { .ops = &si476x_ctrl_ops, .id = V4L2_CID_SI476X_HARMONICS_COUNT, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Count of Harmonics to Reject", .min = 0, .max = 20, .step = 1, }, /** * #V4L2_CID_SI476X_DIVERSITY_MODE -- configuration which * two tuners working in diversity mode are to work in. * * - #SI476X_IDX_PHDIV_DISABLED diversity mode disabled * - #SI476X_IDX_PHDIV_PRIMARY_COMBINING diversity mode is * on, primary tuner's antenna is the main one. * - #SI476X_IDX_PHDIV_PRIMARY_ANTENNA diversity mode is * off, primary tuner's antenna is the main one. * - #SI476X_IDX_PHDIV_SECONDARY_ANTENNA diversity mode is * off, secondary tuner's antenna is the main one. * - #SI476X_IDX_PHDIV_SECONDARY_COMBINING diversity mode is * on, secondary tuner's antenna is the main one. */ [SI476X_IDX_DIVERSITY_MODE] = { .ops = &si476x_ctrl_ops, .id = V4L2_CID_SI476X_DIVERSITY_MODE, .type = V4L2_CTRL_TYPE_MENU, .name = "Phase Diversity Mode", .qmenu = phase_diversity_modes, .min = 0, .max = ARRAY_SIZE(phase_diversity_modes) - 1, }, /** * #V4L2_CID_SI476X_INTERCHIP_LINK -- inter-chip link in * diversity mode indicator. Allows user to determine if two * chips working in diversity mode have established a link * between each other and if the system as a whole uses * signals from both antennas to receive FM radio. */ [SI476X_IDX_INTERCHIP_LINK] = { .ops = &si476x_ctrl_ops, .id = V4L2_CID_SI476X_INTERCHIP_LINK, .type = V4L2_CTRL_TYPE_BOOLEAN, .flags = V4L2_CTRL_FLAG_READ_ONLY | V4L2_CTRL_FLAG_VOLATILE, .name = "Inter-Chip Link", .min = 0, .max = 1, .step = 1, }, }; struct si476x_radio; /** * struct si476x_radio_ops - vtable of tuner functions * * This table holds pointers to functions implementing particular * operations depending on the mode in which the tuner chip was * configured to start in. If the function is not supported * corresponding element is set to #NULL. * * @tune_freq: Tune chip to a specific frequency * @seek_start: Star station seeking * @rsq_status: Get Received Signal Quality(RSQ) status * @rds_blckcnt: Get received RDS blocks count * @phase_diversity: Change phase diversity mode of the tuner * @phase_div_status: Get phase diversity mode status * @acf_status: Get the status of Automatically Controlled * Features(ACF) * @agc_status: Get Automatic Gain Control(AGC) status */ struct si476x_radio_ops { int (*tune_freq)(struct si476x_core *, struct si476x_tune_freq_args *); int (*seek_start)(struct si476x_core *, bool, bool); int (*rsq_status)(struct si476x_core *, struct si476x_rsq_status_args *, struct si476x_rsq_status_report *); int (*rds_blckcnt)(struct si476x_core *, bool, struct si476x_rds_blockcount_report *); int (*phase_diversity)(struct si476x_core *, enum si476x_phase_diversity_mode); int (*phase_div_status)(struct si476x_core *); int (*acf_status)(struct si476x_core *, struct si476x_acf_status_report *); int (*agc_status)(struct si476x_core *, struct si476x_agc_status_report *); }; /** * struct si476x_radio - radio device * * @core: Pointer to underlying core device * @videodev: Pointer to video device created by V4L2 subsystem * @ops: Vtable of functions. See struct si476x_radio_ops for details * @kref: Reference counter * @core_lock: An r/w semaphore to brebvent the deletion of underlying * core structure is the radio device is being used */ struct si476x_radio { struct v4l2_device v4l2dev; struct video_device videodev; struct v4l2_ctrl_handler ctrl_handler; struct si476x_core *core; /* This field should not be accesses unless core lock is held */ const struct si476x_radio_ops *ops; struct dentry *debugfs; u32 audmode; }; static inline struct si476x_radio * v4l2_dev_to_radio(struct v4l2_device *d) { return container_of(d, struct si476x_radio, v4l2dev); } static inline struct si476x_radio * v4l2_ctrl_handler_to_radio(struct v4l2_ctrl_handler *d) { return container_of(d, struct si476x_radio, ctrl_handler); } /* * si476x_vidioc_querycap - query device capabilities */ static int si476x_radio_querycap(struct file *file, void *priv, struct v4l2_capability *capability) { struct si476x_radio *radio = video_drvdata(file); strlcpy(capability->driver, radio->v4l2dev.name, sizeof(capability->driver)); strlcpy(capability->card, DRIVER_CARD, sizeof(capability->card)); snprintf(capability->bus_info, sizeof(capability->bus_info), "platform:%s", radio->v4l2dev.name); capability->device_caps = V4L2_CAP_TUNER | V4L2_CAP_RADIO | V4L2_CAP_HW_FREQ_SEEK; si476x_core_lock(radio->core); if (!si476x_core_is_a_secondary_tuner(radio->core)) capability->device_caps |= V4L2_CAP_RDS_CAPTURE | V4L2_CAP_READWRITE; si476x_core_unlock(radio->core); capability->capabilities = capability->device_caps | V4L2_CAP_DEVICE_CAPS; return 0; } static int si476x_radio_enum_freq_bands(struct file *file, void *priv, struct v4l2_frequency_band *band) { int err; struct si476x_radio *radio = video_drvdata(file); if (band->tuner != 0) return -EINVAL; switch (radio->core->chip_id) { /* AM/FM tuners -- all bands are supported */ case SI476X_CHIP_SI4761: case SI476X_CHIP_SI4764: if (band->index < ARRAY_SIZE(si476x_bands)) { *band = si476x_bands[band->index]; err = 0; } else { err = -EINVAL; } break; /* FM companion tuner chips -- only FM bands are * supported */ case SI476X_CHIP_SI4768: if (band->index == SI476X_BAND_FM) { *band = si476x_bands[band->index]; err = 0; } else { err = -EINVAL; } break; default: err = -EINVAL; } return err; } static int si476x_radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *tuner) { int err; struct si476x_rsq_status_report report; struct si476x_radio *radio = video_drvdata(file); struct si476x_rsq_status_args args = { .primary = false, .rsqack = false, .attune = false, .cancel = false, .stcack = false, }; if (tuner->index != 0) return -EINVAL; tuner->type = V4L2_TUNER_RADIO; tuner->capability = V4L2_TUNER_CAP_LOW /* Measure frequencies * in multiples of * 62.5 Hz */ | V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_HWSEEK_BOUNDED | V4L2_TUNER_CAP_HWSEEK_WRAP | V4L2_TUNER_CAP_HWSEEK_PROG_LIM; si476x_core_lock(radio->core); if (si476x_core_is_a_secondary_tuner(radio->core)) { strlcpy(tuner->name, "FM (secondary)", sizeof(tuner->name)); tuner->rxsubchans = 0; tuner->rangelow = si476x_bands[SI476X_BAND_FM].rangelow; } else if (si476x_core_has_am(radio->core)) { if (si476x_core_is_a_primary_tuner(radio->core)) strlcpy(tuner->name, "AM/FM (primary)", sizeof(tuner->name)); else strlcpy(tuner->name, "AM/FM", sizeof(tuner->name)); tuner->rxsubchans = V4L2_TUNER_SUB_MONO | V4L2_TUNER_SUB_STEREO | V4L2_TUNER_SUB_RDS; tuner->capability |= V4L2_TUNER_CAP_RDS | V4L2_TUNER_CAP_RDS_BLOCK_IO | V4L2_TUNER_CAP_FREQ_BANDS; tuner->rangelow = si476x_bands[SI476X_BAND_AM].rangelow; } else { strlcpy(tuner->name, "FM", sizeof(tuner->name)); tuner->rxsubchans = V4L2_TUNER_SUB_RDS; tuner->capability |= V4L2_TUNER_CAP_RDS | V4L2_TUNER_CAP_RDS_BLOCK_IO | V4L2_TUNER_CAP_FREQ_BANDS; tuner->rangelow = si476x_bands[SI476X_BAND_FM].rangelow; } tuner->audmode = radio->audmode; tuner->afc = 1; tuner->rangehigh = si476x_bands[SI476X_BAND_FM].rangehigh; err = radio->ops->rsq_status(radio->core, &args, &report); if (err < 0) { tuner->signal = 0; } else { /* * tuner->signal value range: 0x0000 .. 0xFFFF, * report.rssi: -128 .. 127 */ tuner->signal = (report.rssi + 128) * 257; } si476x_core_unlock(radio->core); return err; } static int si476x_radio_s_tuner(struct file *file, void *priv, const struct v4l2_tuner *tuner) { struct si476x_radio *radio = video_drvdata(file); if (tuner->index != 0) return -EINVAL; if (tuner->audmode == V4L2_TUNER_MODE_MONO || tuner->audmode == V4L2_TUNER_MODE_STEREO) radio->audmode = tuner->audmode; else radio->audmode = V4L2_TUNER_MODE_STEREO; return 0; } static int si476x_radio_init_vtable(struct si476x_radio *radio, enum si476x_func func) { static const struct si476x_radio_ops fm_ops = { .tune_freq = si476x_core_cmd_fm_tune_freq, .seek_start = si476x_core_cmd_fm_seek_start, .rsq_status = si476x_core_cmd_fm_rsq_status, .rds_blckcnt = si476x_core_cmd_fm_rds_blockcount, .phase_diversity = si476x_core_cmd_fm_phase_diversity, .phase_div_status = si476x_core_cmd_fm_phase_div_status, .acf_status = si476x_core_cmd_fm_acf_status, .agc_status = si476x_core_cmd_agc_status, }; static const struct si476x_radio_ops am_ops = { .tune_freq = si476x_core_cmd_am_tune_freq, .seek_start = si476x_core_cmd_am_seek_start, .rsq_status = si476x_core_cmd_am_rsq_status, .rds_blckcnt = NULL, .phase_diversity = NULL, .phase_div_status = NULL, .acf_status = si476x_core_cmd_am_acf_status, .agc_status = NULL, }; switch (func) { case SI476X_FUNC_FM_RECEIVER: radio->ops = &fm_ops; return 0; case SI476X_FUNC_AM_RECEIVER: radio->ops = &am_ops; return 0; default: WARN(1, "Unexpected tuner function value\n"); return -EINVAL; } } static int si476x_radio_pretune(struct si476x_radio *radio, enum si476x_func func) { int retval; struct si476x_tune_freq_args args = { .zifsr = false, .hd = false, .injside = SI476X_INJSIDE_AUTO, .tunemode = SI476X_TM_VALIDATED_NORMAL_TUNE, .smoothmetrics = SI476X_SM_INITIALIZE_AUDIO, .antcap = 0, }; switch (func) { case SI476X_FUNC_FM_RECEIVER: args.freq = v4l2_to_si476x(radio->core, 92 * FREQ_MUL); retval = radio->ops->tune_freq(radio->core, &args); break; case SI476X_FUNC_AM_RECEIVER: args.freq = v4l2_to_si476x(radio->core, 0.6 * FREQ_MUL); retval = radio->ops->tune_freq(radio->core, &args); break; default: WARN(1, "Unexpected tuner function value\n"); retval = -EINVAL; } return retval; } static int si476x_radio_do_post_powerup_init(struct si476x_radio *radio, enum si476x_func func) { int err; /* regcache_mark_dirty(radio->core->regmap); */ err = regcache_sync_region(radio->core->regmap, SI476X_PROP_DIGITAL_IO_INPUT_SAMPLE_RATE, SI476X_PROP_DIGITAL_IO_OUTPUT_FORMAT); if (err < 0) return err; err = regcache_sync_region(radio->core->regmap, SI476X_PROP_AUDIO_DEEMPHASIS, SI476X_PROP_AUDIO_PWR_LINE_FILTER); if (err < 0) return err; err = regcache_sync_region(radio->core->regmap, SI476X_PROP_INT_CTL_ENABLE, SI476X_PROP_INT_CTL_ENABLE); if (err < 0) return err; /* * Is there any point in restoring SNR and the like * when switching between AM/FM? */ err = regcache_sync_region(radio->core->regmap, SI476X_PROP_VALID_MAX_TUNE_ERROR, SI476X_PROP_VALID_MAX_TUNE_ERROR); if (err < 0) return err; err = regcache_sync_region(radio->core->regmap, SI476X_PROP_VALID_SNR_THRESHOLD, SI476X_PROP_VALID_RSSI_THRESHOLD); if (err < 0) return err; if (func == SI476X_FUNC_FM_RECEIVER) { if (si476x_core_has_diversity(radio->core)) { err = si476x_core_cmd_fm_phase_diversity(radio->core, radio->core->diversity_mode); if (err < 0) return err; } err = regcache_sync_region(radio->core->regmap, SI476X_PROP_FM_RDS_INTERRUPT_SOURCE, SI476X_PROP_FM_RDS_CONFIG); if (err < 0) return err; } return si476x_radio_init_vtable(radio, func); } static int si476x_radio_change_func(struct si476x_radio *radio, enum si476x_func func) { int err; bool soft; /* * Since power/up down is a very time consuming operation, * try to avoid doing it if the requested mode matches the one * the tuner is in */ if (func == radio->core->power_up_parameters.func) return 0; soft = true; err = si476x_core_stop(radio->core, soft); if (err < 0) { /* * OK, if the chip does not want to play nice let's * try to reset it in more brutal way */ soft = false; err = si476x_core_stop(radio->core, soft); if (err < 0) return err; } /* Set the desired radio tuner function */ radio->core->power_up_parameters.func = func; err = si476x_core_start(radio->core, soft); if (err < 0) return err; /* * No need to do the rest of manipulations for the bootlader * mode */ if (func != SI476X_FUNC_FM_RECEIVER && func != SI476X_FUNC_AM_RECEIVER) return err; return si476x_radio_do_post_powerup_init(radio, func); } static int si476x_radio_g_frequency(struct file *file, void *priv, struct v4l2_frequency *f) { int err; struct si476x_radio *radio = video_drvdata(file); if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO) return -EINVAL; si476x_core_lock(radio->core); if (radio->ops->rsq_status) { struct si476x_rsq_status_report report; struct si476x_rsq_status_args args = { .primary = false, .rsqack = false, .attune = true, .cancel = false, .stcack = false, }; err = radio->ops->rsq_status(radio->core, &args, &report); if (!err) f->frequency = si476x_to_v4l2(radio->core, report.readfreq); } else { err = -EINVAL; } si476x_core_unlock(radio->core); return err; } static int si476x_radio_s_frequency(struct file *file, void *priv, const struct v4l2_frequency *f) { int err; u32 freq = f->frequency; struct si476x_tune_freq_args args; struct si476x_radio *radio = video_drvdata(file); const u32 midrange = (si476x_bands[SI476X_BAND_AM].rangehigh + si476x_bands[SI476X_BAND_FM].rangelow) / 2; const int band = (freq > midrange) ? SI476X_BAND_FM : SI476X_BAND_AM; const enum si476x_func func = (band == SI476X_BAND_AM) ? SI476X_FUNC_AM_RECEIVER : SI476X_FUNC_FM_RECEIVER; if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO) return -EINVAL; si476x_core_lock(radio->core); freq = clamp(freq, si476x_bands[band].rangelow, si476x_bands[band].rangehigh); if (si476x_radio_freq_is_inside_of_the_band(freq, SI476X_BAND_AM) && (!si476x_core_has_am(radio->core) || si476x_core_is_a_secondary_tuner(radio->core))) { err = -EINVAL; goto unlock; } err = si476x_radio_change_func(radio, func); if (err < 0) goto unlock; args.zifsr = false; args.hd = false; args.injside = SI476X_INJSIDE_AUTO; args.freq = v4l2_to_si476x(radio->core, freq); args.tunemode = SI476X_TM_VALIDATED_NORMAL_TUNE; args.smoothmetrics = SI476X_SM_INITIALIZE_AUDIO; args.antcap = 0; err = radio->ops->tune_freq(radio->core, &args); unlock: si476x_core_unlock(radio->core); return err; } static int si476x_radio_s_hw_freq_seek(struct file *file, void *priv, const struct v4l2_hw_freq_seek *seek) { int err; enum si476x_func func; u32 rangelow, rangehigh; struct si476x_radio *radio = video_drvdata(file); if (file->f_flags & O_NONBLOCK) return -EAGAIN; if (seek->tuner != 0 || seek->type != V4L2_TUNER_RADIO) return -EINVAL; si476x_core_lock(radio->core); if (!seek->rangelow) { err = regmap_read(radio->core->regmap, SI476X_PROP_SEEK_BAND_BOTTOM, &rangelow); if (!err) rangelow = si476x_to_v4l2(radio->core, rangelow); else goto unlock; } if (!seek->rangehigh) { err = regmap_read(radio->core->regmap, SI476X_PROP_SEEK_BAND_TOP, &rangehigh); if (!err) rangehigh = si476x_to_v4l2(radio->core, rangehigh); else goto unlock; } if (rangelow > rangehigh) { err = -EINVAL; goto unlock; } if (si476x_radio_range_is_inside_of_the_band(rangelow, rangehigh, SI476X_BAND_FM)) { func = SI476X_FUNC_FM_RECEIVER; } else if (si476x_core_has_am(radio->core) && si476x_radio_range_is_inside_of_the_band(rangelow, rangehigh, SI476X_BAND_AM)) { func = SI476X_FUNC_AM_RECEIVER; } else { err = -EINVAL; goto unlock; } err = si476x_radio_change_func(radio, func); if (err < 0) goto unlock; if (seek->rangehigh) { err = regmap_write(radio->core->regmap, SI476X_PROP_SEEK_BAND_TOP, v4l2_to_si476x(radio->core, seek->rangehigh)); if (err) goto unlock; } if (seek->rangelow) { err = regmap_write(radio->core->regmap, SI476X_PROP_SEEK_BAND_BOTTOM, v4l2_to_si476x(radio->core, seek->rangelow)); if (err) goto unlock; } if (seek->spacing) { err = regmap_write(radio->core->regmap, SI476X_PROP_SEEK_FREQUENCY_SPACING, v4l2_to_si476x(radio->core, seek->spacing)); if (err) goto unlock; } err = radio->ops->seek_start(radio->core, seek->seek_upward, seek->wrap_around); unlock: si476x_core_unlock(radio->core); return err; } static int si476x_radio_g_volatile_ctrl(struct v4l2_ctrl *ctrl) { int retval; struct si476x_radio *radio = v4l2_ctrl_handler_to_radio(ctrl->handler); si476x_core_lock(radio->core); switch (ctrl->id) { case V4L2_CID_SI476X_INTERCHIP_LINK: if (si476x_core_has_diversity(radio->core)) { if (radio->ops->phase_diversity) { retval = radio->ops->phase_div_status(radio->core); if (retval < 0) break; ctrl->val = !!SI476X_PHDIV_STATUS_LINK_LOCKED(retval); retval = 0; break; } else { retval = -ENOTTY; break; } } retval = -EINVAL; break; default: retval = -EINVAL; break; } si476x_core_unlock(radio->core); return retval; } static int si476x_radio_s_ctrl(struct v4l2_ctrl *ctrl) { int retval; enum si476x_phase_diversity_mode mode; struct si476x_radio *radio = v4l2_ctrl_handler_to_radio(ctrl->handler); si476x_core_lock(radio->core); switch (ctrl->id) { case V4L2_CID_SI476X_HARMONICS_COUNT: retval = regmap_update_bits(radio->core->regmap, SI476X_PROP_AUDIO_PWR_LINE_FILTER, SI476X_PROP_PWR_HARMONICS_MASK, ctrl->val); break; case V4L2_CID_POWER_LINE_FREQUENCY: switch (ctrl->val) { case V4L2_CID_POWER_LINE_FREQUENCY_DISABLED: retval = regmap_update_bits(radio->core->regmap, SI476X_PROP_AUDIO_PWR_LINE_FILTER, SI476X_PROP_PWR_ENABLE_MASK, 0); break; case V4L2_CID_POWER_LINE_FREQUENCY_50HZ: retval = regmap_update_bits(radio->core->regmap, SI476X_PROP_AUDIO_PWR_LINE_FILTER, SI476X_PROP_PWR_GRID_MASK, SI476X_PROP_PWR_GRID_50HZ); break; case V4L2_CID_POWER_LINE_FREQUENCY_60HZ: retval = regmap_update_bits(radio->core->regmap, SI476X_PROP_AUDIO_PWR_LINE_FILTER, SI476X_PROP_PWR_GRID_MASK, SI476X_PROP_PWR_GRID_60HZ); break; default: retval = -EINVAL; break; } break; case V4L2_CID_SI476X_RSSI_THRESHOLD: retval = regmap_write(radio->core->regmap, SI476X_PROP_VALID_RSSI_THRESHOLD, ctrl->val); break; case V4L2_CID_SI476X_SNR_THRESHOLD: retval = regmap_write(radio->core->regmap, SI476X_PROP_VALID_SNR_THRESHOLD, ctrl->val); break; case V4L2_CID_SI476X_MAX_TUNE_ERROR: retval = regmap_write(radio->core->regmap, SI476X_PROP_VALID_MAX_TUNE_ERROR, ctrl->val); break; case V4L2_CID_RDS_RECEPTION: /* * It looks like RDS related properties are * inaccesable when tuner is in AM mode, so cache the * changes */ if (si476x_core_is_in_am_receiver_mode(radio->core)) regcache_cache_only(radio->core->regmap, true); if (ctrl->val) { retval = regmap_write(radio->core->regmap, SI476X_PROP_FM_RDS_INTERRUPT_FIFO_COUNT, radio->core->rds_fifo_depth); if (retval < 0) break; if (radio->core->client->irq) { retval = regmap_write(radio->core->regmap, SI476X_PROP_FM_RDS_INTERRUPT_SOURCE, SI476X_RDSRECV); if (retval < 0) break; } /* Drain RDS FIFO before enabling RDS processing */ retval = si476x_core_cmd_fm_rds_status(radio->core, false, true, true, NULL); if (retval < 0) break; retval = regmap_update_bits(radio->core->regmap, SI476X_PROP_FM_RDS_CONFIG, SI476X_PROP_RDSEN_MASK, SI476X_PROP_RDSEN); } else { retval = regmap_update_bits(radio->core->regmap, SI476X_PROP_FM_RDS_CONFIG, SI476X_PROP_RDSEN_MASK, !SI476X_PROP_RDSEN); } if (si476x_core_is_in_am_receiver_mode(radio->core)) regcache_cache_only(radio->core->regmap, false); break; case V4L2_CID_TUNE_DEEMPHASIS: retval = regmap_write(radio->core->regmap, SI476X_PROP_AUDIO_DEEMPHASIS, ctrl->val); break; case V4L2_CID_SI476X_DIVERSITY_MODE: mode = si476x_phase_diversity_idx_to_mode(ctrl->val); if (mode == radio->core->diversity_mode) { retval = 0; break; } if (si476x_core_is_in_am_receiver_mode(radio->core)) { /* * Diversity cannot be configured while tuner * is in AM mode so save the changes and carry on. */ radio->core->diversity_mode = mode; retval = 0; } else { retval = radio->ops->phase_diversity(radio->core, mode); if (!retval) radio->core->diversity_mode = mode; } break; default: retval = -EINVAL; break; } si476x_core_unlock(radio->core); return retval; } #ifdef CPTCFG_VIDEO_ADV_DEBUG static int si476x_radio_g_register(struct file *file, void *fh, struct v4l2_dbg_register *reg) { int err; unsigned int value; struct si476x_radio *radio = video_drvdata(file); si476x_core_lock(radio->core); reg->size = 2; err = regmap_read(radio->core->regmap, (unsigned int)reg->reg, &value); reg->val = value; si476x_core_unlock(radio->core); return err; } static int si476x_radio_s_register(struct file *file, void *fh, const struct v4l2_dbg_register *reg) { int err; struct si476x_radio *radio = video_drvdata(file); si476x_core_lock(radio->core); err = regmap_write(radio->core->regmap, (unsigned int)reg->reg, (unsigned int)reg->val); si476x_core_unlock(radio->core); return err; } #endif static int si476x_radio_fops_open(struct file *file) { struct si476x_radio *radio = video_drvdata(file); int err; err = v4l2_fh_open(file); if (err) return err; if (v4l2_fh_is_singular_file(file)) { si476x_core_lock(radio->core); err = si476x_core_set_power_state(radio->core, SI476X_POWER_UP_FULL); if (err < 0) goto done; err = si476x_radio_do_post_powerup_init(radio, radio->core->power_up_parameters.func); if (err < 0) goto power_down; err = si476x_radio_pretune(radio, radio->core->power_up_parameters.func); if (err < 0) goto power_down; si476x_core_unlock(radio->core); /*Must be done after si476x_core_unlock to prevent a deadlock*/ v4l2_ctrl_handler_setup(&radio->ctrl_handler); } return err; power_down: si476x_core_set_power_state(radio->core, SI476X_POWER_DOWN); done: si476x_core_unlock(radio->core); v4l2_fh_release(file); return err; } static int si476x_radio_fops_release(struct file *file) { int err; struct si476x_radio *radio = video_drvdata(file); if (v4l2_fh_is_singular_file(file) && atomic_read(&radio->core->is_alive)) si476x_core_set_power_state(radio->core, SI476X_POWER_DOWN); err = v4l2_fh_release(file); return err; } static ssize_t si476x_radio_fops_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { ssize_t rval; size_t fifo_len; unsigned int copied; struct si476x_radio *radio = video_drvdata(file); /* block if no new data available */ if (kfifo_is_empty(&radio->core->rds_fifo)) { if (file->f_flags & O_NONBLOCK) return -EWOULDBLOCK; rval = wait_event_interruptible(radio->core->rds_read_queue, (!kfifo_is_empty(&radio->core->rds_fifo) || !atomic_read(&radio->core->is_alive))); if (rval < 0) return -EINTR; if (!atomic_read(&radio->core->is_alive)) return -ENODEV; } fifo_len = kfifo_len(&radio->core->rds_fifo); if (kfifo_to_user(&radio->core->rds_fifo, buf, min(fifo_len, count), &copied) != 0) { dev_warn(&radio->videodev.dev, "Error during FIFO to userspace copy\n"); rval = -EIO; } else { rval = (ssize_t)copied; } return rval; } static unsigned int si476x_radio_fops_poll(struct file *file, struct poll_table_struct *pts) { struct si476x_radio *radio = video_drvdata(file); unsigned long req_events = poll_requested_events(pts); unsigned int err = v4l2_ctrl_poll(file, pts); if (req_events & (POLLIN | POLLRDNORM)) { if (atomic_read(&radio->core->is_alive)) poll_wait(file, &radio->core->rds_read_queue, pts); if (!atomic_read(&radio->core->is_alive)) err = POLLHUP; if (!kfifo_is_empty(&radio->core->rds_fifo)) err = POLLIN | POLLRDNORM; } return err; } static const struct v4l2_file_operations si476x_fops = { .owner = THIS_MODULE, .read = si476x_radio_fops_read, .poll = si476x_radio_fops_poll, .unlocked_ioctl = video_ioctl2, .open = si476x_radio_fops_open, .release = si476x_radio_fops_release, }; static const struct v4l2_ioctl_ops si4761_ioctl_ops = { .vidioc_querycap = si476x_radio_querycap, .vidioc_g_tuner = si476x_radio_g_tuner, .vidioc_s_tuner = si476x_radio_s_tuner, .vidioc_g_frequency = si476x_radio_g_frequency, .vidioc_s_frequency = si476x_radio_s_frequency, .vidioc_s_hw_freq_seek = si476x_radio_s_hw_freq_seek, .vidioc_enum_freq_bands = si476x_radio_enum_freq_bands, .vidioc_subscribe_event = v4l2_ctrl_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, #ifdef CPTCFG_VIDEO_ADV_DEBUG .vidioc_g_register = si476x_radio_g_register, .vidioc_s_register = si476x_radio_s_register, #endif }; static const struct video_device si476x_viddev_template = { .fops = &si476x_fops, .name = DRIVER_NAME, .release = video_device_release_empty, }; static ssize_t si476x_radio_read_acf_blob(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { int err; struct si476x_radio *radio = file->private_data; struct si476x_acf_status_report report; si476x_core_lock(radio->core); if (radio->ops->acf_status) err = radio->ops->acf_status(radio->core, &report); else err = -ENOENT; si476x_core_unlock(radio->core); if (err < 0) return err; return simple_read_from_buffer(user_buf, count, ppos, &report, sizeof(report)); } static const struct file_operations radio_acf_fops = { .open = simple_open, .llseek = default_llseek, .read = si476x_radio_read_acf_blob, }; static ssize_t si476x_radio_read_rds_blckcnt_blob(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { int err; struct si476x_radio *radio = file->private_data; struct si476x_rds_blockcount_report report; si476x_core_lock(radio->core); if (radio->ops->rds_blckcnt) err = radio->ops->rds_blckcnt(radio->core, true, &report); else err = -ENOENT; si476x_core_unlock(radio->core); if (err < 0) return err; return simple_read_from_buffer(user_buf, count, ppos, &report, sizeof(report)); } static const struct file_operations radio_rds_blckcnt_fops = { .open = simple_open, .llseek = default_llseek, .read = si476x_radio_read_rds_blckcnt_blob, }; static ssize_t si476x_radio_read_agc_blob(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { int err; struct si476x_radio *radio = file->private_data; struct si476x_agc_status_report report; si476x_core_lock(radio->core); if (radio->ops->rds_blckcnt) err = radio->ops->agc_status(radio->core, &report); else err = -ENOENT; si476x_core_unlock(radio->core); if (err < 0) return err; return simple_read_from_buffer(user_buf, count, ppos, &report, sizeof(report)); } static const struct file_operations radio_agc_fops = { .open = simple_open, .llseek = default_llseek, .read = si476x_radio_read_agc_blob, }; static ssize_t si476x_radio_read_rsq_blob(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { int err; struct si476x_radio *radio = file->private_data; struct si476x_rsq_status_report report; struct si476x_rsq_status_args args = { .primary = false, .rsqack = false, .attune = false, .cancel = false, .stcack = false, }; si476x_core_lock(radio->core); if (radio->ops->rds_blckcnt) err = radio->ops->rsq_status(radio->core, &args, &report); else err = -ENOENT; si476x_core_unlock(radio->core); if (err < 0) return err; return simple_read_from_buffer(user_buf, count, ppos, &report, sizeof(report)); } static const struct file_operations radio_rsq_fops = { .open = simple_open, .llseek = default_llseek, .read = si476x_radio_read_rsq_blob, }; static ssize_t si476x_radio_read_rsq_primary_blob(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { int err; struct si476x_radio *radio = file->private_data; struct si476x_rsq_status_report report; struct si476x_rsq_status_args args = { .primary = true, .rsqack = false, .attune = false, .cancel = false, .stcack = false, }; si476x_core_lock(radio->core); if (radio->ops->rds_blckcnt) err = radio->ops->rsq_status(radio->core, &args, &report); else err = -ENOENT; si476x_core_unlock(radio->core); if (err < 0) return err; return simple_read_from_buffer(user_buf, count, ppos, &report, sizeof(report)); } static const struct file_operations radio_rsq_primary_fops = { .open = simple_open, .llseek = default_llseek, .read = si476x_radio_read_rsq_primary_blob, }; static int si476x_radio_init_debugfs(struct si476x_radio *radio) { struct dentry *dentry; int ret; dentry = debugfs_create_dir(dev_name(radio->v4l2dev.dev), NULL); if (IS_ERR(dentry)) { ret = PTR_ERR(dentry); goto exit; } radio->debugfs = dentry; dentry = debugfs_create_file("acf", S_IRUGO, radio->debugfs, radio, &radio_acf_fops); if (IS_ERR(dentry)) { ret = PTR_ERR(dentry); goto cleanup; } dentry = debugfs_create_file("rds_blckcnt", S_IRUGO, radio->debugfs, radio, &radio_rds_blckcnt_fops); if (IS_ERR(dentry)) { ret = PTR_ERR(dentry); goto cleanup; } dentry = debugfs_create_file("agc", S_IRUGO, radio->debugfs, radio, &radio_agc_fops); if (IS_ERR(dentry)) { ret = PTR_ERR(dentry); goto cleanup; } dentry = debugfs_create_file("rsq", S_IRUGO, radio->debugfs, radio, &radio_rsq_fops); if (IS_ERR(dentry)) { ret = PTR_ERR(dentry); goto cleanup; } dentry = debugfs_create_file("rsq_primary", S_IRUGO, radio->debugfs, radio, &radio_rsq_primary_fops); if (IS_ERR(dentry)) { ret = PTR_ERR(dentry); goto cleanup; } return 0; cleanup: debugfs_remove_recursive(radio->debugfs); exit: return ret; } static int si476x_radio_add_new_custom(struct si476x_radio *radio, enum si476x_ctrl_idx idx) { int rval; struct v4l2_ctrl *ctrl; ctrl = v4l2_ctrl_new_custom(&radio->ctrl_handler, &si476x_ctrls[idx], NULL); rval = radio->ctrl_handler.error; if (ctrl == NULL && rval) dev_err(radio->v4l2dev.dev, "Could not initialize '%s' control %d\n", si476x_ctrls[idx].name, rval); return rval; } static int si476x_radio_probe(struct platform_device *pdev) { int rval; struct si476x_radio *radio; struct v4l2_ctrl *ctrl; static atomic_t instance = ATOMIC_INIT(0); radio = devm_kzalloc(&pdev->dev, sizeof(*radio), GFP_KERNEL); if (!radio) return -ENOMEM; radio->core = i2c_mfd_cell_to_core(&pdev->dev); v4l2_device_set_name(&radio->v4l2dev, DRIVER_NAME, &instance); rval = v4l2_device_register(&pdev->dev, &radio->v4l2dev); if (rval) { dev_err(&pdev->dev, "Cannot register v4l2_device.\n"); return rval; } memcpy(&radio->videodev, &si476x_viddev_template, sizeof(struct video_device)); radio->videodev.v4l2_dev = &radio->v4l2dev; radio->videodev.ioctl_ops = &si4761_ioctl_ops; video_set_drvdata(&radio->videodev, radio); platform_set_drvdata(pdev, radio); radio->v4l2dev.ctrl_handler = &radio->ctrl_handler; v4l2_ctrl_handler_init(&radio->ctrl_handler, 1 + ARRAY_SIZE(si476x_ctrls)); if (si476x_core_has_am(radio->core)) { ctrl = v4l2_ctrl_new_std_menu(&radio->ctrl_handler, &si476x_ctrl_ops, V4L2_CID_POWER_LINE_FREQUENCY, V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0, 0); rval = radio->ctrl_handler.error; if (ctrl == NULL && rval) { dev_err(&pdev->dev, "Could not initialize V4L2_CID_POWER_LINE_FREQUENCY control %d\n", rval); goto exit; } rval = si476x_radio_add_new_custom(radio, SI476X_IDX_HARMONICS_COUNT); if (rval < 0) goto exit; } rval = si476x_radio_add_new_custom(radio, SI476X_IDX_RSSI_THRESHOLD); if (rval < 0) goto exit; rval = si476x_radio_add_new_custom(radio, SI476X_IDX_SNR_THRESHOLD); if (rval < 0) goto exit; rval = si476x_radio_add_new_custom(radio, SI476X_IDX_MAX_TUNE_ERROR); if (rval < 0) goto exit; ctrl = v4l2_ctrl_new_std_menu(&radio->ctrl_handler, &si476x_ctrl_ops, V4L2_CID_TUNE_DEEMPHASIS, V4L2_DEEMPHASIS_75_uS, 0, 0); rval = radio->ctrl_handler.error; if (ctrl == NULL && rval) { dev_err(&pdev->dev, "Could not initialize V4L2_CID_TUNE_DEEMPHASIS control %d\n", rval); goto exit; } ctrl = v4l2_ctrl_new_std(&radio->ctrl_handler, &si476x_ctrl_ops, V4L2_CID_RDS_RECEPTION, 0, 1, 1, 1); rval = radio->ctrl_handler.error; if (ctrl == NULL && rval) { dev_err(&pdev->dev, "Could not initialize V4L2_CID_RDS_RECEPTION control %d\n", rval); goto exit; } if (si476x_core_has_diversity(radio->core)) { si476x_ctrls[SI476X_IDX_DIVERSITY_MODE].def = si476x_phase_diversity_mode_to_idx(radio->core->diversity_mode); si476x_radio_add_new_custom(radio, SI476X_IDX_DIVERSITY_MODE); if (rval < 0) goto exit; si476x_radio_add_new_custom(radio, SI476X_IDX_INTERCHIP_LINK); if (rval < 0) goto exit; } /* register video device */ rval = video_register_device(&radio->videodev, VFL_TYPE_RADIO, -1); if (rval < 0) { dev_err(&pdev->dev, "Could not register video device\n"); goto exit; } rval = si476x_radio_init_debugfs(radio); if (rval < 0) { dev_err(&pdev->dev, "Could not creat debugfs interface\n"); goto exit; } return 0; exit: v4l2_ctrl_handler_free(radio->videodev.ctrl_handler); return rval; } static int si476x_radio_remove(struct platform_device *pdev) { struct si476x_radio *radio = platform_get_drvdata(pdev); v4l2_ctrl_handler_free(radio->videodev.ctrl_handler); video_unregister_device(&radio->videodev); v4l2_device_unregister(&radio->v4l2dev); debugfs_remove_recursive(radio->debugfs); return 0; } MODULE_ALIAS("platform:si476x-radio"); static struct platform_driver si476x_radio_driver = { .driver = { .name = DRIVER_NAME, }, .probe = si476x_radio_probe, .remove = si476x_radio_remove, }; module_platform_driver(si476x_radio_driver); MODULE_AUTHOR("Andrey Smirnov <andrew.smirnov@gmail.com>"); MODULE_DESCRIPTION("Driver for Si4761/64/68 AM/FM Radio MFD Cell"); MODULE_LICENSE("GPL");
kmalekinasab/wireless-network
drivers/media/radio/radio-si476x.c
C
gpl-2.0
41,051
-- -- Copyright (c) 2008 Red Hat, Inc. -- -- This software is licensed to you under the GNU General Public License, -- version 2 (GPLv2). There is NO WARRANTY for this software, express or -- implied, including the implied warranties of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 -- along with this software; if not, see -- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. -- -- Red Hat trademarks are not licensed under GPLv2. No permission is -- granted to use or replicate Red Hat trademarks that are incorporated -- in this software or its documentation. -- -- -- -- -- --monitoring stored procedure create or replace procedure rhn_install_org_satellites ( for_customer_id in web_customer.id%type, sat_cluster_id in rhn_sat_cluster.recid%type, username in rhn_command_queue_instances.last_update_user%type ) is -- the cursor is defined such that the following behavior occurs based on the sat_cluster_id param: -- null results in all of a customer's scout being configured. -- an id for a scout belonging to the cust results in just that scout being configured -- an id for a scout not belonging to the cust results in no action. cursor satellite_cursor is select recid from rhn_sat_cluster where customer_id = for_customer_id and recid not in ( select netsaint_id from rhn_ll_netsaint ) minus select recid from rhn_sat_cluster where customer_id = for_customer_id and recid not in (sat_cluster_id); command_instance_id rhn_command_queue_instances.recid%type; begin rhn_prepare_install(username, command_instance_id, 1); for satellite in satellite_cursor loop rhn_install_satellite(command_instance_id, satellite.recid); end loop; end rhn_install_org_satellites; / show errors -- --Revision 1.5 2004/06/03 20:19:54 pjones --bugzilla: none -- use procedure names after "end". -- --Revision 1.4 2004/05/28 22:05:14 pjones --bugzilla: none -- "rhn_install_customer_satellites" is too long. -- --Revision 1.3 2004/05/27 20:17:38 kja --tweaks to syntax. -- --Revision 1.2 2004/05/10 17:25:08 kja --Fixing syntax things with the stored procs. -- --Revision 1.1 2004/04/21 20:47:41 kja --Added the npcfdb stored procedures. Renamed the nolog procs to rhn_. --
colloquium/spacewalk
schema/spacewalk/oracle/procs/rhn_install_org_satellites.sql
SQL
gpl-2.0
2,364
/****************************************************************************** * Wormux is a convivial mass murder game. * Copyright (C) 2001-2009 Wormux Team. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA ****************************************************************************** * Game menu *****************************************************************************/ #include "menu/game_menu.h" #include "menu/game_mode_editor.h" #include "menu/map_selection_box.h" #include "menu/teams_selection_box.h" #include "game/game.h" #include "game/config.h" #include "game/game_mode.h" #include "graphic/video.h" #include "gui/tabs.h" #include "gui/combo_box.h" #include "include/app.h" #include "tool/resource_manager.h" const uint MARGIN_TOP = 5; const uint MARGIN_SIDE = 5; const uint MARGIN_BOTTOM = 50; const uint TEAMS_BOX_H = 205; const uint OPTIONS_BOX_H = 150; // ################################################ // ## GAME MENU CLASS // ################################################ GameMenu::GameMenu() : Menu("menu/bg_play") { Profile *res = GetResourceManager().LoadXMLProfile( "graphism.xml",false); Point2i stdSize(130, W_UNDEF); Surface& window = GetMainWindow(); // Calculate main box size uint mainBoxWidth = window.GetWidth() - 2*MARGIN_SIDE; uint multitabsHeight = (window.GetHeight() - MARGIN_TOP - MARGIN_BOTTOM - 2*MARGIN_SIDE) - TEAMS_BOX_H; // ################################################ // ## TEAM SELECTION // ################################################ MultiTabs * tabs_team = new MultiTabs(Point2i(mainBoxWidth, TEAMS_BOX_H)); team_box = new TeamsSelectionBox(Point2i(mainBoxWidth, TEAMS_BOX_H - 25)); tabs_team->AddNewTab("TAB_Team", _("Teams"), team_box); tabs_team->SetPosition(MARGIN_SIDE, MARGIN_TOP); widgets.AddWidget(tabs_team); // ################################################ // ## MAP SELECTION // ################################################ MultiTabs * tabs = new MultiTabs(Point2i(mainBoxWidth, multitabsHeight)); map_box = new MapSelectionBox(Point2i(mainBoxWidth-10, multitabsHeight - 50)); tabs->AddNewTab("TAB_Map", _("Map"), map_box); // ################################################ // ## GAME OPTIONS // ################################################ Point2i option_size(130, 130); game_options = new GameModeEditor(mainBoxWidth, option_size, false); tabs->AddNewTab("TAB_Game", _("Game"), game_options); tabs->SetPosition(MARGIN_SIDE, tabs_team->GetPositionY()+tabs_team->GetSizeY()+ MARGIN_TOP); widgets.AddWidget(tabs); widgets.Pack(); GetResourceManager().UnLoadXMLProfile(res); } GameMenu::~GameMenu() { } void GameMenu::OnClick(const Point2i &mousePosition, int button) { widgets.Click(mousePosition, button); } void GameMenu::OnClickUp(const Point2i &mousePosition, int button) { Widget *w = widgets.ClickUp(mousePosition, button); if (w == game_options->GetGameModeComboBox()) { game_options->LoadGameMode(); } } void GameMenu::SaveOptions() { // Map map_box->ValidMapSelection(); // teams team_box->ValidTeamsSelection(); //Save options in XML (including current selected teams, selected map) Config::GetInstance()->Save(true); game_options->ValidGameMode(); } bool GameMenu::signal_ok() { SaveOptions(); play_ok_sound(); Game::UpdateGameRules()->Start(); return true; } bool GameMenu::signal_cancel() { return true; } void GameMenu::key_left() { map_box->ChangeMapDelta(-1); } void GameMenu::key_right() { map_box->ChangeMapDelta(1); } void GameMenu::Draw(const Point2i &/*mousePosition*/) { }
yeKcim/warmux
old/wormux-0.8.5.1/src/menu/game_menu.cpp
C++
gpl-2.0
4,319
/* * iaf_psc_alpha_canon.cpp * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ #include "iaf_psc_alpha_canon.h" #include "exceptions.h" #include "network.h" #include "dict.h" #include "integerdatum.h" #include "doubledatum.h" #include "dictutils.h" #include "numerics.h" #include "universal_data_logger_impl.h" #include "propagator_stability.h" #include <limits> /* ---------------------------------------------------------------- * Recordables map * ---------------------------------------------------------------- */ nest::RecordablesMap< nest::iaf_psc_alpha_canon > nest::iaf_psc_alpha_canon::recordablesMap_; namespace nest { /* * Override the create() method with one call to RecordablesMap::insert_() * for each quantity to be recorded. */ template <> void RecordablesMap< iaf_psc_alpha_canon >::create() { // use standard names wherever you can for consistency! insert_( names::V_m, &iaf_psc_alpha_canon::get_V_m_ ); } } /* ---------------------------------------------------------------- * Default constructors defining default parameters and state * ---------------------------------------------------------------- */ nest::iaf_psc_alpha_canon::Parameters_::Parameters_() : tau_m_( 10.0 ) // ms , tau_syn_( 2.0 ) // ms , c_m_( 250.0 ) // pF , t_ref_( 2.0 ) // ms , E_L_( -70.0 ) // mV , I_e_( 0.0 ) // pA , U_th_( -55.0 - E_L_ ) // mV, rel to E_L_ , U_min_( -std::numeric_limits< double_t >::infinity() ) // mV , U_reset_( -70.0 - E_L_ ) // mV, rel to E_L_ , Interpol_( iaf_psc_alpha_canon::LINEAR ) { } nest::iaf_psc_alpha_canon::State_::State_() : y0_( 0.0 ) , y1_( 0.0 ) , y2_( 0.0 ) , y3_( 0.0 ) , is_refractory_( false ) , last_spike_step_( -1 ) , last_spike_offset_( 0.0 ) { } /* ---------------------------------------------------------------- * Parameter and state extractions and manipulation functions * ---------------------------------------------------------------- */ void nest::iaf_psc_alpha_canon::Parameters_::get( DictionaryDatum& d ) const { def< double >( d, names::E_L, E_L_ ); def< double >( d, names::I_e, I_e_ ); def< double >( d, names::V_th, U_th_ + E_L_ ); def< double >( d, names::V_min, U_min_ + E_L_ ); def< double >( d, names::V_reset, U_reset_ + E_L_ ); def< double >( d, names::C_m, c_m_ ); def< double >( d, names::tau_m, tau_m_ ); def< double >( d, names::tau_syn, tau_syn_ ); def< double >( d, names::t_ref, t_ref_ ); def< long >( d, names::Interpol_Order, Interpol_ ); } double nest::iaf_psc_alpha_canon::Parameters_::set( const DictionaryDatum& d ) { // if U0_ is changed, we need to adjust all variables defined relative to U0_ const double ELold = E_L_; updateValue< double >( d, names::E_L, E_L_ ); const double delta_EL = E_L_ - ELold; updateValue< double >( d, names::tau_m, tau_m_ ); updateValue< double >( d, names::tau_syn, tau_syn_ ); updateValue< double >( d, names::C_m, c_m_ ); updateValue< double >( d, names::t_ref, t_ref_ ); updateValue< double >( d, names::I_e, I_e_ ); if ( updateValue< double >( d, names::V_th, U_th_ ) ) U_th_ -= E_L_; else U_th_ -= delta_EL; if ( updateValue< double >( d, names::V_min, U_min_ ) ) U_min_ -= E_L_; else U_min_ -= delta_EL; if ( updateValue< double >( d, names::V_reset, U_reset_ ) ) U_reset_ -= E_L_; else U_reset_ -= delta_EL; long_t tmp; if ( updateValue< long_t >( d, names::Interpol_Order, tmp ) ) { if ( NO_INTERPOL <= tmp && tmp < END_INTERP_ORDER ) Interpol_ = static_cast< interpOrder >( tmp ); else throw BadProperty( "Invalid interpolation order. " "Valid orders are 0, 1, 2, 3." ); } if ( U_reset_ >= U_th_ ) throw BadProperty( "Reset potential must be smaller than threshold." ); if ( U_reset_ < U_min_ ) throw BadProperty( "Reset potential must be greater equal minimum potential." ); if ( c_m_ <= 0 ) throw BadProperty( "Capacitance must be strictly positive." ); if ( Time( Time::ms( t_ref_ ) ).get_steps() < 1 ) throw BadProperty( "Refractory time must be at least one time step." ); if ( tau_m_ <= 0 || tau_syn_ <= 0 ) throw BadProperty( "All time constants must be strictly positive." ); return delta_EL; } void nest::iaf_psc_alpha_canon::State_::get( DictionaryDatum& d, const Parameters_& p ) const { def< double >( d, names::V_m, y3_ + p.E_L_ ); // Membrane potential def< double >( d, "y1", y1_ ); // y1 state def< double >( d, "y2", y2_ ); // y2 state def< bool >( d, names::is_refractory, is_refractory_ ); } void nest::iaf_psc_alpha_canon::State_::set( const DictionaryDatum& d, const Parameters_& p, double delta_EL ) { if ( updateValue< double >( d, names::V_m, y3_ ) ) y3_ -= p.E_L_; else y3_ -= delta_EL; updateValue< double >( d, "y1", y1_ ); updateValue< double >( d, "y2", y2_ ); } nest::iaf_psc_alpha_canon::Buffers_::Buffers_( iaf_psc_alpha_canon& n ) : logger_( n ) { } nest::iaf_psc_alpha_canon::Buffers_::Buffers_( const Buffers_&, iaf_psc_alpha_canon& n ) : logger_( n ) { } /* ---------------------------------------------------------------- * Default and copy constructor for node * ---------------------------------------------------------------- */ nest::iaf_psc_alpha_canon::iaf_psc_alpha_canon() : Archiving_Node() , P_() , S_() , B_( *this ) { recordablesMap_.create(); } nest::iaf_psc_alpha_canon::iaf_psc_alpha_canon( const iaf_psc_alpha_canon& n ) : Archiving_Node( n ) , P_( n.P_ ) , S_( n.S_ ) , B_( n.B_, *this ) { } /* ---------------------------------------------------------------- * Node initialization functions * ---------------------------------------------------------------- */ void nest::iaf_psc_alpha_canon::init_state_( const Node& proto ) { const iaf_psc_alpha_canon& pr = downcast< iaf_psc_alpha_canon >( proto ); S_ = pr.S_; } void nest::iaf_psc_alpha_canon::init_buffers_() { B_.events_.resize(); B_.events_.clear(); B_.currents_.clear(); // includes resize B_.logger_.reset(); Archiving_Node::clear_history(); } void nest::iaf_psc_alpha_canon::calibrate() { B_.logger_.init(); V_.h_ms_ = Time::get_resolution().get_ms(); V_.PSCInitialValue_ = 1.0 * numerics::e / P_.tau_syn_; V_.gamma_ = 1 / P_.c_m_ / ( 1 / P_.tau_syn_ - 1 / P_.tau_m_ ); V_.gamma_sq_ = 1 / P_.c_m_ / ( ( 1 / P_.tau_syn_ - 1 / P_.tau_m_ ) * ( 1 / P_.tau_syn_ - 1 / P_.tau_m_ ) ); // pre-compute matrix for full time step V_.expm1_tau_m_ = numerics::expm1( -V_.h_ms_ / P_.tau_m_ ); V_.expm1_tau_syn_ = numerics::expm1( -V_.h_ms_ / P_.tau_syn_ ); V_.P30_ = -P_.tau_m_ / P_.c_m_ * V_.expm1_tau_m_; // these are determined according to a numeric stability criterion V_.P31_ = propagator_31( P_.tau_syn_, P_.tau_m_, P_.c_m_, V_.h_ms_ ); V_.P32_ = propagator_32( P_.tau_syn_, P_.tau_m_, P_.c_m_, V_.h_ms_ ); // t_ref_ is the refractory period in ms // refractory_steps_ is the duration of the refractory period in whole // steps, rounded down V_.refractory_steps_ = Time( Time::ms( P_.t_ref_ ) ).get_steps(); assert( V_.refractory_steps_ >= 1 ); // since t_ref_ >= sim step size, this can only fail in error } /* ---------------------------------------------------------------- * Update and spike handling functions * ---------------------------------------------------------------- */ void nest::iaf_psc_alpha_canon::update( Time const& origin, const long_t from, const long_t to ) { assert( to >= 0 ); assert( static_cast< delay >( from ) < Scheduler::get_min_delay() ); assert( from < to ); // at start of slice, tell input queue to prepare for delivery if ( from == 0 ) B_.events_.prepare_delivery(); /* Neurons may have been initialized to superthreshold potentials. We need to check for this here and issue spikes at the beginning of the interval. */ if ( S_.y3_ >= P_.U_th_ ) emit_instant_spike_( origin, from, V_.h_ms_ * ( 1 - std::numeric_limits< double_t >::epsilon() ) ); for ( long_t lag = from; lag < to; ++lag ) { // time at start of update step const long_t T = origin.get_steps() + lag; // if neuron returns from refractoriness during this step, place // pseudo-event in queue to mark end of refractory period if ( S_.is_refractory_ && ( T + 1 - S_.last_spike_step_ == V_.refractory_steps_ ) ) B_.events_.add_refractory( T, S_.last_spike_offset_ ); // save state at beginning of interval for spike-time interpolation V_.y0_before_ = S_.y0_; V_.y2_before_ = S_.y2_; V_.y3_before_ = S_.y3_; // get first event double_t ev_offset; double_t ev_weight; bool end_of_refract; if ( !B_.events_.get_next_spike( T, ev_offset, ev_weight, end_of_refract ) ) { // No incoming spikes, handle with fixed propagator matrix. // Handling this case separately improves performance significantly // if there are many steps without input spikes. // update membrane potential if ( !S_.is_refractory_ ) { S_.y3_ = V_.P30_ * ( P_.I_e_ + S_.y0_ ) + V_.P31_ * S_.y1_ + V_.P32_ * S_.y2_ + V_.expm1_tau_m_ * S_.y3_ + S_.y3_; // lower bound of membrane potential S_.y3_ = ( S_.y3_ < P_.U_min_ ? P_.U_min_ : S_.y3_ ); } // update synaptic currents S_.y2_ = V_.expm1_tau_syn_ * V_.h_ms_ * S_.y1_ + V_.expm1_tau_syn_ * S_.y2_ + V_.h_ms_ * S_.y1_ + S_.y2_; S_.y1_ = V_.expm1_tau_syn_ * S_.y1_ + S_.y1_; /* The following must not be moved before the y1_, y2_ update, since the spike-time interpolation within emit_spike_ depends on all state variables having their values at the end of the interval. */ if ( S_.y3_ >= P_.U_th_ ) emit_spike_( origin, lag, 0, V_.h_ms_ ); } else { // We only get here if there is at least on event, // which has been read above. We can therefore use // a do-while loop. // Time within step is measured by offsets, which are h at the beginning // and 0 at the end of the step. double_t last_offset = V_.h_ms_; // start of step do { // time is measured backward: inverse order in difference const double_t ministep = last_offset - ev_offset; propagate_( ministep ); // check for threshold crossing during ministep // this must be done before adding the input, since // interpolation requires continuity if ( S_.y3_ >= P_.U_th_ ) emit_spike_( origin, lag, V_.h_ms_ - last_offset, ministep ); // handle event if ( end_of_refract ) S_.is_refractory_ = false; // return from refractoriness else S_.y1_ += V_.PSCInitialValue_ * ev_weight; // spike input // store state V_.y2_before_ = S_.y2_; V_.y3_before_ = S_.y3_; last_offset = ev_offset; } while ( B_.events_.get_next_spike( T, ev_offset, ev_weight, end_of_refract ) ); // no events remaining, plain update step across remainder // of interval if ( last_offset > 0 ) // not at end of step, do remainder { propagate_( last_offset ); if ( S_.y3_ >= P_.U_th_ ) emit_spike_( origin, lag, V_.h_ms_ - last_offset, last_offset ); } } // else // Set new input current. The current change occurs at the // end of the interval and thus must come AFTER the threshold- // crossing interpolation S_.y0_ = B_.currents_.get_value( lag ); // logging B_.logger_.record_data( origin.get_steps() + lag ); } // from lag = from ... } // function handles exact spike times void nest::iaf_psc_alpha_canon::handle( SpikeEvent& e ) { assert( e.get_delay() > 0 ); /* We need to compute the absolute time stamp of the delivery time of the spike, since spikes might spend longer than min_delay_ in the queue. The time is computed according to Time Memo, Rule 3. */ const long_t Tdeliver = e.get_stamp().get_steps() + e.get_delay() - 1; B_.events_.add_spike( e.get_rel_delivery_steps( network()->get_slice_origin() ), Tdeliver, e.get_offset(), e.get_weight() * e.get_multiplicity() ); } void nest::iaf_psc_alpha_canon::handle( CurrentEvent& e ) { assert( e.get_delay() > 0 ); const double_t c = e.get_current(); const double_t w = e.get_weight(); // add weighted current; HEP 2002-10-04 B_.currents_.add_value( e.get_rel_delivery_steps( network()->get_slice_origin() ), w * c ); } void nest::iaf_psc_alpha_canon::handle( DataLoggingRequest& e ) { B_.logger_.handle( e ); } // auxiliary functions --------------------------------------------- void nest::iaf_psc_alpha_canon::propagate_( const double_t dt ) { const double_t ps_e_TauSyn = numerics::expm1( -dt / P_.tau_syn_ ); // needed in any case // y3_ remains unchanged at 0.0 while neuron is refractory if ( !S_.is_refractory_ ) { const double_t ps_e_Tau = numerics::expm1( -dt / P_.tau_m_ ); const double_t ps_P30 = -P_.tau_m_ / P_.c_m_ * ps_e_Tau; const double_t ps_P31 = V_.gamma_sq_ * ps_e_Tau - V_.gamma_sq_ * ps_e_TauSyn - dt * V_.gamma_ * ps_e_TauSyn - dt * V_.gamma_; const double_t ps_P32 = V_.gamma_ * ps_e_Tau - V_.gamma_ * ps_e_TauSyn; S_.y3_ = ps_P30 * ( P_.I_e_ + S_.y0_ ) + ps_P31 * S_.y1_ + ps_P32 * S_.y2_ + ps_e_Tau * S_.y3_ + S_.y3_; // lower bound of membrane potential S_.y3_ = ( S_.y3_ < P_.U_min_ ? P_.U_min_ : S_.y3_ ); } // now the synaptic components S_.y2_ = ps_e_TauSyn * dt * S_.y1_ + ps_e_TauSyn * S_.y2_ + dt * S_.y1_ + S_.y2_; S_.y1_ = ps_e_TauSyn * S_.y1_ + S_.y1_; return; } void nest::iaf_psc_alpha_canon::emit_spike_( Time const& origin, const long_t lag, const double_t t0, const double_t dt ) { // we know that the potential is subthreshold at t0, super at t0+dt // compute spike time relative to beginning of step S_.last_spike_step_ = origin.get_steps() + lag + 1; S_.last_spike_offset_ = V_.h_ms_ - ( t0 + thresh_find_( dt ) ); // reset neuron and make it refractory S_.y3_ = P_.U_reset_; S_.is_refractory_ = true; // send spike set_spiketime( Time::step( S_.last_spike_step_ ), S_.last_spike_offset_ ); SpikeEvent se; se.set_offset( S_.last_spike_offset_ ); network()->send( *this, se, lag ); return; } void nest::iaf_psc_alpha_canon::emit_instant_spike_( Time const& origin, const long_t lag, const double_t spike_offs ) { assert( S_.y3_ >= P_.U_th_ ); // ensure we are superthreshold // set stamp and offset for spike S_.last_spike_step_ = origin.get_steps() + lag + 1; S_.last_spike_offset_ = spike_offs; // reset neuron and make it refractory S_.y3_ = P_.U_reset_; S_.is_refractory_ = true; // send spike set_spiketime( Time::step( S_.last_spike_step_ ), S_.last_spike_offset_ ); SpikeEvent se; se.set_offset( S_.last_spike_offset_ ); network()->send( *this, se, lag ); return; } // finds threshpassing inline nest::double_t nest::iaf_psc_alpha_canon::thresh_find_( double_t const dt ) const { switch ( P_.Interpol_ ) { case NO_INTERPOL: return dt; case LINEAR: return thresh_find1_( dt ); case QUADRATIC: return thresh_find2_( dt ); case CUBIC: return thresh_find3_( dt ); default: throw BadProperty( "Invalid interpolation order in iaf_psc_alpha_canon." ); } return 0; } // finds threshpassing via linear interpolation nest::double_t nest::iaf_psc_alpha_canon::thresh_find1_( double_t const dt ) const { double_t tau = ( P_.U_th_ - V_.y3_before_ ) * dt / ( S_.y3_ - V_.y3_before_ ); return tau; } // finds threshpassing via quadratic interpolation nest::double_t nest::iaf_psc_alpha_canon::thresh_find2_( double_t const dt ) const { const double_t h_sq = dt * dt; const double_t derivative = -V_.y3_before_ / P_.tau_m_ + ( P_.I_e_ + V_.y0_before_ + V_.y2_before_ ) / P_.c_m_; const double_t a = ( -V_.y3_before_ / h_sq ) + ( S_.y3_ / h_sq ) - ( derivative / dt ); const double_t b = derivative; const double_t c = V_.y3_before_; const double_t sqr_ = std::sqrt( b * b - 4 * a * c + 4 * a * P_.U_th_ ); const double_t tau1 = ( -b + sqr_ ) / ( 2 * a ); const double_t tau2 = ( -b - sqr_ ) / ( 2 * a ); if ( tau1 >= 0 ) return tau1; else if ( tau2 >= 0 ) return tau2; else return thresh_find1_( dt ); } nest::double_t nest::iaf_psc_alpha_canon::thresh_find3_( double_t const dt ) const { const double_t h_ms = dt; const double_t h_sq = h_ms * h_ms; const double_t h_cb = h_sq * h_ms; const double_t deriv_t1 = -V_.y3_before_ / P_.tau_m_ + ( P_.I_e_ + V_.y0_before_ + V_.y2_before_ ) / P_.c_m_; const double_t deriv_t2 = -S_.y3_ / P_.tau_m_ + ( P_.I_e_ + S_.y0_ + S_.y2_ ) / P_.c_m_; const double_t w3_ = ( 2 * V_.y3_before_ / h_cb ) - ( 2 * S_.y3_ / h_cb ) + ( deriv_t1 / h_sq ) + ( deriv_t2 / h_sq ); const double_t w2_ = -( 3 * V_.y3_before_ / h_sq ) + ( 3 * S_.y3_ / h_sq ) - ( 2 * deriv_t1 / h_ms ) - ( deriv_t2 / h_ms ); const double_t w1_ = deriv_t1; const double_t w0_ = V_.y3_before_; // normal form : x^3 + r*x^2 + s*x + t with coefficients : r, s, t const double_t r = w2_ / w3_; const double_t s = w1_ / w3_; const double_t t = ( w0_ - P_.U_th_ ) / w3_; const double_t r_sq = r * r; // substitution y = x + r/3 : y^3 + p*y + q == 0 const double_t p = -r_sq / 3 + s; const double_t q = 2 * ( r_sq * r ) / 27 - r * s / 3 + t; // discriminante const double_t D = std::pow( ( p / 3 ), 3 ) + std::pow( ( q / 2 ), 2 ); double_t tau1; double_t tau2; double_t tau3; if ( D < 0 ) { const double_t roh = std::sqrt( -( p * p * p ) / 27 ); const double_t phi = std::acos( -q / ( 2 * roh ) ); const double_t a = 2 * std::pow( roh, ( 1.0 / 3.0 ) ); tau1 = ( a * std::cos( phi / 3 ) ) - r / 3; tau2 = ( a * std::cos( phi / 3 + 2 * numerics::pi / 3 ) ) - r / 3; tau3 = ( a * std::cos( phi / 3 + 4 * numerics::pi / 3 ) ) - r / 3; } else { const double_t sgnq = ( q >= 0 ? 1 : -1 ); const double_t u = -sgnq * std::pow( std::fabs( q ) / 2.0 + std::sqrt( D ), 1.0 / 3.0 ); const double_t v = -p / ( 3 * u ); tau1 = ( u + v ) - r / 3; if ( tau1 >= 0 ) { return tau1; } else { return thresh_find2_( dt ); } } // set tau to the smallest root above 0 double tau = ( tau1 >= 0 ) ? tau1 : 2 * h_ms; if ( ( tau2 >= 0 ) && ( tau2 < tau ) ) tau = tau2; if ( ( tau3 >= 0 ) && ( tau3 < tau ) ) tau = tau3; return ( tau <= V_.h_ms_ ) ? tau : thresh_find2_( dt ); }
magnastrazh/NEUCOGAR
nest/noradrenaline/nest-2.10.0/precise/iaf_psc_alpha_canon.cpp
C++
gpl-2.0
19,589
<?php // $Id: advf-forum-list.tpl.php,v 1.1 2009/07/15 00:57:54 eigentor Exp $ /** * @file * Default theme implementation to display a list of forums and containers. * * Available variables: * - $forums: An array of forums and containers to display. It is keyed to the * numeric id's of all child forums and containers. * - $forum_id: Forum id for the current forum. Parent to all items within * the $forums array. * * Each $forum in $forums contains: * - $forum->is_container: Is TRUE if the forum can contain other forums. Is * FALSE if the forum can contain only topics. * - $forum->depth: How deep the forum is in the current hierarchy. * - $forum->zebra: 'even' or 'odd' string used for row class. * - $forum->name: The name of the forum. * - $forum->link: The URL to link to this forum. * - $forum->description: The description of this forum. * - $forum->new_topics: True if the forum contains unread posts. * - $forum->new_url: A URL to the forum's unread posts. * - $forum->new_text: Text for the above URL which tells how many new posts. * - $forum->old_topics: A count of posts that have already been read. * - $forum->num_posts: The total number of posts in the forum. * - $forum->last_reply: Text representing the last time a forum was posted or * commented in. * * @see template_preprocess_forum_list() * @see theme_forum_list() */ ?> <table id="forum-<?php print $forum_id; ?>" class="forum-table forums-overview"> <thead class="forum-header"> <tr> <th class="forum-icon"></th> <th class="forum-name"><!-- <?php print t('Forum'); ?> --></th> <th class="forum-num-topics"><?php print t('Topics');?></th> <th class="forum-posts"><?php print t('Posts'); ?></th> <th class="forum-last-post"><?php print t('Last post'); ?></th> </tr> </thead> <tbody> <?php $container_adjustment = 0; ?> <?php foreach ($forums as $child_id => $forum): ?> <?php if ($forum->is_container): ?> <tr id="forum-list-<?php print $child_id; ?>" class="<?php print $forum->zebra; ?> <?php print $forum->row_classes;?> container-<?php print $forum->container_id;?>" > <td colspan="5" class="container"> <div class="forum-details"> <div class="name"> <a href="<?php print $forum->link; ?>"><?php print $forum->name; ?></a> </div> <?php if ($forum->description): ?> <div class="description"><?php print $forum->description; ?></div> <?php endif; ?> </div> </td> <?php $container_adjustment = 1; ?> </tr> <?php else: ?> <tr id="forum-list-<?php print $child_id; ?>" class="<?php print $forum->zebra; ?> <?php print $forum->row_classes;?> in-container-<?php print $forum->container_id;?>"> <?php if ($forum->depth == 0) {$container_adjustment = 0;} ?> <td class="forum-icon"> <?php print $forum->icon ?> </td> <td> <?php print str_repeat('<div class="indent">', $forum->depth - $container_adjustment); ?> <div class="forum-details"> <div class="name"><a href="<?php print $forum->link; ?>"><?php print $forum->name; ?></a></div> <?php if ($forum->description): ?> <div class="description"><?php print $forum->description; ?></div> <?php endif; ?> </div> <?php print str_repeat('</div>', $forum->depth - $container_adjustment); ?> </td> <td class="topics"> <div class="num num-topics"><?php print $forum->num_topics ?> <?php if ($forum->new_topics): ?> <div class="num num-new-topics"><a href="<?php print $forum->new_url; ?>"><?php print $forum->new_text; ?></a></div> <?php endif; ?> </div> </td> <td class="num posts"> <?php print $forum->num_posts ?> <?php if ($forum->new_posts): ?> <br /> <a href="<?php print $forum->new_url_posts; ?>"><?php print $forum->new_text_posts; ?></a> <?php endif; ?> </td> <td class="last-reply"><?php print $forum->last_reply ?></td> </tr> <?php endif; ?> <?php endforeach; ?> </tbody> </table> <?php if (!empty($forum_statistics)): ?> <?php print $forum_statistics; ?> <?php endif; ?> <?php if (!empty($forum_legend)): ?> <?php print $forum_legend; ?> <?php endif; ?>
bellcom/nextlibrary
sites/nextlibrary.net/modules/contrib/advanced_forum_more_styles/styles/minimal/advf-forum-list.tpl.php
PHP
gpl-2.0
4,617
/* MDB Tools - A library for reading MS Access database file * Copyright (C) 2000 Brian Bruns * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mdbtools.h" #ifdef DMALLOC #include "dmalloc.h" #endif static gint32 mdb_map_find_next0(MdbHandle *mdb, unsigned char *map, unsigned int map_sz, guint32 start_pg) { guint32 pgnum, i, usage_bitlen; unsigned char *usage_bitmap; pgnum = mdb_get_int32(map, 1); usage_bitmap = map + 5; usage_bitlen = (map_sz - 5) * 8; i = (start_pg >= pgnum) ? start_pg-pgnum+1 : 0; for (; i<usage_bitlen; i++) { if (usage_bitmap[i/8] & (1 << (i%8))) { return pgnum + i; } } /* didn't find anything */ return 0; } static gint32 mdb_map_find_next1(MdbHandle *mdb, unsigned char *map, unsigned int map_sz, guint32 start_pg) { guint32 map_ind, max_map_pgs, offset, usage_bitlen; /* * start_pg will tell us where to (re)start the scan * for the next data page. each usage_map entry points to a * 0x05 page which bitmaps (mdb->fmt->pg_size - 4) * 8 pages. * * map_ind gives us the starting usage_map entry * offset gives us a page offset into the bitmap */ usage_bitlen = (mdb->fmt->pg_size - 4) * 8; max_map_pgs = (map_sz - 1) / 4; map_ind = (start_pg + 1) / usage_bitlen; offset = (start_pg + 1) % usage_bitlen; for (; map_ind<max_map_pgs; map_ind++) { unsigned char *usage_bitmap; guint32 i, map_pg; if (!(map_pg = mdb_get_int32(map, (map_ind*4)+1))) { continue; } if(mdb_read_alt_pg(mdb, map_pg) != mdb->fmt->pg_size) { fprintf(stderr, "Oops! didn't get a full page at %d\n", map_pg); exit(1); } usage_bitmap = mdb->alt_pg_buf + 4; for (i=offset; i<usage_bitlen; i++) { if (usage_bitmap[i/8] & (1 << (i%8))) { return map_ind*usage_bitlen + i; } } offset = 0; } /* didn't find anything */ return 0; } /* returns 0 on EOF */ /* returns -1 on error (unsupported map type) */ gint32 mdb_map_find_next(MdbHandle *mdb, unsigned char *map, unsigned int map_sz, guint32 start_pg) { if (map[0] == 0) { return mdb_map_find_next0(mdb, map, map_sz, start_pg); } else if (map[0] == 1) { return mdb_map_find_next1(mdb, map, map_sz, start_pg); } fprintf(stderr, "Warning: unrecognized usage map type: %d\n", map[0]); return -1; } guint32 mdb_alloc_page(MdbTableDef *table) { printf("Allocating new page\n"); return 0; } guint32 mdb_map_find_next_freepage(MdbTableDef *table, int row_size) { MdbCatalogEntry *entry = table->entry; MdbHandle *mdb = entry->mdb; guint32 pgnum; guint32 cur_pg = 0; int free_space; do { pgnum = mdb_map_find_next(mdb, table->free_usage_map, table->freemap_sz, cur_pg); //printf("looking at page %d\n", pgnum); if (!pgnum) { /* allocate new page */ pgnum = mdb_alloc_page(table); return pgnum; } else if (pgnum==-1) { fprintf(stderr, "Error: mdb_map_find_next_freepage error while reading maps.\n"); exit(1); } cur_pg = pgnum; mdb_read_pg(mdb, pgnum); free_space = mdb_pg_get_freespace(mdb); } while (free_space < row_size); //printf("page %d has %d bytes left\n", pgnum, free_space); return pgnum; }
rogerswb/mdbtools
src/libmdb/map.c
C
gpl-2.0
3,800
/***************************************************************************** * * * --------------------------------- mst.c -------------------------------- * * * *****************************************************************************/ #include <float.h> #include <stdlib.h> #include "graph.h" #include "graphalg.h" #include "list.h" /***************************************************************************** * * * ---------------------------------- mst --------------------------------- * * * *****************************************************************************/ int mst(Graph *graph, const MstVertex *start, List *span, int (*match)(const void *key1, const void *key2)) { AdjList *adjlist; MstVertex *mst_vertex, *adj_vertex; ListElmt *element, *member; double minimum; int found, i; /***************************************************************************** * * * Initialize all of the vertices in the graph. * * * *****************************************************************************/ found = 0; for (element = list_head(&graph_adjlists(graph)); element != NULL; element = list_next(element)) { mst_vertex = ((AdjList *)list_data(element))->vertex; if (match(mst_vertex, start)) { /*********************************************************************** * * * Initialize the start vertex. * * * ***********************************************************************/ mst_vertex->color = white; mst_vertex->key = 0; mst_vertex->parent = NULL; found = 1; } else { /*********************************************************************** * * * Initialize vertices other than the start vertex. * * * ***********************************************************************/ mst_vertex->color = white; mst_vertex->key = DBL_MAX; mst_vertex->parent = NULL; } } /***************************************************************************** * * * Return if the start vertex was not found. * * * *****************************************************************************/ if (!found) return -1; /***************************************************************************** * * * Use Prim's algorithm to compute a minimum spanning tree. * * * *****************************************************************************/ i = 0; while (i < graph_vcount(graph)) { /************************************************************************** * * * Select the white vertex with the smallest key value. * * * **************************************************************************/ minimum = DBL_MAX; for (element = list_head(&graph_adjlists(graph)); element != NULL; element = list_next(element)) { mst_vertex = ((AdjList *)list_data(element))->vertex; if (mst_vertex->color == white && mst_vertex->key < minimum) { minimum = mst_vertex->key; adjlist = list_data(element); } } /************************************************************************** * * * Color the selected vertex black. * * * **************************************************************************/ ((MstVertex *)adjlist->vertex)->color = black; /************************************************************************** * * * Traverse each vertex adjacent to the selected vertex. * * * **************************************************************************/ for (member = list_head(&adjlist->adjacent); member != NULL; member = list_next(member)) { adj_vertex = list_data(member); /*********************************************************************** * * * Find the adjacent vertex in the list of adjacency-list structures. * * * ***********************************************************************/ for (element = list_head(&graph_adjlists(graph)); element != NULL; element = list_next(element)) { mst_vertex = ((AdjList *)list_data(element))->vertex; if (match(mst_vertex, adj_vertex)) { /***************************************************************** * * * Decide whether to change the key value and parent of the * * adjacent vertex in the list of adjacency-list structures. * * * *****************************************************************/ if (mst_vertex->color == white && adj_vertex->weight < mst_vertex->key) { mst_vertex->key = adj_vertex->weight; mst_vertex->parent = adjlist->vertex; } break; } } } /************************************************************************** * * * Prepare to select the next vertex. * * * **************************************************************************/ i++; } /***************************************************************************** * * * Load the minimum spanning tree into a list. * * * *****************************************************************************/ list_init(span, NULL); for (element = list_head(&graph_adjlists(graph)); element != NULL; element = list_next(element)) { /************************************************************************** * * * Load each black vertex from the list of adjacency-list structures. * * * **************************************************************************/ mst_vertex = ((AdjList *)list_data(element))->vertex; if (mst_vertex->color == black) { if (list_ins_next(span, list_tail(span), mst_vertex) != 0) { list_destroy(span); return -1; } } } return 0; }
karlstroetmann/Algorithms
Programme/examples/source/mst.c
C
gpl-2.0
8,409
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2009-2017, The Linux Foundation. All rights reserved. * Copyright (c) 2017-2019, Linaro Ltd. */ #include <linux/debugfs.h> #include <linux/err.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/random.h> #include <linux/slab.h> #include <linux/soc/qcom/smem.h> #include <linux/string.h> #include <linux/sys_soc.h> #include <linux/types.h> /* * SoC version type with major number in the upper 16 bits and minor * number in the lower 16 bits. */ #define SOCINFO_MAJOR(ver) (((ver) >> 16) & 0xffff) #define SOCINFO_MINOR(ver) ((ver) & 0xffff) #define SOCINFO_VERSION(maj, min) ((((maj) & 0xffff) << 16)|((min) & 0xffff)) #define SMEM_SOCINFO_BUILD_ID_LENGTH 32 #define SMEM_SOCINFO_CHIP_ID_LENGTH 32 /* * SMEM item id, used to acquire handles to respective * SMEM region. */ #define SMEM_HW_SW_BUILD_ID 137 #ifdef CONFIG_DEBUG_FS #define SMEM_IMAGE_VERSION_BLOCKS_COUNT 32 #define SMEM_IMAGE_VERSION_SIZE 4096 #define SMEM_IMAGE_VERSION_NAME_SIZE 75 #define SMEM_IMAGE_VERSION_VARIANT_SIZE 20 #define SMEM_IMAGE_VERSION_OEM_SIZE 32 /* * SMEM Image table indices */ #define SMEM_IMAGE_TABLE_BOOT_INDEX 0 #define SMEM_IMAGE_TABLE_TZ_INDEX 1 #define SMEM_IMAGE_TABLE_RPM_INDEX 3 #define SMEM_IMAGE_TABLE_APPS_INDEX 10 #define SMEM_IMAGE_TABLE_MPSS_INDEX 11 #define SMEM_IMAGE_TABLE_ADSP_INDEX 12 #define SMEM_IMAGE_TABLE_CNSS_INDEX 13 #define SMEM_IMAGE_TABLE_VIDEO_INDEX 14 #define SMEM_IMAGE_VERSION_TABLE 469 /* * SMEM Image table names */ static const char *const socinfo_image_names[] = { [SMEM_IMAGE_TABLE_ADSP_INDEX] = "adsp", [SMEM_IMAGE_TABLE_APPS_INDEX] = "apps", [SMEM_IMAGE_TABLE_BOOT_INDEX] = "boot", [SMEM_IMAGE_TABLE_CNSS_INDEX] = "cnss", [SMEM_IMAGE_TABLE_MPSS_INDEX] = "mpss", [SMEM_IMAGE_TABLE_RPM_INDEX] = "rpm", [SMEM_IMAGE_TABLE_TZ_INDEX] = "tz", [SMEM_IMAGE_TABLE_VIDEO_INDEX] = "video", }; static const char *const pmic_models[] = { [0] = "Unknown PMIC model", [9] = "PM8994", [11] = "PM8916", [13] = "PM8058", [14] = "PM8028", [15] = "PM8901", [16] = "PM8027", [17] = "ISL9519", [18] = "PM8921", [19] = "PM8018", [20] = "PM8015", [21] = "PM8014", [22] = "PM8821", [23] = "PM8038", [24] = "PM8922", [25] = "PM8917", }; #endif /* CONFIG_DEBUG_FS */ /* Socinfo SMEM item structure */ struct socinfo { __le32 fmt; __le32 id; __le32 ver; char build_id[SMEM_SOCINFO_BUILD_ID_LENGTH]; /* Version 2 */ __le32 raw_id; __le32 raw_ver; /* Version 3 */ __le32 hw_plat; /* Version 4 */ __le32 plat_ver; /* Version 5 */ __le32 accessory_chip; /* Version 6 */ __le32 hw_plat_subtype; /* Version 7 */ __le32 pmic_model; __le32 pmic_die_rev; /* Version 8 */ __le32 pmic_model_1; __le32 pmic_die_rev_1; __le32 pmic_model_2; __le32 pmic_die_rev_2; /* Version 9 */ __le32 foundry_id; /* Version 10 */ __le32 serial_num; /* Version 11 */ __le32 num_pmics; __le32 pmic_array_offset; /* Version 12 */ __le32 chip_family; __le32 raw_device_family; __le32 raw_device_num; /* Version 13 */ __le32 nproduct_id; char chip_id[SMEM_SOCINFO_CHIP_ID_LENGTH]; /* Version 14 */ __le32 num_clusters; __le32 ncluster_array_offset; __le32 num_defective_parts; __le32 ndefective_parts_array_offset; /* Version 15 */ __le32 nmodem_supported; }; #ifdef CONFIG_DEBUG_FS struct socinfo_params { u32 raw_device_family; u32 hw_plat_subtype; u32 accessory_chip; u32 raw_device_num; u32 chip_family; u32 foundry_id; u32 plat_ver; u32 raw_ver; u32 hw_plat; u32 fmt; u32 nproduct_id; u32 num_clusters; u32 ncluster_array_offset; u32 num_defective_parts; u32 ndefective_parts_array_offset; u32 nmodem_supported; }; struct smem_image_version { char name[SMEM_IMAGE_VERSION_NAME_SIZE]; char variant[SMEM_IMAGE_VERSION_VARIANT_SIZE]; char pad; char oem[SMEM_IMAGE_VERSION_OEM_SIZE]; }; #endif /* CONFIG_DEBUG_FS */ struct qcom_socinfo { struct soc_device *soc_dev; struct soc_device_attribute attr; #ifdef CONFIG_DEBUG_FS struct dentry *dbg_root; struct socinfo_params info; #endif /* CONFIG_DEBUG_FS */ }; struct soc_id { unsigned int id; const char *name; }; static const struct soc_id soc_id[] = { { 87, "MSM8960" }, { 109, "APQ8064" }, { 122, "MSM8660A" }, { 123, "MSM8260A" }, { 124, "APQ8060A" }, { 126, "MSM8974" }, { 130, "MPQ8064" }, { 138, "MSM8960AB" }, { 139, "APQ8060AB" }, { 140, "MSM8260AB" }, { 141, "MSM8660AB" }, { 178, "APQ8084" }, { 184, "APQ8074" }, { 185, "MSM8274" }, { 186, "MSM8674" }, { 194, "MSM8974PRO" }, { 206, "MSM8916" }, { 207, "MSM8994" }, { 208, "APQ8074-AA" }, { 209, "APQ8074-AB" }, { 210, "APQ8074PRO" }, { 211, "MSM8274-AA" }, { 212, "MSM8274-AB" }, { 213, "MSM8274PRO" }, { 214, "MSM8674-AA" }, { 215, "MSM8674-AB" }, { 216, "MSM8674PRO" }, { 217, "MSM8974-AA" }, { 218, "MSM8974-AB" }, { 233, "MSM8936" }, { 239, "MSM8939" }, { 240, "APQ8036" }, { 241, "APQ8039" }, { 246, "MSM8996" }, { 247, "APQ8016" }, { 248, "MSM8216" }, { 249, "MSM8116" }, { 250, "MSM8616" }, { 251, "MSM8992" }, { 253, "APQ8094" }, { 291, "APQ8096" }, { 305, "MSM8996SG" }, { 310, "MSM8996AU" }, { 311, "APQ8096AU" }, { 312, "APQ8096SG" }, { 318, "SDM630" }, { 321, "SDM845" }, { 341, "SDA845" }, { 356, "SM8250" }, { 402, "IPQ6018" }, { 425, "SC7180" }, }; static const char *socinfo_machine(struct device *dev, unsigned int id) { int idx; for (idx = 0; idx < ARRAY_SIZE(soc_id); idx++) { if (soc_id[idx].id == id) return soc_id[idx].name; } return NULL; } #ifdef CONFIG_DEBUG_FS #define QCOM_OPEN(name, _func) \ static int qcom_open_##name(struct inode *inode, struct file *file) \ { \ return single_open(file, _func, inode->i_private); \ } \ \ static const struct file_operations qcom_ ##name## _ops = { \ .open = qcom_open_##name, \ .read = seq_read, \ .llseek = seq_lseek, \ .release = single_release, \ } #define DEBUGFS_ADD(info, name) \ debugfs_create_file(__stringify(name), 0400, \ qcom_socinfo->dbg_root, \ info, &qcom_ ##name## _ops) static int qcom_show_build_id(struct seq_file *seq, void *p) { struct socinfo *socinfo = seq->private; seq_printf(seq, "%s\n", socinfo->build_id); return 0; } static int qcom_show_pmic_model(struct seq_file *seq, void *p) { struct socinfo *socinfo = seq->private; int model = SOCINFO_MINOR(le32_to_cpu(socinfo->pmic_model)); if (model < 0) return -EINVAL; if (model < ARRAY_SIZE(pmic_models) && pmic_models[model]) seq_printf(seq, "%s\n", pmic_models[model]); else seq_printf(seq, "unknown (%d)\n", model); return 0; } static int qcom_show_pmic_die_revision(struct seq_file *seq, void *p) { struct socinfo *socinfo = seq->private; seq_printf(seq, "%u.%u\n", SOCINFO_MAJOR(le32_to_cpu(socinfo->pmic_die_rev)), SOCINFO_MINOR(le32_to_cpu(socinfo->pmic_die_rev))); return 0; } static int qcom_show_chip_id(struct seq_file *seq, void *p) { struct socinfo *socinfo = seq->private; seq_printf(seq, "%s\n", socinfo->chip_id); return 0; } QCOM_OPEN(build_id, qcom_show_build_id); QCOM_OPEN(pmic_model, qcom_show_pmic_model); QCOM_OPEN(pmic_die_rev, qcom_show_pmic_die_revision); QCOM_OPEN(chip_id, qcom_show_chip_id); #define DEFINE_IMAGE_OPS(type) \ static int show_image_##type(struct seq_file *seq, void *p) \ { \ struct smem_image_version *image_version = seq->private; \ seq_puts(seq, image_version->type); \ seq_putc(seq, '\n'); \ return 0; \ } \ static int open_image_##type(struct inode *inode, struct file *file) \ { \ return single_open(file, show_image_##type, inode->i_private); \ } \ \ static const struct file_operations qcom_image_##type##_ops = { \ .open = open_image_##type, \ .read = seq_read, \ .llseek = seq_lseek, \ .release = single_release, \ } DEFINE_IMAGE_OPS(name); DEFINE_IMAGE_OPS(variant); DEFINE_IMAGE_OPS(oem); static void socinfo_debugfs_init(struct qcom_socinfo *qcom_socinfo, struct socinfo *info) { struct smem_image_version *versions; struct dentry *dentry; size_t size; int i; qcom_socinfo->dbg_root = debugfs_create_dir("qcom_socinfo", NULL); qcom_socinfo->info.fmt = __le32_to_cpu(info->fmt); debugfs_create_x32("info_fmt", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.fmt); switch (qcom_socinfo->info.fmt) { case SOCINFO_VERSION(0, 15): qcom_socinfo->info.nmodem_supported = __le32_to_cpu(info->nmodem_supported); debugfs_create_u32("nmodem_supported", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.nmodem_supported); fallthrough; case SOCINFO_VERSION(0, 14): qcom_socinfo->info.num_clusters = __le32_to_cpu(info->num_clusters); qcom_socinfo->info.ncluster_array_offset = __le32_to_cpu(info->ncluster_array_offset); qcom_socinfo->info.num_defective_parts = __le32_to_cpu(info->num_defective_parts); qcom_socinfo->info.ndefective_parts_array_offset = __le32_to_cpu(info->ndefective_parts_array_offset); debugfs_create_u32("num_clusters", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.num_clusters); debugfs_create_u32("ncluster_array_offset", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.ncluster_array_offset); debugfs_create_u32("num_defective_parts", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.num_defective_parts); debugfs_create_u32("ndefective_parts_array_offset", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.ndefective_parts_array_offset); fallthrough; case SOCINFO_VERSION(0, 13): qcom_socinfo->info.nproduct_id = __le32_to_cpu(info->nproduct_id); debugfs_create_u32("nproduct_id", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.nproduct_id); DEBUGFS_ADD(info, chip_id); fallthrough; case SOCINFO_VERSION(0, 12): qcom_socinfo->info.chip_family = __le32_to_cpu(info->chip_family); qcom_socinfo->info.raw_device_family = __le32_to_cpu(info->raw_device_family); qcom_socinfo->info.raw_device_num = __le32_to_cpu(info->raw_device_num); debugfs_create_x32("chip_family", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.chip_family); debugfs_create_x32("raw_device_family", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.raw_device_family); debugfs_create_x32("raw_device_number", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.raw_device_num); fallthrough; case SOCINFO_VERSION(0, 11): case SOCINFO_VERSION(0, 10): case SOCINFO_VERSION(0, 9): qcom_socinfo->info.foundry_id = __le32_to_cpu(info->foundry_id); debugfs_create_u32("foundry_id", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.foundry_id); fallthrough; case SOCINFO_VERSION(0, 8): case SOCINFO_VERSION(0, 7): DEBUGFS_ADD(info, pmic_model); DEBUGFS_ADD(info, pmic_die_rev); fallthrough; case SOCINFO_VERSION(0, 6): qcom_socinfo->info.hw_plat_subtype = __le32_to_cpu(info->hw_plat_subtype); debugfs_create_u32("hardware_platform_subtype", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.hw_plat_subtype); fallthrough; case SOCINFO_VERSION(0, 5): qcom_socinfo->info.accessory_chip = __le32_to_cpu(info->accessory_chip); debugfs_create_u32("accessory_chip", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.accessory_chip); fallthrough; case SOCINFO_VERSION(0, 4): qcom_socinfo->info.plat_ver = __le32_to_cpu(info->plat_ver); debugfs_create_u32("platform_version", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.plat_ver); fallthrough; case SOCINFO_VERSION(0, 3): qcom_socinfo->info.hw_plat = __le32_to_cpu(info->hw_plat); debugfs_create_u32("hardware_platform", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.hw_plat); fallthrough; case SOCINFO_VERSION(0, 2): qcom_socinfo->info.raw_ver = __le32_to_cpu(info->raw_ver); debugfs_create_u32("raw_version", 0400, qcom_socinfo->dbg_root, &qcom_socinfo->info.raw_ver); fallthrough; case SOCINFO_VERSION(0, 1): DEBUGFS_ADD(info, build_id); break; } versions = qcom_smem_get(QCOM_SMEM_HOST_ANY, SMEM_IMAGE_VERSION_TABLE, &size); for (i = 0; i < ARRAY_SIZE(socinfo_image_names); i++) { if (!socinfo_image_names[i]) continue; dentry = debugfs_create_dir(socinfo_image_names[i], qcom_socinfo->dbg_root); debugfs_create_file("name", 0400, dentry, &versions[i], &qcom_image_name_ops); debugfs_create_file("variant", 0400, dentry, &versions[i], &qcom_image_variant_ops); debugfs_create_file("oem", 0400, dentry, &versions[i], &qcom_image_oem_ops); } } static void socinfo_debugfs_exit(struct qcom_socinfo *qcom_socinfo) { debugfs_remove_recursive(qcom_socinfo->dbg_root); } #else static void socinfo_debugfs_init(struct qcom_socinfo *qcom_socinfo, struct socinfo *info) { } static void socinfo_debugfs_exit(struct qcom_socinfo *qcom_socinfo) { } #endif /* CONFIG_DEBUG_FS */ static int qcom_socinfo_probe(struct platform_device *pdev) { struct qcom_socinfo *qs; struct socinfo *info; size_t item_size; info = qcom_smem_get(QCOM_SMEM_HOST_ANY, SMEM_HW_SW_BUILD_ID, &item_size); if (IS_ERR(info)) { dev_err(&pdev->dev, "Couldn't find socinfo\n"); return PTR_ERR(info); } qs = devm_kzalloc(&pdev->dev, sizeof(*qs), GFP_KERNEL); if (!qs) return -ENOMEM; qs->attr.family = "Snapdragon"; qs->attr.machine = socinfo_machine(&pdev->dev, le32_to_cpu(info->id)); qs->attr.soc_id = devm_kasprintf(&pdev->dev, GFP_KERNEL, "%u", le32_to_cpu(info->id)); qs->attr.revision = devm_kasprintf(&pdev->dev, GFP_KERNEL, "%u.%u", SOCINFO_MAJOR(le32_to_cpu(info->ver)), SOCINFO_MINOR(le32_to_cpu(info->ver))); if (offsetof(struct socinfo, serial_num) <= item_size) qs->attr.serial_number = devm_kasprintf(&pdev->dev, GFP_KERNEL, "%u", le32_to_cpu(info->serial_num)); qs->soc_dev = soc_device_register(&qs->attr); if (IS_ERR(qs->soc_dev)) return PTR_ERR(qs->soc_dev); socinfo_debugfs_init(qs, info); /* Feed the soc specific unique data into entropy pool */ add_device_randomness(info, item_size); platform_set_drvdata(pdev, qs->soc_dev); return 0; } static int qcom_socinfo_remove(struct platform_device *pdev) { struct qcom_socinfo *qs = platform_get_drvdata(pdev); soc_device_unregister(qs->soc_dev); socinfo_debugfs_exit(qs); return 0; } static struct platform_driver qcom_socinfo_driver = { .probe = qcom_socinfo_probe, .remove = qcom_socinfo_remove, .driver = { .name = "qcom-socinfo", }, }; module_platform_driver(qcom_socinfo_driver); MODULE_DESCRIPTION("Qualcomm SoCinfo driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:qcom-socinfo");
chenshuo/linux-study
drivers/soc/qcom/socinfo.c
C
gpl-2.0
14,855
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code 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 code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * 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 work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.Color; import java.awt.DisplayMode; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; /** * @test * @bug 8019587 * @author Sergey Bylokhov * @library ../../../lib/testlibrary/ * @build ExtendedRobot * @run main IncorrectDisplayModeExitFullscreen */ public class IncorrectDisplayModeExitFullscreen { static ExtendedRobot robot; public static void main(final String[] args) { final GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment() .getScreenDevices(); if (devices.length < 2 || devices[0].getDisplayModes().length < 2 || !devices[0].isFullScreenSupported() || !devices[1].isFullScreenSupported()) { System.err.println("Testcase is not applicable"); return; } final DisplayMode defaultDM = devices[0].getDisplayMode(); final DisplayMode[] dms = devices[0].getDisplayModes(); DisplayMode nonDefaultDM = null; for (final DisplayMode dm : dms) { if (!dm.equals(defaultDM)) { nonDefaultDM = dm; break; } } if (nonDefaultDM == null) { System.err.println("Testcase is not applicable"); return; } try { robot = new ExtendedRobot(); }catch(Exception ex) { ex.printStackTrace(); throw new RuntimeException("Unexpected failure"); } final Frame frame = new Frame(); frame.setBackground(Color.GREEN); frame.setUndecorated(true); try { devices[0].setFullScreenWindow(frame); sleep(); devices[0].setDisplayMode(nonDefaultDM); sleep(); devices[1].setFullScreenWindow(frame); sleep(); if (!defaultDM.equals(devices[0].getDisplayMode())) { throw new RuntimeException("DisplayMode is not restored"); } } finally { // cleaning up devices[0].setFullScreenWindow(null); devices[1].setFullScreenWindow(null); frame.dispose(); } } private static void sleep() { robot.waitForIdle(1500); } }
shelan/jdk9-mirror
jdk/test/java/awt/GraphicsDevice/IncorrectDisplayModeExitFullscreen.java
Java
gpl-2.0
3,379
/* The following code was generated by JFlex 1.4.3 on 3/20/13 2:16 AM */ package edu.stanford.nlp.process; /** Undoes the more common cases of Penn Treebank quoting to producing * something resembling normal text. That is, it is an approximate inverse * of PTBTokenizer. * * Jan 2008: This was both made better, and some quirky weird stuff was added * so as to better handle the NIST MT08 translation system's output. * * @author Joseph Smarr * @author Christopher Manning */ class PTB2TextLexer { /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int INQUOTE = 2; public static final int YYINITIAL = 0; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\12\0\1\71\2\70\1\72\22\0\1\1\1\75\1\2\1\0\1\106"+ "\1\105\1\3\1\30\1\101\1\102\2\0\1\75\1\35\1\74\1\100"+ "\1\67\1\34\10\66\1\75\1\7\3\0\1\76\1\0\1\4\1\63"+ "\1\57\1\61\1\51\1\43\1\15\1\47\1\37\2\33\1\14\1\5"+ "\1\41\1\12\1\6\1\10\1\45\1\31\1\13\1\11\1\65\1\55"+ "\1\33\1\53\1\33\1\0\1\77\3\0\1\73\1\17\1\62\1\56"+ "\1\60\1\50\1\42\1\27\1\46\1\36\2\16\1\26\1\20\1\40"+ "\1\24\1\21\1\22\1\44\1\32\1\25\1\23\1\64\1\54\1\16"+ "\1\52\1\16\1\103\1\0\1\104\7\0\1\70\44\0\1\33\12\0"+ "\1\33\4\0\1\33\5\0\27\33\1\0\37\33\1\0\u013f\33\31\0"+ "\162\33\4\0\14\33\16\0\5\33\11\0\1\33\213\0\1\33\13\0"+ "\1\33\1\0\3\33\1\0\1\33\1\0\24\33\1\0\54\33\1\0"+ "\46\33\1\0\5\33\4\0\202\33\10\0\105\33\1\0\46\33\2\0"+ "\2\33\6\0\20\33\41\0\46\33\2\0\1\33\7\0\47\33\110\0"+ "\33\33\5\0\3\33\56\0\32\33\5\0\13\33\25\0\12\34\4\0"+ "\2\33\1\0\143\33\1\0\1\33\17\0\2\33\7\0\2\33\12\34"+ "\3\33\2\0\1\33\20\0\1\33\1\0\36\33\35\0\3\33\60\0"+ "\46\33\13\0\1\33\u0152\0\66\33\3\0\1\33\22\0\1\33\7\0"+ "\12\33\4\0\12\34\25\0\10\33\2\0\2\33\2\0\26\33\1\0"+ "\7\33\1\0\1\33\3\0\4\33\3\0\1\33\36\0\2\33\1\0"+ "\3\33\4\0\12\34\2\33\23\0\6\33\4\0\2\33\2\0\26\33"+ "\1\0\7\33\1\0\2\33\1\0\2\33\1\0\2\33\37\0\4\33"+ "\1\0\1\33\7\0\12\34\2\0\3\33\20\0\11\33\1\0\3\33"+ "\1\0\26\33\1\0\7\33\1\0\2\33\1\0\5\33\3\0\1\33"+ "\22\0\1\33\17\0\2\33\4\0\12\34\25\0\10\33\2\0\2\33"+ "\2\0\26\33\1\0\7\33\1\0\2\33\1\0\5\33\3\0\1\33"+ "\36\0\2\33\1\0\3\33\4\0\12\34\1\0\1\33\21\0\1\33"+ "\1\0\6\33\3\0\3\33\1\0\4\33\3\0\2\33\1\0\1\33"+ "\1\0\2\33\3\0\2\33\3\0\3\33\3\0\10\33\1\0\3\33"+ "\55\0\11\34\25\0\10\33\1\0\3\33\1\0\27\33\1\0\12\33"+ "\1\0\5\33\46\0\2\33\4\0\12\34\25\0\10\33\1\0\3\33"+ "\1\0\27\33\1\0\12\33\1\0\5\33\3\0\1\33\40\0\1\33"+ "\1\0\2\33\4\0\12\34\25\0\10\33\1\0\3\33\1\0\27\33"+ "\1\0\20\33\46\0\2\33\4\0\12\34\25\0\22\33\3\0\30\33"+ "\1\0\11\33\1\0\1\33\2\0\7\33\72\0\60\33\1\0\2\33"+ "\14\0\7\33\11\0\12\34\47\0\2\33\1\0\1\33\2\0\2\33"+ "\1\0\1\33\2\0\1\33\6\0\4\33\1\0\7\33\1\0\3\33"+ "\1\0\1\33\1\0\1\33\2\0\2\33\1\0\4\33\1\0\2\33"+ "\11\0\1\33\2\0\5\33\1\0\1\33\11\0\12\34\2\0\2\33"+ "\42\0\1\33\37\0\12\34\26\0\10\33\1\0\42\33\35\0\4\33"+ "\164\0\42\33\1\0\5\33\1\0\2\33\25\0\12\34\6\0\6\33"+ "\112\0\46\33\12\0\51\33\7\0\132\33\5\0\104\33\5\0\122\33"+ "\6\0\7\33\1\0\77\33\1\0\1\33\1\0\4\33\2\0\7\33"+ "\1\0\1\33\1\0\4\33\2\0\47\33\1\0\1\33\1\0\4\33"+ "\2\0\37\33\1\0\1\33\1\0\4\33\2\0\7\33\1\0\1\33"+ "\1\0\4\33\2\0\7\33\1\0\7\33\1\0\27\33\1\0\37\33"+ "\1\0\1\33\1\0\4\33\2\0\7\33\1\0\47\33\1\0\23\33"+ "\16\0\11\34\56\0\125\33\14\0\u026c\33\2\0\10\33\12\0\32\33"+ "\5\0\113\33\25\0\15\33\1\0\4\33\16\0\22\33\16\0\22\33"+ "\16\0\15\33\1\0\3\33\17\0\64\33\43\0\1\33\4\0\1\33"+ "\3\0\12\34\46\0\12\34\6\0\130\33\10\0\51\33\127\0\35\33"+ "\51\0\12\34\36\33\2\0\5\33\u038b\0\154\33\224\0\234\33\4\0"+ "\132\33\6\0\26\33\2\0\6\33\2\0\46\33\2\0\6\33\2\0"+ "\10\33\1\0\1\33\1\0\1\33\1\0\1\33\1\0\37\33\2\0"+ "\65\33\1\0\7\33\1\0\1\33\3\0\3\33\1\0\7\33\3\0"+ "\4\33\2\0\6\33\4\0\15\33\5\0\3\33\1\0\7\33\53\0"+ "\2\70\107\0\1\33\15\0\1\33\202\0\1\33\4\0\1\33\2\0"+ "\12\33\1\0\1\33\3\0\5\33\6\0\1\33\1\0\1\33\1\0"+ "\1\33\1\0\4\33\1\0\3\33\1\0\7\33\3\0\3\33\5\0"+ "\5\33\u0ebb\0\2\33\52\0\5\33\5\0\2\33\4\0\126\33\6\0"+ "\3\33\1\0\132\33\1\0\4\33\5\0\50\33\4\0\136\33\21\0"+ "\30\33\70\0\20\33\u0200\0\u19b6\33\112\0\u51a6\33\132\0\u048d\33\u0773\0"+ "\u2ba4\33\u215c\0\u012e\33\2\0\73\33\225\0\7\33\14\0\5\33\5\0"+ "\1\33\1\0\12\33\1\0\15\33\1\0\5\33\1\0\1\33\1\0"+ "\2\33\1\0\2\33\1\0\154\33\41\0\u016b\33\22\0\100\33\2\0"+ "\66\33\50\0\14\33\164\0\5\33\1\0\207\33\23\0\12\34\7\0"+ "\32\33\6\0\32\33\13\0\131\33\3\0\6\33\2\0\6\33\2\0"+ "\6\33\2\0\3\33\43\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\2\0\2\1\1\2\1\3\11\1\1\4\1\1\2\5"+ "\4\1\1\6\1\3\2\0\1\7\3\0\2\7\1\10"+ "\1\11\1\12\7\0\10\1\1\13\1\1\1\14\1\15"+ "\1\16\1\17\1\6\4\0\2\20\3\0\1\21\6\0"+ "\1\22\7\0\13\1\1\23\6\0\1\24\4\0\1\25"+ "\5\0\1\3\2\0\1\26\1\0\1\27\7\0\2\1"+ "\1\0\2\1\1\0\5\1\5\0\1\3\5\0\1\30"+ "\3\0\2\3\1\2\4\0\15\31\1\0\1\1\1\0"+ "\4\1\4\0\2\3\1\6\10\0\1\2\1\0\1\32"+ "\2\33\1\0\1\32\5\31\1\0\20\31\1\0\1\1"+ "\1\0\3\1\3\0\1\6\3\0\1\6\5\0\1\34"+ "\2\0\12\31\1\0\1\1\1\31\1\0\2\1\1\35"+ "\1\0\1\6\3\0\5\31\1\36\2\1\4\31\1\1"+ "\1\0\1\31\1\1\1\0\1\31\1\1\1\0\1\31"+ "\1\1\1\31\22\1"; private static int [] zzUnpackAction() { int [] result = new int[306]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\107\0\216\0\325\0\u011c\0\u0163\0\u01aa\0\u01f1"+ "\0\u0238\0\u027f\0\u02c6\0\u030d\0\u0354\0\u039b\0\u03e2\0\u0429"+ "\0\u0470\0\u04b7\0\u0429\0\u04fe\0\u0545\0\u058c\0\u05d3\0\u0429"+ "\0\u061a\0\u0661\0\u06a8\0\u0429\0\u06ef\0\u0736\0\u077d\0\u07c4"+ "\0\u080b\0\u0429\0\u0429\0\u0429\0\u0852\0\u0899\0\u08e0\0\u0927"+ "\0\u096e\0\u09b5\0\u09fc\0\u0a43\0\u0a8a\0\u0ad1\0\u0b18\0\u0b5f"+ "\0\u0ba6\0\u0bed\0\u0c34\0\u0429\0\u0c7b\0\u0429\0\u0429\0\u0429"+ "\0\u0429\0\u0661\0\u0cc2\0\u0d09\0\u0d50\0\u0d97\0\u0429\0\u0dde"+ "\0\u0e25\0\u0e6c\0\u0eb3\0\u0429\0\u0efa\0\u0f41\0\u0f88\0\u04b7"+ "\0\u0fcf\0\u1016\0\u0429\0\u105d\0\u10a4\0\u10eb\0\u1132\0\u1179"+ "\0\u11c0\0\u1207\0\u124e\0\u1295\0\u12dc\0\u1323\0\u136a\0\u13b1"+ "\0\u13f8\0\u143f\0\u1486\0\u14cd\0\u1514\0\u0429\0\u155b\0\u15a2"+ "\0\u15e9\0\u1630\0\u1677\0\u16be\0\u0429\0\u1705\0\u174c\0\u1793"+ "\0\u17da\0\u0429\0\u1821\0\u1868\0\u18af\0\u18f6\0\u193d\0\u1984"+ "\0\u19cb\0\u1a12\0\u0429\0\u1a59\0\u0429\0\u1aa0\0\u1ae7\0\u1b2e"+ "\0\u1b75\0\u1bbc\0\u1c03\0\u1c4a\0\u1c91\0\u1cd8\0\u1d1f\0\u1d66"+ "\0\u1dad\0\u1df4\0\u1e3b\0\u1e82\0\u1ec9\0\u1f10\0\u1f57\0\u1f9e"+ "\0\u1fe5\0\u202c\0\u2073\0\u20ba\0\u2101\0\u2148\0\u218f\0\u21d6"+ "\0\u221d\0\u2264\0\u0429\0\u22ab\0\u22f2\0\u2339\0\u2380\0\u23c7"+ "\0\u240e\0\u2455\0\u249c\0\u24e3\0\u252a\0\u2571\0\u25b8\0\u25ff"+ "\0\u2646\0\u268d\0\u26d4\0\u271b\0\u2762\0\u27a9\0\u27f0\0\u2837"+ "\0\u287e\0\u28c5\0\u290c\0\u2953\0\u299a\0\u29e1\0\u2a28\0\u2a6f"+ "\0\u2ab6\0\u2afd\0\u2b44\0\u2b8b\0\u2bd2\0\u2c19\0\u2c60\0\u2ca7"+ "\0\u2cee\0\u2d35\0\u2d7c\0\u2dc3\0\u2e0a\0\u2e51\0\u23c7\0\u2e98"+ "\0\u2edf\0\u2f26\0\u0429\0\u0429\0\u2f6d\0\u2fb4\0\u2ffb\0\u3042"+ "\0\u3089\0\u30d0\0\u3117\0\u315e\0\u2ffb\0\u31a5\0\u31ec\0\u3233"+ "\0\u327a\0\u32c1\0\u3308\0\u334f\0\u3396\0\u33dd\0\u3424\0\u346b"+ "\0\u34b2\0\u34f9\0\u3540\0\u3587\0\u35ce\0\u3615\0\u365c\0\u36a3"+ "\0\u36ea\0\u3731\0\u3778\0\u37bf\0\u3806\0\u384d\0\u3894\0\u38db"+ "\0\u2c60\0\u3922\0\u3969\0\u39b0\0\u39f7\0\u3a3e\0\u3a85\0\u3acc"+ "\0\u0429\0\u3b13\0\u3b5a\0\u3ba1\0\u3be8\0\u3c2f\0\u3c76\0\u3cbd"+ "\0\u3d04\0\u3d4b\0\u3d92\0\u3dd9\0\u3e20\0\u3e67\0\u3eae\0\u3ef5"+ "\0\u3f3c\0\u3f83\0\u3fca\0\u0429\0\u4011\0\u4058\0\u409f\0\u40e6"+ "\0\u412d\0\u4174\0\u41bb\0\u4202\0\u4249\0\u4290\0\u0429\0\u42d7"+ "\0\u431e\0\u4365\0\u43ac\0\u43f3\0\u443a\0\u4481\0\u44c8\0\u450f"+ "\0\u4556\0\u459d\0\u45e4\0\u462b\0\u4672\0\u46b9\0\u4700\0\u4672"+ "\0\u4747\0\u478e\0\u47d5\0\u481c\0\u4863\0\u48aa\0\u48f1\0\u4938"+ "\0\u497f\0\u49c6\0\u4a0d\0\u4a54\0\u4a9b\0\u4ae2\0\u4b29\0\u4b70"+ "\0\u4bb7\0\u4bfe"; private static int [] zzUnpackRowMap() { int [] result = new int[306]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\3\1\4\1\5\1\6\3\7\1\3\6\7\12\10"+ "\1\3\1\11\1\12\2\7\1\13\1\10\1\7\1\10"+ "\1\7\1\10\1\7\1\10\1\7\1\14\1\15\1\10"+ "\1\7\1\10\1\7\1\10\1\7\1\16\1\17\1\10"+ "\1\7\1\10\1\7\1\10\3\7\1\3\1\20\1\3"+ "\1\21\3\3\1\22\1\23\1\24\1\3\1\25\2\3"+ "\1\26\1\3\1\27\1\30\1\31\3\7\1\3\6\7"+ "\12\10\1\3\1\11\1\12\2\7\1\13\1\10\1\7"+ "\1\10\1\7\1\10\1\7\1\10\1\7\1\14\1\15"+ "\1\10\1\7\1\10\1\7\1\10\1\7\1\16\1\17"+ "\1\10\1\7\1\10\1\7\1\10\3\7\1\3\1\20"+ "\1\3\1\21\3\3\1\22\1\23\1\24\1\3\1\25"+ "\2\3\1\26\1\3\3\0\65\3\1\0\5\3\2\0"+ "\6\3\2\0\1\32\1\33\3\0\1\34\20\0\1\35"+ "\4\0\1\36\2\0\2\37\32\0\1\40\1\34\1\41"+ "\3\0\1\42\1\0\1\43\1\44\2\0\1\45\106\0"+ "\1\46\2\0\1\47\3\0\1\50\3\0\1\51\1\52"+ "\1\0\1\47\2\0\1\50\3\0\1\51\1\52\57\0"+ "\1\3\1\53\2\0\3\7\1\3\20\7\1\3\4\7"+ "\1\3\32\7\1\3\1\0\5\3\2\0\7\3\1\53"+ "\2\0\3\7\1\3\6\7\12\54\1\3\1\7\1\54"+ "\2\7\1\3\1\54\1\7\1\54\1\7\1\54\1\7"+ "\1\54\1\7\1\54\1\7\1\54\1\7\1\54\1\7"+ "\1\54\1\7\1\54\1\7\1\54\1\7\1\54\1\7"+ "\1\54\3\7\1\3\1\0\5\3\2\0\7\3\1\53"+ "\2\0\1\55\2\7\1\3\7\7\1\55\10\7\1\3"+ "\4\7\1\3\32\7\1\3\1\0\5\3\2\0\7\3"+ "\1\53\2\0\1\55\2\7\1\3\6\7\1\54\1\56"+ "\10\54\1\3\1\7\1\54\2\7\1\3\1\54\1\7"+ "\1\54\1\7\1\54\1\7\1\54\1\7\1\54\1\7"+ "\1\54\1\7\1\54\1\7\1\54\1\7\1\54\1\7"+ "\1\54\1\7\1\54\1\7\1\54\3\7\1\3\1\0"+ "\5\3\2\0\7\3\3\0\10\3\1\57\11\3\1\57"+ "\42\3\1\0\5\3\2\0\7\3\1\53\2\0\3\7"+ "\1\3\6\7\12\54\1\3\1\7\1\54\2\7\1\3"+ "\1\54\1\7\1\54\1\7\1\54\1\7\1\54\1\7"+ "\1\54\1\7\1\60\1\61\1\54\1\7\1\54\1\7"+ "\1\54\1\7\1\54\1\7\1\54\1\7\1\54\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\53\2\0\3\7"+ "\1\3\20\7\1\3\4\7\1\3\12\7\2\61\16\7"+ "\1\3\1\0\5\3\2\0\7\3\1\53\2\0\1\62"+ "\2\7\1\3\6\7\1\54\1\63\10\54\1\3\1\7"+ "\1\54\2\7\1\3\1\54\1\7\1\54\1\7\1\54"+ "\1\7\1\54\1\7\1\54\1\7\1\54\1\7\1\54"+ "\1\7\1\54\1\7\1\54\1\7\1\54\1\7\1\54"+ "\1\7\1\54\3\7\1\3\1\0\5\3\2\0\7\3"+ "\1\53\2\0\1\62\2\7\1\3\7\7\1\62\10\7"+ "\1\3\4\7\1\3\32\7\1\3\1\0\5\3\2\0"+ "\6\3\107\0\1\3\1\64\2\0\65\3\1\0\1\3"+ "\1\65\3\3\2\0\6\3\100\0\1\66\6\0\1\3"+ "\1\67\2\0\65\3\1\0\5\3\2\0\7\3\1\70"+ "\2\0\65\3\1\0\5\3\2\0\7\3\1\71\2\0"+ "\65\3\1\0\5\3\2\0\6\3\2\0\1\72\1\73"+ "\3\0\1\34\20\0\1\35\4\0\1\36\2\0\2\37"+ "\32\0\1\40\1\34\1\41\3\0\1\42\1\0\1\43"+ "\1\44\2\0\1\74\2\0\1\75\3\0\1\76\3\0"+ "\1\51\1\52\1\0\1\75\2\0\1\76\3\0\1\51"+ "\1\52\147\0\2\77\1\100\15\0\1\101\2\0\1\102"+ "\3\0\1\103\6\0\1\102\2\0\1\103\64\0\30\34"+ "\1\104\40\34\1\0\15\34\44\0\2\105\71\0\1\106"+ "\152\0\1\107\111\0\1\110\11\0\1\111\1\112\3\113"+ "\1\0\20\113\1\0\3\113\2\0\30\113\25\0\1\114"+ "\3\0\1\50\6\0\1\114\2\0\1\50\71\0\1\115"+ "\12\0\1\115\77\0\1\116\11\0\1\116\76\0\1\117"+ "\11\0\1\117\74\0\1\120\11\0\1\120\111\0\1\121"+ "\4\0\1\122\51\0\1\3\1\53\2\0\3\7\1\3"+ "\6\7\12\123\1\3\1\7\1\123\2\7\1\3\1\123"+ "\1\7\1\123\1\7\1\123\1\7\1\123\1\7\1\123"+ "\1\7\1\123\1\7\1\123\1\7\1\123\1\7\1\123"+ "\1\7\1\123\1\7\1\123\1\7\1\123\3\7\1\3"+ "\1\0\5\3\2\0\7\3\1\53\2\0\3\7\1\3"+ "\20\7\1\3\4\7\1\3\2\124\12\7\2\125\14\7"+ "\1\3\1\0\5\3\2\0\7\3\1\53\2\0\3\7"+ "\1\3\6\7\12\123\1\3\1\7\1\123\2\7\1\3"+ "\1\126\1\124\1\123\1\7\1\123\1\7\1\123\1\7"+ "\1\123\1\7\1\123\1\7\1\127\1\125\1\123\1\7"+ "\1\123\1\7\1\123\1\7\1\123\1\7\1\123\3\7"+ "\1\3\1\0\5\3\2\0\7\3\3\0\40\3\2\130"+ "\10\3\2\131\11\3\1\0\5\3\2\0\7\3\1\53"+ "\2\0\1\132\2\7\1\3\6\7\1\123\1\133\10\123"+ "\1\3\1\7\1\123\2\7\1\3\1\123\1\7\1\123"+ "\1\7\1\123\1\7\1\123\1\7\1\123\1\7\1\123"+ "\1\7\1\123\1\7\1\123\1\7\1\123\1\7\1\123"+ "\1\7\1\123\1\7\1\123\3\7\1\3\1\0\5\3"+ "\2\0\7\3\1\53\2\0\1\132\2\7\1\3\7\7"+ "\1\132\10\7\1\3\4\7\1\3\32\7\1\3\1\0"+ "\5\3\2\0\7\3\1\53\2\0\3\7\1\3\20\7"+ "\1\3\4\7\1\3\2\7\2\134\26\7\1\3\1\0"+ "\5\3\2\0\7\3\1\53\2\0\3\7\1\3\6\7"+ "\12\123\1\3\1\7\1\123\2\7\1\3\1\123\1\7"+ "\1\135\1\134\1\123\1\7\1\123\1\7\1\123\1\7"+ "\1\123\1\7\1\123\1\7\1\123\1\7\1\123\1\7"+ "\1\123\1\7\1\123\1\7\1\123\3\7\1\3\1\0"+ "\5\3\2\0\7\3\1\136\2\0\65\3\1\0\5\3"+ "\2\0\6\3\1\0\1\137\2\0\1\140\3\0\1\141"+ "\6\0\1\140\2\0\1\141\70\0\1\142\3\0\1\76"+ "\6\0\1\142\2\0\1\76\71\0\1\143\12\0\1\143"+ "\77\0\1\144\11\0\1\144\154\0\1\145\21\0\1\102"+ "\3\0\1\103\6\0\1\102\2\0\1\103\71\0\1\146"+ "\12\0\1\146\77\0\1\147\11\0\1\147\127\0\2\150"+ "\10\0\2\151\42\0\1\152\11\0\1\152\155\0\1\34"+ "\13\0\1\153\106\0\1\154\2\0\1\155\3\0\1\156"+ "\6\0\1\155\2\0\1\156\71\0\1\157\12\0\1\157"+ "\74\0\1\160\12\0\1\160\77\0\1\161\11\0\1\161"+ "\63\0\1\162\5\0\1\163\100\0\1\164\5\0\1\165"+ "\112\0\1\166\11\0\1\166\12\0\2\167\6\0\2\170"+ "\4\0\2\171\6\0\1\172\21\0\1\173\105\0\1\3"+ "\1\174\2\0\3\7\1\3\6\7\12\175\1\3\1\7"+ "\1\175\2\7\1\3\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\3\7\1\3\1\0\5\3\2\0\7\3"+ "\1\53\2\0\3\7\1\3\20\7\1\3\4\7\1\3"+ "\22\7\2\176\6\7\1\3\1\0\5\3\2\0\7\3"+ "\1\177\2\0\3\7\1\3\20\7\1\3\2\176\2\7"+ "\1\3\2\200\30\7\1\3\1\0\5\3\2\0\7\3"+ "\1\174\2\0\3\7\1\3\6\7\12\175\1\3\1\7"+ "\1\175\2\7\1\3\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\201\1\176\1\175"+ "\1\7\1\175\3\7\1\3\1\0\5\3\2\0\7\3"+ "\1\202\2\0\3\7\1\3\6\7\12\175\1\3\1\176"+ "\1\201\2\7\1\3\1\203\1\200\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\3\7\1\3\1\0\5\3\2\0\7\3"+ "\3\0\56\3\2\204\5\3\1\0\5\3\2\0\7\3"+ "\3\0\56\3\2\205\5\3\1\0\5\3\2\0\7\3"+ "\1\53\2\0\3\7\1\3\20\7\1\3\4\7\1\3"+ "\22\7\2\206\6\7\1\3\1\0\5\3\2\0\7\3"+ "\1\174\2\0\3\7\1\3\6\7\12\175\1\3\1\7"+ "\1\175\2\7\1\3\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\207\1\206\1\175"+ "\1\7\1\175\3\7\1\3\1\0\5\3\2\0\7\3"+ "\1\210\2\0\3\7\1\3\20\7\1\3\4\7\1\3"+ "\32\7\1\3\1\0\5\3\2\0\7\3\1\211\2\0"+ "\3\7\1\3\6\7\12\175\1\3\1\7\1\175\2\7"+ "\1\3\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\1\7\1\175\1\7\1\175\1\7\1\175\1\7\1\175"+ "\3\7\1\3\1\0\5\3\2\0\6\3\4\0\1\140"+ "\3\0\1\141\6\0\1\140\2\0\1\141\71\0\1\212"+ "\12\0\1\212\77\0\1\213\11\0\1\213\70\0\1\214"+ "\12\0\1\214\74\0\1\215\12\0\1\215\77\0\1\216"+ "\11\0\1\216\70\0\1\217\12\0\1\217\77\0\1\220"+ "\11\0\1\220\144\0\2\221\105\0\2\222\27\0\3\223"+ "\1\0\20\223\1\0\3\223\2\0\30\223\25\0\1\155"+ "\3\0\1\156\6\0\1\155\2\0\1\156\71\0\1\224"+ "\12\0\1\224\77\0\1\225\11\0\1\225\71\0\1\226"+ "\12\0\1\226\66\0\1\227\5\0\1\230\112\0\1\231"+ "\11\0\1\231\70\0\1\163\106\0\1\165\135\0\2\232"+ "\77\0\1\233\63\0\1\233\12\0\1\233\72\0\1\234"+ "\12\0\1\234\156\0\1\235\23\0\1\236\2\237\1\0"+ "\2\237\1\240\1\241\3\237\1\236\4\237\1\240\1\241"+ "\2\237\1\0\2\242\1\237\2\0\2\243\2\244\2\245"+ "\2\246\2\247\2\237\2\250\2\251\4\237\2\252\2\237"+ "\51\0\1\253\4\0\1\122\51\0\1\3\1\174\2\0"+ "\3\7\1\3\6\7\12\254\1\3\1\7\1\254\2\7"+ "\1\3\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\1\7\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\1\7\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\3\7\1\3\1\0\5\3\2\0\7\3\1\177\2\0"+ "\3\7\1\3\20\7\1\3\4\7\1\3\32\7\1\3"+ "\1\0\5\3\2\0\6\3\30\0\1\121\4\0\1\255"+ "\51\0\1\3\1\53\2\0\3\7\1\3\20\7\1\3"+ "\4\7\1\3\2\7\2\256\26\7\1\3\1\0\5\3"+ "\2\0\7\3\1\202\2\0\3\7\1\3\6\7\12\254"+ "\1\3\1\7\1\254\2\7\1\3\1\254\1\7\1\254"+ "\1\7\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\1\7\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\1\7\1\254\1\7\1\254\3\7\1\3\1\0\5\3"+ "\2\0\6\3\30\0\1\253\4\0\1\255\51\0\1\3"+ "\1\174\2\0\3\7\1\3\6\7\12\254\1\3\1\7"+ "\1\254\2\7\1\3\1\254\1\7\1\257\1\256\1\254"+ "\1\7\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\1\7\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\1\7\1\254\3\7\1\3\1\0\5\3\2\0\7\3"+ "\3\0\31\3\1\24\33\3\1\0\5\3\2\0\7\3"+ "\3\0\31\3\1\25\33\3\1\0\5\3\2\0\7\3"+ "\1\53\2\0\3\7\1\3\4\7\1\260\11\7\1\260"+ "\1\7\1\3\4\7\1\3\32\7\1\3\1\0\5\3"+ "\2\0\7\3\1\174\2\0\3\7\1\3\4\7\1\260"+ "\1\7\10\254\1\261\1\254\1\3\1\7\1\254\2\7"+ "\1\3\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\1\7\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\1\7\1\254\1\7\1\254\1\7\1\254\1\7\1\254"+ "\3\7\1\3\1\0\5\3\2\0\6\3\30\0\1\121"+ "\4\0\1\122\2\0\2\262\75\0\1\253\4\0\1\122"+ "\2\0\2\262\53\0\1\263\12\0\1\263\77\0\1\264"+ "\11\0\1\264\70\0\1\265\12\0\1\265\66\0\1\266"+ "\5\0\1\267\112\0\1\270\11\0\1\270\62\0\1\271"+ "\5\0\1\272\112\0\1\273\11\0\1\273\116\0\1\42"+ "\106\0\1\43\57\0\1\274\12\0\1\274\77\0\1\275"+ "\11\0\1\275\63\0\1\276\5\0\1\277\106\0\1\230"+ "\100\0\1\300\6\0\1\50\11\0\1\50\65\0\1\301"+ "\5\0\1\5\113\0\1\302\11\0\1\302\61\0\1\303"+ "\66\0\2\304\1\305\25\0\1\306\11\0\1\306\114\0"+ "\2\233\55\0\1\307\2\0\3\237\1\0\3\237\1\310"+ "\11\237\1\310\2\237\1\0\2\310\1\237\2\0\2\237"+ "\2\311\2\312\2\313\10\237\2\314\6\237\2\0\2\304"+ "\1\305\15\0\1\315\2\0\3\237\1\0\20\237\1\0"+ "\3\237\2\0\30\237\22\0\1\315\2\0\3\237\1\0"+ "\20\237\1\0\3\237\2\0\2\237\2\316\24\237\22\0"+ "\1\315\2\0\3\237\1\0\2\237\1\310\11\237\1\310"+ "\3\237\1\0\3\237\2\0\10\237\2\317\16\237\22\0"+ "\1\315\2\0\3\237\1\0\1\237\1\320\1\321\10\237"+ "\1\320\1\321\3\237\1\0\3\237\2\0\10\237\2\322"+ "\16\237\22\0\1\315\2\0\3\237\1\0\20\237\1\0"+ "\2\310\1\237\2\0\2\237\2\323\24\237\22\0\1\315"+ "\2\0\3\237\1\0\20\237\1\0\3\237\2\0\12\237"+ "\2\324\14\237\22\0\1\315\2\0\3\237\1\0\2\237"+ "\1\325\11\237\1\325\3\237\1\0\3\237\2\0\30\237"+ "\22\0\1\315\2\0\3\237\1\0\20\237\1\0\3\237"+ "\2\0\12\237\2\326\14\237\22\0\1\315\2\0\1\327"+ "\2\237\1\0\7\237\1\327\10\237\1\0\3\237\2\0"+ "\12\237\2\330\14\237\22\0\1\315\2\0\3\237\1\0"+ "\2\237\1\331\11\237\1\331\3\237\1\0\3\237\2\0"+ "\30\237\22\0\1\315\2\0\1\332\2\237\1\0\2\237"+ "\1\333\4\237\1\332\4\237\1\333\3\237\1\0\3\237"+ "\2\0\10\237\2\334\2\330\14\237\22\0\1\315\2\0"+ "\3\237\1\0\20\237\1\0\3\237\2\0\12\237\2\335"+ "\14\237\22\0\1\336\11\0\1\166\11\0\1\166\12\0"+ "\2\167\6\0\2\170\4\0\2\171\6\0\1\172\20\0"+ "\1\3\1\174\2\0\3\7\1\3\6\7\12\337\1\3"+ "\1\7\1\337\2\7\1\3\1\337\1\7\1\337\1\7"+ "\1\337\1\7\1\337\1\7\1\337\1\7\1\337\1\7"+ "\1\337\1\7\1\337\1\7\1\337\1\7\1\337\1\7"+ "\1\337\1\7\1\337\3\7\1\3\1\0\5\3\2\0"+ "\6\3\1\0\1\340\105\0\1\3\1\53\2\0\3\7"+ "\1\3\5\7\1\176\11\7\1\176\1\3\4\7\1\3"+ "\32\7\1\3\1\0\5\3\2\0\7\3\1\174\2\0"+ "\3\7\1\3\5\7\1\176\11\337\1\341\1\3\1\7"+ "\1\337\2\7\1\3\1\337\1\7\1\337\1\7\1\337"+ "\1\7\1\337\1\7\1\337\1\7\1\337\1\7\1\337"+ "\1\7\1\337\1\7\1\337\1\7\1\337\1\7\1\337"+ "\1\7\1\337\3\7\1\3\1\0\5\3\2\0\7\3"+ "\1\53\2\0\3\7\1\3\20\7\1\3\4\7\1\3"+ "\2\342\30\7\1\3\1\0\5\3\2\0\7\3\1\174"+ "\2\0\3\7\1\3\6\7\12\337\1\3\1\7\1\337"+ "\2\7\1\3\1\343\1\342\1\337\1\7\1\337\1\7"+ "\1\337\1\7\1\337\1\7\1\337\1\7\1\337\1\7"+ "\1\337\1\7\1\337\1\7\1\337\1\7\1\337\1\7"+ "\1\337\3\7\1\3\1\0\5\3\2\0\6\3\12\0"+ "\1\344\11\0\1\344\63\0\1\345\5\0\1\346\112\0"+ "\1\347\11\0\1\347\62\0\1\350\5\0\1\351\106\0"+ "\1\267\100\0\1\352\6\0\1\76\11\0\1\76\65\0"+ "\1\353\5\0\1\30\106\0\1\272\100\0\1\354\6\0"+ "\1\103\11\0\1\103\65\0\1\355\5\0\1\32\60\0"+ "\2\77\1\100\15\0\1\356\5\0\1\357\112\0\1\360"+ "\11\0\1\360\70\0\1\277\107\0\1\50\11\0\1\50"+ "\65\0\1\45\1\111\1\112\3\113\1\5\20\113\1\0"+ "\3\113\2\0\30\113\22\0\1\303\12\0\1\233\11\0"+ "\1\233\41\0\2\304\1\305\105\0\1\361\46\0\2\362"+ "\111\0\1\363\52\0\1\307\2\0\3\237\1\0\20\237"+ "\1\0\3\237\2\0\30\237\2\0\2\304\1\305\15\0"+ "\1\315\2\0\3\237\1\0\20\237\1\0\3\237\2\0"+ "\22\237\2\310\4\237\22\0\1\315\2\0\2\237\1\310"+ "\1\0\3\237\1\364\5\237\1\310\3\237\1\364\2\237"+ "\1\0\3\237\2\0\30\237\22\0\1\315\2\0\3\237"+ "\1\0\20\237\1\0\3\237\2\0\12\237\2\310\14\237"+ "\22\0\1\315\2\0\3\237\1\0\20\237\1\0\3\237"+ "\2\0\20\237\2\365\6\237\22\0\1\307\2\0\3\237"+ "\1\0\20\237\1\0\3\237\2\0\12\237\2\310\14\237"+ "\2\0\2\304\1\305\15\0\1\315\2\0\1\366\2\237"+ "\1\0\1\237\1\332\1\367\4\237\1\366\3\237\1\332"+ "\1\367\3\237\1\0\3\237\2\0\2\332\10\237\2\370"+ "\14\237\22\0\1\315\2\0\3\237\1\0\20\237\1\0"+ "\3\237\2\0\20\237\2\371\6\237\22\0\1\307\2\0"+ "\1\237\1\313\1\237\1\0\10\237\1\313\7\237\1\0"+ "\3\237\2\0\30\237\2\0\2\304\1\305\15\0\1\315"+ "\2\0\3\237\1\0\2\237\1\333\11\237\1\333\3\237"+ "\1\0\3\237\2\0\12\237\2\310\14\237\22\0\1\307"+ "\2\0\3\237\1\0\20\237\1\0\3\237\2\0\20\237"+ "\2\372\6\237\2\0\2\304\1\305\15\0\1\315\2\0"+ "\3\237\1\0\20\237\1\0\3\237\2\0\16\237\2\332"+ "\10\237\22\0\1\315\2\0\3\237\1\0\20\237\1\0"+ "\3\237\2\0\6\237\2\310\20\237\22\0\1\315\2\0"+ "\3\237\1\0\1\237\1\373\11\237\1\373\4\237\1\0"+ "\3\237\2\0\30\237\22\0\1\315\2\0\3\237\1\0"+ "\20\237\1\0\2\310\1\237\2\0\26\237\2\313\22\0"+ "\1\307\2\0\3\237\1\0\20\237\1\0\3\237\2\0"+ "\6\237\2\313\20\237\2\0\2\304\1\305\15\0\1\315"+ "\2\0\3\237\1\0\1\237\1\310\11\237\1\310\4\237"+ "\1\0\3\237\2\0\30\237\22\0\1\315\2\0\3\237"+ "\1\0\20\237\1\0\2\310\1\237\2\0\30\237\22\0"+ "\1\315\2\0\3\237\1\0\1\237\1\374\11\237\1\374"+ "\4\237\1\0\3\237\2\0\30\237\22\0\1\315\2\0"+ "\3\237\1\0\2\237\1\310\11\237\1\310\3\237\1\0"+ "\3\237\2\0\2\320\26\237\22\0\1\315\2\0\3\237"+ "\1\0\20\237\1\0\3\237\2\0\4\237\2\375\22\237"+ "\52\0\2\376\54\0\1\3\1\174\2\0\3\7\1\3"+ "\6\7\12\377\1\3\1\7\1\377\2\7\1\3\1\377"+ "\1\7\1\377\1\7\1\377\1\7\1\377\1\7\1\377"+ "\1\7\1\377\1\7\1\377\1\7\1\377\1\7\1\377"+ "\1\7\1\377\1\7\1\377\1\7\1\377\3\7\1\3"+ "\1\0\5\3\2\0\6\3\4\0\3\u0100\1\0\20\u0100"+ "\1\0\3\u0100\1\u0101\1\0\30\u0100\2\u0101\17\0\1\3"+ "\1\202\2\0\3\7\1\3\6\7\12\377\1\3\1\7"+ "\1\377\2\7\1\3\1\377\1\7\1\377\1\7\1\377"+ "\1\7\1\377\1\7\1\377\1\7\1\377\1\7\1\377"+ "\1\7\1\377\1\7\1\377\1\7\1\377\1\7\1\377"+ "\1\7\1\377\3\7\1\3\1\0\5\3\2\0\7\3"+ "\1\53\2\0\3\7\1\3\20\7\1\3\4\7\1\3"+ "\2\7\2\u0102\26\7\1\3\1\0\5\3\2\0\7\3"+ "\1\174\2\0\3\7\1\3\6\7\12\377\1\3\1\7"+ "\1\377\2\7\1\3\1\377\1\7\1\u0103\1\u0102\1\377"+ "\1\7\1\377\1\7\1\377\1\7\1\377\1\7\1\377"+ "\1\7\1\377\1\7\1\377\1\7\1\377\1\7\1\377"+ "\1\7\1\377\3\7\1\3\1\0\5\3\2\0\6\3"+ "\13\0\1\u0104\11\0\1\u0104\70\0\1\346\100\0\1\u0105"+ "\6\0\1\141\11\0\1\141\65\0\1\u0106\5\0\1\72"+ "\60\0\2\77\1\100\23\0\1\351\107\0\1\76\11\0"+ "\1\76\73\0\1\30\107\0\1\103\11\0\1\103\73\0"+ "\1\32\60\0\2\77\1\100\23\0\1\357\100\0\1\u0107"+ "\6\0\1\156\11\0\1\156\65\0\1\u0108\5\0\1\111"+ "\147\0\2\233\36\0\1\u0109\106\0\1\315\2\0\3\237"+ "\1\0\20\237\1\0\3\237\2\0\12\237\2\325\14\237"+ "\22\0\1\315\2\0\3\237\1\0\2\237\1\u010a\11\237"+ "\1\u010a\3\237\1\0\3\237\2\0\30\237\22\0\1\315"+ "\2\0\3\237\1\0\3\237\1\310\11\237\1\310\2\237"+ "\1\0\3\237\2\0\30\237\22\0\1\315\2\0\3\237"+ "\1\0\20\237\1\0\2\313\1\237\2\0\30\237\22\0"+ "\1\307\2\0\3\237\1\0\20\237\1\0\2\313\1\237"+ "\2\0\6\237\2\u010b\4\237\2\310\12\237\2\0\2\304"+ "\1\305\15\0\1\315\2\0\3\237\1\0\20\237\1\0"+ "\3\237\2\0\10\237\2\310\16\237\22\0\1\315\2\0"+ "\3\237\1\0\4\237\1\u010c\11\237\1\u010c\1\237\1\0"+ "\3\237\2\0\30\237\22\0\1\315\2\0\3\237\1\0"+ "\3\237\1\u010d\11\237\1\u010d\2\237\1\0\3\237\2\0"+ "\30\237\22\0\1\315\2\0\3\237\1\0\4\237\1\311"+ "\11\237\1\311\1\237\1\0\3\237\2\0\30\237\22\0"+ "\1\315\2\0\3\237\1\0\2\237\1\u010e\11\237\1\u010e"+ "\3\237\1\0\3\237\2\0\30\237\22\0\1\u010f\105\0"+ "\1\3\1\174\2\0\3\7\1\3\6\7\12\u0110\1\3"+ "\1\7\1\u0110\2\7\1\3\1\u0110\1\7\1\u0110\1\7"+ "\1\u0110\1\7\1\u0110\1\7\1\u0110\1\7\1\u0110\1\7"+ "\1\u0110\1\7\1\u0110\1\7\1\u0110\1\7\1\u0110\1\7"+ "\1\u0110\1\7\1\u0110\3\7\1\3\1\0\5\3\2\0"+ "\6\3\1\0\1\307\2\0\3\u0100\1\0\20\u0100\1\0"+ "\3\u0100\1\u0101\1\0\30\u0100\2\u0101\2\304\1\305\15\0"+ "\1\303\2\0\3\u0101\1\0\20\u0101\1\0\4\u0101\1\0"+ "\32\u0101\2\304\1\305\14\0\1\3\1\53\2\0\3\7"+ "\1\3\20\7\1\3\4\7\1\3\12\7\2\176\16\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0110\1\3\1\7\1\u0110\2\7\1\3"+ "\1\u0110\1\7\1\u0110\1\7\1\u0110\1\7\1\u0110\1\7"+ "\1\u0110\1\7\1\u0111\1\176\1\u0110\1\7\1\u0110\1\7"+ "\1\u0110\1\7\1\u0110\1\7\1\u0110\1\7\1\u0110\3\7"+ "\1\3\1\0\5\3\2\0\6\3\10\0\1\141\11\0"+ "\1\141\73\0\1\72\60\0\2\77\1\100\24\0\1\156"+ "\11\0\1\156\65\0\1\153\2\0\3\223\1\111\20\223"+ "\1\0\3\223\2\0\30\223\25\0\3\u0112\1\0\20\u0112"+ "\1\0\3\u0112\2\0\30\u0112\22\0\1\315\2\0\3\237"+ "\1\0\20\237\1\0\3\237\2\0\6\237\2\u0113\20\237"+ "\22\0\1\315\2\0\3\237\1\0\20\237\1\0\3\237"+ "\2\0\12\237\2\u0114\14\237\22\0\1\315\2\0\3\237"+ "\1\0\1\237\1\u0113\11\237\1\u0113\4\237\1\0\3\237"+ "\2\0\30\237\22\0\1\315\2\0\3\237\1\0\20\237"+ "\1\0\3\237\2\0\12\237\2\u0115\14\237\22\0\1\315"+ "\2\0\3\237\1\0\20\237\1\0\3\237\2\0\6\237"+ "\2\313\20\237\21\0\1\3\1\174\2\0\3\7\1\3"+ "\6\7\12\u0116\1\3\1\7\1\u0116\2\7\1\3\1\u0116"+ "\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116"+ "\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116"+ "\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116\3\7\1\3"+ "\1\0\5\3\2\0\7\3\1\202\2\0\3\7\1\3"+ "\6\7\12\u0116\1\3\1\7\1\u0116\2\7\1\3\1\u0116"+ "\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116"+ "\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116"+ "\1\7\1\u0116\1\7\1\u0116\1\7\1\u0116\3\7\1\3"+ "\1\0\5\3\2\0\6\3\1\0\1\u0117\2\0\3\u0112"+ "\1\0\20\u0112\1\0\3\u0112\2\0\30\u0112\22\0\1\315"+ "\2\0\3\237\1\0\20\237\1\0\3\237\2\0\22\237"+ "\2\u0118\4\237\22\0\1\307\2\0\3\237\1\0\20\237"+ "\1\0\3\237\2\0\4\237\2\375\22\237\2\0\2\304"+ "\1\305\15\0\1\315\2\0\3\237\1\0\20\237\1\0"+ "\3\237\2\0\6\237\2\332\20\237\21\0\1\3\1\174"+ "\2\0\3\7\1\3\6\7\12\u0119\1\3\1\7\1\u0119"+ "\2\7\1\3\1\u0119\1\7\1\u0119\1\7\1\u0119\1\7"+ "\1\u0119\1\7\1\u0119\1\7\1\u0119\1\7\1\u0119\1\7"+ "\1\u0119\1\7\1\u0119\1\7\1\u0119\1\7\1\u0119\1\7"+ "\1\u0119\3\7\1\3\1\0\5\3\2\0\6\3\35\0"+ "\1\u011a\52\0\1\315\2\0\3\237\1\0\20\237\1\0"+ "\3\237\2\0\2\u011b\26\237\21\0\1\3\1\174\2\0"+ "\3\7\1\3\6\7\12\u011c\1\3\1\7\1\u011c\2\7"+ "\1\3\1\u011c\1\7\1\u011c\1\7\1\u011c\1\7\1\u011c"+ "\1\7\1\u011c\1\7\1\u011c\1\7\1\u011c\1\7\1\u011c"+ "\1\7\1\u011c\1\7\1\u011c\1\7\1\u011c\1\7\1\u011c"+ "\3\7\1\3\1\0\5\3\2\0\6\3\1\0\1\u011d"+ "\106\0\1\315\2\0\3\237\1\0\20\237\1\0\3\237"+ "\2\0\2\237\2\u011e\24\237\21\0\1\3\1\174\2\0"+ "\3\7\1\3\6\7\12\u011f\1\3\1\7\1\u011f\2\7"+ "\1\3\1\u011f\1\7\1\u011f\1\7\1\u011f\1\7\1\u011f"+ "\1\7\1\u011f\1\7\1\u011f\1\7\1\u011f\1\7\1\u011f"+ "\1\7\1\u011f\1\7\1\u011f\1\7\1\u011f\1\7\1\u011f"+ "\3\7\1\3\1\0\5\3\2\0\6\3\4\0\3\u0120"+ "\1\0\20\u0120\1\0\3\u0120\2\0\30\u0120\22\0\1\315"+ "\2\0\3\237\1\0\5\237\1\310\11\237\1\310\1\0"+ "\3\237\2\0\30\237\21\0\1\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0121\1\3\1\7\1\u0121\2\7\1\3"+ "\1\u0121\1\7\1\u0121\1\7\1\u0121\1\7\1\u0121\1\7"+ "\1\u0121\1\7\1\u0121\1\7\1\u0121\1\7\1\u0121\1\7"+ "\1\u0121\1\7\1\u0121\1\7\1\u0121\1\7\1\u0121\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0122\1\3\1\7\1\u0122\2\7\1\3"+ "\1\u0122\1\7\1\u0122\1\7\1\u0122\1\7\1\u0122\1\7"+ "\1\u0122\1\7\1\u0122\1\7\1\u0122\1\7\1\u0122\1\7"+ "\1\u0122\1\7\1\u0122\1\7\1\u0122\1\7\1\u0122\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0123\1\3\1\7\1\u0123\2\7\1\3"+ "\1\u0123\1\7\1\u0123\1\7\1\u0123\1\7\1\u0123\1\7"+ "\1\u0123\1\7\1\u0123\1\7\1\u0123\1\7\1\u0123\1\7"+ "\1\u0123\1\7\1\u0123\1\7\1\u0123\1\7\1\u0123\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0124\1\3\1\7\1\u0124\2\7\1\3"+ "\1\u0124\1\7\1\u0124\1\7\1\u0124\1\7\1\u0124\1\7"+ "\1\u0124\1\7\1\u0124\1\7\1\u0124\1\7\1\u0124\1\7"+ "\1\u0124\1\7\1\u0124\1\7\1\u0124\1\7\1\u0124\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0125\1\3\1\7\1\u0125\2\7\1\3"+ "\1\u0125\1\7\1\u0125\1\7\1\u0125\1\7\1\u0125\1\7"+ "\1\u0125\1\7\1\u0125\1\7\1\u0125\1\7\1\u0125\1\7"+ "\1\u0125\1\7\1\u0125\1\7\1\u0125\1\7\1\u0125\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0126\1\3\1\7\1\u0126\2\7\1\3"+ "\1\u0126\1\7\1\u0126\1\7\1\u0126\1\7\1\u0126\1\7"+ "\1\u0126\1\7\1\u0126\1\7\1\u0126\1\7\1\u0126\1\7"+ "\1\u0126\1\7\1\u0126\1\7\1\u0126\1\7\1\u0126\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0127\1\3\1\7\1\u0127\2\7\1\3"+ "\1\u0127\1\7\1\u0127\1\7\1\u0127\1\7\1\u0127\1\7"+ "\1\u0127\1\7\1\u0127\1\7\1\u0127\1\7\1\u0127\1\7"+ "\1\u0127\1\7\1\u0127\1\7\1\u0127\1\7\1\u0127\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0128\1\3\1\7\1\u0128\2\7\1\3"+ "\1\u0128\1\7\1\u0128\1\7\1\u0128\1\7\1\u0128\1\7"+ "\1\u0128\1\7\1\u0128\1\7\1\u0128\1\7\1\u0128\1\7"+ "\1\u0128\1\7\1\u0128\1\7\1\u0128\1\7\1\u0128\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0129\1\3\1\7\1\u0129\2\7\1\3"+ "\1\u0129\1\7\1\u0129\1\7\1\u0129\1\7\1\u0129\1\7"+ "\1\u0129\1\7\1\u0129\1\7\1\u0129\1\7\1\u0129\1\7"+ "\1\u0129\1\7\1\u0129\1\7\1\u0129\1\7\1\u0129\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u012a\1\3\1\7\1\u012a\2\7\1\3"+ "\1\u012a\1\7\1\u012a\1\7\1\u012a\1\7\1\u012a\1\7"+ "\1\u012a\1\7\1\u012a\1\7\1\u012a\1\7\1\u012a\1\7"+ "\1\u012a\1\7\1\u012a\1\7\1\u012a\1\7\1\u012a\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u012b\1\3\1\7\1\u012b\2\7\1\3"+ "\1\u012b\1\7\1\u012b\1\7\1\u012b\1\7\1\u012b\1\7"+ "\1\u012b\1\7\1\u012b\1\7\1\u012b\1\7\1\u012b\1\7"+ "\1\u012b\1\7\1\u012b\1\7\1\u012b\1\7\1\u012b\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u012c\1\3\1\7\1\u012c\2\7\1\3"+ "\1\u012c\1\7\1\u012c\1\7\1\u012c\1\7\1\u012c\1\7"+ "\1\u012c\1\7\1\u012c\1\7\1\u012c\1\7\1\u012c\1\7"+ "\1\u012c\1\7\1\u012c\1\7\1\u012c\1\7\1\u012c\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u012d\1\3\1\7\1\u012d\2\7\1\3"+ "\1\u012d\1\7\1\u012d\1\7\1\u012d\1\7\1\u012d\1\7"+ "\1\u012d\1\7\1\u012d\1\7\1\u012d\1\7\1\u012d\1\7"+ "\1\u012d\1\7\1\u012d\1\7\1\u012d\1\7\1\u012d\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u012e\1\3\1\7\1\u012e\2\7\1\3"+ "\1\u012e\1\7\1\u012e\1\7\1\u012e\1\7\1\u012e\1\7"+ "\1\u012e\1\7\1\u012e\1\7\1\u012e\1\7\1\u012e\1\7"+ "\1\u012e\1\7\1\u012e\1\7\1\u012e\1\7\1\u012e\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u012f\1\3\1\7\1\u012f\2\7\1\3"+ "\1\u012f\1\7\1\u012f\1\7\1\u012f\1\7\1\u012f\1\7"+ "\1\u012f\1\7\1\u012f\1\7\1\u012f\1\7\1\u012f\1\7"+ "\1\u012f\1\7\1\u012f\1\7\1\u012f\1\7\1\u012f\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0130\1\3\1\7\1\u0130\2\7\1\3"+ "\1\u0130\1\7\1\u0130\1\7\1\u0130\1\7\1\u0130\1\7"+ "\1\u0130\1\7\1\u0130\1\7\1\u0130\1\7\1\u0130\1\7"+ "\1\u0130\1\7\1\u0130\1\7\1\u0130\1\7\1\u0130\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0131\1\3\1\7\1\u0131\2\7\1\3"+ "\1\u0131\1\7\1\u0131\1\7\1\u0131\1\7\1\u0131\1\7"+ "\1\u0131\1\7\1\u0131\1\7\1\u0131\1\7\1\u0131\1\7"+ "\1\u0131\1\7\1\u0131\1\7\1\u0131\1\7\1\u0131\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\6\7\12\u0132\1\3\1\7\1\u0132\2\7\1\3"+ "\1\u0132\1\7\1\u0132\1\7\1\u0132\1\7\1\u0132\1\7"+ "\1\u0132\1\7\1\u0132\1\7\1\u0132\1\7\1\u0132\1\7"+ "\1\u0132\1\7\1\u0132\1\7\1\u0132\1\7\1\u0132\3\7"+ "\1\3\1\0\5\3\2\0\7\3\1\174\2\0\3\7"+ "\1\3\20\7\1\3\4\7\1\3\32\7\1\3\1\0"+ "\5\3\2\0\6\3"; private static int [] zzUnpackTrans() { int [] result = new int[19525]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\2\0\15\1\1\11\2\1\1\11\4\1\1\11\1\1"+ "\2\0\1\11\3\0\2\1\3\11\7\0\10\1\1\11"+ "\1\1\4\11\1\1\4\0\1\11\1\1\3\0\1\11"+ "\6\0\1\11\7\0\13\1\1\11\6\0\1\11\4\0"+ "\1\11\5\0\1\1\2\0\1\11\1\0\1\11\7\0"+ "\2\1\1\0\2\1\1\0\5\1\5\0\1\1\5\0"+ "\1\11\3\0\3\1\4\0\15\1\1\0\1\1\1\0"+ "\4\1\4\0\3\1\10\0\1\1\1\0\2\11\1\1"+ "\1\0\6\1\1\0\20\1\1\0\1\1\1\0\3\1"+ "\3\0\1\1\3\0\1\1\5\0\1\11\2\0\12\1"+ "\1\0\2\1\1\0\2\1\1\11\1\0\1\1\3\0"+ "\5\1\1\11\7\1\1\0\2\1\1\0\2\1\1\0"+ "\25\1"; private static int [] zzUnpackAttribute() { int [] result = new int[306]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the input device */ private java.io.Reader zzReader; /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** number of newlines encountered up to the start of the matched text */ private int yyline; /** the number of characters up to the start of the matched text */ private int yychar; /** * the number of characters from the last newline up to the start of the * matched text */ private int yycolumn; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; /* user code: */ /* "'T WAS" { return("'TWAS"); } "'T was" { return("'Twas"); } "'t was" { return("'twas"); } "'T IS" { return("'TIS"); } "'T is" { return("'Tis"); } "'t is" { return("'tis"); } */ private static String removeWhite(String in) { StringBuilder out = new StringBuilder(); for (int i = 0, len = in.length(); i < len; i++) { char ch = in.charAt(i); if (ch != ' ') { out.append(ch); } } return out.toString(); } /** * Creates a new scanner * There is also a java.io.InputStream version of this constructor. * * @param in the java.io.Reader to read input from. */ PTB2TextLexer(java.io.Reader in) { this.zzReader = in; } /** * Creates a new scanner. * There is also java.io.Reader version of this constructor. * * @param in the java.io.Inputstream to read input from. */ PTB2TextLexer(java.io.InputStream in) { this(new java.io.InputStreamReader(in)); } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 1348) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } /** * Refills the input buffer. * * @return <code>false</code>, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead > 0) { zzEndRead+= numRead; return false; } // unlikely but not impossible: read 0 characters, but not at end of stream if (numRead == 0) { int c = zzReader.read(); if (c == -1) { return true; } else { zzBuffer[zzEndRead++] = (char) c; return false; } } // numRead < 0 return true; } /** * Closes the input stream. */ public final void yyclose() throws java.io.IOException { zzAtEOF = true; /* indicate end of file */ zzEndRead = zzStartRead; /* invalidate buffer */ if (zzReader != null) zzReader.close(); } /** * Resets the scanner to read from a new input stream. * Does not close the old reader. * * All internal variables are reset, the old input stream * <b>cannot</b> be reused (internal buffer is discarded and lost). * Lexical state is set to <tt>ZZ_INITIAL</tt>. * * @param reader the new input stream */ public final void yyreset(java.io.Reader reader) { zzReader = reader; zzAtBOL = true; zzAtEOF = false; zzEOFDone = false; zzEndRead = zzStartRead = 0; zzCurrentPos = zzMarkedPos = 0; yyline = yychar = yycolumn = 0; zzLexicalState = YYINITIAL; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final String yytext() { return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer[zzStartRead+pos]; } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public String next() throws java.io.IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; char [] zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferL[zzCurrentPosL++]; else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = zzBufferL[zzCurrentPosL++]; } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 21: { return("n't"); } case 31: break; case 28: // lookahead expression with fixed lookahead length yypushback(2); { return yytext(); } case 32: break; case 27: // lookahead expression with fixed lookahead length yypushback(1); { return yytext(); } case 33: break; case 26: // lookahead expression with fixed lookahead length yypushback(1); { return yytext(); } case 34: break; case 12: { return "/"; } case 35: break; case 5: { return yytext(); } case 36: break; case 3: { return "&"; } case 37: break; case 6: { yybegin(YYINITIAL); return "\""; } case 38: break; case 13: { return "("; } case 39: break; case 8: { return(")"); } case 40: break; case 22: { return "<"; } case 41: break; case 23: { return ">"; } case 42: break; case 29: { return "cannot"; } case 43: break; case 1: { return(yytext()); } case 44: break; case 20: // lookahead expression with fixed lookahead length yypushback(2); { return "\""; } case 45: break; case 16: // lookahead expression with fixed lookahead length yypushback(1); { return "\""; } case 46: break; case 17: { return "\""; } case 47: break; case 11: { return("`"); } case 48: break; case 14: { return("{"); } case 49: break; case 19: { return("\""); } case 50: break; case 15: { return("$"); } case 51: break; case 7: { return(yytext().substring(1, yytext().length())); } case 52: break; case 24: // lookahead expression with fixed lookahead length yypushback(1); { yybegin(INQUOTE); return "\" \""; } case 53: break; case 10: { return("%"); } case 54: break; case 4: { yybegin(YYINITIAL); return(yytext()); } case 55: break; case 9: { return("}"); } case 56: break; case 30: // lookahead expression with fixed lookahead length yypushback(1); { return removeWhite(yytext()); } case 57: break; case 25: { return removeWhite(yytext()); } case 58: break; case 18: // lookahead expression with fixed lookahead length yypushback(1); { yybegin(INQUOTE); return "\""; } case 59: break; case 2: { yybegin(INQUOTE); return "\""; } case 60: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; { return null; } } else { zzScanError(ZZ_NO_MATCH); } } } } }
paulirwin/Stanford.NER.Net
stanford-ner-3.2.0-sources/edu/stanford/nlp/process/PTB2TextLexer.java
Java
gpl-2.0
49,996
<?php /* * This file is part of EC-CUBE * * Copyright(c) 2000-2013 LOCKON CO.,LTD. All Rights Reserved. * * http://www.lockon.co.jp/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ require_once CLASS_REALDIR . 'db/dbfactory/SC_DB_DBFactory_MYSQL.php'; /** * MySQL 固有の処理をするクラス(拡張). * * SC_DB_DBFactory_MYSQL をカスタマイズする場合は, このクラスを使用する. * * @package DB * @author LOCKON CO.,LTD. * @version $Id: SC_DB_DBFactory_MYSQL_Ex.php 22856 2013-06-08 07:35:27Z Seasoft $ */ class SC_DB_DBFactory_MYSQL_Ex extends SC_DB_DBFactory_MYSQL { }
kazuma-fujita/taheebo-ec
data/class_extends/db_extends/dbfactory/SC_DB_DBFactory_MYSQL_Ex.php
PHP
gpl-2.0
1,284
/******************************************************************************* * * This confidential and proprietary software may be used only as * authorised by a licensing agreement from CORERIVER Semiconductor Co., Ltd. * * If you change and distribute this Program, you are obligated to report * the details of the change to CORERIVER Semiconductor Co., Ltd. byrequest. * * (c) Copyright 2013 CORERIVER Semiconductor Co., Ltd. * All Rights Reserved * * The entire notice above must be reproduced on all authorised * copies and copies may only be made to the extent permitted * by a licensing agreement from CORERIVER Semiconductor Co., Ltd. * * ------------------------------------------------------------------------------ * * FILE : cr_tk_300k.c * AUTHOR : CORERIVER * DESCRIPTION : Demo Board Code for Touch Key Device Driver * VERSION : 2013 11/22 * * History : * 2013/11/28 : Modified for 4-key machine. * 2013/11/26 : Added Power Managerment Func. (Suspend/Resume) * 2013/11/22 : TC300K 1'st Release Driver Code * : add ISP Upgrade *******************************************************************************/ #include <linux/device.h> #include <linux/init.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/irq.h> #include <linux/slab.h> #include <linux/hrtimer.h> #include <asm/unaligned.h> #include <linux/delay.h> #include <linux/fs.h> #include <linux/gpio.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/string.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <asm/io.h> #include <linux/pm.h> #include <linux/miscdevice.h> #include <linux/leds.h> #include <asm/uaccess.h> #include <linux/input/cr_tk_300k.h> #include "cr_tk_fw.h" #include <linux/powersuspend.h> static struct power_suspend tk_suspend; /* -------------------------------------------------------------------- */ /* debug option */ /* -------------------------------------------------------------------- */ #define PAN_TOUCH_TM_DEBUG_OPERATION_ERR_MASK 0x00000001 #define PAN_TOUCH_TM_DEBUG_OPERATION_MASK 0x00000002 #define PAN_TOUCH_TM_DEBUG_FIRMWARE_MASK 0x00000004 #define PAN_TOUCH_TM_DEBUG_LED_MASK 0x00000004 #define PAN_TOUCH_TM_DEBUG_ALL_MASK 0x00000007 static int pan_tm_debug_state = PAN_TOUCH_TM_DEBUG_OPERATION_ERR_MASK; #define dbg_cr(fmt, args...) printk("[+++ TM] " fmt, ##args); #define dbg_op_err(fmt,args...) if(pan_tm_debug_state & PAN_TOUCH_TM_DEBUG_OPERATION_ERR_MASK) printk("[+++ TM] " fmt,##args); #define dbg_op(fmt,args...) if(pan_tm_debug_state & PAN_TOUCH_TM_DEBUG_OPERATION_MASK) printk("[+++ TM] " fmt,##args); #define dbg_firmw(fmt,args...) if(pan_tm_debug_state & PAN_TOUCH_TM_DEBUG_FIRMWARE_MASK) printk("[+++ TM] " fmt,##args); #define dbg_led(fmt,args...) if(pan_tm_debug_state & PAN_TOUCH_TM_DEBUG_LED_MASK) printk("[+++ TM] " fmt,##args); //[*]------------------------------------------------------------------------[*] // // Touch Key : Function Prototype Define // //[*]------------------------------------------------------------------------[*] static int __devinit tkey_i2c_probe (struct i2c_client *client, const struct i2c_device_id *id); static int __devexit tkey_i2c_remove (struct i2c_client *client); static int __init tkey_i2c_init (void); static void __exit tkey_i2c_exit (void); static void tkey_suspend (struct power_suspend *h); static void tkey_resume (struct power_suspend *h); int pan_tm_key_resume (void); int pan_tm_key_suspend (void); irqreturn_t tkey_irq (int irq, void *handle); static void tkey_work_q (struct work_struct *work); static void tkey_input_close (struct input_dev *input); static int tkey_input_open (struct input_dev *input); static int tkey_remove (struct device *dev); static int tkey_probe (struct i2c_client *client); int cr_tk_key_select(int button); void set_i2c_from_gpio_function(bool state); #ifdef PAN_TM_LED_OPERATION static void pan_tm_set_led_onoff(struct led_classdev *cdev,enum led_brightness brightness); #endif void pan_tm_set_mode(int mode); void init_gpio_cr(void); // p13106 static int tm_fops_open(struct inode *inode, struct file *filp); static long tm_fops_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); static ssize_t tm_fops_write(struct file *file, const char *buf, size_t count, loff_t *ppos); int cr_tk_i2c_write(struct i2c_client *client, unsigned char *data, unsigned int len); int cr_tk_i2c_read(struct i2c_client *client, unsigned char *data, unsigned int len); void read_raw_data_tm(void); static struct tkey *pan_tm; /* Modify Key Codes for Dependency of AP Machine */ static unsigned int cr_tk_keycode[] = { KEY_BACK, KEY_MENU, KEY_HOME, KEY_SEARCH }; // misc driver set. static struct file_operations tm_fops = { .owner = THIS_MODULE, .open = tm_fops_open, .unlocked_ioctl = tm_fops_ioctl, .write = tm_fops_write, }; static struct miscdevice tm_event = { .minor = MISC_DYNAMIC_MINOR, .name = "tm_fops", .fops = &tm_fops, }; static int tm_fops_open(struct inode *inode, struct file *filp) { return 0; } static long tm_fops_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int rc, fw_ver=0; u8 data[3]; switch(cmd) { case TM_IOCTL_SET_NORMAL_MODE: pan_tm_set_mode(PAN_TM_SET_NORMAL_MODE); break; case TM_IOCTL_SET_GLOVE_MODE: pan_tm_set_mode(PAN_TM_SET_GLOVE_MODE); break; case TM_IOCTL_SET_PEN_MODE: pan_tm_set_mode(PAN_TM_SET_PEN_MODE); break; case TM_IOCTL_SET_THRESHOLD_VALUE: if(arg > TK_KEY_THRESHOLD_MAX) { arg = TK_KEY_THRESHOLD_MAX; } else if(arg < TK_KEY_THRESHOLD_MIN) { arg = TK_KEY_THRESHOLD_MIN; } data[0] = 0x8f; data[1] = (arg >> 8) & 0xff; data[2] = (arg & 0xff); rc = i2c_smbus_write_i2c_block_data(pan_tm->client, REG_CMD_KEY_CODE, sizeof(data), data); if(rc < 0) { dbg_cr("%s : failed to set TM THRESHOLD_VALUE, error = %d\n", __func__, rc); return rc; } else { dbg_cr("%s : set TM THRESHOLD_VALUE\n", __func__); } break; case TM_IOCTL_READ_RAW_DATA: read_raw_data_tm(); if (copy_to_user(argp, pan_tm->rawdata, sizeof(pan_tm->rawdata))) return false; break; case TM_IOCTL_SET_LED_ON: rc = i2c_smbus_write_byte_data(pan_tm->client, 0, TK_KEY_LED_ON); if(rc < 0) { dbg_cr("%s : failed to set TM_LED ON, error = %d\n", __func__, rc); return rc; } else { dbg_cr("%s : set TM_LED ON\n", __func__); } break; case TM_IOCTL_SET_LED_OFF: rc = i2c_smbus_write_byte_data(pan_tm->client, 0, TK_KEY_LED_OFF); if(rc < 0) { dbg_cr("%s : failed to set TM_LED OFF, error = %d\n", __func__, rc); return rc; } else { dbg_cr("%s : set TM_LED OFF\n", __func__); } break; case TM_IOCTL_READ_FW_VERSION: rc = i2c_smbus_read_i2c_block_data(pan_tm->client, 0,sizeof(data), data); if(rc < 0) { dbg_cr("%s : failed to read TM FW version, error = %d\n", __func__, rc); fw_ver = -1; return rc; } else { fw_ver=data[1]; } if (copy_to_user(argp,&fw_ver, sizeof(fw_ver))) return false; break; default : dbg_cr("%s : unexpected command : %d\n", __func__, cmd); break; } return 0; } static ssize_t tm_fops_write(struct file *file, const char *buf, size_t count, loff_t *ppos) { int i, nBufSize = 0; int rc, fw_ver, mode = 0; u8 data[2]; if((size_t)(*ppos) > 0) return 0; if(buf != NULL) { nBufSize=strlen(buf); if(strncmp(buf, "debug_",6) == 0) { if(buf[6] > '0') { i = buf[6] - '1'; if(pan_tm_debug_state & 0x00000001 <<i) { pan_tm_debug_state &= ~(0x00000001 <<i); } else { pan_tm_debug_state |= (0x00000001 <<i); } } dbg_cr("%s : pan_tm_debug_state = %x, i = %d\n", __func__, pan_tm_debug_state, i); } else if(strncmp(buf, "set_normal_mode", 15) == 0) { pan_tm_set_mode(PAN_TM_SET_NORMAL_MODE); } else if(strncmp(buf, "set_glove_mode", 14) == 0) { pan_tm_set_mode(PAN_TM_SET_GLOVE_MODE); } else if (strncmp(buf, "read_fw_ver", 11) == 0) { rc = i2c_smbus_read_i2c_block_data(pan_tm->client, REG_CMD_FW_VERSION, sizeof(data), data); if(rc < 0) { dbg_cr("%s : failed to read TM FW version, error : %d\n", __func__, rc); return rc; } else { fw_ver = data[0]; } dbg_cr("%s : TM FW version : %d\n", __func__, fw_ver); } else if (strncmp(buf, "read_mode", 9) == 0) { rc = i2c_smbus_read_i2c_block_data(pan_tm->client, REG_CMD_MODE, sizeof(data), data); if(rc < 0) { dbg_cr("%s : failed to read TM_KEY mode, error : %d\n", __func__, rc); return rc; } else { mode = data[0]; } dbg_cr("%s : TM_KEY mode : %d\n", __func__, mode); } else { dbg_cr("%s : unexpected command\n", __func__); } } return nBufSize; } //[*]------------------------------------------------------------------------[*] // // Touch Key : Function // //[*]------------------------------------------------------------------------[*] void read_raw_data_tm(void) { int rc,i; u8 data[16]; memset(data, 0, sizeof(data)); rc=i2c_smbus_read_i2c_block_data(pan_tm->client, 0x10,sizeof(data),data); if(rc<0) dbg_cr("read_raw_data_tm i2c_smbus_read_i2c_block_data rc-> %d\n",rc); for(i=0;i<PAN_TM_LED_RAWDATA_MAX;i++){ pan_tm->rawdata[i]=((data[i*2]<<8)|data[i*2+1]); } } //[*]------------------------------------------------------------------------[*] // Touch Key : I2C Control Function //[*]------------------------------------------------------------------------[*] int cr_tk_i2c_read(struct i2c_client *client, unsigned char *data, unsigned int len) { /* Standard I2C Read Function (Combined Mode) */ struct i2c_msg msg[2]; int ret; if((len == 0) || (data == NULL)) { dev_err(&client->dev, "I2C read error: Null pointer or length == 0\n"); } memset(msg, 0x00, sizeof(msg)); msg[0].addr = client->addr; msg[0].flags = 0; msg[0].len = 1; msg[0].buf = data; msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].len = len; msg[1].buf = data; if((ret = i2c_transfer(client->adapter, msg, 2)) != 2) { dev_err(&client->dev, "I2C read error: (%d) reg: 0x%X len: %d\n", ret, *data, len); return -EIO; } return len; } int cr_tk_i2c_write(struct i2c_client *client, unsigned char *data, unsigned int len) { /* Standard I2C Write Function */ struct i2c_msg msg; int ret; if((len == 0) || (data == NULL)) { dev_err(&client->dev, "I2C read error: Null pointer or length == 0\n"); return -1; } memset(&msg, 0x00, sizeof(msg)); msg.addr = client->addr; msg.flags = 0; msg.len = len; msg.buf = data; if ((ret = i2c_transfer(client->adapter, &msg, 1)) != 1) { dev_err(&client->dev, "I2C command send error: (%d) reg: 0x%x\n", ret, *data); return -EIO; } return len; } #ifdef PAN_TM_LED_OPERATION static void pan_tm_set_led_onoff(struct led_classdev *tm_led_cdev,enum led_brightness brightness) { int rc = 0; struct tkey *tk = container_of(tm_led_cdev, struct tkey, tm_led_cdev); dbg_op("%s : brightness = %d\n", __func__, brightness); tk->tm_led_brightness = brightness; if(tk->state != APPMODE) { dbg_cr(" %s : TM state is not APPMODE\n", __func__); return; } if(tk->tm_led_brightness) { rc = i2c_smbus_write_byte_data(tk->client, 0, TK_KEY_LED_ON); if(rc < 0) { dbg_cr("%s : failed to set TM_LED ON, error = %d\n", __func__, rc); return; } else { dbg_op("%s : set TM_LED ON\n", __func__); } } else { rc=i2c_smbus_write_byte_data(tk->client, 0, TK_KEY_LED_OFF); if(rc < 0) { dbg_cr("%s : failed to set TM_LED OFF, error = %d\n", __func__, rc); return; } else { dbg_op("%s : set TM_LED OFF\n", __func__); } } } #endif void pan_tm_set_mode(int mode) { int rc = 0; dbg_op("%s enter, mode = %d\n",__func__, mode); if(pan_tm == NULL) return; if(pan_tm->state != APPMODE) { dbg_cr(" %s : TM state is not APPMODE\n", __func__); return; } switch (mode) { case PAN_TM_SET_NORMAL_MODE: rc = i2c_smbus_write_byte_data(pan_tm->client, REG_CMD_KEY_CODE, TK_KEY_GLOVE_MODE_OFF); if(rc < 0) { dbg_cr("%s : failed to set TM_KEY normal mode, error = %d\n", __func__, rc); return; } else { dbg_cr("%s : set TM_KEY normal mode\n", __func__); pan_tm->mode = 0; } break; case PAN_TM_SET_GLOVE_MODE: rc=i2c_smbus_write_byte_data(pan_tm->client, REG_CMD_KEY_CODE, TK_KEY_GLOVE_MODE_ON); if(rc < 0) { dbg_cr("%s : failed to set TM_KEY glove mode, error = %d\n", __func__, rc); return; } else { dbg_cr("%s : set TM_KEY glove mode\n", __func__); pan_tm->mode = 1; } break; case PAN_TM_SET_PEN_MODE: rc = i2c_smbus_write_byte_data(pan_tm->client, REG_CMD_KEY_CODE, TK_KEY_GLOVE_MODE_ON); if(rc < 0) { dbg_cr("%s : failed to set TM_KEY pen mode, error = %d\n", __func__, rc); return; } else { dbg_cr("%s : set TM_KEY pen mode\n", __func__); pan_tm->mode = 1; } break; default: dbg_cr("%s : unexpected argument = %d\n", __func__, mode); break; } } EXPORT_SYMBOL(pan_tm_set_mode); //[*]------------------------------------------------------------------------[*] // Touch Key : Data Processing Function //[*]------------------------------------------------------------------------[*] void cr_tk_work(struct tkey *tk) { unsigned char cnt, buf[I2C_READ_MAX_SIZE] = {0}; int keyCode = 0; dbg_op("%s\n",__func__); /* I2C Data Read Buffer */ buf[0] = REG_CMD_KEY_CODE; //if(cr_tk_i2c_read(tk->client, buf, I2C_READ_MAX_SIZE)<0) if(cr_tk_i2c_read(tk->client, buf, 1)<0) return; tk->touch_key = buf[REG_CMD_KEY_CODE]&0x07; tk->touch_event = buf[REG_CMD_KEY_CODE]&0x08; /* Received Key Code Check */ for(cnt=0; cnt<TK_KEY_COUNT_MAX; cnt++) { if(tk->touch_key == (TK_KEY1+cnt)) break; } if(cnt == TK_KEY_COUNT_MAX) return; /* Key Touch Event */ if(tk->touch_event == TK_KEY_UP) { dbg_op("Key Code (%d) <= (%d) \n", tk->touch_key, tk->touch_event); keyCode = cr_tk_key_select(tk->touch_key); if (keyCode < 0) { return; } input_report_key(tk->input, cr_tk_keycode[keyCode], false); } else { dbg_op("Key Code (%d) => (%d) \n", tk->touch_key, tk->touch_event); keyCode = cr_tk_key_select(tk->touch_key); if (keyCode < 0) { return; } input_report_key(tk->input, cr_tk_keycode[keyCode], true); } input_sync(tk->input); } //[*]------------------------------------------------------------------------[*] // Touch Key : Data Report Function //[*]------------------------------------------------------------------------[*] int cr_tk_key_select(int button) { /* Temporary Function */ switch(button){ case TK_KEY1: return 0; case TK_KEY2: return 1; case TK_KEY3: return 2; case TK_KEY4: return 3; default: dbg_cr(" ERROR : key select fail, button_X : %d \n", button); return -1; break; } // return (button-1); } static void cr_tk_event_clear(struct tkey *tk) { unsigned char cnt = 0; dbg_op("%s\n",__func__); // All key Release for (cnt = 0; cnt<TK_KEY_MAX_CNT ; cnt++) { input_report_key(tk->input, cr_tk_keycode[cnt], false); } input_sync(tk->input); } //[*]------------------------------------------------------------------------[*] // Touch Key : Enable/Disable Function //[*]------------------------------------------------------------------------[*] void cr_tk_enable(struct tkey *tk) { unsigned char buf[I2C_READ_MAX_SIZE]={0}; if(tk->disabled) { dbg_op("%s\n",__func__); // Check Interrupt Clear while(!gpio_get_value(TK_GPIO_INT)) { /* INT Clear after I2C Read of TSP buffer - Dummy Data */ /* I2C Data Read Buffer */ buf[0] = REG_CMD_KEY_CODE; if(cr_tk_i2c_read(tk->client, buf, I2C_READ_MAX_SIZE)<0) return; } dbg_op("%s : INT = %x, Disable = %x\n",__func__, gpio_get_value(TK_GPIO_INT), tk->disabled); enable_irq(tk->irq); tk->disabled = false; } } void cr_tk_disable(struct tkey *tk) { if(!tk->disabled) { disable_irq(tk->irq); tk->disabled = true; cr_tk_event_clear(tk); dbg_op("%s\n",__func__); } } /* //[*]------------------------------------------------------------------------[*] // Touch Key : ISP Define(FW Image Upgrade) //[*]------------------------------------------------------------------------[*] void cr_tk_fw_gpio(int pin, unsigned int dir, unsigned int value, unsigned int pull) { if(gpio_request(pin, "GPX3") < 0) { printk("%s : GPIO request port error!\n", __func__); } else { if(dir) { s3c_gpio_cfgpin(pin, S3C_GPIO_OUTPUT); gpio_direction_output(pin, 0); // GPIO OUTPUT } else { s3c_gpio_cfgpin(pin, S3C_GPIO_INPUT); gpio_direction_input(pin); // GPIO INPUT } if(value) gpio_set_value(pin, 1); // High else gpio_set_value(pin, 0); // Low if(pull == 2) s3c_gpio_setpull(pin, S3C_GPIO_PULL_UP); else if(pull == 1) s3c_gpio_setpull(pin, S3C_GPIO_PULL_DOWN); else s3c_gpio_setpull(pin, S3C_GPIO_PULL_NONE); printk("%s : GPIO %d = InOut %x, LowHigh %x, Pull UpDown %x\n", __func__, pin, dir, value, pull); gpio_free(pin); } } */ #if defined(ISP_UPGRADE) #define CSYNC1 0xA3 #define CSYNC2 0xAC #define CSYNC3 0xA5 #define CCFG 0x92 #define PCRST 0xB4 #define PECHIP 0x8A #define PWDATA 0x83 #define LDDATA 0xB2 #define LDMODE 0xB8 #define PEDISC 0xB0 #define PRDATA 0x81 #define RDDATA 0xB9 #define TSYNC1 300 // us #define TSYNC2 50 // 1ms~50ms #define TSYNC3 100 // us #define TDLY1 1 // us #define TDLY2 2 // us #define TFERASE 20 // ms #define TPROG 20 // us #define POWERON_DELAY 100 #define FW_FLASH_RETRY 5 #define BD_VERSION 4 #define ISP_FW_HEADER_LEN CR_TK_FW_TABLE[1] static inline void setsda(struct tkey *tk, int state) { if(state){ //gpio_direction_output(TK_GPIO_SDA, 1); gpio_set_value(TK_GPIO_SDA, 1); }else{ //gpio_direction_output(TK_GPIO_SDA, 0); gpio_set_value(TK_GPIO_SDA, 0); } return; /* Place your code to control SDA pin (GPIO) */ if(gpio_request(TK_GPIO_SDA, "tkey sda")) { dbg_cr("%s : request port error\n", __func__); } else { if (state) { // set sda gpio_set_value(TK_GPIO_SDA, 1); } else { // clear sda gpio_direction_output(TK_GPIO_SDA, 0); gpio_set_value(TK_GPIO_SDA, 0); } gpio_free(TK_GPIO_SDA); } } static inline void setscl(struct tkey *tk, int state) { if(state){ //gpio_direction_output(TK_GPIO_SCL, 1); gpio_set_value(TK_GPIO_SCL, 1); }else{ //gpio_direction_output(TK_GPIO_SCL, 0); gpio_set_value(TK_GPIO_SCL, 0); } return; /* Place your code to control SCL pin (GPIO) */ if(gpio_request(TK_GPIO_SCL, "tkey scl")) { dbg_cr("%s : request port error\n", __func__); } else { //printk("setscl state -> %d\n",state); if (state) { // set scl //gpio_direction_input(TK_GPIO_SCL); gpio_set_value(TK_GPIO_SCL, 1); } else { // clear scl // GPIO_SCL_PULL_UPDOWN &= (unsigned long)(~(GPIO_PULLUP << (GPIO_SCL_PIN * 2))); // GPIO_SCL_PULL_UPDOWN |= (unsigned long)( (GPIO_PULLUP << (GPIO_SCL_PIN * 2))); gpio_direction_output(TK_GPIO_SCL, 0); gpio_set_value(TK_GPIO_SCL, 0); } gpio_free(TK_GPIO_SCL); } } static inline int getsda(struct tkey *tk) { /* Place your code to control SDA pin (GPIO) */ int data; //data = gpio_get_value(TK_GPIO_SDA); //return data; //gpio_direction_input(TK_GPIO_SDA); data = gpio_get_value(TK_GPIO_SDA); //gpio_direction_output(TK_GPIO_SDA,0); return data; } static inline int getscl(struct tkey *tk) { /* Place your code to control SCL pin (GPIO) */ int data; //data = gpio_get_value(TK_GPIO_SCL); //return data; //gpio_direction_input(TK_GPIO_SCL); data = gpio_get_value(TK_GPIO_SCL); //gpio_direction_output(TK_GPIO_SCL,0); return data; } #if 0 static void gpio_to_i2c_conf(unsigned char pin) { /* Place your code to change pin Conf. here (SDA/SCL : GPIO to I2C) */ if(pin == GPIO_SDA_PIN) { GPIO_I2C_SDA_CON_PORT &= (unsigned long)(~(0xF << (pin * 4))); // clear all pins GPIO_I2C_SDA_CON_PORT |= (unsigned long)( (0x2 << (pin * 4))); // set i2c pin } else if(pin == GPIO_SCL_PIN) { GPIO_I2C_SCL_CON_PORT &= (unsigned long)(~(0xF << (pin * 4))); GPIO_I2C_SCL_CON_PORT |= (unsigned long)( (0x2 << (pin * 4))); } } #endif static void cr_tk_fw_power_onoff(struct tkey *tk, bool onoff) { /* Place Power On/Off Sequence Here */ if(onoff){ gpio_set_value(TM_1P8_EN, 1); msleep(64); gpio_set_value(KEY_3P3_EN, 1); dbg_cr("Power On\n"); }else{ gpio_set_value(TM_1P8_EN, 0); gpio_set_value(KEY_3P3_EN, 0); dbg_cr("Power Off\n"); } } static void send_9bit(struct tkey *tk, unsigned char data) { int i; setscl(tk, 1); setsda(tk, 0); setscl(tk, 0); for(i = 0; i < 8; i++) { setscl(tk, 1); setsda(tk, (data>>i)&0x01); setscl(tk, 0); } setsda(tk, 0); } static unsigned char wait_9bit(struct tkey *tk) { //struct i2c_client *client = tk->client; int i; int buf; unsigned char data = 0; gpio_request(TK_GPIO_SDA,"TK_GPIO_SDA"); gpio_direction_input(TK_GPIO_SDA); getsda(tk); setscl(tk, 1); setscl(tk, 0); for(i = 0; i < 8; i++) { setscl(tk, 1); buf = getsda(tk); setscl(tk, 0); data |= (buf&0x01)<<i; } gpio_free(TK_GPIO_SDA); set_i2c_from_gpio_function(false); return data; } static void load(struct tkey *tk, unsigned char data) { send_9bit(tk, LDDATA); udelay(TDLY1); send_9bit(tk, data); udelay(TDLY1); } static void step(struct tkey *tk, unsigned char data) { send_9bit(tk, CCFG); udelay(TDLY1); send_9bit(tk, data); udelay(TDLY2); } static void setpc(struct tkey *tk, unsigned int addr) { unsigned char buf[4]; int i; buf[0] = 0x02; buf[1] = addr>>8; buf[2] = addr&0xff; buf[3] = 0x00; for(i = 0; i < 4; i++) step(tk, buf[i]); } static void configure_isp(struct tkey *tk) { unsigned char buf[7]; int i; buf[0] = 0x75; buf[1] = 0xFC; buf[2] = 0xAC; buf[3] = 0x75; buf[4] = 0xFC; buf[5] = 0x35; buf[6] = 0x00; /* Step(cmd) */ for(i = 0; i < 7; i++) step(tk, buf[i]); dbg_cr(" configure_isp end\n"); } static unsigned char isp_enable_condition(struct tkey *tk) { unsigned char state; udelay(TSYNC1); send_9bit(tk, CSYNC1); udelay(TDLY1); send_9bit(tk, CSYNC2); udelay(TDLY1); send_9bit(tk, CSYNC3); udelay(TSYNC3); state = wait_9bit(tk); dbg_cr("%s : state = %d\n", __func__, state); return state; } static void reset_for_isp(struct tkey *tk) { /* Place Reset Sequence Here */ cr_tk_fw_power_onoff(tk, 0); setscl(tk, 0); setsda(tk, 0); mdelay(POWERON_DELAY); cr_tk_fw_power_onoff(tk, 1); usleep_range(5000, 6000); #if defined(DEBUG_TKEY) dev_info(&tk->client->dev, "%s\n", __func__); #endif } static int tc300k_erase_fw(struct tkey *tk) { //struct i2c_client *client = tk->client; unsigned char data_buf; int test=5; dbg_cr("%s Start\n", __func__); /* Enter ISP Mode */ reset_for_isp(tk); udelay(TSYNC1); if(isp_enable_condition(tk) != 0x01) { dbg_cr("ISP enable error\n"); return -1; } configure_isp(tk); /* Full Chip Erase */ send_9bit(tk, PCRST); udelay(TDLY1); send_9bit(tk, PECHIP); mdelay(TFERASE); do { if(test<0) break; test--; udelay(TDLY2); send_9bit(tk, CSYNC1); udelay(TDLY1); send_9bit(tk, CSYNC2); udelay(TDLY1); send_9bit(tk, CSYNC3); udelay(TSYNC3); data_buf = wait_9bit(tk); dbg_cr(" data_buf -> 0x%x\n",data_buf); } while((data_buf&0x04) != 0x00); dbg_cr("%s -> STATUS : %d\n", __func__, data_buf); return 0; } static int tc300k_write_fw(struct tkey *tk, unsigned int Start_Addr) { struct i2c_client *client = tk->client; unsigned int addr, code_size; dbg_cr("%s Start\n", __func__); addr = Start_Addr; Start_Addr += ISP_FW_HEADER_LEN; setpc(tk, addr); load(tk, PWDATA); send_9bit(tk, LDMODE); udelay(TDLY1); code_size = sizeof(CR_TK_FW_TABLE) - Start_Addr; // code_size = CR_TK_FW_TABLE[9]*256 + CR_TK_FW_TABLE[8]; dbg_cr("\nCODE Size : %d\n", code_size); dev_info(&client->dev, "fw code size = 0x%04X", code_size); while(addr < code_size) { //if((addr % 0x40) == 0) // dbg_cr("\n0x%04X ", addr); load(tk, CR_TK_FW_TABLE[Start_Addr + (addr++)]); //dbg_cr("."); udelay(TPROG); } dbg_cr("\n"); send_9bit(tk, PEDISC); udelay(TDLY1); return 0; } static int tc300k_verify_fw(struct tkey *tk, unsigned int Start_Addr) { // struct i2c_client *client = tk->client; unsigned int addr, code_size; unsigned char code_data; dbg_cr("%s Start\n", __func__); addr = Start_Addr; Start_Addr += ISP_FW_HEADER_LEN; setpc(tk, addr); code_size = sizeof(CR_TK_FW_TABLE) - Start_Addr; while(addr < code_size) { //if((addr % 0x40) == 0) // dbg_cr("\n0x%04X ", addr); send_9bit(tk, PRDATA); udelay(TDLY2); code_data = wait_9bit(tk); udelay(TDLY1); //dbg_cr("."); if(code_data != CR_TK_FW_TABLE[Start_Addr + (addr++)]) { dbg_cr("\nAddr : 0x%04X, Data is not correct (0x%02X)\n", addr-1, code_data); return -1; } } dbg_cr("\n"); return 0; } int cr_tk_fw_upgrade(struct tkey *tk) { struct i2c_client *client = tk->client; int retries; int ret; unsigned long flags; retries = FW_FLASH_RETRY; /* set gpio of scl and sda to gpio function. */ set_i2c_from_gpio_function(false); gpio_set_value(TK_GPIO_SCL, 0); gpio_set_value(TK_GPIO_SDA, 0); mdelay(100); dbg_cr("--------------------------------------------------------\n"); dbg_cr(" TSP ISP Upgrade (%s) \n",__func__); dbg_cr("--------------------------------------------------------\n"); erase_fw: // Full Erase local_irq_save(flags); ret = tc300k_erase_fw(tk); if(ret < 0) { dev_err(&client->dev, "fail to erase fw (%d)\n", ret); if(retries-- > 0) { dev_info(&client->dev, "retry erasing fw (%d)\n", retries); goto erase_fw; } else { goto err; } } dev_info(&client->dev, "succeed in erasing fw\n"); retries = FW_FLASH_RETRY; //write_fw: // FW "cr_tk_fw.i" ret = tc300k_write_fw(tk, 0); if(ret < 0) { dev_err(&client->dev, "fail to write fw (%d)\n", ret); if (retries-- > 0) { dev_info(&client->dev, "retry writing fw (%d)\n", retries); goto erase_fw; //write_fw; } else { goto err; } } dev_info(&client->dev, "succeed in writing fw\n"); retries = FW_FLASH_RETRY; //verify_fw: ret = tc300k_verify_fw(tk, 0); if(ret < 0) { dev_err(&client->dev, "fail to verify fw (%d)\n", ret); if (retries-- > 0) { dev_info(&client->dev, "retry verify fw (%d)\n", retries); goto erase_fw; //write_fw; } else { goto err; } } dev_info(&client->dev, "succeed in verify fw\n"); /* Power Reset */ cr_tk_fw_power_onoff(tk, 0); mdelay(100); cr_tk_fw_power_onoff(tk, 1); mdelay(100); /* set gpio of scl and sda to qup-i2c function. */ set_i2c_from_gpio_function(true); local_irq_restore(flags); return ret; err: /* data is not deallocated for debugging */ dev_err(&client->dev, "fail to fw flash. driver is removed\n"); /* GPIO to I2C */ //gpio_to_i2c_conf(GPIO_SDA_PIN); //gpio_to_i2c_conf(GPIO_SCL_PIN); local_irq_restore(flags); return ret; } #endif int cr_tk_fw_check(struct tkey *tk) // read my fw ver { int ret; ret = CR_TK_FW_TABLE[2]; //ret = BD_VERSION; tk->bd_version = ret; return ret; } int cr_tk_fw_probe(struct tkey *tk) { unsigned char buf[I2C_READ_MAX_SIZE]={0}; int ret; dbg_cr("%s\n",__func__); /* TKey FW Version */ buf[0] = REG_CMD_FW_VERSION; // Ignore when I2C Fail (-6 = No such device or address), Not Exist FW Image if(cr_tk_i2c_read(tk->client, buf, 2)<0) { tk->fw_version = 0xEE; dbg_cr(" TKey has Problem or Blank FW\n"); } else { tk->fw_version = buf[0]; // TSP FW Problem and bd_version is '0' when I2C Fail (-6) dbg_cr(" TKey Version(%02X), INT = %X\n",tk->fw_version, gpio_get_value(TK_GPIO_INT)); } /* Version Compare TSP Board vs FW Image */ ret = cr_tk_fw_check(tk); #if defined(ISP_UPGRADE) if(((ret != tk->fw_version)&&(ret >= 0)) || (tk->fw_version == 0xEE)) { /* ISP FW Image Upgrade */ if(cr_tk_fw_upgrade(tk)<0) return -1; dbg_cr(" FW Upgrade Completed...\n"); tk->fw_version = CR_TK_FW_TABLE[2]; } #endif return 0; } //[*]------------------------------------------------------------------------[*] // Touch Key : Interrupt Function //[*]------------------------------------------------------------------------[*] irqreturn_t tkey_irq(int irq, void *handle) { struct tkey *tk = handle; queue_work(tk->work_queue, &tk->work); // normal mode (work q used) return IRQ_HANDLED; } static void tkey_work_q(struct work_struct *work) { struct tkey *tk = container_of(work, struct tkey, work); cr_tk_work(tk); } //[*]------------------------------------------------------------------------[*] // Touch Key : First Called Function from Device Driver //[*]------------------------------------------------------------------------[*] static void tkey_enable (struct tkey *tk) { dbg_op("%s\n", __func__); if(tk->disabled) { if(tk->irq) enable_irq(tk->irq); tk->disabled = false; } } EXPORT_SYMBOL(tkey_enable); static void tkey_disable (struct tkey *tk) { dbg_op("%s\n", __func__); if(!tk->disabled) { if(tk->irq) disable_irq(tk->irq); tk->disabled = true; } } EXPORT_SYMBOL(tkey_disable); static int tkey_input_open(struct input_dev *input) { struct tkey *tk = input_get_drvdata(input); dbg_op("%s\n", __func__); /* FW Upgrade Check (ISP) */ //cr_tk_fw_probe(tk); cr_tk_enable(tk); return 0; } static void tkey_input_close(struct input_dev *input) { struct tkey *tk = input_get_drvdata(input); cr_tk_disable(tk); dbg_op("%s\n", __func__); } int tkey_info_display(struct tkey *tk) { dbg_cr("--------------------------------------------------------\n"); dbg_cr(" TOUCH KEY INFORMATION\n"); dbg_cr("--------------------------------------------------------\n"); dbg_cr("TOUCH INPUT Name = %s\n", I2C_TKEY_NAME); dbg_cr("TOUCH IRQ Mode = %s\n", "IRQ_MODE_NORMAL"); dbg_cr("TOUCH Key/Binary Version = %02X / %02X (%x)\n", tk->fw_version, tk->bd_version, gpio_get_value(TK_GPIO_INT)); dbg_cr("TOUCH KEY MAX = %d\n", TK_KEY_MAX_CNT); dbg_cr("--------------------------------------------------------\n"); return 0; } void init_gpio_cr(void){ int rc=0; dbg_cr("init_gpio_cr\n"); rc=gpio_request_one(KEY_3P3_EN,GPIOF_OUT_INIT_HIGH,"cr-key-3p3"); if(rc<0) dbg_cr("KEY_3P3_EN init is failed\n"); rc=gpio_request_one(TM_1P8_EN,GPIOF_OUT_INIT_HIGH,"cr-key-1p8"); if(rc<0) dbg_cr("TM_1P8_EN init is failed\n"); rc=gpio_request_one(TK_GPIO_INT,GPIOF_IN,"cr-key-irq"); if(rc<0) dbg_cr("TK_GPIO_INT init is failed\n"); } void set_i2c_from_gpio_function(bool state) { unsigned gpioConfig; int rc; if(state){ //printk("%s : state true\n",__FUNCTION__); gpioConfig = GPIO_CFG(TK_GPIO_SDA, 3, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA); // GPIO_CFG_INPUT / GPIO_CFG_NO_PULL rc = gpio_tlmm_config(gpioConfig, GPIO_CFG_ENABLE); if (rc) { dbg_cr("%s: TK_GPIO_SDA failed (%d)\n",__func__, rc); return; } gpioConfig = GPIO_CFG(TK_GPIO_SCL, 3, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA); // GPIO_CFG_INPUT / GPIO_CFG_NO_PULL rc = gpio_tlmm_config(gpioConfig, GPIO_CFG_ENABLE); if (rc) { dbg_cr("%s: TK_GPIO_SCL failed (%d)\n",__func__, rc); return; } }else{ //printk("%s : state false\n",__FUNCTION__); gpioConfig = GPIO_CFG(TK_GPIO_SDA, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA); // GPIO_CFG_INPUT / GPIO_CFG_NO_PULL rc = gpio_tlmm_config(gpioConfig, GPIO_CFG_ENABLE); if (rc) { dbg_cr("%s: TK_GPIO_SDA failed (%d)\n",__func__, rc); return; } gpioConfig = GPIO_CFG(TK_GPIO_SCL, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA); // GPIO_CFG_INPUT / GPIO_CFG_NO_PULL rc = gpio_tlmm_config(gpioConfig, GPIO_CFG_ENABLE); if (rc) { dbg_cr("%s: TK_GPIO_SCL failed (%d)\n",__func__, rc); return; } } } struct tkey *tk_shared; int tkey_probe (struct i2c_client *client) { int rc = -1; int key; struct device *dev = &client->dev; struct tkey *tk; dbg_cr("%s\n", __func__); /* Memory Allocation for tk data */ if(!(tk = kzalloc(sizeof(struct tkey), GFP_KERNEL))) { kfree(tk); dbg_cr("tkey struct malloc error!\n"); return -ENOMEM; } pan_tm = tk; /* Linux - I2C Client Device Set */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dbg_cr("i2c byte data not supported\n"); return -EIO; } tk->client = client; i2c_set_clientdata(client, tk); /* Linux - Set Device Driver */ dev_set_drvdata(dev, tk); /* Linux - Alloc Device */ if(!(tk->input = input_allocate_device())) goto err_free_mem; snprintf(tk->phys, sizeof(tk->phys), "%s/input0", I2C_TKEY_NAME); /* Linux - Set Event */ tk->input->open = tkey_input_open; tk->input->close = tkey_input_close; tk->input->name = I2C_TKEY_NAME; tk->input->phys = tk->phys; tk->input->dev.parent = dev; tk->input->id.bustype = BUS_I2C; tk->input->id.vendor = 0x16B4; tk->input->id.product = 0x0702; tk->input->id.version = 0x0001; input_set_drvdata(tk->input, tk); /* Linux - Key Touch Coordinate Event */ set_bit(EV_KEY, tk->input->evbit); for(key = 0; key < TK_KEY_COUNT_MAX; key++) { if(cr_tk_keycode[key] <= 0) continue; set_bit(cr_tk_keycode[key] & KEY_MAX, tk->input->keybit); } /* Linux - Register Device */ if ((rc = input_register_device(tk->input))) { dev_err(dev, "(%s) input register fail!\n", I2C_TKEY_NAME); goto err_free_input_mem; } /* init gpio config */ init_gpio_cr(); /* Linux - FW Upgrade Check (ISP) */ if((rc = cr_tk_fw_probe(tk)) < 0) goto err_free_all; //cr_tk_fw_gpio(TK_GPIO_INT, 0, 1, 2); p13106 temp /* Linux - Display TKey Information */ tkey_info_display(tk); //if, is in USER_SLEEP status and no active auto expiring wake lock register_power_suspend(&tk_suspend); /* Linux - Register ISR for Interupt */ tk->irq = gpio_to_irq(TK_GPIO_INT); if(tk->irq) { //INIT_WORK(&tk->work, tkey_work_q); if((tk->work_queue = create_singlethread_workqueue("tm_work_queue")) == NULL) goto err_free_irq; INIT_WORK(&tk->work, tkey_work_q); #if defined(TK_INT_ACTIVE_HIGH_EDGE) if((rc = request_irq(tk->irq, tkey_irq, IRQF_TRIGGER_RISING|IRQF_DISABLED, I2C_TKEY_NAME, tk))) #else if((rc = request_irq(tk->irq, tkey_irq, IRQF_TRIGGER_FALLING|IRQF_DISABLED, I2C_TKEY_NAME, tk))) #endif { dbg_cr("irq %d request fail!\n", tk->irq); goto err_free_irq; } //disable_irq_nosync(tk->irq); } tk->disabled = false; #ifdef PAN_TM_LED_OPERATION // init ledclass device tk->tm_led_cdev.name = "pan_tm_led"; tk->tm_led_cdev.brightness=0; tk->tm_led_cdev.brightness_set=pan_tm_set_led_onoff; rc = led_classdev_register(dev, &tk->tm_led_cdev); if (rc < 0) { dbg_cr("%s: couldn't register TM LED device\n", __func__); return rc; } #endif tk->threshold_normal = TK_KEY_THRESHOLD_DEFAULT_NORMAL; tk->threshold_globe = TK_KEY_THRESHOLD_DEFAULT_GLOVE; // register set rc = misc_register(&tm_event); if (rc) { dbg_cr("tm_event can''t register misc device\n"); } tk->state = APPMODE; tk->mode = 0; tk->cover_state = 0; tk_shared = tk; return 0; err_free_all: err_free_irq: free_irq(tk->irq, tk); /* Linux - Un-Register Device */ input_unregister_device(tk->input); dbg_cr("%s err_free_irq\n", __func__); err_free_input_mem: /* Linux - Free Device */ input_free_device(tk->input); tk->input = NULL; dbg_cr("%s err_free_input_mem\n", __func__); err_free_mem: kfree(tk); tk = NULL; dbg_cr("%s err_free_mem\n", __func__); pan_tm=NULL; return rc; } int tkey_remove (struct device *dev) { struct tkey *tk = dev_get_drvdata(dev); int rc; dbg_cr("%s\n", __func__); if(tk->irq) free_irq(tk->irq, tk); input_unregister_device(tk->input); dev_set_drvdata(dev, NULL); rc = misc_deregister(&tm_event); if (rc) { dbg_cr("tm_event can''t deregister misc device\n"); } #ifdef PAN_TM_LED_OPERATION led_classdev_unregister(&tk->tm_led_cdev); #endif kfree(tk); unregister_power_suspend(&tk_suspend); return 0; } static void tkey_resume (struct power_suspend *h) { tkey_enable(tk_shared); } static void tkey_suspend (struct power_suspend *h) { tkey_disable(tk_shared); } static struct power_suspend tk_suspend = { .suspend = tkey_suspend, .resume = tkey_resume, }; #ifdef CONFIG_KEYBOARD_TC370 static int tkey_i2c_resume (struct i2c_client *client) { struct tkey *tk = i2c_get_clientdata(client); int rc; dbg_cr("%s\n",__FUNCTION__); // check resume. return 0; // enable tm key irq. tkey_enable(tk); #ifdef PAN_TM_LED_OPERATION // set pan_tm_led on state. rc=i2c_smbus_write_byte_data(tk->client, 0, 0x10); if(rc) dbg_cr("TM i2c_smbus_write_byte_data rc -> %d\n",rc); #endif return 0; } static int tkey_i2c_suspend (struct i2c_client *client, pm_message_t message) { struct tkey *tk = i2c_get_clientdata(client); int rc; dbg_cr("%s\n",__FUNCTION__); // check suspend. return 0; // disable tm key irq. tkey_disable(tk); #ifdef PAN_TM_LED_OPERATION // set pan_tm_led off state. rc=i2c_smbus_write_byte_data(tk->client, 0, 0x20); if(rc) dbg_cr("TM i2c_smbus_write_byte_data rc -> %d\n",rc); #endif return 0; } #else // suspend & resume func of pan_tm_key driver is called for stmicro touch ic sus & resum func(). int pan_tm_key_resume (void) { int rc = 0; dbg_cr("%s\n",__FUNCTION__); if(pan_tm == NULL) return 0; if(pan_tm->state == APPMODE) { dbg_cr("%s : TM state is already APPMODE\n", __func__); return 0; } if(pan_tm->cover_state == 1) { dbg_cr("%s : cover state is closed\n", __func__); return 0; } // set gpio mode to qup i2c set_i2c_from_gpio_function(true); msleep(10); cr_tk_fw_power_onoff(pan_tm, 1); msleep(100); #ifdef PAN_TM_LED_OPERATION if(pan_tm->tm_led_brightness) { rc = i2c_smbus_write_byte_data(pan_tm->client, 0, TK_KEY_LED_ON); if(rc < 0) { dbg_cr("%s : failed to set TM_LED ON, error = %d\n", __func__, rc); return rc; } else { dbg_cr("%s : set TM_LED ON\n", __func__); } msleep(20); } #endif // set APPMODE pan_tm->state = APPMODE; // set mode pan_tm_set_mode(pan_tm->mode); // enable tm key irq. tkey_enable(pan_tm); return 0; } EXPORT_SYMBOL(pan_tm_key_resume); int pan_tm_key_suspend (void) { int rc = 0; dbg_cr("%s\n",__FUNCTION__); if(pan_tm == NULL) return 0; if(pan_tm->state == SUSMODE) { dbg_cr("%s : TM state is already SUSMODE\n", __func__); return 0; } // disable tm key irq. tkey_disable(pan_tm); #ifdef PAN_TM_LED_OPERATION if(pan_tm->tm_led_brightness) { rc = i2c_smbus_write_byte_data(pan_tm->client, 0, TK_KEY_LED_OFF); if(rc < 0) { dbg_cr("%s : failed to set TM_LED OFF, error = %d\n", __func__, rc); return rc; } else { dbg_cr("%s : set TM_LED OFF\n", __func__); } pan_tm->tm_led_brightness = 0; } #endif // set qup i2c to gpio mode set_i2c_from_gpio_function(false); msleep(10); gpio_set_value(TK_GPIO_SCL, 0); gpio_set_value(TK_GPIO_SCL, 0); // power off cr_tk_fw_power_onoff(pan_tm, 0); pan_tm->state = SUSMODE; return 0; } EXPORT_SYMBOL(pan_tm_key_suspend); #endif static int __devinit tkey_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { dbg_cr("%s\n", __func__); return tkey_probe(client); } static int __devexit tkey_i2c_remove(struct i2c_client *client) { printk("%s\n", __func__); return tkey_remove(&client->dev); } static const struct i2c_device_id touch_id[] = { { I2C_TKEY_NAME, 0 }, { } }; static struct of_device_id cr_match_table[] = { { .compatible = "coreriver,tk-300k",}, { }, }; MODULE_DEVICE_TABLE(i2c, touch_id); static struct i2c_driver tkey_i2c_driver = { .driver = { .name = I2C_TKEY_NAME, .owner = THIS_MODULE, .of_match_table = cr_match_table, }, .probe = tkey_i2c_probe, .remove = __devexit_p(tkey_i2c_remove), #ifdef CONFIG_KEYBOARD_TC370_SLLEP // suspend & resume func is called from stmicro touch driver. .suspend = tkey_i2c_suspend, .resume = tkey_i2c_resume, #endif .id_table = touch_id, }; static int __init tkey_i2c_init(void) { dbg_cr("%s\n", __func__); return i2c_add_driver(&tkey_i2c_driver); } static void __exit tkey_i2c_exit(void) { i2c_del_driver(&tkey_i2c_driver); dbg_cr("%s\n", __func__); } module_init(tkey_i2c_init); module_exit(tkey_i2c_exit); //[*]------------------------------------------------------------------------[*] MODULE_AUTHOR("HardKernel Co., Ltd."); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("TouchKey Driver"); MODULE_ALIAS("i2c:tkey"); //[*]------------------------------------------------------------------------[*]
thanhphat11/kernel-cm12.1-910
drivers/input/touchscreen/coreriver/cr_tk_300k.c
C
gpl-2.0
45,927
/* Copyright (C) 1992-2017 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <hurd.h> #include <hurd/signal.h> /* Run signals handlers on the stack specified by SS (if not NULL). If OSS is not NULL, it is filled in with the old signal stack status. */ int __sigaltstack (const struct sigaltstack *argss, struct sigaltstack *oss) { struct hurd_sigstate *s; struct sigaltstack ss, old; /* Fault before taking any locks. */ if (argss != NULL) ss = *argss; if (oss != NULL) *(volatile struct sigaltstack *) oss = *oss; s = _hurd_self_sigstate (); __spin_lock (&s->lock); if (argss != NULL && (ss.ss_flags & SS_DISABLE) && (s->sigaltstack.ss_flags & SS_ONSTACK)) { /* Can't disable a stack that is in use. */ __spin_unlock (&s->lock); errno = EINVAL; return -1; } old = s->sigaltstack; if (argss != NULL) s->sigaltstack = ss; __spin_unlock (&s->lock); if (oss != NULL) *oss = old; return 0; } weak_alias (__sigaltstack, sigaltstack)
norov/glibc
sysdeps/mach/hurd/sigaltstack.c
C
gpl-2.0
1,763
<?php /** * @version: $Id: file.php 2013 2011-11-27 12:41:44Z Radek Suski $ * @package: SobiPro Library * =================================================== * @author * Name: Sigrid Suski & Radek Suski, Sigsiu.NET GmbH * Email: sobi[at]sigsiu.net * Url: http://www.Sigsiu.NET * =================================================== * @copyright Copyright (C) 2006 - 2011 Sigsiu.NET GmbH (http://www.sigsiu.net). All rights reserved. * @license see http://www.gnu.org/licenses/lgpl.html GNU/LGPL Version 3. * You can use, redistribute this file and/or modify it under the terms of the GNU Lesser General Public License version 3 * =================================================== * $Date: 2011-11-27 13:41:44 +0100 (Sun, 27 Nov 2011) $ * $Revision: 2013 $ * $Author: Radek Suski $ * File location: components/com_sobipro/lib/base/fs/file.php $ */ defined( 'SOBIPRO' ) || exit( 'Restricted access' ); SPLoader::loadClass( 'cms.base.fs' ); /** * @author Radek Suski * @version 1.0 * @created 10-Jan-2009 5:02:55 PM */ class SPFile { /** * file path * * @var string */ protected $_filename = null; /** * @var string */ protected $_content = null; /** * @var string */ protected $_pathinfo = null; /** * @param string $filename */ public function __construct( $filename = null ) { $this->_filename = $filename; if( $this->_filename ) { $this->_pathinfo = pathinfo( $this->_filename ); } } /** * @return string */ public function getName() { return SPFs::fixPath( $this->_filename ); } /** * @return string - full path to current file */ public function getPathname() { return $this->getName(); } /** * @return string - name of the current file */ public function getFileName() { return $this->_pathinfo[ 'basename' ]; } /** * @return bool */ public function isDot() { return in_array( $this->getFileName(), array( '.', '..' ) ); } /** * Check if file is a directory * @return bool */ public function isDir() { return is_dir( $this->_filename ); } /** * Check if file is file * @return bool */ public function isFile() { return is_file( $this->_filename ); } /** * @param string $mode * @return bool */ public function chmod( $mode ) { return SPFs::chmod( $this->_filename, $mode ); } /** * Copy file * @param string $target - path * @return bool */ public function copy( $target ) { return SPFs::copy( $this->_filename, $target ); } /** * Get file from the request and upload to the given path * @param string $name - file name from the request * @param string $dest - destination path * @return bool */ public function upload( $name, $dest ) { if( SPFs::upload( $name, $dest ) ) { $this->_filename = $dest; return $this->_filename; } else { return false; } } /** * Deletes a file * @return bool */ public function delete() { return SPFs::delete( $this->_filename ); } /** * Moves file to new location * @param string $target - destination path * @return bool */ public function move( $target ) { $f = explode( DS, $target ); $path = str_replace( $f[ count( $f ) - 1 ], null, $target ); if( !( SPFs::exists( $path ) ) ) { SPFs::mkdir( $path ); } if( SPFs::move( $this->_filename, $target ) ) { $this->_filename = $target; } return $this; } /** * Reads file and returns the content of it * @return string */ public function & read() { $this->_content = SPFs::read( $this->_filename ); return $this->_content; } /** * Set file content * @param $content - string * @return void */ public function content( $content ) { $this->_content = $content; return $this; } /** * Writes the content to the file * @return bool */ public function write() { return SPFs::write( $this->_filename, $this->_content ); } /** * alias for @see SPFile#write() * @return bool */ public function save() { return $this->write(); } /** * Saves file as a copu * @param string $path * @return bool */ public function saveAs( $path ) { return SPFs::write( $path, $this->_content ); } /** * @deprecated * @return string */ public function filename() { return $this->_filename; } /** * @param $filename * @return void */ public function setFile( $filename ) { $this->_filename = $filename; $this->_pathinfo = pathinfo( $this->_filename ); } /** * string $name * @return bool */ public function rename( $name ) { $filename = SPFs::getFileName( $this->_filename ); $new = str_replace( $filename, $name, $this->_filename ); if( SPFs::move( $this->_filename , $new ) ) { $this->_filename = $new; return true; } else { return false; } } } ?>
cyberalpha/GarbageSocial
components/com_sobipro/lib/base/fs/file.php
PHP
gpl-2.0
5,028
/******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Martin Gräßlin <mgraesslin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *********************************************************************/ #include <KDE/KAboutData> #include <KDE/KCmdLineArgs> #include <KDE/KComponentData> #include <KDE/KConfigGroup> #include <KDE/KGlobal> #include <KDE/KLocalizedString> // Qt #include <QDBusConnection> #include <QDBusMessage> bool migrateRulesShortcut() { const QString KEY = "shortcut"; const QString ALT = "Alt"; const QString CTRL = "Ctrl"; const QString META = "Meta"; const QString SHIFT = "Shift"; KConfig config("kwinrulesrc"); if (config.groupList().isEmpty()) { return false; } bool updated = false; Q_FOREACH (const QString &groupName, config.groupList()) { KConfigGroup group = config.group(groupName); if (!group.hasKey(KEY)) { continue; } const QString value = group.readEntry(KEY, QString()); if (value.contains(" - ")) { // already migrated continue; } if (!value.contains(' ')) { // nothing to migrate continue; } // space might be either the shortcut separator or part of the shortcut // let's try to detect it properly const QStringList shortcuts = value.split(' '); // let's take the first part as it is QString newValue = shortcuts.first(); for (int i=1; i<shortcuts.length(); ++i) { const QString &cs = shortcuts.at(i); if (cs.contains('+') && (cs.contains(ALT) || cs.contains(CTRL) || cs.contains(META) || cs.contains(SHIFT))) { // our shortcuts consist of at least one modifier and a key, so having a plus and a modifier means it's a shortcut newValue.append(" - "); } else { // otherwise it's part of a key like "Volume Up" newValue.append(' '); } newValue.append(cs); } group.writeEntry(KEY, newValue); group.sync(); updated = true; } if (updated) { config.sync(); } return updated; } int main( int argc, char* argv[] ) { KAboutData about( "kwin_update_settings_4_11", "kwin", KLocalizedString(), 0 ); KCmdLineArgs::init( argc, argv, &about ); KComponentData inst( &about ); Q_UNUSED( KGlobal::locale() ); // jump-start locales to get to translated descriptions bool reload = migrateRulesShortcut(); // Send signal to all kwin instances if (reload) { QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); QDBusConnection::sessionBus().send(message); } }
aarontc/kde-workspace
kwin/data/update_kwin_411.cpp
C++
gpl-2.0
3,446
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Sat Jun 26 10:05:24 PDT 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.hermit.utils.Bitwise </TITLE> <META NAME="date" CONTENT="2010-06-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.hermit.utils.Bitwise"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/hermit/utils/Bitwise.html" title="class in org.hermit.utils"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/hermit/utils//class-useBitwise.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Bitwise.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.hermit.utils.Bitwise</B></H2> </CENTER> No usage of org.hermit.utils.Bitwise <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/hermit/utils/Bitwise.html" title="class in org.hermit.utils"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/hermit/utils//class-useBitwise.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Bitwise.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
ryanpeng84/HermitLibrary
doc/org/hermit/utils/class-use/Bitwise.html
HTML
gpl-2.0
5,801
section #huge_it_videogallery #fullPreview { background-color: #333333; border-top: 2px solid #333333; border-bottom: 2px solid #333333; padding: 50px 0 30px 0; display: none; } section #huge_it_videogallery #fullPreview img, section #huge_it_videogallery #fullPreview .fullCaption { max-width: 960px; width: 100%; margin: 0 auto; display: block; } section #huge_it_videogallery #fullPreview .fullCaption { font-family: Helvetica, Arial, sans-serif; font-size: 13px; line-height: 15px; font-weight: 300; color: white; margin: 15px auto 0 auto; } section #huge_it_videogallery #fullPreview figure { background-image: url("../img/effects/close.png"); background-size: 100%; width: 30px; height: 30px; position: absolute; top: 10px; right: 20px; cursor: pointer; } section #huge_it_videogallery li { display: inline-block; vertical-align: top; position: relative; } section #huge_it_videogallery li a.spinner { background-size: 100%; background-image: url("../img/effects/spinner.gif"); width: 50px; height: 50px; position: absolute; left: 95px; top: 60px; } section #huge_it_videogallery li img { border: none; margin: 10px 10px 0 0; } section #huge_it_videogallery li .overLayer ul, section #huge_it_videogallery li .infoLayer ul { padding: 1px 0 0 0; } section #huge_it_videogallery li .overLayer ul li, section #huge_it_videogallery li .infoLayer ul li { display: block; margin: 0 auto; width: 85%; padding: 0 0 5px 0; } section #huge_it_videogallery li .overLayer ul li:first-child, section #huge_it_videogallery li .infoLayer ul li:first-child { border-bottom: 2px white solid; } section #huge_it_videogallery li .overLayer ul li:last-child, section #huge_it_videogallery li .infoLayer ul li:last-child { padding: 5px 0 0 0; text-transform: lowercase; } section #huge_it_videogallery li .projectInfo { display: none; } #huge_it_gallery li .overLayer ul, section #huge_it_videogallery li .infoLayer ul { padding: 0px; margin: 0px; margin-top: 10%; }
satishux/fitnesshack
wp-content/plugins/gallery-video/style/thumb_view.css
CSS
gpl-2.0
2,435
/********************************************************************* * ____ _____ _ * * / ___| ___ _ __ _ _ | ____|_ __(_) ___ ___ ___ ___ _ __ * * \___ \ / _ \| '_ \| | | | | _| | '__| |/ __/ __/ __|/ _ \| '_ \ * * ___) | (_) | | | | |_| | | |___| | | | (__\__ \__ \ (_) | | | | * * |____/ \___/|_| |_|\__, | |_____|_| |_|\___|___/___/\___/|_| |_| * * |___/ * * * *********************************************************************/ /* [linux/drivers/mmc/core/sd_check_mbr.c] * * Copyright (C) [2011] Sony Ericsson Mobile Communications AB. * Copyright (C) 2012 Sony Mobile Communications AB. * * Author: Daisuke Okitsu <daisuke.x.okitsu@sonyericsson.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. */ #include <linux/mmc/core.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/scatterlist.h> #include <linux/slab.h> #include "core.h" #include "sd_check_mbr.h" #define SD_BLOCK_SIZE 512 /* * Configure correct block size in card */ static int mmc_sd_set_blksize(struct mmc_card *card, unsigned size) { int ret = 0; struct mmc_command cmd; if (!(mmc_card_blockaddr(card))) { cmd.opcode = MMC_SET_BLOCKLEN; cmd.arg = size; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; ret = mmc_wait_for_cmd(card->host, &cmd, 0); } return ret; } /* * Fill in the mmc_request structure given a set of transfer parameters. */ static void mmc_sd_prepare_mrq(struct mmc_card *card, struct mmc_request *mrq, struct scatterlist *sg, unsigned sg_len, unsigned dev_addr, unsigned blocks, unsigned blksz) { mrq->cmd->opcode = MMC_READ_SINGLE_BLOCK; mrq->cmd->arg = dev_addr; if (!mmc_card_blockaddr(card)) { /* MMC_STATE_BLOCKADDR */ mrq->cmd->arg *= SD_BLOCK_SIZE; } mrq->cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; mrq->stop = NULL; mrq->data->blksz = blksz; mrq->data->blocks = blocks; mrq->data->flags = MMC_DATA_READ; mrq->data->sg = sg; mrq->data->sg_len = sg_len; mmc_set_data_timeout(mrq->data, card); } /* * Checks that a normal transfer didn't have any errors */ static int mmc_sd_check_result(struct mmc_card *card, struct mmc_request *mrq) { int ret = 0; if ((mrq->cmd->error) || (mrq->data->error) || (mrq->stop && mrq->stop->error) || (mrq->data->bytes_xfered != mrq->data->blocks * mrq->data->blksz)) { ret = -EIO; } return ret; } /* * transfer with certain parameters */ static int mmc_sd_transfer(struct mmc_card *card, struct scatterlist *sg, unsigned sg_len, unsigned dev_addr, unsigned blocks, unsigned blksz) { struct mmc_request mrq; struct mmc_command cmd; struct mmc_command stop; struct mmc_data data; memset(&mrq, 0, sizeof(struct mmc_request)); memset(&cmd, 0, sizeof(struct mmc_command)); memset(&data, 0, sizeof(struct mmc_data)); memset(&stop, 0, sizeof(struct mmc_command)); mrq.cmd = &cmd; mrq.data = &data; mrq.stop = &stop; mmc_sd_prepare_mrq(card, &mrq, sg, sg_len, dev_addr, blocks, blksz); mmc_wait_for_req(card->host, &mrq); return mmc_sd_check_result(card, &mrq); } static int mmc_sd_read_block(struct mmc_card *card, unsigned long addr, unsigned long len, unsigned char *buff) { int ret = -EIO; struct scatterlist sg; if (len == 1) { ret = mmc_sd_set_blksize(card, SD_BLOCK_SIZE); if (!ret) { sg_init_one(&sg, buff, SD_BLOCK_SIZE); ret = mmc_sd_transfer(card, &sg, 1, addr, len, SD_BLOCK_SIZE); } } return ret; } int mmc_sd_check_boot_signature(struct mmc_card *card) { int ret = 0; unsigned char *buff; buff = kmalloc(SD_BLOCK_SIZE, GFP_KERNEL); if (buff) { if (!(mmc_sd_read_block(card, 0, 1, buff))) { if ((buff[510] != 0x55) || (buff[511] != 0xAA)) { /* no boot signature */ ret = -EINVAL; } } else { /* read error */ ret = -EIO; } kfree(buff); } return ret; }
DooMLoRD/android_kernel_sony_msm8960t_aosp
drivers/mmc/core/sd_check_mbr.c
C
gpl-2.0
4,263
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * CSVSaver.java * Copyright (C) 2004 University of Waikato, Hamilton, New Zealand * */ package weka.core.converters; import weka.core.Capabilities; import weka.core.Instance; import weka.core.Instances; import weka.core.RevisionUtils; import weka.core.SparseInstance; import weka.core.Capabilities.Capability; import weka.core.Utils; import java.io.IOException; import java.io.PrintWriter; /** <!-- globalinfo-start --> * Writes to a destination that is in csv format * <p/> <!-- globalinfo-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -i &lt;the input file&gt; * The input file</pre> * * <pre> -o &lt;the output file&gt; * The output file</pre> * <!-- options-end --> * * @author Stefan Mutter (mutter@cs.waikato.ac.nz) * @version $Revision: 7950 $ * @see Saver */ public class CSVSaver extends AbstractFileSaver implements BatchConverter, IncrementalConverter, FileSourcedConverter { /** for serialization */ static final long serialVersionUID = 476636654410701807L; /** Constructor */ public CSVSaver(){ resetOptions(); } /** * Returns a string describing this Saver * @return a description of the Saver suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "Writes to a destination that is in csv format"; } /** * Returns a description of the file type. * * @return a short file description */ public String getFileDescription() { return "CSV file: comma separated files"; } /** * Resets the Saver */ public void resetOptions() { super.resetOptions(); setFileExtension(".csv"); } /** * Returns the Capabilities of this saver. * * @return the capabilities of this object * @see Capabilities */ public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); // attributes result.enable(Capability.NOMINAL_ATTRIBUTES); result.enable(Capability.NUMERIC_ATTRIBUTES); result.enable(Capability.DATE_ATTRIBUTES); result.enable(Capability.STRING_ATTRIBUTES); result.enable(Capability.MISSING_VALUES); // class result.enable(Capability.NOMINAL_CLASS); result.enable(Capability.NUMERIC_CLASS); result.enable(Capability.DATE_CLASS); result.enable(Capability.STRING_CLASS); result.enable(Capability.MISSING_CLASS_VALUES); result.enable(Capability.NO_CLASS); return result; } /** Saves an instances incrementally. Structure has to be set by using the * setStructure() method or setInstances() method. * @param inst the instance to save * @throws IOException throws IOEXception if an instance cannot be saved incrementally. */ public void writeIncremental(Instance inst) throws IOException{ int writeMode = getWriteMode(); Instances structure = getInstances(); PrintWriter outW = null; if(getRetrieval() == BATCH || getRetrieval() == NONE) throw new IOException("Batch and incremental saving cannot be mixed."); if(getWriter() != null) outW = new PrintWriter(getWriter()); if(writeMode == WAIT){ if(structure == null){ setWriteMode(CANCEL); if(inst != null) System.err.println("Structure(Header Information) has to be set in advance"); } else setWriteMode(STRUCTURE_READY); writeMode = getWriteMode(); } if(writeMode == CANCEL){ if(outW != null) outW.close(); cancel(); } if(writeMode == STRUCTURE_READY){ setWriteMode(WRITE); //write header if(retrieveFile() == null && outW == null){ // print out attribute names as first row for (int i = 0; i < structure.numAttributes(); i++) { System.out.print(structure.attribute(i).name()); if (i < structure.numAttributes()-1) { System.out.print(","); } else { System.out.println(); } } } else{ for (int i = 0; i < structure.numAttributes(); i++) { outW.print(structure.attribute(i).name()); if (i < structure.numAttributes()-1) { outW.print(","); } else { outW.println(); } } outW.flush(); } writeMode = getWriteMode(); } if(writeMode == WRITE){ if(structure == null) throw new IOException("No instances information available."); if(inst != null){ //write instance if(retrieveFile() == null && outW == null) System.out.println(inst); else{ outW.println(instanceToString(inst)); //flushes every 100 instances m_incrementalCounter++; if(m_incrementalCounter > 100){ m_incrementalCounter = 0; outW.flush(); } } } else{ //close if(outW != null){ outW.flush(); outW.close(); } m_incrementalCounter = 0; resetStructure(); outW = null; resetWriter(); } } } /** Writes a Batch of instances * @throws IOException throws IOException if saving in batch mode is not possible */ public void writeBatch() throws IOException { if(getInstances() == null) throw new IOException("No instances to save"); if(getRetrieval() == INCREMENTAL) throw new IOException("Batch and incremental saving cannot be mixed."); setRetrieval(BATCH); setWriteMode(WRITE); if(retrieveFile() == null && getWriter() == null){ // print out attribute names as first row for (int i = 0; i < getInstances().numAttributes(); i++) { System.out.print(getInstances().attribute(i).name()); if (i < getInstances().numAttributes()-1) { System.out.print(","); } else { System.out.println(); } } for (int i = 0; i < getInstances().numInstances(); i++) { System.out.println(getInstances().instance(i)); } setWriteMode(WAIT); return; } PrintWriter outW = new PrintWriter(getWriter()); // print out attribute names as first row for (int i = 0; i < getInstances().numAttributes(); i++) { outW.print(Utils.quote(getInstances().attribute(i).name())); if (i < getInstances().numAttributes()-1) { outW.print(","); } else { outW.println(); } } for (int i = 0; i < getInstances().numInstances(); i++) { outW.println(instanceToString((getInstances().instance(i)))); } outW.flush(); outW.close(); setWriteMode(WAIT); outW = null; resetWriter(); setWriteMode(CANCEL); } /** * turns an instance into a string. takes care of sparse instances as well. * * @param inst the instance to turn into a string */ protected String instanceToString(Instance inst) { StringBuffer result; Instance outInst; int i; result = new StringBuffer(); if (inst instanceof SparseInstance) { outInst = new Instance(inst.weight(), inst.toDoubleArray()); outInst.setDataset(inst.dataset()); } else { outInst = inst; } for (i = 0; i < outInst.numAttributes(); i++) { if (i > 0) result.append(","); if (outInst.isMissing(i)) result.append("?"); else result.append(outInst.toString(i)); } return result.toString(); } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 7950 $"); } /** * Main method. * * @param args should contain the options of a Saver. */ public static void main(String[] args) { runFileSaver(new CSVSaver(), args); } }
kingwilly71/1032_DM
src/weka/core/converters/CSVSaver.java
Java
gpl-2.0
9,019
<?php /** * Base class for objects which tally individual questions. * See SecurePoll_ElectionTallier for an object which can tally multiple * questions. */ abstract class SecurePoll_Tallier { var $context, $question, $electionTallier, $election, $optionsById; abstract function addVote( $scores ); abstract function getHtmlResult(); abstract function getTextResult(); abstract function finishTally(); static function factory( $context, $type, $electionTallier, $question ) { switch ( $type ) { case 'plurality': return new SecurePoll_PluralityTallier( $context, $electionTallier, $question ); case 'schulze': return new SecurePoll_SchulzeTallier( $context, $electionTallier, $question ); case 'histogram-range': return new SecurePoll_HistogramRangeTallier( $context, $electionTallier, $question ); case 'alternative-vote': return new SecurePoll_AlternativeVoteTallier( $context, $electionTallier, $question ); default: throw new MWException( "Invalid tallier type: $type" ); } } /** * @param $context SecurePoll_Context * @param $electionTallier SecurePoll_ElectionTallier * @param $question SecurePoll_Question */ function __construct( $context, $electionTallier, $question ) { $this->context = $context; $this->question = $question; $this->electionTallier = $electionTallier; $this->election = $electionTallier->election; foreach ( $this->question->getOptions() as $option ) { $this->optionsById[$option->getId()] = $option; } } function convertRanksToHtml( $ranks ) { $s = "<table class=\"securepoll-table\">"; $ids = array_keys( $ranks ); foreach ( $ids as $i => $oid ) { $rank = $ranks[$oid]; $prevRank = isset( $ids[$i-1] ) ? $ranks[$ids[$i-1]] : false; $nextRank = isset( $ids[$i+1] ) ? $ranks[$ids[$i+1]] : false; if ( $rank === $prevRank || $rank === $nextRank ) { $rank .= '*'; } $option = $this->optionsById[$oid]; $s .= "<tr>" . Xml::element( 'td', array(), $rank ) . Xml::element( 'td', array(), $option->parseMessage( 'text' ) ) . "</tr>\n"; } $s .= "</table>"; return $s; } function convertRanksToText( $ranks ) { $s = ''; $ids = array_keys( $ranks ); $colWidth = 6; foreach ( $this->optionsById as $option ) { $colWidth = max( $colWidth, $option->getMessage( 'text' ) ); } foreach ( $ids as $i => $oid ) { $rank = $ranks[$oid]; $prevRank = isset( $ids[$i-1] ) ? $ranks[$ids[$i-1]] : false; $nextRank = isset( $ids[$i+1] ) ? $ranks[$ids[$i+1]] : false; if ( $rank === $prevRank || $rank === $nextRank ) { $rank .= '*'; } $option = $this->optionsById[$oid]; $s .= str_pad( $rank, 6 ) . ' | ' . $option->getMessage( 'text' ) . "\n"; } return $s; } }
xuechong87/Moegirlwiki
extensions/SecurePoll/includes/talliers/Tallier.php
PHP
gpl-2.0
2,749
<?php /** * Manage link administration actions. * * This page is accessed by the link management pages and handles the forms and * AJAX processes for link actions. * * @package WordPress * @subpackage Administration */ /** Load WordPress Administration Bootstrap */ require_once ('admin.php'); wp_reset_vars(array('action', 'cat_id', 'linkurl', 'name', 'image', 'description', 'visible', 'target', 'category', 'link_id', 'submit', 'order_by', 'links_show_cat_id', 'rating', 'rel', 'notes', 'linkcheck[]')); if ( ! current_user_can('manage_links') ) wp_die( __('You do not have sufficient permissions to edit the links for this site.') ); if ( !empty($_POST['deletebookmarks']) ) $action = 'deletebookmarks'; if ( !empty($_POST['move']) ) $action = 'move'; if ( !empty($_POST['linkcheck']) ) $linkcheck = $_POST['linkcheck']; $this_file = admin_url('link-manager.php'); switch ($action) { case 'deletebookmarks' : check_admin_referer('bulk-bookmarks'); //for each link id (in $linkcheck[]) change category to selected value if (count($linkcheck) == 0) { wp_redirect($this_file); exit; } $deleted = 0; foreach ($linkcheck as $link_id) { $link_id = (int) $link_id; if ( wp_delete_link($link_id) ) $deleted++; } wp_redirect("$this_file?deleted=$deleted"); exit; break; case 'move' : check_admin_referer('bulk-bookmarks'); //for each link id (in $linkcheck[]) change category to selected value if (count($linkcheck) == 0) { wp_redirect($this_file); exit; } $all_links = join(',', $linkcheck); // should now have an array of links we can change //$q = $wpdb->query("update $wpdb->links SET link_category='$category' WHERE link_id IN ($all_links)"); wp_redirect($this_file); exit; break; case 'add' : check_admin_referer('add-bookmark'); $redir = wp_get_referer(); if ( add_link() ) $redir = add_query_arg( 'added', 'true', $redir ); wp_redirect( $redir ); exit; break; case 'save' : $link_id = (int) $_POST['link_id']; check_admin_referer('update-bookmark_' . $link_id); edit_link($link_id); wp_redirect($this_file); exit; break; case 'delete' : $link_id = (int) $_GET['link_id']; check_admin_referer('delete-bookmark_' . $link_id); wp_delete_link($link_id); wp_redirect($this_file); exit; break; case 'edit' : wp_enqueue_script('link'); wp_enqueue_script('xfn'); $parent_file = 'link-manager.php'; $submenu_file = 'link-manager.php'; $title = __('Edit Link'); $link_id = (int) $_GET['link_id']; if (!$link = get_link_to_edit($link_id)) wp_die(__('Link not found.')); include ('edit-link-form.php'); include ('admin-footer.php'); break; default : break; } ?>
jacktandrew/plg
wp-admin/link.php
PHP
gpl-2.0
2,726
Fx.ProgressBar=new Class({Extends:Fx,options:{text:null,url:null,transition:Fx.Transitions.Circ.easeOut,fit:!0,link:"cancel",html5:!0},initialize:function(a,c){this.element=document.id(a);this.parent(c);var d=this.options.url;(this.useHtml5=this.options.html5&&this.supportsHtml5())?(this.progressElement=(new Element("progress")).replaces(this.element),this.progressElement.max=100,this.progressElement.value=0):(this.element.set("role","progressbar"),this.element.set("aria-valuenow","0"),this.element.set("aria-valuemin", "0"),this.element.set("aria-valuemax","100"),d&&this.element.setStyles({"background-image":"url("+d+")","background-repeat":"no-repeat"}));if(this.options.fit&&!this.useHtml5){if(d=d||this.element.getStyle("background-image").replace(/^url\(["']?|["']?\)$/g,"")){var b=new Image;b.onload=function(){this.fill=b.width;b=b.onload=null;this.set(this.now||0)}.bind(this);b.src=d;if(!this.fill&&b.width)b.onload()}}else this.set(0)},supportsHtml5:function(){return"value"in document.createElement("progress")}, start:function(a,c){return this.parent(this.now,arguments.length==1?a.limit(0,100):a/c*100)},set:function(a){this.now=a;this.useHtml5?this.progressElement.value=a:(this.element.setStyle("backgroundPosition",(this.fill?(this.fill/-2+a/100*(this.element.width||1)||0).round()+"px":100-a+"%")+" 0px").title=Math.round(a)+"%",this.element.set("aria-valuenow",a));var c=document.id(this.options.text);c&&c.set("text",Math.round(a)+"%");return this}});
lion01/tiagogarcia.com.br
media/system/js/progressbar.js
JavaScript
gpl-2.0
1,477
/* * 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) 2007, 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. * * lustre/fid/fid_lib.c * * Miscellaneous fid functions. * * Author: Nikita Danilov <nikita@clusterfs.com> * Author: Yury Umanets <umka@clusterfs.com> */ #define DEBUG_SUBSYSTEM S_FID #include <linux/libcfs/libcfs.h> #include <linux/module.h> #include <lustre/lustre_idl.h> #include <lustre_fid.h> /** * A cluster-wide range from which fid-sequences are granted to servers and * then clients. * * Fid namespace: * <pre> * Normal FID: seq:64 [2^33,2^64-1] oid:32 ver:32 * IGIF : 0:32, ino:32 gen:32 0:32 * IDIF : 0:31, 1:1, ost-index:16, objd:48 0:32 * </pre> * * The first 0x400 sequences of normal FID are reserved for special purpose. * FID_SEQ_START + 1 is for local file id generation. * FID_SEQ_START + 2 is for .lustre directory and its objects */ const struct lu_seq_range LUSTRE_SEQ_SPACE_RANGE = { FID_SEQ_NORMAL, (__u64)~0ULL }; EXPORT_SYMBOL(LUSTRE_SEQ_SPACE_RANGE); /* Zero range, used for init and other purposes. */ const struct lu_seq_range LUSTRE_SEQ_ZERO_RANGE = { 0, 0 }; EXPORT_SYMBOL(LUSTRE_SEQ_ZERO_RANGE); /* Lustre Big Fs Lock fid. */ const struct lu_fid LUSTRE_BFL_FID = { .f_seq = FID_SEQ_SPECIAL, .f_oid = FID_OID_SPECIAL_BFL, .f_ver = 0x0000000000000000 }; EXPORT_SYMBOL(LUSTRE_BFL_FID); /** Special fid for ".lustre" directory */ const struct lu_fid LU_DOT_LUSTRE_FID = { .f_seq = FID_SEQ_DOT_LUSTRE, .f_oid = FID_OID_DOT_LUSTRE, .f_ver = 0x0000000000000000 }; EXPORT_SYMBOL(LU_DOT_LUSTRE_FID); /** Special fid for "fid" special object in .lustre */ const struct lu_fid LU_OBF_FID = { .f_seq = FID_SEQ_DOT_LUSTRE, .f_oid = FID_OID_DOT_LUSTRE_OBF, .f_ver = 0x0000000000000000 }; EXPORT_SYMBOL(LU_OBF_FID);
pbeeler/Linux-stable
drivers/staging/lustre/lustre/fid/fid_lib.c
C
gpl-2.0
3,073
/* * Elan I2C/SMBus Touchpad driver - I2C interface * * Copyright (c) 2013 ELAN Microelectronics Corp. * * Author: 林政維 (Duson Lin) <dusonlin@emc.com.tw> * * Based on cyapa driver: * copyright (c) 2011-2012 Cypress Semiconductor, Inc. * copyright (c) 2011-2012 Google, Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * Trademarks are the property of their respective owners. */ #include <linux/completion.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/sched.h> #include <asm/unaligned.h> #include "elan_i2c.h" /* Elan i2c commands */ #define ETP_I2C_RESET 0x0100 #define ETP_I2C_WAKE_UP 0x0800 #define ETP_I2C_SLEEP 0x0801 #define ETP_I2C_DESC_CMD 0x0001 #define ETP_I2C_REPORT_DESC_CMD 0x0002 #define ETP_I2C_STAND_CMD 0x0005 #define ETP_I2C_UNIQUEID_CMD 0x0101 #define ETP_I2C_FW_VERSION_CMD 0x0102 #define ETP_I2C_SM_VERSION_CMD 0x0103 #define ETP_I2C_XY_TRACENUM_CMD 0x0105 #define ETP_I2C_MAX_X_AXIS_CMD 0x0106 #define ETP_I2C_MAX_Y_AXIS_CMD 0x0107 #define ETP_I2C_RESOLUTION_CMD 0x0108 #define ETP_I2C_PRESSURE_CMD 0x010A #define ETP_I2C_IAP_VERSION_CMD 0x0110 #define ETP_I2C_SET_CMD 0x0300 #define ETP_I2C_POWER_CMD 0x0307 #define ETP_I2C_FW_CHECKSUM_CMD 0x030F #define ETP_I2C_IAP_CTRL_CMD 0x0310 #define ETP_I2C_IAP_CMD 0x0311 #define ETP_I2C_IAP_RESET_CMD 0x0314 #define ETP_I2C_IAP_CHECKSUM_CMD 0x0315 #define ETP_I2C_CALIBRATE_CMD 0x0316 #define ETP_I2C_MAX_BASELINE_CMD 0x0317 #define ETP_I2C_MIN_BASELINE_CMD 0x0318 #define ETP_I2C_REPORT_LEN 34 #define ETP_I2C_DESC_LENGTH 30 #define ETP_I2C_REPORT_DESC_LENGTH 158 #define ETP_I2C_INF_LENGTH 2 #define ETP_I2C_IAP_PASSWORD 0x1EA5 #define ETP_I2C_IAP_RESET 0xF0F0 #define ETP_I2C_MAIN_MODE_ON (1 << 9) #define ETP_I2C_IAP_REG_L 0x01 #define ETP_I2C_IAP_REG_H 0x06 static int elan_i2c_read_block(struct i2c_client *client, u16 reg, u8 *val, u16 len) { __le16 buf[] = { cpu_to_le16(reg), }; struct i2c_msg msgs[] = { { .addr = client->addr, .flags = client->flags & I2C_M_TEN, .len = sizeof(buf), .buf = (u8 *)buf, }, { .addr = client->addr, .flags = (client->flags & I2C_M_TEN) | I2C_M_RD, .len = len, .buf = val, } }; int ret; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); return ret == ARRAY_SIZE(msgs) ? 0 : (ret < 0 ? ret : -EIO); } static int elan_i2c_read_cmd(struct i2c_client *client, u16 reg, u8 *val) { int retval; retval = elan_i2c_read_block(client, reg, val, ETP_I2C_INF_LENGTH); if (retval < 0) { dev_err(&client->dev, "reading cmd (0x%04x) fail.\n", reg); return retval; } return 0; } static int elan_i2c_write_cmd(struct i2c_client *client, u16 reg, u16 cmd) { __le16 buf[] = { cpu_to_le16(reg), cpu_to_le16(cmd), }; struct i2c_msg msg = { .addr = client->addr, .flags = client->flags & I2C_M_TEN, .len = sizeof(buf), .buf = (u8 *)buf, }; int ret; ret = i2c_transfer(client->adapter, &msg, 1); if (ret != 1) { if (ret >= 0) ret = -EIO; dev_err(&client->dev, "writing cmd (0x%04x) failed: %d\n", reg, ret); return ret; } return 0; } static int elan_i2c_initialize(struct i2c_client *client) { struct device *dev = &client->dev; int error; u8 val[256]; error = elan_i2c_write_cmd(client, ETP_I2C_STAND_CMD, ETP_I2C_RESET); if (error) { dev_err(dev, "device reset failed: %d\n", error); return error; } /* Wait for the device to reset */ msleep(100); /* get reset acknowledgement 0000 */ error = i2c_master_recv(client, val, ETP_I2C_INF_LENGTH); if (error < 0) { dev_err(dev, "failed to read reset response: %d\n", error); return error; } error = elan_i2c_read_block(client, ETP_I2C_DESC_CMD, val, ETP_I2C_DESC_LENGTH); if (error) { dev_err(dev, "cannot get device descriptor: %d\n", error); return error; } error = elan_i2c_read_block(client, ETP_I2C_REPORT_DESC_CMD, val, ETP_I2C_REPORT_DESC_LENGTH); if (error) { dev_err(dev, "fetching report descriptor failed.: %d\n", error); return error; } return 0; } static int elan_i2c_sleep_control(struct i2c_client *client, bool sleep) { return elan_i2c_write_cmd(client, ETP_I2C_STAND_CMD, sleep ? ETP_I2C_SLEEP : ETP_I2C_WAKE_UP); } static int elan_i2c_power_control(struct i2c_client *client, bool enable) { u8 val[2]; u16 reg; int error; error = elan_i2c_read_cmd(client, ETP_I2C_POWER_CMD, val); if (error) { dev_err(&client->dev, "failed to read current power state: %d\n", error); return error; } reg = le16_to_cpup((__le16 *)val); if (enable) reg &= ~ETP_DISABLE_POWER; else reg |= ETP_DISABLE_POWER; error = elan_i2c_write_cmd(client, ETP_I2C_POWER_CMD, reg); if (error) { dev_err(&client->dev, "failed to write current power state: %d\n", error); return error; } return 0; } static int elan_i2c_set_mode(struct i2c_client *client, u8 mode) { return elan_i2c_write_cmd(client, ETP_I2C_SET_CMD, mode); } static int elan_i2c_calibrate(struct i2c_client *client) { return elan_i2c_write_cmd(client, ETP_I2C_CALIBRATE_CMD, 1); } static int elan_i2c_calibrate_result(struct i2c_client *client, u8 *val) { return elan_i2c_read_block(client, ETP_I2C_CALIBRATE_CMD, val, 1); } static int elan_i2c_get_baseline_data(struct i2c_client *client, bool max_baseline, u8 *value) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, max_baseline ? ETP_I2C_MAX_BASELINE_CMD : ETP_I2C_MIN_BASELINE_CMD, val); if (error) return error; *value = le16_to_cpup((__le16 *)val); return 0; } static int elan_i2c_get_version(struct i2c_client *client, bool iap, u8 *version) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, iap ? ETP_I2C_IAP_VERSION_CMD : ETP_I2C_FW_VERSION_CMD, val); if (error) { dev_err(&client->dev, "failed to get %s version: %d\n", iap ? "IAP" : "FW", error); return error; } *version = val[0]; return 0; } static int elan_i2c_get_sm_version(struct i2c_client *client, u8 *ic_type, u8 *version) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_SM_VERSION_CMD, val); if (error) { dev_err(&client->dev, "failed to get SM version: %d\n", error); return error; } *version = val[0]; *ic_type = val[1]; return 0; } static int elan_i2c_get_product_id(struct i2c_client *client, u16 *id) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_UNIQUEID_CMD, val); if (error) { dev_err(&client->dev, "failed to get product ID: %d\n", error); return error; } *id = le16_to_cpup((__le16 *)val); return 0; } static int elan_i2c_get_checksum(struct i2c_client *client, bool iap, u16 *csum) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, iap ? ETP_I2C_IAP_CHECKSUM_CMD : ETP_I2C_FW_CHECKSUM_CMD, val); if (error) { dev_err(&client->dev, "failed to get %s checksum: %d\n", iap ? "IAP" : "FW", error); return error; } *csum = le16_to_cpup((__le16 *)val); return 0; } static int elan_i2c_get_max(struct i2c_client *client, unsigned int *max_x, unsigned int *max_y) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_MAX_X_AXIS_CMD, val); if (error) { dev_err(&client->dev, "failed to get X dimension: %d\n", error); return error; } *max_x = le16_to_cpup((__le16 *)val) & 0x0fff; error = elan_i2c_read_cmd(client, ETP_I2C_MAX_Y_AXIS_CMD, val); if (error) { dev_err(&client->dev, "failed to get Y dimension: %d\n", error); return error; } *max_y = le16_to_cpup((__le16 *)val) & 0x0fff; return 0; } static int elan_i2c_get_resolution(struct i2c_client *client, u8 *hw_res_x, u8 *hw_res_y) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_RESOLUTION_CMD, val); if (error) { dev_err(&client->dev, "failed to get resolution: %d\n", error); return error; } *hw_res_x = val[0]; *hw_res_y = val[1]; return 0; } static int elan_i2c_get_num_traces(struct i2c_client *client, unsigned int *x_traces, unsigned int *y_traces) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_XY_TRACENUM_CMD, val); if (error) { dev_err(&client->dev, "failed to get trace info: %d\n", error); return error; } *x_traces = val[0]; *y_traces = val[1]; return 0; } static int elan_i2c_get_pressure_adjustment(struct i2c_client *client, int *adjustment) { int error; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_PRESSURE_CMD, val); if (error) { dev_err(&client->dev, "failed to get pressure format: %d\n", error); return error; } if ((val[0] >> 4) & 0x1) *adjustment = 0; else *adjustment = ETP_PRESSURE_OFFSET; return 0; } static int elan_i2c_iap_get_mode(struct i2c_client *client, enum tp_mode *mode) { int error; u16 constant; u8 val[3]; error = elan_i2c_read_cmd(client, ETP_I2C_IAP_CTRL_CMD, val); if (error) { dev_err(&client->dev, "failed to read iap control register: %d\n", error); return error; } constant = le16_to_cpup((__le16 *)val); dev_dbg(&client->dev, "iap control reg: 0x%04x.\n", constant); *mode = (constant & ETP_I2C_MAIN_MODE_ON) ? MAIN_MODE : IAP_MODE; return 0; } static int elan_i2c_iap_reset(struct i2c_client *client) { int error; error = elan_i2c_write_cmd(client, ETP_I2C_IAP_RESET_CMD, ETP_I2C_IAP_RESET); if (error) { dev_err(&client->dev, "cannot reset IC: %d\n", error); return error; } return 0; } static int elan_i2c_set_flash_key(struct i2c_client *client) { int error; error = elan_i2c_write_cmd(client, ETP_I2C_IAP_CMD, ETP_I2C_IAP_PASSWORD); if (error) { dev_err(&client->dev, "cannot set flash key: %d\n", error); return error; } return 0; } static int elan_i2c_prepare_fw_update(struct i2c_client *client) { struct device *dev = &client->dev; int error; enum tp_mode mode; u8 val[3]; u16 password; /* Get FW in which mode (IAP_MODE/MAIN_MODE) */ error = elan_i2c_iap_get_mode(client, &mode); if (error) return error; if (mode == IAP_MODE) { /* Reset IC */ error = elan_i2c_iap_reset(client); if (error) return error; msleep(30); } /* Set flash key*/ error = elan_i2c_set_flash_key(client); if (error) return error; /* Wait for F/W IAP initialization */ msleep(mode == MAIN_MODE ? 100 : 30); /* Check if we are in IAP mode or not */ error = elan_i2c_iap_get_mode(client, &mode); if (error) return error; if (mode == MAIN_MODE) { dev_err(dev, "wrong mode: %d\n", mode); return -EIO; } /* Set flash key again */ error = elan_i2c_set_flash_key(client); if (error) return error; /* Wait for F/W IAP initialization */ msleep(30); /* read back to check we actually enabled successfully. */ error = elan_i2c_read_cmd(client, ETP_I2C_IAP_CMD, val); if (error) { dev_err(dev, "cannot read iap password: %d\n", error); return error; } password = le16_to_cpup((__le16 *)val); if (password != ETP_I2C_IAP_PASSWORD) { dev_err(dev, "wrong iap password: 0x%X\n", password); return -EIO; } return 0; } static int elan_i2c_write_fw_block(struct i2c_client *client, const u8 *page, u16 checksum, int idx) { struct device *dev = &client->dev; u8 page_store[ETP_FW_PAGE_SIZE + 4]; u8 val[3]; u16 result; int ret, error; page_store[0] = ETP_I2C_IAP_REG_L; page_store[1] = ETP_I2C_IAP_REG_H; memcpy(&page_store[2], page, ETP_FW_PAGE_SIZE); /* recode checksum at last two bytes */ put_unaligned_le16(checksum, &page_store[ETP_FW_PAGE_SIZE + 2]); ret = i2c_master_send(client, page_store, sizeof(page_store)); if (ret != sizeof(page_store)) { error = ret < 0 ? ret : -EIO; dev_err(dev, "Failed to write page %d: %d\n", idx, error); return error; } /* Wait for F/W to update one page ROM data. */ msleep(20); error = elan_i2c_read_cmd(client, ETP_I2C_IAP_CTRL_CMD, val); if (error) { dev_err(dev, "Failed to read IAP write result: %d\n", error); return error; } result = le16_to_cpup((__le16 *)val); if (result & (ETP_FW_IAP_PAGE_ERR | ETP_FW_IAP_INTF_ERR)) { dev_err(dev, "IAP reports failed write: %04hx\n", result); return -EIO; } return 0; } static int elan_i2c_finish_fw_update(struct i2c_client *client, struct completion *completion) { struct device *dev = &client->dev; long ret; int error; int len; u8 buffer[ETP_I2C_INF_LENGTH]; reinit_completion(completion); enable_irq(client->irq); error = elan_i2c_write_cmd(client, ETP_I2C_STAND_CMD, ETP_I2C_RESET); if (!error) ret = wait_for_completion_interruptible_timeout(completion, msecs_to_jiffies(300)); disable_irq(client->irq); if (error) { dev_err(dev, "device reset failed: %d\n", error); return error; } else if (ret == 0) { dev_err(dev, "timeout waiting for device reset\n"); return -ETIMEDOUT; } else if (ret < 0) { error = ret; dev_err(dev, "error waiting for device reset: %d\n", error); return error; } len = i2c_master_recv(client, buffer, ETP_I2C_INF_LENGTH); if (len != ETP_I2C_INF_LENGTH) { error = len < 0 ? len : -EIO; dev_err(dev, "failed to read INT signal: %d (%d)\n", error, len); return error; } return 0; } static int elan_i2c_get_report(struct i2c_client *client, u8 *report) { int len; len = i2c_master_recv(client, report, ETP_I2C_REPORT_LEN); if (len < 0) { dev_err(&client->dev, "failed to read report data: %d\n", len); return len; } if (len != ETP_I2C_REPORT_LEN) { dev_err(&client->dev, "wrong report length (%d vs %d expected)\n", len, ETP_I2C_REPORT_LEN); return -EIO; } return 0; } const struct elan_transport_ops elan_i2c_ops = { .initialize = elan_i2c_initialize, .sleep_control = elan_i2c_sleep_control, .power_control = elan_i2c_power_control, .set_mode = elan_i2c_set_mode, .calibrate = elan_i2c_calibrate, .calibrate_result = elan_i2c_calibrate_result, .get_baseline_data = elan_i2c_get_baseline_data, .get_version = elan_i2c_get_version, .get_sm_version = elan_i2c_get_sm_version, .get_product_id = elan_i2c_get_product_id, .get_checksum = elan_i2c_get_checksum, .get_pressure_adjustment = elan_i2c_get_pressure_adjustment, .get_max = elan_i2c_get_max, .get_resolution = elan_i2c_get_resolution, .get_num_traces = elan_i2c_get_num_traces, .iap_get_mode = elan_i2c_iap_get_mode, .iap_reset = elan_i2c_iap_reset, .prepare_fw_update = elan_i2c_prepare_fw_update, .write_fw_block = elan_i2c_write_fw_block, .finish_fw_update = elan_i2c_finish_fw_update, .get_report = elan_i2c_get_report, };
zhuyj/gmac
drivers/input/mouse/elan_i2c_i2c.c
C
gpl-2.0
14,725
/* * Special handling for DW core on Intel MID platform * * Copyright (c) 2009, 2014 Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #include <linux/dma-mapping.h> #include <linux/dmaengine.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/types.h> #include "spi-dw.h" #ifdef CONFIG_SPI_DW_MID_DMA #include <linux/pci.h> #include <linux/platform_data/dma-dw.h> #define RX_BUSY 0 #define TX_BUSY 1 static struct dw_dma_slave mid_dma_tx = { .dst_id = 1 }; static struct dw_dma_slave mid_dma_rx = { .src_id = 0 }; static bool mid_spi_dma_chan_filter(struct dma_chan *chan, void *param) { struct dw_dma_slave *s = param; if (s->dma_dev != chan->device->dev) return false; chan->private = s; return true; } static int mid_spi_dma_init(struct dw_spi *dws) { struct pci_dev *dma_dev; struct dw_dma_slave *tx = dws->dma_tx; struct dw_dma_slave *rx = dws->dma_rx; dma_cap_mask_t mask; /* * Get pci device for DMA controller, currently it could only * be the DMA controller of Medfield */ dma_dev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x0827, NULL); if (!dma_dev) return -ENODEV; dma_cap_zero(mask); dma_cap_set(DMA_SLAVE, mask); /* 1. Init rx channel */ rx->dma_dev = &dma_dev->dev; dws->rxchan = dma_request_channel(mask, mid_spi_dma_chan_filter, rx); if (!dws->rxchan) goto err_exit; dws->master->dma_rx = dws->rxchan; /* 2. Init tx channel */ tx->dma_dev = &dma_dev->dev; dws->txchan = dma_request_channel(mask, mid_spi_dma_chan_filter, tx); if (!dws->txchan) goto free_rxchan; dws->master->dma_tx = dws->txchan; dws->dma_inited = 1; return 0; free_rxchan: dma_release_channel(dws->rxchan); err_exit: return -EBUSY; } static void mid_spi_dma_exit(struct dw_spi *dws) { if (!dws->dma_inited) return; dmaengine_terminate_all(dws->txchan); dma_release_channel(dws->txchan); dmaengine_terminate_all(dws->rxchan); dma_release_channel(dws->rxchan); } static irqreturn_t dma_transfer(struct dw_spi *dws) { u16 irq_status = dw_readl(dws, DW_SPI_ISR); if (!irq_status) return IRQ_NONE; dw_readl(dws, DW_SPI_ICR); spi_reset_chip(dws); dev_err(&dws->master->dev, "%s: FIFO overrun/underrun\n", __func__); dws->master->cur_msg->status = -EIO; spi_finalize_current_transfer(dws->master); return IRQ_HANDLED; } static bool mid_spi_can_dma(struct spi_master *master, struct spi_device *spi, struct spi_transfer *xfer) { struct dw_spi *dws = spi_master_get_devdata(master); if (!dws->dma_inited) return false; return xfer->len > dws->fifo_len; } static enum dma_slave_buswidth convert_dma_width(u32 dma_width) { if (dma_width == 1) return DMA_SLAVE_BUSWIDTH_1_BYTE; else if (dma_width == 2) return DMA_SLAVE_BUSWIDTH_2_BYTES; return DMA_SLAVE_BUSWIDTH_UNDEFINED; } /* * dws->dma_chan_busy is set before the dma transfer starts, callback for tx * channel will clear a corresponding bit. */ static void dw_spi_dma_tx_done(void *arg) { struct dw_spi *dws = arg; clear_bit(TX_BUSY, &dws->dma_chan_busy); if (test_bit(RX_BUSY, &dws->dma_chan_busy)) return; spi_finalize_current_transfer(dws->master); } static struct dma_async_tx_descriptor *dw_spi_dma_prepare_tx(struct dw_spi *dws, struct spi_transfer *xfer) { struct dma_slave_config txconf; struct dma_async_tx_descriptor *txdesc; if (!xfer->tx_buf) return NULL; txconf.direction = DMA_MEM_TO_DEV; txconf.dst_addr = dws->dma_addr; txconf.dst_maxburst = 16; txconf.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; txconf.dst_addr_width = convert_dma_width(dws->dma_width); txconf.device_fc = false; dmaengine_slave_config(dws->txchan, &txconf); txdesc = dmaengine_prep_slave_sg(dws->txchan, xfer->tx_sg.sgl, xfer->tx_sg.nents, DMA_MEM_TO_DEV, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!txdesc) return NULL; txdesc->callback = dw_spi_dma_tx_done; txdesc->callback_param = dws; return txdesc; } /* * dws->dma_chan_busy is set before the dma transfer starts, callback for rx * channel will clear a corresponding bit. */ static void dw_spi_dma_rx_done(void *arg) { struct dw_spi *dws = arg; clear_bit(RX_BUSY, &dws->dma_chan_busy); if (test_bit(TX_BUSY, &dws->dma_chan_busy)) return; spi_finalize_current_transfer(dws->master); } static struct dma_async_tx_descriptor *dw_spi_dma_prepare_rx(struct dw_spi *dws, struct spi_transfer *xfer) { struct dma_slave_config rxconf; struct dma_async_tx_descriptor *rxdesc; if (!xfer->rx_buf) return NULL; rxconf.direction = DMA_DEV_TO_MEM; rxconf.src_addr = dws->dma_addr; rxconf.src_maxburst = 16; rxconf.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; rxconf.src_addr_width = convert_dma_width(dws->dma_width); rxconf.device_fc = false; dmaengine_slave_config(dws->rxchan, &rxconf); rxdesc = dmaengine_prep_slave_sg(dws->rxchan, xfer->rx_sg.sgl, xfer->rx_sg.nents, DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!rxdesc) return NULL; rxdesc->callback = dw_spi_dma_rx_done; rxdesc->callback_param = dws; return rxdesc; } static int mid_spi_dma_setup(struct dw_spi *dws, struct spi_transfer *xfer) { u16 dma_ctrl = 0; dw_writel(dws, DW_SPI_DMARDLR, 0xf); dw_writel(dws, DW_SPI_DMATDLR, 0x10); if (xfer->tx_buf) dma_ctrl |= SPI_DMA_TDMAE; if (xfer->rx_buf) dma_ctrl |= SPI_DMA_RDMAE; dw_writel(dws, DW_SPI_DMACR, dma_ctrl); /* Set the interrupt mask */ spi_umask_intr(dws, SPI_INT_TXOI | SPI_INT_RXUI | SPI_INT_RXOI); dws->transfer_handler = dma_transfer; return 0; } static int mid_spi_dma_transfer(struct dw_spi *dws, struct spi_transfer *xfer) { struct dma_async_tx_descriptor *txdesc, *rxdesc; /* Prepare the TX dma transfer */ txdesc = dw_spi_dma_prepare_tx(dws, xfer); /* Prepare the RX dma transfer */ rxdesc = dw_spi_dma_prepare_rx(dws, xfer); /* rx must be started before tx due to spi instinct */ if (rxdesc) { set_bit(RX_BUSY, &dws->dma_chan_busy); dmaengine_submit(rxdesc); dma_async_issue_pending(dws->rxchan); } if (txdesc) { set_bit(TX_BUSY, &dws->dma_chan_busy); dmaengine_submit(txdesc); dma_async_issue_pending(dws->txchan); } return 0; } static void mid_spi_dma_stop(struct dw_spi *dws) { if (test_bit(TX_BUSY, &dws->dma_chan_busy)) { dmaengine_terminate_all(dws->txchan); clear_bit(TX_BUSY, &dws->dma_chan_busy); } if (test_bit(RX_BUSY, &dws->dma_chan_busy)) { dmaengine_terminate_all(dws->rxchan); clear_bit(RX_BUSY, &dws->dma_chan_busy); } } static struct dw_spi_dma_ops mid_dma_ops = { .dma_init = mid_spi_dma_init, .dma_exit = mid_spi_dma_exit, .dma_setup = mid_spi_dma_setup, .can_dma = mid_spi_can_dma, .dma_transfer = mid_spi_dma_transfer, .dma_stop = mid_spi_dma_stop, }; #endif /* Some specific info for SPI0 controller on Intel MID */ /* HW info for MRST Clk Control Unit, 32b reg per controller */ #define MRST_SPI_CLK_BASE 100000000 /* 100m */ #define MRST_CLK_SPI_REG 0xff11d86c #define CLK_SPI_BDIV_OFFSET 0 #define CLK_SPI_BDIV_MASK 0x00000007 #define CLK_SPI_CDIV_OFFSET 9 #define CLK_SPI_CDIV_MASK 0x00000e00 #define CLK_SPI_DISABLE_OFFSET 8 int dw_spi_mid_init(struct dw_spi *dws) { void __iomem *clk_reg; u32 clk_cdiv; clk_reg = ioremap_nocache(MRST_CLK_SPI_REG, 16); if (!clk_reg) return -ENOMEM; /* Get SPI controller operating freq info */ clk_cdiv = readl(clk_reg + dws->bus_num * sizeof(u32)); clk_cdiv &= CLK_SPI_CDIV_MASK; clk_cdiv >>= CLK_SPI_CDIV_OFFSET; dws->max_freq = MRST_SPI_CLK_BASE / (clk_cdiv + 1); iounmap(clk_reg); #ifdef CONFIG_SPI_DW_MID_DMA dws->dma_tx = &mid_dma_tx; dws->dma_rx = &mid_dma_rx; dws->dma_ops = &mid_dma_ops; #endif return 0; }
rspc/mmc-sd40
drivers/spi/spi-dw-mid.c
C
gpl-2.0
8,045
/* * linux/drivers/video/acornfb.c * * Copyright (C) 1998-2001 Russell King * * 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. * * Frame buffer code for Acorn platforms * * NOTE: Most of the modes with X!=640 will disappear shortly. * NOTE: Startup setting of HS & VS polarity not supported. * (do we need to support it if we're coming up in 640x480?) * * FIXME: (things broken by the "new improved" FBCON API) * - Blanking 8bpp displays with VIDC */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/ctype.h> #include <linux/mm.h> #include <linux/init.h> #include <linux/fb.h> #include <linux/platform_device.h> #include <linux/dma-mapping.h> #include <linux/io.h> #include <linux/gfp.h> #include <mach/hardware.h> #include <asm/irq.h> #include <asm/mach-types.h> #include <asm/pgtable.h> #include "acornfb.h" /* * VIDC machines can't do 16 or 32BPP modes. */ #ifdef HAS_VIDC #undef FBCON_HAS_CFB16 #undef FBCON_HAS_CFB32 #endif /* * Default resolution. * NOTE that it has to be supported in the table towards * the end of this file. */ #define DEFAULT_XRES 640 #define DEFAULT_YRES 480 #define DEFAULT_BPP 4 /* * define this to debug the video mode selection */ #undef DEBUG_MODE_SELECTION /* * Translation from RISC OS monitor types to actual * HSYNC and VSYNC frequency ranges. These are * probably not right, but they're the best info I * have. Allow 1% either way on the nominal for TVs. */ #define NR_MONTYPES 6 static struct fb_monspecs monspecs[NR_MONTYPES] = { { /* TV */ .hfmin = 15469, .hfmax = 15781, .vfmin = 49, .vfmax = 51, }, { /* Multi Freq */ .hfmin = 0, .hfmax = 99999, .vfmin = 0, .vfmax = 199, }, { /* Hi-res mono */ .hfmin = 58608, .hfmax = 58608, .vfmin = 64, .vfmax = 64, }, { /* VGA */ .hfmin = 30000, .hfmax = 70000, .vfmin = 60, .vfmax = 60, }, { /* SVGA */ .hfmin = 30000, .hfmax = 70000, .vfmin = 56, .vfmax = 75, }, { .hfmin = 30000, .hfmax = 70000, .vfmin = 60, .vfmax = 60, } }; static struct fb_info fb_info; static struct acornfb_par current_par; static struct vidc_timing current_vidc; extern unsigned int vram_size; /* set by setup.c */ #ifdef HAS_VIDC #define MAX_SIZE 480*1024 /* CTL VIDC Actual * 24.000 0 8.000 * 25.175 0 8.392 * 36.000 0 12.000 * 24.000 1 12.000 * 25.175 1 12.588 * 24.000 2 16.000 * 25.175 2 16.783 * 36.000 1 18.000 * 24.000 3 24.000 * 36.000 2 24.000 * 25.175 3 25.175 * 36.000 3 36.000 */ struct pixclock { u_long min_clock; u_long max_clock; u_int vidc_ctl; u_int vid_ctl; }; static struct pixclock arc_clocks[] = { /* we allow +/-1% on these */ { 123750, 126250, VIDC_CTRL_DIV3, VID_CTL_24MHz }, /* 8.000MHz */ { 82500, 84167, VIDC_CTRL_DIV2, VID_CTL_24MHz }, /* 12.000MHz */ { 61875, 63125, VIDC_CTRL_DIV1_5, VID_CTL_24MHz }, /* 16.000MHz */ { 41250, 42083, VIDC_CTRL_DIV1, VID_CTL_24MHz }, /* 24.000MHz */ }; static struct pixclock * acornfb_valid_pixrate(struct fb_var_screeninfo *var) { u_long pixclock = var->pixclock; u_int i; if (!var->pixclock) return NULL; for (i = 0; i < ARRAY_SIZE(arc_clocks); i++) if (pixclock > arc_clocks[i].min_clock && pixclock < arc_clocks[i].max_clock) return arc_clocks + i; return NULL; } /* VIDC Rules: * hcr : must be even (interlace, hcr/2 must be even) * hswr : must be even * hdsr : must be odd * hder : must be odd * * vcr : must be odd * vswr : >= 1 * vdsr : >= 1 * vder : >= vdsr * if interlaced, then hcr/2 must be even */ static void acornfb_set_timing(struct fb_var_screeninfo *var) { struct pixclock *pclk; struct vidc_timing vidc; u_int horiz_correction; u_int sync_len, display_start, display_end, cycle; u_int is_interlaced; u_int vid_ctl, vidc_ctl; u_int bandwidth; memset(&vidc, 0, sizeof(vidc)); pclk = acornfb_valid_pixrate(var); vidc_ctl = pclk->vidc_ctl; vid_ctl = pclk->vid_ctl; bandwidth = var->pixclock * 8 / var->bits_per_pixel; /* 25.175, 4bpp = 79.444ns per byte, 317.776ns per word: fifo = 2,6 */ if (bandwidth > 143500) vidc_ctl |= VIDC_CTRL_FIFO_3_7; else if (bandwidth > 71750) vidc_ctl |= VIDC_CTRL_FIFO_2_6; else if (bandwidth > 35875) vidc_ctl |= VIDC_CTRL_FIFO_1_5; else vidc_ctl |= VIDC_CTRL_FIFO_0_4; switch (var->bits_per_pixel) { case 1: horiz_correction = 19; vidc_ctl |= VIDC_CTRL_1BPP; break; case 2: horiz_correction = 11; vidc_ctl |= VIDC_CTRL_2BPP; break; case 4: horiz_correction = 7; vidc_ctl |= VIDC_CTRL_4BPP; break; default: case 8: horiz_correction = 5; vidc_ctl |= VIDC_CTRL_8BPP; break; } if (var->sync & FB_SYNC_COMP_HIGH_ACT) /* should be FB_SYNC_COMP */ vidc_ctl |= VIDC_CTRL_CSYNC; else { if (!(var->sync & FB_SYNC_HOR_HIGH_ACT)) vid_ctl |= VID_CTL_HS_NHSYNC; if (!(var->sync & FB_SYNC_VERT_HIGH_ACT)) vid_ctl |= VID_CTL_VS_NVSYNC; } sync_len = var->hsync_len; display_start = sync_len + var->left_margin; display_end = display_start + var->xres; cycle = display_end + var->right_margin; /* if interlaced, then hcr/2 must be even */ is_interlaced = (var->vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED; if (is_interlaced) { vidc_ctl |= VIDC_CTRL_INTERLACE; if (cycle & 2) { cycle += 2; var->right_margin += 2; } } vidc.h_cycle = (cycle - 2) / 2; vidc.h_sync_width = (sync_len - 2) / 2; vidc.h_border_start = (display_start - 1) / 2; vidc.h_display_start = (display_start - horiz_correction) / 2; vidc.h_display_end = (display_end - horiz_correction) / 2; vidc.h_border_end = (display_end - 1) / 2; vidc.h_interlace = (vidc.h_cycle + 1) / 2; sync_len = var->vsync_len; display_start = sync_len + var->upper_margin; display_end = display_start + var->yres; cycle = display_end + var->lower_margin; if (is_interlaced) cycle = (cycle - 3) / 2; else cycle = cycle - 1; vidc.v_cycle = cycle; vidc.v_sync_width = sync_len - 1; vidc.v_border_start = display_start - 1; vidc.v_display_start = vidc.v_border_start; vidc.v_display_end = display_end - 1; vidc.v_border_end = vidc.v_display_end; if (machine_is_a5k()) __raw_writeb(vid_ctl, IOEB_VID_CTL); if (memcmp(&current_vidc, &vidc, sizeof(vidc))) { current_vidc = vidc; vidc_writel(0xe0000000 | vidc_ctl); vidc_writel(0x80000000 | (vidc.h_cycle << 14)); vidc_writel(0x84000000 | (vidc.h_sync_width << 14)); vidc_writel(0x88000000 | (vidc.h_border_start << 14)); vidc_writel(0x8c000000 | (vidc.h_display_start << 14)); vidc_writel(0x90000000 | (vidc.h_display_end << 14)); vidc_writel(0x94000000 | (vidc.h_border_end << 14)); vidc_writel(0x98000000); vidc_writel(0x9c000000 | (vidc.h_interlace << 14)); vidc_writel(0xa0000000 | (vidc.v_cycle << 14)); vidc_writel(0xa4000000 | (vidc.v_sync_width << 14)); vidc_writel(0xa8000000 | (vidc.v_border_start << 14)); vidc_writel(0xac000000 | (vidc.v_display_start << 14)); vidc_writel(0xb0000000 | (vidc.v_display_end << 14)); vidc_writel(0xb4000000 | (vidc.v_border_end << 14)); vidc_writel(0xb8000000); vidc_writel(0xbc000000); } #ifdef DEBUG_MODE_SELECTION printk(KERN_DEBUG "VIDC registers for %dx%dx%d:\n", var->xres, var->yres, var->bits_per_pixel); printk(KERN_DEBUG " H-cycle : %d\n", vidc.h_cycle); printk(KERN_DEBUG " H-sync-width : %d\n", vidc.h_sync_width); printk(KERN_DEBUG " H-border-start : %d\n", vidc.h_border_start); printk(KERN_DEBUG " H-display-start : %d\n", vidc.h_display_start); printk(KERN_DEBUG " H-display-end : %d\n", vidc.h_display_end); printk(KERN_DEBUG " H-border-end : %d\n", vidc.h_border_end); printk(KERN_DEBUG " H-interlace : %d\n", vidc.h_interlace); printk(KERN_DEBUG " V-cycle : %d\n", vidc.v_cycle); printk(KERN_DEBUG " V-sync-width : %d\n", vidc.v_sync_width); printk(KERN_DEBUG " V-border-start : %d\n", vidc.v_border_start); printk(KERN_DEBUG " V-display-start : %d\n", vidc.v_display_start); printk(KERN_DEBUG " V-display-end : %d\n", vidc.v_display_end); printk(KERN_DEBUG " V-border-end : %d\n", vidc.v_border_end); printk(KERN_DEBUG " VIDC Ctrl (E) : 0x%08X\n", vidc_ctl); printk(KERN_DEBUG " IOEB Ctrl : 0x%08X\n", vid_ctl); #endif } static int acornfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, u_int trans, struct fb_info *info) { union palette pal; if (regno >= current_par.palette_size) return 1; pal.p = 0; pal.vidc.reg = regno; pal.vidc.red = red >> 12; pal.vidc.green = green >> 12; pal.vidc.blue = blue >> 12; current_par.palette[regno] = pal; vidc_writel(pal.p); return 0; } #endif #ifdef HAS_VIDC20 #include <mach/acornfb.h> #define MAX_SIZE 2*1024*1024 /* VIDC20 has a different set of rules from the VIDC: * hcr : must be multiple of 4 * hswr : must be even * hdsr : must be even * hder : must be even * vcr : >= 2, (interlace, must be odd) * vswr : >= 1 * vdsr : >= 1 * vder : >= vdsr */ static void acornfb_set_timing(struct fb_info *info) { struct fb_var_screeninfo *var = &info->var; struct vidc_timing vidc; u_int vcr, fsize; u_int ext_ctl, dat_ctl; u_int words_per_line; memset(&vidc, 0, sizeof(vidc)); vidc.h_sync_width = var->hsync_len - 8; vidc.h_border_start = vidc.h_sync_width + var->left_margin + 8 - 12; vidc.h_display_start = vidc.h_border_start + 12 - 18; vidc.h_display_end = vidc.h_display_start + var->xres; vidc.h_border_end = vidc.h_display_end + 18 - 12; vidc.h_cycle = vidc.h_border_end + var->right_margin + 12 - 8; vidc.h_interlace = vidc.h_cycle / 2; vidc.v_sync_width = var->vsync_len - 1; vidc.v_border_start = vidc.v_sync_width + var->upper_margin; vidc.v_display_start = vidc.v_border_start; vidc.v_display_end = vidc.v_display_start + var->yres; vidc.v_border_end = vidc.v_display_end; vidc.control = acornfb_default_control(); vcr = var->vsync_len + var->upper_margin + var->yres + var->lower_margin; if ((var->vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED) { vidc.v_cycle = (vcr - 3) / 2; vidc.control |= VIDC20_CTRL_INT; } else vidc.v_cycle = vcr - 2; switch (var->bits_per_pixel) { case 1: vidc.control |= VIDC20_CTRL_1BPP; break; case 2: vidc.control |= VIDC20_CTRL_2BPP; break; case 4: vidc.control |= VIDC20_CTRL_4BPP; break; default: case 8: vidc.control |= VIDC20_CTRL_8BPP; break; case 16: vidc.control |= VIDC20_CTRL_16BPP; break; case 32: vidc.control |= VIDC20_CTRL_32BPP; break; } acornfb_vidc20_find_rates(&vidc, var); fsize = var->vsync_len + var->upper_margin + var->lower_margin - 1; if (memcmp(&current_vidc, &vidc, sizeof(vidc))) { current_vidc = vidc; vidc_writel(VIDC20_CTRL| vidc.control); vidc_writel(0xd0000000 | vidc.pll_ctl); vidc_writel(0x80000000 | vidc.h_cycle); vidc_writel(0x81000000 | vidc.h_sync_width); vidc_writel(0x82000000 | vidc.h_border_start); vidc_writel(0x83000000 | vidc.h_display_start); vidc_writel(0x84000000 | vidc.h_display_end); vidc_writel(0x85000000 | vidc.h_border_end); vidc_writel(0x86000000); vidc_writel(0x87000000 | vidc.h_interlace); vidc_writel(0x90000000 | vidc.v_cycle); vidc_writel(0x91000000 | vidc.v_sync_width); vidc_writel(0x92000000 | vidc.v_border_start); vidc_writel(0x93000000 | vidc.v_display_start); vidc_writel(0x94000000 | vidc.v_display_end); vidc_writel(0x95000000 | vidc.v_border_end); vidc_writel(0x96000000); vidc_writel(0x97000000); } iomd_writel(fsize, IOMD_FSIZE); ext_ctl = acornfb_default_econtrol(); if (var->sync & FB_SYNC_COMP_HIGH_ACT) /* should be FB_SYNC_COMP */ ext_ctl |= VIDC20_ECTL_HS_NCSYNC | VIDC20_ECTL_VS_NCSYNC; else { if (var->sync & FB_SYNC_HOR_HIGH_ACT) ext_ctl |= VIDC20_ECTL_HS_HSYNC; else ext_ctl |= VIDC20_ECTL_HS_NHSYNC; if (var->sync & FB_SYNC_VERT_HIGH_ACT) ext_ctl |= VIDC20_ECTL_VS_VSYNC; else ext_ctl |= VIDC20_ECTL_VS_NVSYNC; } vidc_writel(VIDC20_ECTL | ext_ctl); words_per_line = var->xres * var->bits_per_pixel / 32; if (current_par.using_vram && info->fix.smem_len == 2048*1024) words_per_line /= 2; /* RiscPC doesn't use the VIDC's VRAM control. */ dat_ctl = VIDC20_DCTL_VRAM_DIS | VIDC20_DCTL_SNA | words_per_line; /* The data bus width is dependent on both the type * and amount of video memory. * DRAM 32bit low * 1MB VRAM 32bit * 2MB VRAM 64bit */ if (current_par.using_vram && current_par.vram_half_sam == 2048) dat_ctl |= VIDC20_DCTL_BUS_D63_0; else dat_ctl |= VIDC20_DCTL_BUS_D31_0; vidc_writel(VIDC20_DCTL | dat_ctl); #ifdef DEBUG_MODE_SELECTION printk(KERN_DEBUG "VIDC registers for %dx%dx%d:\n", var->xres, var->yres, var->bits_per_pixel); printk(KERN_DEBUG " H-cycle : %d\n", vidc.h_cycle); printk(KERN_DEBUG " H-sync-width : %d\n", vidc.h_sync_width); printk(KERN_DEBUG " H-border-start : %d\n", vidc.h_border_start); printk(KERN_DEBUG " H-display-start : %d\n", vidc.h_display_start); printk(KERN_DEBUG " H-display-end : %d\n", vidc.h_display_end); printk(KERN_DEBUG " H-border-end : %d\n", vidc.h_border_end); printk(KERN_DEBUG " H-interlace : %d\n", vidc.h_interlace); printk(KERN_DEBUG " V-cycle : %d\n", vidc.v_cycle); printk(KERN_DEBUG " V-sync-width : %d\n", vidc.v_sync_width); printk(KERN_DEBUG " V-border-start : %d\n", vidc.v_border_start); printk(KERN_DEBUG " V-display-start : %d\n", vidc.v_display_start); printk(KERN_DEBUG " V-display-end : %d\n", vidc.v_display_end); printk(KERN_DEBUG " V-border-end : %d\n", vidc.v_border_end); printk(KERN_DEBUG " Ext Ctrl (C) : 0x%08X\n", ext_ctl); printk(KERN_DEBUG " PLL Ctrl (D) : 0x%08X\n", vidc.pll_ctl); printk(KERN_DEBUG " Ctrl (E) : 0x%08X\n", vidc.control); printk(KERN_DEBUG " Data Ctrl (F) : 0x%08X\n", dat_ctl); printk(KERN_DEBUG " Fsize : 0x%08X\n", fsize); #endif } /* * We have to take note of the VIDC20's 16-bit palette here. * The VIDC20 looks up a 16 bit pixel as follows: * * bits 111111 * 5432109876543210 * red ++++++++ (8 bits, 7 to 0) * green ++++++++ (8 bits, 11 to 4) * blue ++++++++ (8 bits, 15 to 8) * * We use a pixel which looks like: * * bits 111111 * 5432109876543210 * red +++++ (5 bits, 4 to 0) * green +++++ (5 bits, 9 to 5) * blue +++++ (5 bits, 14 to 10) */ static int acornfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, u_int trans, struct fb_info *info) { union palette pal; if (regno >= current_par.palette_size) return 1; if (regno < 16 && info->fix.visual == FB_VISUAL_DIRECTCOLOR) { u32 pseudo_val; pseudo_val = regno << info->var.red.offset; pseudo_val |= regno << info->var.green.offset; pseudo_val |= regno << info->var.blue.offset; ((u32 *)info->pseudo_palette)[regno] = pseudo_val; } pal.p = 0; pal.vidc20.red = red >> 8; pal.vidc20.green = green >> 8; pal.vidc20.blue = blue >> 8; current_par.palette[regno] = pal; if (info->var.bits_per_pixel == 16) { int i; pal.p = 0; vidc_writel(0x10000000); for (i = 0; i < 256; i += 1) { pal.vidc20.red = current_par.palette[ i & 31].vidc20.red; pal.vidc20.green = current_par.palette[(i >> 1) & 31].vidc20.green; pal.vidc20.blue = current_par.palette[(i >> 2) & 31].vidc20.blue; vidc_writel(pal.p); /* Palette register pointer auto-increments */ } } else { vidc_writel(0x10000000 | regno); vidc_writel(pal.p); } return 0; } #endif /* * Before selecting the timing parameters, adjust * the resolution to fit the rules. */ static int acornfb_adjust_timing(struct fb_info *info, struct fb_var_screeninfo *var, u_int fontht) { u_int font_line_len, sam_size, min_size, size, nr_y; /* xres must be even */ var->xres = (var->xres + 1) & ~1; /* * We don't allow xres_virtual to differ from xres */ var->xres_virtual = var->xres; var->xoffset = 0; if (current_par.using_vram) sam_size = current_par.vram_half_sam * 2; else sam_size = 16; /* * Now, find a value for yres_virtual which allows * us to do ywrap scrolling. The value of * yres_virtual must be such that the end of the * displayable frame buffer must be aligned with * the start of a font line. */ font_line_len = var->xres * var->bits_per_pixel * fontht / 8; min_size = var->xres * var->yres * var->bits_per_pixel / 8; /* * If minimum screen size is greater than that we have * available, reject it. */ if (min_size > info->fix.smem_len) return -EINVAL; /* Find int 'y', such that y * fll == s * sam < maxsize * y = s * sam / fll; s = maxsize / sam */ for (size = info->fix.smem_len; nr_y = size / font_line_len, min_size <= size; size -= sam_size) { if (nr_y * font_line_len == size) break; } nr_y *= fontht; if (var->accel_flags & FB_ACCELF_TEXT) { if (min_size > size) { /* * failed, use ypan */ size = info->fix.smem_len; var->yres_virtual = size / (font_line_len / fontht); } else var->yres_virtual = nr_y; } else if (var->yres_virtual > nr_y) var->yres_virtual = nr_y; current_par.screen_end = info->fix.smem_start + size; /* * Fix yres & yoffset if needed. */ if (var->yres > var->yres_virtual) var->yres = var->yres_virtual; if (var->vmode & FB_VMODE_YWRAP) { if (var->yoffset > var->yres_virtual) var->yoffset = var->yres_virtual; } else { if (var->yoffset + var->yres > var->yres_virtual) var->yoffset = var->yres_virtual - var->yres; } /* hsync_len must be even */ var->hsync_len = (var->hsync_len + 1) & ~1; #ifdef HAS_VIDC /* left_margin must be odd */ if ((var->left_margin & 1) == 0) { var->left_margin -= 1; var->right_margin += 1; } /* right_margin must be odd */ var->right_margin |= 1; #elif defined(HAS_VIDC20) /* left_margin must be even */ if (var->left_margin & 1) { var->left_margin += 1; var->right_margin -= 1; } /* right_margin must be even */ if (var->right_margin & 1) var->right_margin += 1; #endif if (var->vsync_len < 1) var->vsync_len = 1; return 0; } static int acornfb_validate_timing(struct fb_var_screeninfo *var, struct fb_monspecs *monspecs) { unsigned long hs, vs; /* * hs(Hz) = 10^12 / (pixclock * xtotal) * vs(Hz) = hs(Hz) / ytotal * * No need to do long long divisions or anything * like that if you factor it correctly */ hs = 1953125000 / var->pixclock; hs = hs * 512 / (var->xres + var->left_margin + var->right_margin + var->hsync_len); vs = hs / (var->yres + var->upper_margin + var->lower_margin + var->vsync_len); return (vs >= monspecs->vfmin && vs <= monspecs->vfmax && hs >= monspecs->hfmin && hs <= monspecs->hfmax) ? 0 : -EINVAL; } static inline void acornfb_update_dma(struct fb_info *info, struct fb_var_screeninfo *var) { u_int off = var->yoffset * info->fix.line_length; #if defined(HAS_MEMC) memc_write(VDMA_INIT, off >> 2); #elif defined(HAS_IOMD) iomd_writel(info->fix.smem_start + off, IOMD_VIDINIT); #endif } static int acornfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { u_int fontht; int err; /* * FIXME: Find the font height */ fontht = 8; var->red.msb_right = 0; var->green.msb_right = 0; var->blue.msb_right = 0; var->transp.msb_right = 0; switch (var->bits_per_pixel) { case 1: case 2: case 4: case 8: var->red.offset = 0; var->red.length = var->bits_per_pixel; var->green = var->red; var->blue = var->red; var->transp.offset = 0; var->transp.length = 0; break; #ifdef HAS_VIDC20 case 16: var->red.offset = 0; var->red.length = 5; var->green.offset = 5; var->green.length = 5; var->blue.offset = 10; var->blue.length = 5; var->transp.offset = 15; var->transp.length = 1; break; case 32: var->red.offset = 0; var->red.length = 8; var->green.offset = 8; var->green.length = 8; var->blue.offset = 16; var->blue.length = 8; var->transp.offset = 24; var->transp.length = 4; break; #endif default: return -EINVAL; } /* * Check to see if the pixel rate is valid. */ if (!acornfb_valid_pixrate(var)) return -EINVAL; /* * Validate and adjust the resolution to * match the video generator hardware. */ err = acornfb_adjust_timing(info, var, fontht); if (err) return err; /* * Validate the timing against the * monitor hardware. */ return acornfb_validate_timing(var, &info->monspecs); } static int acornfb_set_par(struct fb_info *info) { switch (info->var.bits_per_pixel) { case 1: current_par.palette_size = 2; info->fix.visual = FB_VISUAL_MONO10; break; case 2: current_par.palette_size = 4; info->fix.visual = FB_VISUAL_PSEUDOCOLOR; break; case 4: current_par.palette_size = 16; info->fix.visual = FB_VISUAL_PSEUDOCOLOR; break; case 8: current_par.palette_size = VIDC_PALETTE_SIZE; #ifdef HAS_VIDC info->fix.visual = FB_VISUAL_STATIC_PSEUDOCOLOR; #else info->fix.visual = FB_VISUAL_PSEUDOCOLOR; #endif break; #ifdef HAS_VIDC20 case 16: current_par.palette_size = 32; info->fix.visual = FB_VISUAL_DIRECTCOLOR; break; case 32: current_par.palette_size = VIDC_PALETTE_SIZE; info->fix.visual = FB_VISUAL_DIRECTCOLOR; break; #endif default: BUG(); } info->fix.line_length = (info->var.xres * info->var.bits_per_pixel) / 8; #if defined(HAS_MEMC) { unsigned long size = info->fix.smem_len - VDMA_XFERSIZE; memc_write(VDMA_START, 0); memc_write(VDMA_END, size >> 2); } #elif defined(HAS_IOMD) { unsigned long start, size; u_int control; start = info->fix.smem_start; size = current_par.screen_end; if (current_par.using_vram) { size -= current_par.vram_half_sam; control = DMA_CR_E | (current_par.vram_half_sam / 256); } else { size -= 16; control = DMA_CR_E | DMA_CR_D | 16; } iomd_writel(start, IOMD_VIDSTART); iomd_writel(size, IOMD_VIDEND); iomd_writel(control, IOMD_VIDCR); } #endif acornfb_update_dma(info, &info->var); acornfb_set_timing(info); return 0; } static int acornfb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) { u_int y_bottom = var->yoffset; if (!(var->vmode & FB_VMODE_YWRAP)) y_bottom += info->var.yres; if (y_bottom > info->var.yres_virtual) return -EINVAL; acornfb_update_dma(info, var); return 0; } static struct fb_ops acornfb_ops = { .owner = THIS_MODULE, .fb_check_var = acornfb_check_var, .fb_set_par = acornfb_set_par, .fb_setcolreg = acornfb_setcolreg, .fb_pan_display = acornfb_pan_display, .fb_fillrect = cfb_fillrect, .fb_copyarea = cfb_copyarea, .fb_imageblit = cfb_imageblit, }; /* * Everything after here is initialisation!!! */ static struct fb_videomode modedb[] = { { /* 320x256 @ 50Hz */ NULL, 50, 320, 256, 125000, 92, 62, 35, 19, 38, 2, FB_SYNC_COMP_HIGH_ACT, FB_VMODE_NONINTERLACED }, { /* 640x250 @ 50Hz, 15.6 kHz hsync */ NULL, 50, 640, 250, 62500, 185, 123, 38, 21, 76, 3, 0, FB_VMODE_NONINTERLACED }, { /* 640x256 @ 50Hz, 15.6 kHz hsync */ NULL, 50, 640, 256, 62500, 185, 123, 35, 18, 76, 3, 0, FB_VMODE_NONINTERLACED }, { /* 640x512 @ 50Hz, 26.8 kHz hsync */ NULL, 50, 640, 512, 41667, 113, 87, 18, 1, 56, 3, 0, FB_VMODE_NONINTERLACED }, { /* 640x250 @ 70Hz, 31.5 kHz hsync */ NULL, 70, 640, 250, 39722, 48, 16, 109, 88, 96, 2, 0, FB_VMODE_NONINTERLACED }, { /* 640x256 @ 70Hz, 31.5 kHz hsync */ NULL, 70, 640, 256, 39722, 48, 16, 106, 85, 96, 2, 0, FB_VMODE_NONINTERLACED }, { /* 640x352 @ 70Hz, 31.5 kHz hsync */ NULL, 70, 640, 352, 39722, 48, 16, 58, 37, 96, 2, 0, FB_VMODE_NONINTERLACED }, { /* 640x480 @ 60Hz, 31.5 kHz hsync */ NULL, 60, 640, 480, 39722, 48, 16, 32, 11, 96, 2, 0, FB_VMODE_NONINTERLACED }, { /* 800x600 @ 56Hz, 35.2 kHz hsync */ NULL, 56, 800, 600, 27778, 101, 23, 22, 1, 100, 2, 0, FB_VMODE_NONINTERLACED }, { /* 896x352 @ 60Hz, 21.8 kHz hsync */ NULL, 60, 896, 352, 41667, 59, 27, 9, 0, 118, 3, 0, FB_VMODE_NONINTERLACED }, { /* 1024x 768 @ 60Hz, 48.4 kHz hsync */ NULL, 60, 1024, 768, 15385, 160, 24, 29, 3, 136, 6, 0, FB_VMODE_NONINTERLACED }, { /* 1280x1024 @ 60Hz, 63.8 kHz hsync */ NULL, 60, 1280, 1024, 9090, 186, 96, 38, 1, 160, 3, 0, FB_VMODE_NONINTERLACED } }; static struct fb_videomode acornfb_default_mode = { .name = NULL, .refresh = 60, .xres = 640, .yres = 480, .pixclock = 39722, .left_margin = 56, .right_margin = 16, .upper_margin = 34, .lower_margin = 9, .hsync_len = 88, .vsync_len = 2, .sync = 0, .vmode = FB_VMODE_NONINTERLACED }; static void acornfb_init_fbinfo(void) { static int first = 1; if (!first) return; first = 0; fb_info.fbops = &acornfb_ops; fb_info.flags = FBINFO_DEFAULT | FBINFO_HWACCEL_YPAN; fb_info.pseudo_palette = current_par.pseudo_palette; strcpy(fb_info.fix.id, "Acorn"); fb_info.fix.type = FB_TYPE_PACKED_PIXELS; fb_info.fix.type_aux = 0; fb_info.fix.xpanstep = 0; fb_info.fix.ypanstep = 1; fb_info.fix.ywrapstep = 1; fb_info.fix.line_length = 0; fb_info.fix.accel = FB_ACCEL_NONE; /* * setup initial parameters */ memset(&fb_info.var, 0, sizeof(fb_info.var)); #if defined(HAS_VIDC20) fb_info.var.red.length = 8; fb_info.var.transp.length = 4; #elif defined(HAS_VIDC) fb_info.var.red.length = 4; fb_info.var.transp.length = 1; #endif fb_info.var.green = fb_info.var.red; fb_info.var.blue = fb_info.var.red; fb_info.var.nonstd = 0; fb_info.var.activate = FB_ACTIVATE_NOW; fb_info.var.height = -1; fb_info.var.width = -1; fb_info.var.vmode = FB_VMODE_NONINTERLACED; fb_info.var.accel_flags = FB_ACCELF_TEXT; current_par.dram_size = 0; current_par.montype = -1; current_par.dpms = 0; } /* * setup acornfb options: * * mon:hmin-hmax:vmin-vmax:dpms:width:height * Set monitor parameters: * hmin = horizontal minimum frequency (Hz) * hmax = horizontal maximum frequency (Hz) (optional) * vmin = vertical minimum frequency (Hz) * vmax = vertical maximum frequency (Hz) (optional) * dpms = DPMS supported? (optional) * width = width of picture in mm. (optional) * height = height of picture in mm. (optional) * * montype:type * Set RISC-OS style monitor type: * 0 (or tv) - TV frequency * 1 (or multi) - Multi frequency * 2 (or hires) - Hi-res monochrome * 3 (or vga) - VGA * 4 (or svga) - SVGA * auto, or option missing * - try hardware detect * * dram:size * Set the amount of DRAM to use for the frame buffer * (even if you have VRAM). * size can optionally be followed by 'M' or 'K' for * MB or KB respectively. */ static void acornfb_parse_mon(char *opt) { char *p = opt; current_par.montype = -2; fb_info.monspecs.hfmin = simple_strtoul(p, &p, 0); if (*p == '-') fb_info.monspecs.hfmax = simple_strtoul(p + 1, &p, 0); else fb_info.monspecs.hfmax = fb_info.monspecs.hfmin; if (*p != ':') goto bad; fb_info.monspecs.vfmin = simple_strtoul(p + 1, &p, 0); if (*p == '-') fb_info.monspecs.vfmax = simple_strtoul(p + 1, &p, 0); else fb_info.monspecs.vfmax = fb_info.monspecs.vfmin; if (*p != ':') goto check_values; fb_info.monspecs.dpms = simple_strtoul(p + 1, &p, 0); if (*p != ':') goto check_values; fb_info.var.width = simple_strtoul(p + 1, &p, 0); if (*p != ':') goto check_values; fb_info.var.height = simple_strtoul(p + 1, NULL, 0); check_values: if (fb_info.monspecs.hfmax < fb_info.monspecs.hfmin || fb_info.monspecs.vfmax < fb_info.monspecs.vfmin) goto bad; return; bad: printk(KERN_ERR "Acornfb: bad monitor settings: %s\n", opt); current_par.montype = -1; } static void acornfb_parse_montype(char *opt) { current_par.montype = -2; if (strncmp(opt, "tv", 2) == 0) { opt += 2; current_par.montype = 0; } else if (strncmp(opt, "multi", 5) == 0) { opt += 5; current_par.montype = 1; } else if (strncmp(opt, "hires", 5) == 0) { opt += 5; current_par.montype = 2; } else if (strncmp(opt, "vga", 3) == 0) { opt += 3; current_par.montype = 3; } else if (strncmp(opt, "svga", 4) == 0) { opt += 4; current_par.montype = 4; } else if (strncmp(opt, "auto", 4) == 0) { opt += 4; current_par.montype = -1; } else if (isdigit(*opt)) current_par.montype = simple_strtoul(opt, &opt, 0); if (current_par.montype == -2 || current_par.montype > NR_MONTYPES) { printk(KERN_ERR "acornfb: unknown monitor type: %s\n", opt); current_par.montype = -1; } else if (opt && *opt) { if (strcmp(opt, ",dpms") == 0) current_par.dpms = 1; else printk(KERN_ERR "acornfb: unknown monitor option: %s\n", opt); } } static void acornfb_parse_dram(char *opt) { unsigned int size; size = simple_strtoul(opt, &opt, 0); if (opt) { switch (*opt) { case 'M': case 'm': size *= 1024; case 'K': case 'k': size *= 1024; default: break; } } current_par.dram_size = size; } static struct options { char *name; void (*parse)(char *opt); } opt_table[] = { { "mon", acornfb_parse_mon }, { "montype", acornfb_parse_montype }, { "dram", acornfb_parse_dram }, { NULL, NULL } }; static int acornfb_setup(char *options) { struct options *optp; char *opt; if (!options || !*options) return 0; acornfb_init_fbinfo(); while ((opt = strsep(&options, ",")) != NULL) { if (!*opt) continue; for (optp = opt_table; optp->name; optp++) { int optlen; optlen = strlen(optp->name); if (strncmp(opt, optp->name, optlen) == 0 && opt[optlen] == ':') { optp->parse(opt + optlen + 1); break; } } if (!optp->name) printk(KERN_ERR "acornfb: unknown parameter: %s\n", opt); } return 0; } /* * Detect type of monitor connected * For now, we just assume SVGA */ static int acornfb_detect_monitortype(void) { return 4; } /* * This enables the unused memory to be freed on older Acorn machines. * We are freeing memory on behalf of the architecture initialisation * code here. */ static inline void free_unused_pages(unsigned int virtual_start, unsigned int virtual_end) { int mb_freed = 0; /* * Align addresses */ virtual_start = PAGE_ALIGN(virtual_start); virtual_end = PAGE_ALIGN(virtual_end); while (virtual_start < virtual_end) { struct page *page; /* * Clear page reserved bit, * set count to 1, and free * the page. */ page = virt_to_page(virtual_start); ClearPageReserved(page); init_page_count(page); free_page(virtual_start); virtual_start += PAGE_SIZE; mb_freed += PAGE_SIZE / 1024; } printk("acornfb: freed %dK memory\n", mb_freed); } static int acornfb_probe(struct platform_device *dev) { unsigned long size; u_int h_sync, v_sync; int rc, i; char *option = NULL; if (fb_get_options("acornfb", &option)) return -ENODEV; acornfb_setup(option); acornfb_init_fbinfo(); current_par.dev = &dev->dev; if (current_par.montype == -1) current_par.montype = acornfb_detect_monitortype(); if (current_par.montype == -1 || current_par.montype > NR_MONTYPES) current_par.montype = 4; if (current_par.montype >= 0) { fb_info.monspecs = monspecs[current_par.montype]; fb_info.monspecs.dpms = current_par.dpms; } /* * Try to select a suitable default mode */ for (i = 0; i < ARRAY_SIZE(modedb); i++) { unsigned long hs; hs = modedb[i].refresh * (modedb[i].yres + modedb[i].upper_margin + modedb[i].lower_margin + modedb[i].vsync_len); if (modedb[i].xres == DEFAULT_XRES && modedb[i].yres == DEFAULT_YRES && modedb[i].refresh >= fb_info.monspecs.vfmin && modedb[i].refresh <= fb_info.monspecs.vfmax && hs >= fb_info.monspecs.hfmin && hs <= fb_info.monspecs.hfmax) { acornfb_default_mode = modedb[i]; break; } } fb_info.screen_base = (char *)SCREEN_BASE; fb_info.fix.smem_start = SCREEN_START; current_par.using_vram = 0; /* * If vram_size is set, we are using VRAM in * a Risc PC. However, if the user has specified * an amount of DRAM then use that instead. */ if (vram_size && !current_par.dram_size) { size = vram_size; current_par.vram_half_sam = vram_size / 1024; current_par.using_vram = 1; } else if (current_par.dram_size) size = current_par.dram_size; else size = MAX_SIZE; /* * Limit maximum screen size. */ if (size > MAX_SIZE) size = MAX_SIZE; size = PAGE_ALIGN(size); #if defined(HAS_VIDC20) if (!current_par.using_vram) { dma_addr_t handle; void *base; /* * RiscPC needs to allocate the DRAM memory * for the framebuffer if we are not using * VRAM. */ base = dma_alloc_writecombine(current_par.dev, size, &handle, GFP_KERNEL); if (base == NULL) { printk(KERN_ERR "acornfb: unable to allocate screen " "memory\n"); return -ENOMEM; } fb_info.screen_base = base; fb_info.fix.smem_start = handle; } #endif #if defined(HAS_VIDC) /* * Archimedes/A5000 machines use a fixed address for their * framebuffers. Free unused pages */ free_unused_pages(PAGE_OFFSET + size, PAGE_OFFSET + MAX_SIZE); #endif fb_info.fix.smem_len = size; current_par.palette_size = VIDC_PALETTE_SIZE; /* * Lookup the timing for this resolution. If we can't * find it, then we can't restore it if we change * the resolution, so we disable this feature. */ do { rc = fb_find_mode(&fb_info.var, &fb_info, NULL, modedb, ARRAY_SIZE(modedb), &acornfb_default_mode, DEFAULT_BPP); /* * If we found an exact match, all ok. */ if (rc == 1) break; rc = fb_find_mode(&fb_info.var, &fb_info, NULL, NULL, 0, &acornfb_default_mode, DEFAULT_BPP); /* * If we found an exact match, all ok. */ if (rc == 1) break; rc = fb_find_mode(&fb_info.var, &fb_info, NULL, modedb, ARRAY_SIZE(modedb), &acornfb_default_mode, DEFAULT_BPP); if (rc) break; rc = fb_find_mode(&fb_info.var, &fb_info, NULL, NULL, 0, &acornfb_default_mode, DEFAULT_BPP); } while (0); /* * If we didn't find an exact match, try the * generic database. */ if (rc == 0) { printk("Acornfb: no valid mode found\n"); return -EINVAL; } h_sync = 1953125000 / fb_info.var.pixclock; h_sync = h_sync * 512 / (fb_info.var.xres + fb_info.var.left_margin + fb_info.var.right_margin + fb_info.var.hsync_len); v_sync = h_sync / (fb_info.var.yres + fb_info.var.upper_margin + fb_info.var.lower_margin + fb_info.var.vsync_len); printk(KERN_INFO "Acornfb: %dkB %cRAM, %s, using %dx%d, " "%d.%03dkHz, %dHz\n", fb_info.fix.smem_len / 1024, current_par.using_vram ? 'V' : 'D', VIDC_NAME, fb_info.var.xres, fb_info.var.yres, h_sync / 1000, h_sync % 1000, v_sync); printk(KERN_INFO "Acornfb: Monitor: %d.%03d-%d.%03dkHz, %d-%dHz%s\n", fb_info.monspecs.hfmin / 1000, fb_info.monspecs.hfmin % 1000, fb_info.monspecs.hfmax / 1000, fb_info.monspecs.hfmax % 1000, fb_info.monspecs.vfmin, fb_info.monspecs.vfmax, fb_info.monspecs.dpms ? ", DPMS" : ""); if (fb_set_var(&fb_info, &fb_info.var)) printk(KERN_ERR "Acornfb: unable to set display parameters\n"); if (register_framebuffer(&fb_info) < 0) return -EINVAL; return 0; } static struct platform_driver acornfb_driver = { .probe = acornfb_probe, .driver = { .name = "acornfb", }, }; static int __init acornfb_init(void) { return platform_driver_register(&acornfb_driver); } module_init(acornfb_init); MODULE_AUTHOR("Russell King"); MODULE_DESCRIPTION("VIDC 1/1a/20 framebuffer driver"); MODULE_LICENSE("GPL");
ubuntustudio-kernel/ubuntu-saucy-lowlatency
drivers/video/acornfb.c
C
gpl-2.0
35,720
/* * Copyright (C) 2012 Intel Corporation * Author: Jim Kukunas <james.t.kukunas@linux.intel.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. */ #if CONFIG_AS_AVX2 #include <linux/raid/pq.h> #include "x86.h" static int raid6_has_avx2(void) { return boot_cpu_has(X86_FEATURE_AVX2) && boot_cpu_has(X86_FEATURE_AVX); } static void raid6_2data_recov_avx2(int disks, size_t bytes, int faila, int failb, void **ptrs) { u8 *p, *q, *dp, *dq; const u8 *pbmul; /* P multiplier table for B data */ const u8 *qmul; /* Q multiplier table (for both) */ const u8 x0f = 0x0f; p = (u8 *)ptrs[disks-2]; q = (u8 *)ptrs[disks-1]; /* Compute syndrome with zero for the missing data pages Use the dead data pages as temporary storage for delta p and delta q */ dp = (u8 *)ptrs[faila]; ptrs[faila] = (void *)raid6_empty_zero_page; ptrs[disks-2] = dp; dq = (u8 *)ptrs[failb]; ptrs[failb] = (void *)raid6_empty_zero_page; ptrs[disks-1] = dq; raid6_call.gen_syndrome(disks, bytes, ptrs); /* Restore pointer table */ ptrs[faila] = dp; ptrs[failb] = dq; ptrs[disks-2] = p; ptrs[disks-1] = q; /* Now, pick the proper data tables */ pbmul = raid6_vgfmul[raid6_gfexi[failb-faila]]; qmul = raid6_vgfmul[raid6_gfinv[raid6_gfexp[faila] ^ raid6_gfexp[failb]]]; kernel_fpu_begin(); /* ymm0 = x0f[16] */ asm volatile("vpbroadcastb %0, %%ymm7" : : "m" (x0f)); while (bytes) { #ifdef CONFIG_X86_64 asm volatile("vmovdqa %0, %%ymm1" : : "m" (q[0])); asm volatile("vmovdqa %0, %%ymm9" : : "m" (q[32])); asm volatile("vmovdqa %0, %%ymm0" : : "m" (p[0])); asm volatile("vmovdqa %0, %%ymm8" : : "m" (p[32])); asm volatile("vpxor %0, %%ymm1, %%ymm1" : : "m" (dq[0])); asm volatile("vpxor %0, %%ymm9, %%ymm9" : : "m" (dq[32])); asm volatile("vpxor %0, %%ymm0, %%ymm0" : : "m" (dp[0])); asm volatile("vpxor %0, %%ymm8, %%ymm8" : : "m" (dp[32])); /* * 1 = dq[0] ^ q[0] * 9 = dq[32] ^ q[32] * 0 = dp[0] ^ p[0] * 8 = dp[32] ^ p[32] */ asm volatile("vbroadcasti128 %0, %%ymm4" : : "m" (qmul[0])); asm volatile("vbroadcasti128 %0, %%ymm5" : : "m" (qmul[16])); asm volatile("vpsraw $4, %ymm1, %ymm3"); asm volatile("vpsraw $4, %ymm9, %ymm12"); asm volatile("vpand %ymm7, %ymm1, %ymm1"); asm volatile("vpand %ymm7, %ymm9, %ymm9"); asm volatile("vpand %ymm7, %ymm3, %ymm3"); asm volatile("vpand %ymm7, %ymm12, %ymm12"); asm volatile("vpshufb %ymm9, %ymm4, %ymm14"); asm volatile("vpshufb %ymm1, %ymm4, %ymm4"); asm volatile("vpshufb %ymm12, %ymm5, %ymm15"); asm volatile("vpshufb %ymm3, %ymm5, %ymm5"); asm volatile("vpxor %ymm14, %ymm15, %ymm15"); asm volatile("vpxor %ymm4, %ymm5, %ymm5"); /* * 5 = qx[0] * 15 = qx[32] */ asm volatile("vbroadcasti128 %0, %%ymm4" : : "m" (pbmul[0])); asm volatile("vbroadcasti128 %0, %%ymm1" : : "m" (pbmul[16])); asm volatile("vpsraw $4, %ymm0, %ymm2"); asm volatile("vpsraw $4, %ymm8, %ymm6"); asm volatile("vpand %ymm7, %ymm0, %ymm3"); asm volatile("vpand %ymm7, %ymm8, %ymm14"); asm volatile("vpand %ymm7, %ymm2, %ymm2"); asm volatile("vpand %ymm7, %ymm6, %ymm6"); asm volatile("vpshufb %ymm14, %ymm4, %ymm12"); asm volatile("vpshufb %ymm3, %ymm4, %ymm4"); asm volatile("vpshufb %ymm6, %ymm1, %ymm13"); asm volatile("vpshufb %ymm2, %ymm1, %ymm1"); asm volatile("vpxor %ymm4, %ymm1, %ymm1"); asm volatile("vpxor %ymm12, %ymm13, %ymm13"); /* * 1 = pbmul[px[0]] * 13 = pbmul[px[32]] */ asm volatile("vpxor %ymm5, %ymm1, %ymm1"); asm volatile("vpxor %ymm15, %ymm13, %ymm13"); /* * 1 = db = DQ * 13 = db[32] = DQ[32] */ asm volatile("vmovdqa %%ymm1, %0" : "=m" (dq[0])); asm volatile("vmovdqa %%ymm13,%0" : "=m" (dq[32])); asm volatile("vpxor %ymm1, %ymm0, %ymm0"); asm volatile("vpxor %ymm13, %ymm8, %ymm8"); asm volatile("vmovdqa %%ymm0, %0" : "=m" (dp[0])); asm volatile("vmovdqa %%ymm8, %0" : "=m" (dp[32])); bytes -= 64; p += 64; q += 64; dp += 64; dq += 64; #else asm volatile("vmovdqa %0, %%ymm1" : : "m" (*q)); asm volatile("vmovdqa %0, %%ymm0" : : "m" (*p)); asm volatile("vpxor %0, %%ymm1, %%ymm1" : : "m" (*dq)); asm volatile("vpxor %0, %%ymm0, %%ymm0" : : "m" (*dp)); /* 1 = dq ^ q; 0 = dp ^ p */ asm volatile("vbroadcasti128 %0, %%ymm4" : : "m" (qmul[0])); asm volatile("vbroadcasti128 %0, %%ymm5" : : "m" (qmul[16])); /* * 1 = dq ^ q * 3 = dq ^ p >> 4 */ asm volatile("vpsraw $4, %ymm1, %ymm3"); asm volatile("vpand %ymm7, %ymm1, %ymm1"); asm volatile("vpand %ymm7, %ymm3, %ymm3"); asm volatile("vpshufb %ymm1, %ymm4, %ymm4"); asm volatile("vpshufb %ymm3, %ymm5, %ymm5"); asm volatile("vpxor %ymm4, %ymm5, %ymm5"); /* 5 = qx */ asm volatile("vbroadcasti128 %0, %%ymm4" : : "m" (pbmul[0])); asm volatile("vbroadcasti128 %0, %%ymm1" : : "m" (pbmul[16])); asm volatile("vpsraw $4, %ymm0, %ymm2"); asm volatile("vpand %ymm7, %ymm0, %ymm3"); asm volatile("vpand %ymm7, %ymm2, %ymm2"); asm volatile("vpshufb %ymm3, %ymm4, %ymm4"); asm volatile("vpshufb %ymm2, %ymm1, %ymm1"); asm volatile("vpxor %ymm4, %ymm1, %ymm1"); /* 1 = pbmul[px] */ asm volatile("vpxor %ymm5, %ymm1, %ymm1"); /* 1 = db = DQ */ asm volatile("vmovdqa %%ymm1, %0" : "=m" (dq[0])); asm volatile("vpxor %ymm1, %ymm0, %ymm0"); asm volatile("vmovdqa %%ymm0, %0" : "=m" (dp[0])); bytes -= 32; p += 32; q += 32; dp += 32; dq += 32; #endif } kernel_fpu_end(); } static void raid6_datap_recov_avx2(int disks, size_t bytes, int faila, void **ptrs) { u8 *p, *q, *dq; const u8 *qmul; /* Q multiplier table */ const u8 x0f = 0x0f; p = (u8 *)ptrs[disks-2]; q = (u8 *)ptrs[disks-1]; /* Compute syndrome with zero for the missing data page Use the dead data page as temporary storage for delta q */ dq = (u8 *)ptrs[faila]; ptrs[faila] = (void *)raid6_empty_zero_page; ptrs[disks-1] = dq; raid6_call.gen_syndrome(disks, bytes, ptrs); /* Restore pointer table */ ptrs[faila] = dq; ptrs[disks-1] = q; /* Now, pick the proper data tables */ qmul = raid6_vgfmul[raid6_gfinv[raid6_gfexp[faila]]]; kernel_fpu_begin(); asm volatile("vpbroadcastb %0, %%ymm7" : : "m" (x0f)); while (bytes) { #ifdef CONFIG_X86_64 asm volatile("vmovdqa %0, %%ymm3" : : "m" (dq[0])); asm volatile("vmovdqa %0, %%ymm8" : : "m" (dq[32])); asm volatile("vpxor %0, %%ymm3, %%ymm3" : : "m" (q[0])); asm volatile("vpxor %0, %%ymm8, %%ymm8" : : "m" (q[32])); /* * 3 = q[0] ^ dq[0] * 8 = q[32] ^ dq[32] */ asm volatile("vbroadcasti128 %0, %%ymm0" : : "m" (qmul[0])); asm volatile("vmovapd %ymm0, %ymm13"); asm volatile("vbroadcasti128 %0, %%ymm1" : : "m" (qmul[16])); asm volatile("vmovapd %ymm1, %ymm14"); asm volatile("vpsraw $4, %ymm3, %ymm6"); asm volatile("vpsraw $4, %ymm8, %ymm12"); asm volatile("vpand %ymm7, %ymm3, %ymm3"); asm volatile("vpand %ymm7, %ymm8, %ymm8"); asm volatile("vpand %ymm7, %ymm6, %ymm6"); asm volatile("vpand %ymm7, %ymm12, %ymm12"); asm volatile("vpshufb %ymm3, %ymm0, %ymm0"); asm volatile("vpshufb %ymm8, %ymm13, %ymm13"); asm volatile("vpshufb %ymm6, %ymm1, %ymm1"); asm volatile("vpshufb %ymm12, %ymm14, %ymm14"); asm volatile("vpxor %ymm0, %ymm1, %ymm1"); asm volatile("vpxor %ymm13, %ymm14, %ymm14"); /* * 1 = qmul[q[0] ^ dq[0]] * 14 = qmul[q[32] ^ dq[32]] */ asm volatile("vmovdqa %0, %%ymm2" : : "m" (p[0])); asm volatile("vmovdqa %0, %%ymm12" : : "m" (p[32])); asm volatile("vpxor %ymm1, %ymm2, %ymm2"); asm volatile("vpxor %ymm14, %ymm12, %ymm12"); /* * 2 = p[0] ^ qmul[q[0] ^ dq[0]] * 12 = p[32] ^ qmul[q[32] ^ dq[32]] */ asm volatile("vmovdqa %%ymm1, %0" : "=m" (dq[0])); asm volatile("vmovdqa %%ymm14, %0" : "=m" (dq[32])); asm volatile("vmovdqa %%ymm2, %0" : "=m" (p[0])); asm volatile("vmovdqa %%ymm12,%0" : "=m" (p[32])); bytes -= 64; p += 64; q += 64; dq += 64; #else asm volatile("vmovdqa %0, %%ymm3" : : "m" (dq[0])); asm volatile("vpxor %0, %%ymm3, %%ymm3" : : "m" (q[0])); /* 3 = q ^ dq */ asm volatile("vbroadcasti128 %0, %%ymm0" : : "m" (qmul[0])); asm volatile("vbroadcasti128 %0, %%ymm1" : : "m" (qmul[16])); asm volatile("vpsraw $4, %ymm3, %ymm6"); asm volatile("vpand %ymm7, %ymm3, %ymm3"); asm volatile("vpand %ymm7, %ymm6, %ymm6"); asm volatile("vpshufb %ymm3, %ymm0, %ymm0"); asm volatile("vpshufb %ymm6, %ymm1, %ymm1"); asm volatile("vpxor %ymm0, %ymm1, %ymm1"); /* 1 = qmul[q ^ dq] */ asm volatile("vmovdqa %0, %%ymm2" : : "m" (p[0])); asm volatile("vpxor %ymm1, %ymm2, %ymm2"); /* 2 = p ^ qmul[q ^ dq] */ asm volatile("vmovdqa %%ymm1, %0" : "=m" (dq[0])); asm volatile("vmovdqa %%ymm2, %0" : "=m" (p[0])); bytes -= 32; p += 32; q += 32; dq += 32; #endif } kernel_fpu_end(); } const struct raid6_recov_calls raid6_recov_avx2 = { .data2 = raid6_2data_recov_avx2, .datap = raid6_datap_recov_avx2, .valid = raid6_has_avx2, #ifdef CONFIG_X86_64 .name = "avx2x2", #else .name = "avx2x1", #endif .priority = 2, }; #else #warning "your version of binutils lacks AVX2 support" #endif
andrsbub/linux
lib/raid6/recov_avx2.c
C
gpl-2.0
9,227